cant get ESelect2 extension in yii concatenate two or more columns in the dropdown - drop-down-menu

Eselect2 is the extension am using and myADropDown() fetches the data and displays but then my need is concatenate two or more columns in the dropdown
model1 view
<?php $this->widget('ext.select2.ESelect2', array(
'name' => 'id',
'model' => $model,
'options' => array(
'placeholder' => $model->getAttributeLabel('id'),
),
'data' => $model->myADropDown(),
));?>
model1
public function getConcatened()
{
return $this->name.' '.$this->locate.' '.$this->rating;
}
public function myADropDown()
{
$vid=Yii::app()->SESSION['vid'];
$gid=Model2::model()->xyz($vid);
$list=CHtml::listData($gid,'id','concatened');
return $list;
}
// id is fk in another tbl
in the dropdownlist my need is name ,location,rating for each person , am unable to do so
Please Let me know how do i achieve it

For concatenating the table fields in listdata, Please check this Yii forum answer:
Link
As per the link suggestion, you need to add a function in model to get concatenated string.
public function __get($key){
$action = 'get'.str_replace(' ','',ucwords(str_replace('_',' ',$key)));
if(method_exists($this, $action)) return $this->$action();
return parent::__get($key);
}

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

Many-To-Many Relationship in backpack 4.1 for laravel

I use laravel 8 and backpack 4.1 for laravel. I have to add in one column more then one comma-separated-values. I have one pivot table with 2 foreign keys. The user can see with foreign key the available objects. I have to put all available objects into one column in setupListOperation() in CrudController of the user. How can I do it?
UserModel:
public function Objects(): belongsToMany
{
return $this->belongsToMany(Object::class);
}
CRUD::column('object_id')
->type('relationship')
->relation_type('BelongsToMany')
->model(Object::class)
->entity('name')
->label('Objects');
Thank you for your answers in advance.
I have found another method for the user crud. This method supposed to get the values from the method of the model.
$this->crud->addColumn(
[
// run a function on the CRUD model and show its return value
'name' => 'rentalObjects',
'label' => 'RentalObjects', // Table column heading
'type' => 'model_function_attribute',
'function_name' => 'getRentalObjects',
'attribute' => 'name'
]);
Method in the model User:
public function getRentalObjects(): string
{
$users = User::all();
foreach ($users as $user) {
$rentalObjects = $user->rentalObjects;
foreach ($rentalObjects as $rentalObject) {
$objectsNames = $rentalObject->name;
}
$objects = implode(",", array($objectsNames));
}
return $objects;
}
I coudn't see the new column on the small screen und thought, that the column wasn't in the table. By backpack one can choose the columns, if the screen is small.
The problem was solved:
$this->crud->addColumn([
'label' => 'Objekte', // Table column heading
'type' => 'select_multiple',
'name' => 'rentalObjects', // the method that defines the relationship in your Model
'entity' => 'rentalObjects', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => 'App\Models\RentalObject', // foreign key model
]);

How to use relationships in laravel 8

my question has two parts
Firstly, My if statement is not working. My if statement is as followed:
if ($request->is_published) {
$resources_page->published_at = now();
}
This is stored in my controller, I have a model for this and it is as followed:
public function is_published()
{
return $this->published_at !== null;
}
It is meant to check whether my checkbox is checked and return the timestamp, I have it cast in my model like followed:
protected $casts = [
'published_at' => 'datetime',
];
And in my view:
#include('components.form.input-checkbox', [
'label' => 'Publish?',
'form_object' => 'page',
'name' => 'is_published'
])
Could anyone elude to the answer?
Secondly, when trying to sync, it is not storing to my resources_category_resources_page table
In my controller, i have the following code
$resources_page->resources_categories()->sync(
ResourcesCategory::whereIn('slug', $request->resources_categories)->pluck('id')
);
In my model I have the relationships declared properly, so I don't know why its not storing?

Adding Columns with nested relationships in backpack for laravel

I have 3 models created in backpack for laravel CRUD:
Driver, Municipality and Province.
Driver has a 'municipality_id' and the relationship function:
public function municipality()
{
return $this->belongsTo('App\Models\Municipality');
}
To get the province of the driver i need to use a relationship function inside Municipality model:
public function province()
{
return $this->belongsTo('App\Models\Province');
}
The driver model does not contain the province function so i have to to something like
$objdriver->municipality->province->name;
To get the province name.
Now the problem is that i have to add 2 columns in the table created by artisan that display the municipality name and the province name.
For the municipality it's easy and i did it like this:
$this->crud->addColumn('municipality_id', [
// 1-n relationship
'label' => "Comune", // Table column heading
'type' => "select",
'name' => 'municipality_id', // the column that contains the ID of that connected entity;
'entity' => 'municipality', // the method that defines the relationship in your Model
'attribute' => "name", // foreign key attribute that is shown to user
'model' => "App\Models\Municipality", // foreign key model
]);
And it works Fine, but how do i add a column for the Provinces? Since the method is not in the driver model i can't use the same approach.
I already tried using a custom function to fetch what i need from the province table, something like:
$this->crud->addColumn('province_id', [
// run a function on the CRUD model and show its return value
'name' => "province_id",
'label' => "Provincia", // Table column heading
'type' => "model_function",
'function_name' => 'GetProvinceName', // the method in your Model
])
where GetProvinceName is:
public function GetProvinceName()
{
return $this->municipality->province->name;
}
but that just gives out an error.
You could try the following code.
$this->crud->addColumn([
'name' => 'municipality.province.name', // the relationships are handled automatically
'label' => 'Provincia', // the grid's column heading
'type' => 'text'
]);

Yii2: Labels with attributeLabels() in GridView

I generated a model which got the function attributeLabels():
public function attributeLabels()
{
return [
'column1' => 'name of column1',
'column2' => 'name of column2',
];
}
I also wrote a function in my model, which creates a SQL statement:
public function getReminders()
{
$sql = Yii::$app->db->createCommand('SELECT
[[column1]], [[column2]]
FROM {{%table}}
WHERE column1 > :value')
-> bindValue(':value', '10');
return $sql;
}
Then I created a controller with an actionIndex() function:
public function actionIndex()
{
$model = new TestObject();
$testmodels= new ActiveDataProvider([
'models' => $model->getReminders()->queryAll(),
]);
return $this->render('index', [
'testmodels' => $testmodels,
]);
Finally I created a View
GridView::widget([
'dataProvider' => $testmodels,
'layout' => '{items}{pager}',
'columns' => ['column1', column2,],
]);
For some reason, the column names of the resulting page are column1 and column2. I have tried to create a listView and got the correct names for the columns. How comes that the column names are not set by attributeLabels() in this case? I really don't want to use the label property in the gridview.
Thank you in advance!
If you just need to change the label for the gridview column you can configure you column with proper value for label
GridView::widget([
'dataProvider' => $testmodels,
'layout' => '{items}{pager}',
'columns' => [
[
'attribute'=> column1',
'label' => 'Your Lable for column 1',
],
[
'attribute'=> column2',
'label' => 'Your Lable for column 2',
],
],
]);
you can take a look at thsi for a brief guide http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html or here for ref http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html
I would do the following:
make the base class for the TestObject be ActiveRecord
Override tableName
Simplify getReminders, make it static, and let it return Query not a Command
class TestModel extends yii\db\ActiveRecord
{
...
public static function tableName()
{
return {{%table}};
}
public static function getReminders()
{
$query = self::find()->select(['column1', 'column2'])
->where(['>', 'column1', 10]);
return $query;
}
...
}
Don't set models of the ActiveDataProvier and instead set query
'models' => TestObject::getReminders(),

Resources