I'm using CakePHP 2.0 and I have a model that I use validation on it like this:
var $validate = array(
'title' => array(
'unique_rule'=>array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This title has already been taken.'
),
'required_rule'=>array(
'required' => true,
'allowEmpty' => false,
'message' => 'The title field is required.'
)
)
);
, and in the controller I have an edit action and I use $model->save() to save date from $this->request->data, but it fails the isUnique validation rule, although it is not a new record insertion.
Is there any way to specify that it is an existing record, not a new one ?
If I got the question right you have to set the model's ID before calling $model->save(); so cakephp knows it's an update.
See http://book.cakephp.org/2.0/en/models/saving-your-data.html:
"Creating or updating is controlled by the model’s id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created:"
<?php
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
your validation array is wrong you haven't set a rule for 'required_rule' wich might trigger the isUnique error message.
var $validate = array(
'title' => array(
'unique_rule'=>array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This title has already been taken.',
'last' => true
),
'required_rule'=>array(
'rule' => array('notEmpty'),
'message' => 'The title field is required.'
)
)
);
Also remember that using required=>true will NOT result check for actual data, it only wants the field to be present in the data-array and "" is also considered as present
Related
I have a requirement to add an extra field on to the Role Creation form.
I was able to do by 2 ways
- Using Event Observer
- Or by rewriting blocks
But I want to save this field into the data base and want to populate this value on edit role page.
I tried -
$fieldset = $form->addFieldset('navigator_information', array(
'legend' => 'Navigator Information',
'class' => 'fieldset-wide'
)
);
$options = array();
$options['client'] = 'client';
$options['report'] = 'report';
//add new field
$fieldset->addField('navigator_role', 'select',
array(
'name' => 'navigator_role',
'label' => Mage::helper('adminhtml')->__('Navigator Roles'),
'id' => 'navigator_role',
'class' => 'required-entry',
'values' => $options,
'required' => true,
)
);
and it shows me the new fieldset and new field but How to store this value
into db?
Any help would be appreciated.
I have uploaded screen shot that shows new field
$this->form_validation->set_rules('newusername', 'newfullname', 'newcity','newemail');
// is the set_rules correct. I want that if any one input field with above names are set. It should pass the validation . Please help me if there are any corrections.
May be you should read the manual again. If you want at least one of them filled, you'll need to write your own validation.
Using the following rules:
public $rules = array(
'newusername' => array(
'field' => 'newusername',
'label' => 'New User Name',
'rules' => 'trim|xss_clean|callback_needone'
),
'newfullname' => array(
'field' => 'newusername',
'label' => 'New Full Name',
'rules' => 'trim|xss_clean|callback_needone'
),
'newcity' => array(
'field' => 'newcity',
'label' => 'New City',
'rules' => 'trim|xss_clean|callback_needone'
),
'newemail' => array(
'field' => 'newemail',
'label' => 'New Email',
'rules' => 'trim|xss_clean|callback_needone'
)
)
in your controller you have to write
public function needone(){
if ( empty($this->input->post('newusername')) && empty($this->input->post('newfullname')) && empty($this->input->post('newcity')) && empty($this->input->post('newmail')) ) {
$this->form_validation->set_message('needone', 'At least one field must be entered');
return FALSE;
}
return TRUE;
}
Put the rule on any of the form's fields, or all of them to hilite those who are in the required group, it's up to you.
Each input field in your form, requires it's own validation rules. Which should look like this;
$this->form_validation->set_rules('field name', 'human name', 'rules');
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
So, you would have 4 set_rules functions, like this;
$this->form_validation->set_rules('newusername', 'New username', 'trim|xss_clean|required');
$this->form_validation->set_rules('newfullname', 'New full name', 'trim|xss_clean|required');
$this->form_validation->set_rules('newcity', 'New City', 'trim|xss_clean|required');
$this->form_validation->set_rules('newemail', 'New Email', 'trim|xss_clean|required');
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#cascadingrules
Here's a rule reference, all the available rules;
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#rulereference
Now, to check if ANY of the items are set, I would do this;
if ($this->input->post('newusername') OR $this->input->post('newusername') OR $this->input->post('newusername') OR $this->input->post('newusername'))
{
// One of them is set
}
else
{
// Nothing is set
}
I have validation for the email input in my form but I would also like to create an exception for a string: "Not given" as some contact information do not have an email address. I know I can remove the email validation to do this but I want that validation there for new contacts. Those that do not have email addresses are some of the old contacts. So I would need an exception in order for me to add those contacts into this new system.
My current email validation in the model is as follows:
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Please enter a valid email address',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
'uniqueEmail' => array(
'rule'=>'isUnique',
'message' => 'This email has already been added'
),
)
How do I implement this exception and where?
Any help would be great. Thanks!!
Just uncomment that 'allowEmpty' => false line and change it to true, this will permit the email filled to be submitted as an empty string.
I've been at this most of the day now, and I cannot get this working for the life of me (well I can get it 1/2 working but not fully correctly).
Basically, I am trying to use Validation on a search form field like so:
if(isset($search['ApplicantAge']) && !empty($search['ApplicantAge'])) {
if ($this->Plan->validates()) {
$ApplicantAge = $search['ApplicantAge'];
}
}
And here is my model code:
...
'ApplicantAge' => array(
'required' => true,
'allowEmpty' => false,
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'),
...
The validation is working BUT when I enter a number (numeric), it displays my error! And when it's blank NO error displays, and when I enter letters it seems to work : ( ??
Does anyone know a trick to this odd behavior?
Try using the 'notEmpty' rule instead of the required/allowEmpty stuff.
'ApplicantAge' => array(
'applicant-age-numeric'=> array(
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'
),
'applicant-age-not-empty'=> array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank'
)
)
firstly why are you using the field 'ApplicantAge' when the conventions say its should be lower case under scored?
to answer your question the best way to do validation like that is http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
the other option is to do $this->Model->save($data, array('validate' => 'only'));
The manual did not assist me at all : (
But your suggestion on the validate => only array seems to have done the trick. This is how I got it working:
plans_controller.php
if (isset($search['ApplicantAge'])) {
$this->Plan->save($search, array('validate' => 'only'));
if ($this->Plan->validates($this->data)) {
$ApplicantAge = $search['ApplicantAge'];
}
}
plan.php (model)
var $validate = array(
'ApplicantAge' => array(
'applicant-age-numeric' => array(
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'),
'applicant-age-not-empty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank'),
),
Now, if no data is entered in the ApplicateAge field, the proper message is displayed. And if a non-numeric is entered, the correct message is also displayed.
This was a lot more challenging than I thought it would be!
For the record, I'll make a correction to my earlier accepted post. Little did I know the validate => only on the save() was actually still saving data to my plans table.
I was able to get it working using set(). Here is the code that completely solved the problem:
plans_controller.php
if (isset($search['ApplicantAge'])) {
$this->Plan->set($this->data);
if ($this->Plan->validates()) {
$ApplicantAge = $search['ApplicantAge'];
}
}
plan.php (model):
var $validate = array(
'ApplicantAge' => array(
'applicant-age-numeric' => array(
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'),
'applicant-age-not-empty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank'),
)
How to make file uploading as optional with validation?
The code below validates even if i didn't selected any file.
I want to check the extension only if i selected the the file.
If i am not selecting any file it should not return any validation error.
class Catalog extends AppModel{
var $name = 'Catalog';
var $validate = array(
'name' => array(
'rule' => '/^[a-z0-9 ]{0,}$/i',
'allowEmpty' => false,
'message' => 'Invalid Catalog name'
),
'imageupload' => array(
'rule' => array('extension',array('jpeg','jpg','png','gif')),
'required' => false,
'allowEmpty' => true,
'message' => 'Invalid file'
),
);
}
thanks in advance
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.
Concept:
In Controller, before validating, or saving (which does validation automatically by default) check if any file is uploaded. If not uploaded, then unset validator for the file field.
Sample code:
Controller
// is any image uploaded?
$isNoFileUploaded = ($this->request->data['Model']['field_name']['error'] == UPLOAD_ERR_NO_FILE) ? true : false ;
if ($isNoFileUploaded) {
$this->Model->validator()->remove('field_name');
}
Notes:
This solution comes under preprocessing as one of the two alternative approaches (preprocessing in controller, custom validation in model) suggested by #deceze's answer