Showing relation table fields with filters in yii2 - filter

I'm showing has many relation table value in my girdview as follows
[
'attribute' => 'Resume Title',
'value' => function($model, $key, $index) {
return implode(\yii\helpers\ArrayHelper::map(
$model->jobSeekerProfiles,
'job_seeker_profile_id',
'resume_title'
));
},
],
my table relation is
public function getJobSeekerProfiles()
{
return $this->hasMany(JobSeekerProfile::className(), ['user_id' => 'user_id']);
}
But how to make this column with filter and sortable ?

Related

create nested droptown using laravel admin panel

i have a table buss_catgry_mst
fields:- buss_catgry_mst_id , category_name ,parent_id, depth.
i want to create nested category using select_2_nested in backpack laravel.
ex:-
buss_catgry_mst_id=1 , category_name=restaurent ,parent_id=0, depth=1.
i want to create it's sub category and i want to take depth value which is +1 from it's main category depth value.
code in crud controller:-
{
CRUD::setValidation(StoreRequest::class);
//for nested
CRUD::addField([
'name' => 'parent_id',
'label' => "Category",
'type' => 'select2_nested',
'entity' => 'category', // the method that defines the relationship in your Model
'attribute' => 'category_name', // foreign key attribute that is shown to user
'model' => "App\Models\BussCatgryMst",
]); ```
***model buss_catgry_mst***
public function category()
{
return $this->hasMany(BussCatgryMst::class);
}
public function children()
{
return $this->hasMany('App\Models\BussCatgryMst','parent_id');
}

Laravel Backpack select2_from_ajax select change the result and default value

For the backpack-demo, I would like to show the ID and Title together.
For the search result no issue, selected at the select2 also no issue, the problem is after save, it will not display, it become blank.
How can I set it?
Like below
backpack-demo/app/Http/Controllers/Admin/MonsterCrudController.php
[ // select2_from_ajax: 1-n relationship
'label' => 'Select2_from_ajax', // Table column heading
'type' => 'select2_from_ajax',
'name' => 'select2_from_ajax', // the column that contains the ID of that connected entity;
'entity' => 'article', // the method that defines the relationship in your Model
'attribute' => 'id_title', // foreign key attribute that is shown to user
'model' => "Backpack\NewsCRUD\app\Models\Article", // foreign key model
'data_source' => url('api/article'), // url to controller search function (with /{id} should return model)
'placeholder' => 'Select an article', // placeholder for the select
'minimum_input_length' => 2, // minimum characters to type before querying results
'tab' => 'Relationships',
'wrapperAttributes' => ['class' => 'form-group col-md-12'],
],
backpack-demo/app/Http/Controllers/Api/ArticleController.php
if ($search_term) {
return Article::
selectRaw("CONCAT('Article ID: ', id,' | Title: ', Title) AS id_title, articles.*")
->where('title', 'LIKE', '%'.$search_term.'%')->paginate(10);
} else {
return Article::selectRaw("CONCAT('Article ID: ', id,' | Title: ', Title) AS id_title, articles.*")
->paginate(10);
}
The solution is at the Article Model create another accessor function
public function getIdTitleAttribute()
{
return 'Article ID: ' . $this->id . ' | Title: ' . $this->title;
}

laravel 7 Validation unique multiple columns

how to viladate multiple columns
table name "exam_starts"
columns
id
exam_id
exam_multi_id
student_id
exam_class_id
exam_code_id
Status
class Student extends Model
{
// exam
public function exams(){
return $this->belongsToMany('App\Exam','exam_starts','student_id','exam_id')
->withPivot(['id','exam_multi_id','exam_class_id','exam_code_id','Attend','pass','Status'])-
>withTimestamps();
}
}
how to unique columns student_id and exam_class_id in table exam_starts ?
My Try in controller
class ExamClassController extends Controller
{
$this->validate($request, [
'exam_class_id' => [
'required',
'integer',
'unique:exam_startss,exam_class_id,'.$request->exam_class_id .',student_id' ,
],
'student_id' => 'bail|required|integer',
'exam_start_id' => 'bail|required|integer',
'exam_id' => 'bail|required|integer',
'exam_multi_id' => 'bail|required|integer',
'code' => 'nullable|string',
'student' => 'bail|required|string',
]);
}
this mysql resulte
(SQL: select count(*) as aggregate from `exam_starts` where `exam_class_id` = 1 and `student_id` <> 1)
Use Unique rule class and you can pass multiple wheres to it, to make an unique constraint that takes two columns.
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id);
Set it into validation like so
'exam_class_id' => [
'required',
'integer',
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id),
],

Sort yii2 gridview by column that's not in a model

I have Gridview and one column value I get via http request. Is there a way to sort the table by this column?
myTableModel.php
class myTableModel extends \yii\db\ActiveRecord
{
...,
public function getExternalValue() {
$client = new Client();
return $client->createRequest()->setMethod('get')
->setUrl('http:://...')->setData(['id' => 1])->send()->content;
}
}
myTableModelSearch.php
class myTableModelSearch extends myTableModel
{
public function rules()
{
return [
[[...,'externalValue'], 'string'],
[[..., 'externalValue'], 'safe']
];
}
public $externalValue;
public function searchView($params) {
$query = SomeTable::find();
$dataProvider = new ActiveDataProvider(['query' => $query]);
$dataProvider->setSort(['attributes' => [
'externalValue' => [
'asc' => ['externalValue' => SORT_ASC],
'desc' => ['externalValue' => SORT_DESC]
]
]]);
if (!($this->load($params) && $this->validate()))
return $dataProvider;
return $dataProvider;
}
}
view.php
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
... ,
[
'attribute' => 'externalValue',
'value' => function($item) {
return $item->externalValue;
},
]
],
]);
I also tried to add value to view simply with $item->getExternalValue() (and without public property set), but it makes no difference - when trying to sort I get database exception error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'externalValue' in 'order clause'. How could I trick gridview, to make it sort my table by externalValue column?
You're using yii\data\ActiveDataProvider which uses an instance of ActiveQuery to find its data.
Try using yii\data\ArrayDataProvider, or extend yii\data\ActiveDataProvider to allow a second source for your data.
Additionally, you have to implement a sort function that can sort using your attribute.
see more here and here

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