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;
}
}
Related
I tried to validate a simple form in zend framework 2 for days now.
I checked the documentation and a lot of posts considering this topic but I found no solution!
I have a very simple form:
class AlimentForm extends Form
{
public function __construct($name = null)
{
parent::__construct('aliment');
$this->add(array(
'required'=>true,
'name' => 'year',
'type' => 'Text',
'options' => array(
'label' => 'Jahr',
),
));
$this->add(array(
'required'=>true,
'name' => 'number',
'type' => 'Text',
'options' => array(
'label' => 'Number',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
I created a custom InputFilter:
namespace Application\Form;
use Zend\InputFilter\InputFilter;
class AlimentInputFilter extends InputFilter {
public function init()
{
$this->add([
'name' => AlimentForm::year,
'required' => true,
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1900,
'max' => 3000,
),
),
),
]);
}
}
and finally in my controller I try to validate the form
public function alimentAction(){
$form = new AlimentForm();
$form->setInputFilter(new AlimentInputFilter());
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$year = $form->get('year')->getValue();
$number = $form->get('number')->getValue();
return array('result' => array(
"msg" => "In the Year ".$year." you get ".$number." Points"
));
}
}
return array('form' => $form);
}
It can't be that difficult, but from all those different ways to validate a form I found in the net, I'm a bit confused...
What am I missing?
Greetings and thanks in advance
U.H.
Ok, I solved the problem.
I created a Model for the aliment Form that has a year and a number attribute
and I defined an input filter within that model:
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Aliment implements InputFilterAwareInterface
{
public $year;
public $number;
public function exchangeArray($data){
$this->year = (!empty($data['year']))?$data['year']:null;
$this->number = (!empty($data['number']))?$data['number']:null;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'year',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1900,
'max' => 3000
)
)
),
));
$inputFilter->add(array(
'name' => 'number',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1,
'max' => 10
)
)
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
In the action method of the controller I was able to set the InputFilter of the model to the form and voila! It worked!
public function alimentAction(){
$form = new AlimentForm();
$request = $this->getRequest();
if ($request->isPost()) {
$aliment = new \Application\Model\Aliment;
$form->setInputFilter($aliment->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$aliment->exchangeArray($form->getData());
$year = $form->get('year')->getValue();
return array(
'result' => array(
//your result
)
);
}
}
return array('form' => $form);
}
The form is correctly validated now and returns the corresponding error messages.
I hope, it help somebody whos got similar problems with validating!
I've taken the "auth" controller and copied it and renamed it as "site". I have renamed the references to views etc. to "site". When I go to www.mysite/index.php/site/create_user the form loads fine. However on hitting submit I get redirected to www.mysite.com/index.php/site/login and nothing is added to the database. Can anyone tell me why this does not work? My site controller is below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends CI_Controller {
//
//Authentication
//
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library(array('ion_auth','form_validation'));
$this->load->helper(array('url','language'));
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth');
}
//Function to log the user in
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
// check to see if the user is logging in
// check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
}
else
{
// if the login was un-successful
// redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('site/login', 'refresh'); // use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{
// the user is not logging in so display the login page
// set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('site/login', $this->data);
}
}
//Function to log the user out
function logout()
{
$this->data['title'] = "Logout";
// log the user out
$logout = $this->ion_auth->logout();
// redirect them to the login page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('site/login', 'refresh');
}
//Function to create a user
function create_user()
{
$this->data['title'] = "Create User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
{
//redirect('site/login', 'refresh');
}
$tables = $this->config->item('tables','ion_auth');
// validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required');
$this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'required');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email|is_unique['.$tables['users'].'.email]');
$this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'required');
$this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'), 'required');
$this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');
if ($this->form_validation->run() == true)
{
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = strtolower($this->input->post('email'));
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone'),
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data))
{
// check to see if we are creating the user
// redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("site", 'refresh');
}
else
{
// display the create user form
// set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name'),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name'),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company'),
);
$this->data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'type' => 'text',
'value' => $this->form_validation->set_value('phone'),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'value' => $this->form_validation->set_value('password'),
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'value' => $this->form_validation->set_value('password_confirm'),
);
$this->_render_page('site/create_user', $this->data);
}
}
//Function to render the page
function _render_page($view, $data=null, $returnhtml=false)//I think this makes more sense
{
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $returnhtml);
if ($returnhtml) return $view_html;//This will return html on 3rd argument being true
}
}
This exact code works when in the auth controller. When in the site controller I make it so you must login and you must be an admin to make a user (i.e. uncommenting out this line //redirect('site/login', 'refresh');) then it also works, but for some reason when that line is commented it works in the auth controller but not the site controller.
Any help is much appreciated. I've tried to figure it out but can't see why it works in one and not the other (and why it works in site but only as an admin when that code is uncommented and not at all when it is commented, whilst in auth it works in either case).
Thanks in advance.
The reason you get redirected is one of two reasons.
First : $this->_render_page('site/login', $this->data);
When you hit the submit button it is still pointing to the login controller.
Second : if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
The create user function in the Auth controller is for admins only, You will have to // out the code or you will be redirected to the login page due to not being logged and not being an admin.
try this:
//$this->_render_page('site/login', $this->data);
//if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
By marking out these two lines you should be able to veiw and submit your page without being redirected.
:)
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've created custom validation library class MY_Form_validation as MY_Form_validation.php in application/libraries as follows.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct($rules = array()) {
parent::__construct($rules);
}
public function file_required($file) {
if($file['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
}
?>
In my validation function I've included following rules as follows.
public function validate() {
$this->load->library('form_validation');
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run()) {
return true;
}
return false;
}
The core validation rules are working fine but custom rule is not working. So please help me to get the soultion and Its literally wasting my time. The work would be more appreciated.
As far as i understand your function always return true. Because of $file Not $_FILES
public function file_required($file) {
if($_FILES[$file]['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
Check the rules in the function validate()
What I think it's incorrect:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
What I think is correct:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|file_required|xss_clean'
),
);
I think good is not a php function, or an internal codeigniter function.
Edit:
What about using:
if ($file['size'] == 0) {
Instead of
if ($file['size'] === 0) {
Using === means the value MUST BE integer 0, but if $file['size'] returns 0 as string the if won't be true, and the function always will return true.
I had the same problem and found the cause while looking in CodeIgniter's source code. It seems the writers thought that if a field didn't have "required", then it would just skip all the rules and always return that the form has validated. See it for yourself from their code:
// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))
However, if you add "callback_" in front of your rule, you can still make it run, for the procedure, look here:
https://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks
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
}