If the first field called sendEmail has value ="Yes" the rest of the fields are to be validated...
I have this set_rules defined in the form_validation.php file in the config folder..
$config = array(
array(
'field' => 'sendEmail',
'label' => 'Send Email',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
),
array(
'field' => 'first_name',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'last_name',
'label' => 'Last Name',
'rules' => 'required'
)
);
but email, first_name and last_name fields are to be validated only if sendEmail has value="Yes".
Not sure how to do this, can someone please help me with this?
thanks
Do the conditions like this in your controller:
if ($this->input->post('sendEmail') == 'Yes'){
$this->form_validation->set_rules('email', 'Email', 'required');
... [etc]
}
The validation only runs when you call $this->form_validation->run(), so just write an if statement before that. Something like this:
if ($this->input->post("sendEmail") == 'Yes') {
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE)
{
// failed validated
}
else
{
// passed validation
}
} else {
// never attempted validation
}
Related
I am loading a model in different controller.
Controller name in which I am loading different model is - "MembersController" and I am loading "Usermgmt" Model of "UsermgmtController".
"Usermgmt" Model has validation as following-
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for email.'
),
'duplicate' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This email is already exist.'
),
'duplicate1' => array(
'rule' => 'email',
'message' => 'Please enter valid email.'
)
),
'firstname' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for first name.'
)
),
'username' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for user name.'
),
'duplicate' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This user is already exist.'
)
),
'password' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for password.'
)
),
'confirm_password' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for confirm password.'
),
'duplicate2' => array(
'rule' => 'matchpassword',
'on' => 'create',
'message' => 'Password must be same.'
)
)
);
And now I am applying and loading model in following way.
$this->loadModel('Usermgmt');
$this->Usermgmt->set($this->data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
But validation are not working and it is inserting empty values.
try uses to load model
Example :
public $uses = array('Usermgmt');
You are using two different instances of $data. namely $this->data and $data
You should be validating the same set of data you want to save, like either of the two following examples, whichever holds your data.
$this->loadModel('Usermgmt');
$this->Usermgmt->set($data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
Or
$this->loadModel('Usermgmt');
$this->Usermgmt->set($this->data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($this->data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
Unless you are requiring to do some other logic after validation and before saving you could do away with explicitly calling validates() and just save the data as save() will automatically validate the data for you. Also, I've noticed you are using $this->data, it looks like you are using CakePHP 2 in which case you need to use $this->request->data instead:-
$this->loadModel('Usermgmt');
if ($this->Usermgmt->save($this->request->data) !== false) {
$this->Session->setFlash('User has been added', 'success');
}
If this still fails then make sure you are not overriding beforeValidate() in your model in a way that would cause validation to break.
I'm new to CakePHP. I'm validating my form, but the problem is that no validation is working except the not empty validation.
My model file is:
class User extends AppModel {
public $name = 'User';
public $validate = array(
'rule_name' => array(
'alphaNumeric' => array(
'rule' => 'Numeric',
'required' => true,
'message' => 'Letters and numbers only'
)
)
);
}
My View file is:
echo $this->Form->create('User');
echo $this->Form->input('rule_name',array('class'=>'form-control','autocomplete'=>'off'));
Please suggest how I can fix this.
General usage pattern adding a rule for a single field:
public $validate = array(
'fieldName1' => array(
'rule' => 'ruleName',
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
)
);
Must be look at Data Validation in cakePHP
I have created a custom extension just like a customer module and I want backend just like a customer.
My extension has two tables and two models.
My modules are:
Mage::getModel('custommod/reg') - just like Mage::getModel('customer/customer'), reg saves data of registration
Mage::getModel('custommod/personal') - just like Mage::getModel('customer/address'), //personal data of a reg records.
Please check the image below:
Now I am facing the problem to show the data and edit .
In Magento customer admin section, Customer edit position has multiple tabs: Account information, Address etc.
Here, Account information tab saves data in customer/customer
and Address information tab saves data in customer/address.
I like this type of section.
After a long time work i have done it ,Here the solution
The tabs.php show left panel
<?php
class Amit_Vendor_Block_Adminhtml_List_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId('vendor_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(Mage::helper('vendor')->__('Manage Vendor'));
}
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => Mage::helper('vendor')->__('General Information'),
'title' => Mage::helper('vendor')->__('General Information'),
'content' => $this->getLayout()->createBlock('vendor/adminhtml_list_edit_tab_form')->toHtml(),
));
$this->addTab('vendor_details',array(
'label'=>Mage::helper('vendor')->__('Vendor Store Details'),
'title'=>Mage::helper('vendor')->__('Vendor Store Details'),
'content'=>$this->getLayout()->createBlock('vendor/adminhtml_list_edit_tab_storedetails')->toHtml(),
));
return parent::_beforeToHtml();
}
}
after the form.php
<?php
class Amit_Vendor_Block_Adminhtml_List_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$vendor = Mage::registry('vendor_data');
$form = new Varien_Data_Form();
$fieldset = $form->addFieldset('vendor_form', array(
'legend' => Mage::helper('vendor')->__('Vendor Registration')
));
$fieldset->addField('name', 'text', array(
'name' => 'name',
'label' => Mage::helper('vendor')->__('Name'),
'required' => true,
));
$fieldset->addField('email', 'text', array(
'name' => 'email',
'label' => Mage::helper('vendor')->__('Email'),
'required' => true,
));
$fieldset->addField('user_name', 'text', array(
'name' => 'user_name',
'label' => Mage::helper('vendor')->__('User name'),
'required' => true,
));
$fieldset->addField('password', 'password', array(
'name' => 'password',
'class' => 'required-entry',
'label' => Mage::helper('vendor')->__('Password'),
'required' => true,
));
$this->setForm($form);
$form->setValues($vendor->getData());
return parent::_prepareForm();
}
public function filter($value)
{
return number_format($value, 2);
}
}
Second form Storedetails.php
<?php
class Amit_Vendor_Block_Adminhtml_List_Edit_Tab_Storedetails extends Mage_Adminhtml_Block_Widget_Form{
protected function _prepareForm(){
$vendorStore = Mage::registry('vendor_store_details');// new registry for different module
$form = new Varien_Data_Form();
//$form->setFieldNameSuffix('vendor_store');
$fieldset = $form->addFieldset('vendor_form', array(
'legend' => Mage::helper('vendor')->__('Vendor deatsilsn')
));
$fieldset->addField('alternative_email','text',array(
'name' =>'alternative_email',
'label' => Mage::helper('vendor')->__('Alternative Email'),
'required'=> false
));
$fieldset->addField('shopname','text',array(
'name' =>'shopname',
'label' => Mage::helper('vendor')->__('Shop Name'),
'required'=> true,
'class' => 'required-entry',
));
$fieldset->addField('company', 'text', array(
'name' => 'company',
'label' => Mage::helper('vendor')->__('Company'),
'required' => true,
'class' => 'required-entry',
));
$fieldset->addField('street','text',array(
'name' =>'vendor_details[street]',
'label' => Mage::helper('vendor')->__('Street Address'),
'required'=> false
));
$this->setForm($form);
$form->addValues($vendorStore->getData());
return parent::_prepareForm();
}
}
I am using CodeIgniter 2.3.1 and created a form_validation.php file in config and the content is as below.
<?php
$config = array(
array(
'field' => 'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'lastname',
'label' => 'Last Name',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_unique_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|matches[confirm_password]'
),
array(
'field' => 'confirm_password',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
function unique_email($email) {
if($email == 'm#gmail.com') {
$this->form_validation->set_message('unique_email', 'Hello World !');
return false;
}
}
?>
And checking the form_validation in register function of user controller. The code is below.
public function register() {
$this->load->helper('form');
$data['message'] = '';
if($this->input->post('submit')) {
$this->load->library('form_validation');
if($this->form_validation->run() == FALSE) {
$data['message'] = 'User could not be saved.';
} else {
$user_data['firstname'] = $this->input->post('firstname');
$user_data['lastname'] = $this->input->post('lastname');
$user_data['email'] = $this->input->post('email');
$user_data['password'] = md5($this->input->post('password'));
if($this->user_model->insert($user_data)) {
if($this->user_model->login($user_data)) {
$this->session->set_flashdata('message', 'User saved successfully.');
redirect('/user', 'refresh');
}
}
}
}
$this->load->view('user/register', $data);
}
But I am not getting validation message for the custom method. Please suggest me how to do it?. The work is more appreciated.
Have a look at the following documentation: http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks
As you can see int the documentation, the custom validation function actually belongs in the controller, and not in the config file. By moving the validation function to the controller, the callback function should start getting called.
Another fun fact, people can access this unique_email function through a url (ie. http://yoursite.com/index.php/user/unique_email). To avoid this, we can write the function as a private function by simply placing an underscore at the beginning of the function, like so:
function _unique_email($email) {
...
}
You can then call the function in your validation by using the new function name in your config (notice the extra underscore in the callback:
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email|callback__unique_email'
)
In the end, your controller should look similar to the following:
class User extends CI_Controller {
public function register() {
$this->load->helper('form');
$data['message'] = '';
if($this->input->post('submit')) {
$this->load->library('form_validation');
if($this->form_validation->run() == FALSE) {
$data['message'] = 'User could not be saved.';
} else {
$user_data['firstname'] = $this->input->post('firstname');
$user_data['lastname'] = $this->input->post('lastname');
$user_data['email'] = $this->input->post('email');
$user_data['password'] = md5($this->input->post('password'));
if($this->user_model->insert($user_data)) {
if($this->user_model->login($user_data)) {
$this->session->set_flashdata('message', 'User saved successfully.');
redirect('/user', 'refresh');
}
}
}
}
$this->load->view('user/register', $data);
}
function _unique_email($email) {
if($email == 'm#gmail.com') {
$this->form_validation->set_message('unique_email', 'Hello World !');
return false;
}
}
}
Your config would look similar to the following:
$config = array(
array(
'field' => 'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'lastname',
'label' => 'Last Name',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email|callback__unique_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|matches[confirm_password]'
),
array(
'field' => 'confirm_password',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
I used this answer and got error:
Unable to access an error message corresponding to your field name.
In function _unique_email instead set_message('unique_email', 'Hello World !'); should be set_message('_unique_email', 'Hello World !'); like this:
function _unique_email($email) {
if($email == 'm#gmail.com') {
$this->form_validation->set_message('_unique_email', 'Hello World !');
return false;
}
}
I am working with cakephp. I need to add three validation on email field. First validation if email not given, second for valid email address, third if email address is given then it should be unique. Because its a signup form.
How I have add three validations on one field I try with the following code but it did not work for me.
public $validate = array(
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Invalid email address',
'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
)
),
'email' => array(
'rule' => 'isUnique',
'message' => 'Email already registered'
)
);
You have two identical indexes 'email' which PHP won't allow you. Change to something like:-
array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Provide an email address'
),
'validEmailRule' => array(
'rule' => array('email'),
'message' => 'Invalid email address'
),
'uniqueEmailRule' => array(
'rule' => 'isUnique',
'message' => 'Email already registered'
)
)
);
Otherwise only one of your rules will be used.
As of cakephp 3.0 in the entities table it should look something like this
namespace App\Model\Table;
public function validationDefault($validator)
{
$validator
->email('email')
->add('email', 'email', [
'rule' => [$this, 'isUnique'],
'message' => __('Email already registered')
])
->requirePresence('email', 'create')
->notEmpty('email', 'Email is Required', function( $context ){
if(isset($context['data']['role_id']) && $context['data']['role_id'] != 4){
return true;
}
return false;
});
return $validator;
}
}
function isUnique($email){
$user = $this->find('all')
->where([
'Users.email' => $email,
])
->first();
if($user){
return false;
}
return true;
}
What version of Cakephp do you use?
Because I think if you use 2.3, it should be:
public $validate = array( 'email' => 'email' );
with the field email in your SQL table set as a primary key.