Search in Laravel Datatables - laravel

In my datatables, the search function works only on the name column. The name column ist different that the others. It means, the name column gives the value of the database back, while the others gives a value back with the function add column
In the column array there are the following values:
´´´
protected function getColumns()
{
return [
'status',
'name' => [
'title' => 'Name',
'orderable' => true,
'searchable' => true
],
'location' => [
'title' => 'Standort',
],
'department' => [
'title' => 'Abteilung',
'orderable' => true,
'searchable' => true
],
'division' => [
'title' => 'Bereich',
'orderable' => true,
'searchable' => true
],
'leader' => [
'title' => 'Verantwortlicher',
'orderable' => true,
'searchable' => true
],
'start_date' => [
'title' => 'Startdatum',
'searchable'=> true,
],
'end_date' => [
'title' => 'Enddatum',
'searchable'=> true
]
];
}
```
Why it doesn't search on all columns? What i have to do?

Try to search by using this code.
return Datatables::of($tasks)
->filter(function ($query) use ($request) {
$title = $request->title;
if (isset($title) && !empty($title)) {
$query->where('title', 'like', '%'.$title.'%');
}
})->make(true);
OR
return Datatables::of($tasks)
->filterColumn('title', function($query, $value) {
$query->whereRaw("title like ?", ["%{$value}%"]);
})->make(true);

Related

broken column sequence backpack laravel

There was a column order issue. I finished making edits, after a few hours I returned to the project and saw that the columns of the table were mixed up, although before that everything worked correctly.
This is my setup method
public function setup()
{
/*
|--------------------------------------------------------------------------
| CrudPanel Basic Information
|--------------------------------------------------------------------------
*/
$this->crud->setModel('App\Models\Geozone');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/geozone');
/*
|--------------------------------------------------------------------------
| CrudPanel Configuration
|--------------------------------------------------------------------------
*/
$this->crud->allowAccess('show');
$this->crud->setActionsColumnPriority(10000);
$this->transIt();
$this->addColumnsT([
[
'name' => "polygons_json",
'visibleInTable' => false,
],
[
'name' => 'groups', // the method that defines the relationship in your Model
'type' => "select_multiple",
'entity' => 'groups', // the method that defines the relationship in your Model
'attribute' => "description", // foreign key attribute that is shown to user
'model' => "App\Models\GeozoneGroup", // foreign key model
//'visibleInTable' => false,
'number_columns' => 1,
],
[
'name' => "priority",
'visibleInTable' => false,
],
[
'name' => 'uz',
'type' => 'check',
],
[
'name' => 'frz',
'type' => 'check',
],
[
'name' => 'slz',
'type' => 'check',
],
[
'name' => 'ntz',
'type' => 'check',
]
]);
if(\Request::has('filter')) $this->crud->query = $this->crud->query->where(\Request::get('filter'), true);
if(\Request::has('deleted')){
$this->crud->addClause('onlyTrashed');
$this->crud->removeAllButtonsFromStack('line');
$this->crud->addButtonFromModelFunction('line', 'restore', 'restoreActionButton');
}
$this->addFieldsT([
[
'type' => "textarea",
'name' => 'polygons_json',
'attributes' => [
'readonly'=>'readonly',
],
],
]);
$this->addFieldsT([
[
'type' => "checklist",
'name' => 'groups', // the method that defines the relationship in your Model
'entity' => 'groups', // the method that defines the relationship in your Model
'attribute' => "description", // foreign key attribute that is shown to user
'model' => "App\Models\GeozoneGroup", // foreign key model
'pivot' => true,
'direction' => 'row'
],
]);
$this->addFieldsT([
[
'type' => "color_picker",
'name' => 'fill_color',
'attributes' => [
'pattern' => '^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$'
]
],
]);
$this->addFieldsT([
[
'type' => "color_picker",
'name' => 'stroke_color',
'attributes' => [
'pattern' => '^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$'
]
],
]);
$this->addFieldsT([
[
'name' => 'fill_opacity',
'attributes' => [
'pattern' => '\d{1}(\.\d{1,2})?'
]
],
]);
$this->addFieldsT([
[
'name' => 'stroke_opacity',
'attributes' => [
'pattern' => '\d{1}(\.\d{1,2})?'
]
],
]);
$this->crud->addFilter([ // select2_multiple filter
'type' => 'select2_multiple',
'name' => 'car_group',
'label'=> trans('columns.groups'),
], function() { // the options that show up in the select2
return \App\Models\GeozoneGroup::all()->pluck('description','id')->toArray();
}, function($values) {
$this->crud->addClause('join', 'geozone_to_group', 'id', 'geozone_to_group.geozone_id');
$this->crud->addClause('wherein', 'geozone_to_group.geozone_group_id', json_decode($values));
});
$this->crud->setCreateView('geozone_create');
$this->crud->setEditView('geozone_edit');
// add asterisk for fields that are required in GeozoneRequest
$this->crud->setRequiredFields(StoreRequest::class, 'create');
$this->crud->setRequiredFields(UpdateRequest::class, 'edit');
}
So the columns were arranged
[![enter image description here](https://i.stack.imgur.com/kQ1rP.jpg)](https://i.stack.imgur.com/kQ1rP.jpg)
I tried to change their location in the addColumns method, but it doesn't work. Although it works in other controllers.

How to override the select2 action that disables subfield options selected in a previous subfield in Backpack for Laravel?

Controller (field definition):
$this->crud->addField([
'name' => 'precios',
'type' => "relationship",
'pivotSelect' => [
'ajax' => true,
'inline_create' => [ 'entity' => 'precio' ],
'data_source' => backpack_url('presupuesto/fetch/precio'),
'minimum_input_length' => 0,
'wrapper' => [
'class' => 'col-md-3 order-2'
],
'attributes' => [
'required' => 'required',
],
'dependencies' => ['categoria_precio_id']
],
'subfields' => [
[
'name' => 'categoria_precio_id',
'type' => 'relationship',
'label' => 'Categoría',
'wrapper' => [
'class' => 'form-group col-md-2 order-1',
],
'dependencies' => ['tipo'],
'ajax' => true,
'data_source' => backpack_url('presupuesto/fetch/categoria-precio'),
'minimum_input_length' => 0
],
[
'name' => 'costo',
'type' => 'text',
'label' => 'Costo Unitario',
'wrapper' => [
'class' => 'form-group col-md-1 order-3',
],
],
[
'name' => 'cantidad',
'type' => 'text',
'wrapper' => [
'class' => 'form-group col-md-1 order-4',
],
],
[
'name' => 'duracion',
'type' => 'text',
'wrapper' => [
'class' => 'form-group col-md-2 order-5',
]
],
[
'name' => 'costo_final',
'type' => 'text',
'label' => 'Costo',
'wrapper' => [
'class' => 'form-group col-md-1 order-6 costo_final',
],
'attributes' => array('readonly' => 'readonly', 'disabled' => 'disabled')
],
],
'tab' => "Precios",
'force_delete' => true]);
My Form capture
When I tried to select an option that I selected previously it does not allow me. For example, in the image "animación 2d" (ID:82).
First I have in my table "precio_presupuesto"
precio_id (PK)
presupuesto_id (PK)
costo
...
created_at
updated_at
And I change that for:
id (PK)
precio_id (FK)
presupuest_id (FK)
costo
...
created_at
updated_at
In my model I had:
public function precios()
{
return $this->belongsToMany(\App\Models\Precio::class)->withPivot('costo', 'cantidad', 'duracion', 'categoria_precio_id', 'costo_final')->withTimestamps();
}
And I change that for:
public function precios()
{
return $this->belongsToMany(\App\Models\Precio::class,'precio_presupuesto', 'presupuesto_id','precio_id', 'id')->withPivot('costo', 'cantidad', 'duracion', 'categoria_precio_id', 'costo_final')->withTimestamps();
}
I'm new to Laravel and Backpack, but I think my definition is fine, I just don't know how to tell Backpack to allow adding two elements with repeated "price_id" and "presupuesto_id", this because there will be cases where you can change the "cantidad" field or the "costo" field for the same combination (precio_id, presupuesto_id).
In other words I just want the "Select2" subfields not to disable previously selected options.
My model
I have tried changing the definition of my models again. Create a class for the pivot table following the documentation and example of:
doc
example
Presupuesto Model
class Presupuesto extends Model implements Auditable{
public function precio_presupuesto(){
return $this->hasMany(PrecioPresupuesto::class, 'presupuesto_id');
}
public function precios(){
return $this->belongsToMany(\App\Models\Precio::class)->using(\App\Models\PrecioPresupuesto::class)->
withPivot('costo', 'cantidad', 'duracion', 'categoria_precio_id', 'costo_final')->withTimestamps();
}
}
Precio Model:
class Precio extends Model{
public function precio_presupuesto()
{
return $this->hasMany(PrecioPresupuesto::class, 'precio_id');
}
public function presupuestos()
{
// return $this->belongsToMany(\App\Models\Presupuesto::class);
return $this->belongsToMany(\App\Models\Presupuesto::class)->using(\App\Models\PrecioPresupuesto::class)->
withPivot('costo', 'cantidad', 'duracion', 'categoria_precio_id', 'costo_final')->withTimestamps();
}}
Pivot Model:
class PrecioPresupuesto extends Pivot{
public function presupuesto(){
return $this->belongsTo(Presupuesto::class, 'presupuesto_id');
}
public function precio(){
return $this->belongsTo(Precio::class, 'precio_id');
}}
Does Backpack allow me to save several pairs of elements like in the image pivot table precio_presupuesto? what is what I need? because it currently does not allow me.

yajra/laravel-datatables filterColumn doesnt work

Page loading correctly and every things work fine while bringing datas. Now I want to filter them but FilterColumn() method doesnt even work. When I tried filter() method it's working but then I won't get $keywords variable. I am missing something while querying leads ?
if (request()->ajax()) {
$leads = Lead::with('country','agent','detail')->orderBy('id','DESC');
$leads->where(function($q) use ($user){
if ($user->hasRole('agent') && !$user->hasRole('admin') && !$user->hasRole('lead')){ //agent isem
$q->where('agent_id',$user->id)
->orWhere('agent_id',null);
}
});
return DataTables::of($leads)->
addColumn('edit_button', function ($lead) {
$link = route('leads.edit',$lead->id);
return ' Edit ';
})->
filterColumn('edit_button', function ($query, $keyword) {
dd($keyword);
return $query->whereHas('patient', function ($query) use ($keyword) {
$query->whereRaw("CONCAT( name, ' ', surname ) like ?", ["%$keyword%"]);
});
})->rawColumns(['edit_button','phone','detail.conversion_notes'])->
toJson();
}
$tableColumn = [
['data' => 'edit_button', 'name' => 'edit_button', 'title' => 'Edit', 'searchable' => false],
['data' => 'full_name', 'name' => 'full_name', 'title' => 'Full Name'],
['data' => 'phone', 'name' => 'phone', 'title' => 'Phone'],
['data' => 'email', 'name' => 'email', 'title' => 'Email'],
['data' => 'country.name', 'name' => 'country.name', 'title' => 'Country'],
['data' => 'agent.name', 'name' => 'agent.name', 'title' => 'Agent'],
['data' => 'treatment', 'name' => 'treatment', 'title' => 'Treatment'],
['data' => 'find_us', 'name' => 'find_us', 'title' => 'Find Us'],
['data' => 'form_type', 'name' => 'form_type', 'title' => 'Form','visible' => false],
['data' => 'social_account', 'name' => 'social_account', 'title' => 'Sosyal Medya'],
['data' => 'created_at', 'name' => 'created_at', 'title' => 'Created At'],
['data' => 'detail.conversion_notes', 'name' => 'detail.conversion_notes', 'title' => 'Primary Notes'],
];
$html = $builder->columns($tableColumn)->parameters([
"pageLength" => 25,
"lengthMenu" => [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
'dom' => 'Bfrtip',
'columnDefs' => [
['width' => '2%', 'targets' => 0],
['width' => '7%', 'targets' => 1],
'buttons' => [
'pageLength',
[
'extend' => 'colvis',
'collectionLayout' => 'fixed two-column',
'columns' => ':not(.noVis)'
]
]
]);

Yii2 add related attribute to sort

I have normal ModelSearch with ActiveDataProvider, and I would like to add a virtual/related attribute to sorting in gridview. If I'm doing with setSort, and I'm adding this only attribute, then all other attributes are not sortable any more. Is there a built-in way to add an attribute to Sort? Thanks a lot!
public function search($params) {
$query = Za::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => ['aonr' => SORT_ASC]],
'pagination' => [
'pageSize' => 15,
],
]);
$dataProvider->setSort([
'attributes' => [
'lwnr' => [
'asc' => ['lwnr' => SORT_ASC],
'desc' => ['lwnr' => SORT_DESC],
'label' => 'lwnr',
'default' => SORT_DESC,
],
]
]);
$this->load($params);
...
}
You can set the sortable attributes with the setSort method, but in this case you need to set all the columns you want to sort, not just the column from the relation.
If you want to add one column you can try this (merging the currently existing sort attributes with the new one):
$dataProvider->setSort([
'attributes' => array_merge(
$dataProvider->getSort()->attributes,
[
'lwnr' => [
'asc' => ['lwnr' => SORT_ASC],
'desc' => ['lwnr' => SORT_DESC],
'label' => 'lwnr',
'default' => SORT_DESC,
],
]
),
]);
or you can add the missing attributes/columns by hand (which is a far better idea)
$dataProvider->setSort([
'attributes' =>
[
'lwnr' => [
'asc' => ['lwnr' => SORT_ASC],
'desc' => ['lwnr' => SORT_DESC],
'label' => 'lwnr',
'default' => SORT_DESC,
],
// Other attribute
'id' => [
'asc' => ['id' => SORT_ASC],
'desc' => ['id' => SORT_DESC],
],
...
],
]);
Another way:
$dataProvider->getSort()->attributes['lwnr'] = [
'asc' => ['lwnr' => SORT_ASC],
'desc' => ['lwnr' => SORT_DESC],
'label' => 'lwnr',
'default' => SORT_DESC,
];

How to always show single validation message in ZF2 validators?

I have the following input:
private function addBirthdayElement()
{
return $this->add(
array(
'type' => 'DateSelect',
'name' => 'x_bdate',
'options' => [
'label' => 'astropay_birthday',
'label_attributes' => array(
'class' => 'astropay-label'
),
'create_empty_option' => true,
'render_delimiters' => false,
],
'attributes' => array(
'required' => true,
'class' => 'astropay-input',
)
)
);
}
It has the following filter:
public function addBirthdayFilter()
{
$time = new \DateTime('now');
$eighteenYearAgo = $time->modify(sprintf('-%d year', self::EIGHTEEN_YEARS))->format('Y-m-d');
$this->add(
[
'name' => 'x_bdate',
'required' => true,
'validators' => [
[
'name' => 'Between',
'break_chain_on_failure' => true,
'options' => [
'min' => 1900,
'max' => $eighteenYearAgo,
'messages' => [
Between::NOT_BETWEEN => 'astropay_invalid_birth_date_18',
Between::NOT_BETWEEN_STRICT => 'astropay_invalid_birth_date_18',
]
]
],
[
'name' => 'Date',
'break_chain_on_failure' => true,
'options' => [
'messages' => [
Date::INVALID => 'astropay_invalid_birth_date',
Date::FALSEFORMAT => 'astropay_invalid_birth_date',
Date::INVALID_DATE => 'astropay_invalid_birth_date',
],
]
],
],
]
);
return $this;
}
However, putting an empty date, I get the error message defined for:
Date::INVALID_DATE
But it's not the overridden one. The break_chain_on_failure works for the two validators I have defined, but the default Zend message is always there. For example I get this as an error in my form:
The input does not appear to be a valid date
astropay_invalid_birth_date_18
How can I display only the overidden error messages and 1 at a time?
You can use a message key in your validator configuration instead of a messages array to always show a single message per validator.
For example, replace this:
'options' => [
'messages' => [
Date::INVALID => 'astropay_invalid_birth_date',
Date::FALSEFORMAT => 'astropay_invalid_birth_date',
Date::INVALID_DATE => 'astropay_invalid_birth_date',
],
]
with this one:
'options' => [
'message' => 'Invalid birth date given!',
]

Resources