In my form.ctp I have some inputs which are named with dot notation, so they are joined on the POST to the same array inside $this->request->data.
The problem is that I can't manage to create a Modelless form for it, because it won't map dot notations to array, and searchs the fields like consumer.name literally in request->data. Is there anything I can do to validate this data with a simple $form->execute()?
My Cake version is 3.1.1
The code:
//Form Class
protected function _buildSchema(Schema $schema)
{
return $schema->addField('consumer.name', 'string')
->addField('consumer.card_number', ['type' => 'string'])
->addField('consumer.expire_month', ['type' => 'string'])
->addField('consumer.expire_year', ['type' => 'string'])
->addField('type', ['type' => 'string'])
->addField('consumer.cvv', ['type' => 'string']);
}
protected function _buildValidator(Validator $validator)
{
return $validator->add('consumer.name', 'length', [
'rule' => ['minLength', 3],
'message' => 'Consumer name too short',
])
->requirePresence('type', true)
->requirePresence('consumer.name', true)
->requirePresence('consumer.card_number', true)
->requirePresence('consumer.expire_month', true)
->requirePresence('consumer.expire_year', true)
->requirePresence('consumer.cvv', true)
->add('consumer.card_number', 'validFormat', [
'rule' => array('custom', '/[0-9]{16}/'),
'message' => 'A valid card number is required',
])
->add('consumer.expire_month', 'validFormat', [
'rule' => array('custom', '/[01]?[0-9]/'),
'message' => 'A valid expire month is required',
])
->add('consumer.expire_year', 'validFormat', [
'rule' => array('custom', '/[0-9]{2}/'),
'message' => 'A valid expire year is required',
])
->add('consumer.cvv', 'validFormat', [
'rule' => array('custom', '/[0-9]{3}/'),
'message' => 'A valid CVV is required',
]);
}
My view has several inputs like this:
<?php echo $this->Form->input('consumer.name', [
'label' => false,
'class' => 'form-control inputbox_user',
'pattern' => "^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+$",
'required' => true,
'title' => 'Introduce el nombre del titular de la tarjeta.',
]);
?>
And my controller logic:
$form = new PaymentForm;
if ($this->request->is(['patch', 'post', 'put'])){
if( $form->execute($this->request->data) ){
//ok
}
}
}
The dot notation will be already turned into a "HTML array" in the view. Debug your request and you'll see ['consumer']['name']. This works as intended by the framework and is correct. AFAIK there is no way around that - and not needed.
Simply change your notation to underscore: consumer_name for example. To use the dots is for another reason a bad idea as well: You will make things difficult for yourself if you need to access them via JS or CSS.
Related
Here my code :
$rules = [
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'unit' => 'required|in:piece,kg,m',
'price_type' =>'required|string',
'service' => [
'string',
'required',
Rule::in($services_ids->all()),
],
'facility' => [
'string',
'required',
Rule::in($facilities_ids->all()),
],
'conciergeries' => [
'array',
'required',
Rule::in($conciergeries_ids->all()),
],
];
$custom_messages = [
'required' => 'Vous devez sélectionner un(e) :attribute.'
];
$validated = request()->validate($rules, $custom_messages);
The problem is that my custom_messages only works with 'name', 'price', 'unit', 'price_type' but not with 'service', 'facility' and 'conciergeries'.
Questions :
How to apply my custom messages with 'service', 'facility' and 'conciergeries' too ?
How to create a custom message for specifically one field ?
Thank's !
You just need to specify for which field you want to change the message
Try it like:-
$custom_messages = [
'service.required' => 'Your custom message for required service',
'service.string' => 'Your custom message of service should be string',];
And same process for facility and conciergeries.
I have field "type" that need to be unique and rule for the field will be "active" == 1.
$validator
->notEmpty('type')
->add('type', [
'unique' => [
'rule' => ['validateUnique', ['scope' => ['aktivan' => '1']]],
'provider' => 'table',
'message' => 'Not unique']
]);
I try this but doesn't work. I am new to Cakephp and I need help with this.
For some reason I am not getting any validation errors when saving multiple records. I can grab the errors using print_r($user->errors()); but they are not automatically injected into the form like when adding a single user. According to the docs "Validating entities before saving is done automatically when using the newEntity(), newEntities()." I am not sure if there is a specific way to set up the form to make it return validation for multiple records or if you have to do special validation in the model for inputs that have indexes or what?
view:
<div class="page-wrap">
<div class="form">
<h1>Join Now</h1>
<?php
echo $this->Form->create(null, ['controller' => 'users', 'action' => 'addMultiple']);
echo $this->Form->input('1.full_name');
echo $this->Form->input('1.username');
echo $this->Form->input('1.email');
echo $this->Form->input('1.password');
echo $this->Form->input('1.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('1.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->input('2.full_name');
echo $this->Form->input('2.username');
echo $this->Form->input('2.email');
echo $this->Form->input('2.password');
echo $this->Form->input('2.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('2.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->button(__('Sign Up'));
echo $this->Form->end();
?>
</div>
</div>
Controller:
public function addMultiple()
{
$users = $this->Users->newEntities($this->request->data());
if ($this->request->is('post')) {
foreach($users as $user) {
if( empty($this->request->session()->read('Auth.User')) || $this->request->session()->read('Auth.User.role') !== 1 ) {
$user->role = 4;
}
if ($this->Users->save($user)) {
$this->Flash->success(__('You have been added.'));
} else {
$this->Flash->error(__('You could not be added. Please, try again.'));
}
}
}
}
Table:
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('MembershipOrders', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasMany('MembershipOrders', [
'foreignKey' => 'affiliate_token',
'joinType' => 'INNER'
]);
}
public function validationDefault(Validator $validator)
{
$validator
->notEmpty('full_name', 'A full name is required')
->add('full_name', 'notBlank', [
'rule' => 'notBlank',
'message' => __('A full name is required'),
]);
$validator
->notEmpty('username', 'A username is required')
->add('username', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __('A username is required'),
]
]);
$validator
->notEmpty('email', 'An email is required')
->add('email', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __('A full name is required'),
],
'unique' => [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => __('That email has already been used.'),
]
]);
$validator
->notEmpty('old_password', 'You must enter your old password is required')
->add('old_password', 'notBlank', [
'rule' => 'notBlank',
'message' => __('Your old password is required'),
]);
$validator
->notEmpty('password', 'A password is required')
->add('password', 'notBlank', [
'rule' => 'notBlank',
'message' => __('A full name is required'),
]);
$validator
->notEmpty('password_confirmation', 'Password confirmation is required')
->add('password_confirmation',
'comareWith', [
'rule' => ['compareWith', 'password'],
'message' => 'Passwords do not match.'
]);
$validator
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['1', '2', '3', '4']],
'message' => 'Please enter a valid role'
]);
return $validator;
}
You can use 'addNestedMany()' : http://book.cakephp.org/3.0/en/core-libraries/validation.html#nesting-validators
You have to pass the entity object to the Form->create(... function, instead of passing nullas the following:
echo $this->Form->create($user, .....
I am using ZF2 form validation.I have to validate two fields USERNAME and PASSWORD.
everything is working fine but I am getting message like
Please enter username.
Username can not be less than 3 characters.
Please enter password.
Password can not be less than 6 characters.
If user is not entering any value then only this message should display
Please enter username.
Please enter password.
I don't want do display all the error messages on a field on failure.
Thanks in advance.
I got the answer :
In order to break the validation chain in ZF2 , we have to use
'break_chain_on_failure' => true
$this->add(
array(
'name' => 'usernmae',
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim')
),
'validators' => array(
array('name' => 'NotEmpty',
'options' => array('encoding' => 'UTF-8',
'messages' => array(
NotEmpty::IS_EMPTY => 'Please enter username')),
'break_chain_on_failure' => true),
array(
'name' => 'Zend\Validator\StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 30,
'messages' => array(
StringLength::TOO_LONG => 'Username can not be more than 30 characters long',
StringLength::TOO_SHORT => 'Username can not be less than 3 characters.')
),
'break_chain_on_failure' => true
)
)
)
);
My Blog : http://programming-tips.in
Zend_Validate allow you to break validators chain if certain vaildation fails. The second parameter of addValidator() function $breakChainOnFailure should be TRUE in this case.
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(new Zend_Validate_NotEmpty(), TRUE)
->addValidator(new Zend_Validate_StringLength(6, 12));
You can also set the 'error_message' key, for example:
'email' => [
'required' => true,
'error_message' => 'Incorrect email address ',
'filters' => [
[
'name' => 'StripTags',
],
[
'name' => 'StringToLower',
]
],
'validators' => [
[
'name' => 'EmailAddress',
'break_chain_on_failure' => true
]
]
],
I wrote a custom validation method inside my Submission model that basically allows a blank input field, but once someone enters something in it, it'll validate the data entered.
The validation inside my Submission Model looks like this (All other validation rules are working except for 'description'):
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'checkDescription' => array(
'rule' => array('validateDescription'),
'message' => 'Description must be greater than 5 characters'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL'
),
'website' => array(
'rule' => 'url',
'message' => 'Please enter a valid source URL'
),
)
);
My method which is also in my Submission model (below the above code) is:
public function validateDescription($data) {
if(empty($data['Submission']['description']))
return true;
if((strlen($data['Submission']['description'])) <= 5)
return false;
}
I'm not sure why this isn't working at all. In my view, I've got this to display the error:
if ($form->isFieldError('Submission.description'))
echo ($form->error('Submission.description', null, array('class' => 'error')));
The only reason I'm trying to do this, is because using the normal validation with required => false and allowEmpty => true along with a minLength and maxLength validation rule weren't behaving how I intended.
Any help would be greatly appreciated! :)
The $data variable passed into the validation method only contains array($fieldname => $value). You're also not returning true for strings over length of 5. Your method should look like this:
public function validateDescription(array $data) {
$value = current($data);
return !$value || strlen($value) > 5;
}