cakephp-3 form validation for length range (between) - validation

I am converting Cakephp-1 project to Cakephp-3. So I need help to convert the validation code:
Cakephp-1 Code
'name' => array(
'between' => array(
'rule' => array('between', 2, 50),
'message' => 'Ditt namn måste vara minst två tecken långt!'
)
)
I have try the code:
Cakephp-3 Code
$validator
->requirePresence('name', 'create')
->notEmpty('name')
->add('name', [
'between' => [
'rule' => [2, 50],
'message' => 'Namnet måste vara mellan 2 och 50 tecken lång!',
]
]);
But it gives me the error:
Unable to call method "2" in "default" provider for field "name"...
Now what can I do ??

The correct code should be
->add('name', [
[
'rule' => ['lengthbetween', 2, 50],
'message' => 'Namnet måste vara mellan 2 och 50 tecken lång!',
]
]);

You can also set different validation messages for each minimum length and maximum length:
$validator
->add('body', [
'minLength' => [
'rule' => ['minLength', 10],
'last' => true,
'message' => 'Comments must have a substantial body.'
],
'maxLength' => [
'rule' => ['maxLength', 250],
'message' => 'Comments cannot be too long.'
]
]);

Related

I have a problem with repeatable -> select2_from_array field in BackPack

I have this code:
Controller
$this->crud->addField(
[
'name' => 'schedule',
'label' => 'Schedule',
'type' => 'repeatable',
'fields' => [
[
'name' => 'day',
'label' => 'Day',
'type' => 'select_from_array',
'options' => Day::titles(),
'allows_null' => false,
],
[
'name' => 'range',
'label' => 'Range',
'type' => 'select2_from_array',
'options' => $this->getScheduleRange(),
'default' => $this->getDefaultScheduleRange(),
'allows_null' => false,
"allows_multiple" => true,
],
],
]
);
Model
protected $casts = [
'schedule' => 'array',
];
stored data in DB(schedule column):
[{"day": "1", "range[]": ["1:30:00", "2:00:00"]}]
But selected data not showing on the page when it is multi selected.
UPD:
After Pedro's recomandation it's not help me. In DB it's storing as:
[{"day": "1", "range[]": ["0", "1"]}]
viper.
when using multiple with default please use numeric keys like:
'options' => [0 => 'option 0', 1 => 'option 1'],
'default' => [0,1]
I think Backpack can do something here to improve multiple string keys like
'options' => ['option_0', 'option_1'],
'default' => ['option_0', 'option_1']
I will open an issue to discuss this in the package repository.
Thanks
Pedro

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)'
]
]
]);

Laravel validation: required field in not required array

Request can contain field coord ({x: 1, y: 2}) or not contain it. For example:
Correct (without coord):
[
'another_param' => 'value',
],
Correct:
[
'another_param' => 'value',
'coord' => [
'x' => 1,
'y' => 2,
],
],
Invalid (wrong format of coord):
[
'another_param' => 'value',
'coord' => [
'x' => 1,
],
],
Whether it can be written by standard rules (without custom and closures).
My attempt:
'rules' => [
'coord' => 'array',
'coord.x' => 'required',
'coord.y' => 'required',
],
But if a request don't contain coord then Error: The coord.x field is required.
You can use the sometimes validation rule so it only applies when the field is present.
'rules' => [
'coord' => 'sometimes|array',
'coord.x' => 'required',
'coord.y' => 'required',
],
You can require the fields when the array is provided using required_with:
'rules' => [
'coord' => 'sometimes|array|min:1',
'coord.x' => 'required_with:coord',
'coord.y' => 'required_with:coord',
],
The sometimes rule allows this field to be discarded and min:1 ensures when this coord field is provided, it's not an empty array.
You can try validating the array fields as coord.*.x
I mean:
'rules' => [
'coord' => 'array',
'coord.*.x' => 'required',
'coord.*.y' => 'required',
],
Then if coord array has an element, x and y will be required
Not sure if it's still actual but here's how I solved it:
'rules' => [
'coord' => ['nullable', 'array'],
'coord.x' => 'required_unless:coord,null',
'coord.y' => 'required_unless:coord,null',
],

How to remove element from multidimensional cakephp session

I am working on eCommerce website where is stored all cart product in session that is working perfectly.
Here are debug of cart session.
debug($this->request->getsession()->read('cart'));
[
(int) 1 => [
(int) 0 => [
'id' => (int) 1,
'picture' => '1_1.webp',
'sku' => 'TH447WA38OUMINDFAS',
'name' => 'The Vanca Multicoloured Printed Strappy Top',
'size' => 'S',
'price' => '480'
]
],
(int) 2 => [
(int) 0 => [
'id' => (int) 2,
'picture' => '2_1.webp',
'sku' => 'AL384WA86QOSINDFAS',
'name' => 'All About You Pink Embroidered Blouse',
'size' => 'S',
'price' => '1330'
]
],
(int) 3 => [
(int) 0 => [
'id' => (int) 3,
'picture' => '3_1.webp',
'sku' => 'RE367WA35NDKINDFAS',
'name' => 'Renka Comfortable Black Color Seamless Summer Tops For Women',
'size' => 'S',
'price' => '495'
]
]
]
Now i want to remove any row from cart but that is not working for me.
unset($this->request->getsession()->read('cart')[1]);
should be simply
$this->request->getSession()->delete('cart.1');
you can use dot notation when accessing session arrays
you could also read and delete the data in one command
$cart = $this->request->getSession()->consume('cart');
see the manual here and the API here and here

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