I want to display validation error msg on registration form. Msg should be displayed when Login already exist in database.
MY error: Unable to access an error message corresponding to your field name Login_r.(rule)
Pleas try to help me, its very important. Thank you
config/form_validation.php
$config = array(
'login' => array(
array(
'field' => 'login',
'label' => 'Login',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
)
),
'register' => array(
array(
'field' => 'name_r',
'label' => 'Name',
'rules' => 'required|alpha'
),
array(
'field' => 'lastname_r',
'label' => 'Lastname',
'rules' => 'required|alpha'
),
array(
'field' => 'login_r',
'label' => 'Login_r',
'rules' => 'required|callback_rule'
),
array(
'field' => 'password_r',
'label' => 'Password_r',
'rules' => 'required|min_length[4]|max_length[12]'
),
array(
'field' => 'confirm_password_r',
'label' => 'Confirm_password',
'rules' => 'required|matches[password_r]'
),
array(
'field' => 'email_r',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'adres_r',
'label' => 'Adres',
'rules' => 'required'
)
),
);
Controller:
if ($this->form_validation->run('register') == false)
{
$this->form_validation->set_message('rule', 'Dzialaj !');
$this->load->view('content/register');
}
else
{
$this->load->view('content/index');
$name_r = $this->input->post('name_r');
$lastname_r = $this->input->post('lastname_r');
$login_r = $this->input->post('login_r');
$password_r = $this->input->post('password_r');
$email_r = $this->input->post('email_r');
$adres_r = $this->input->post('adres_r');
$data_db = array(
'name' => $name_r,
'lastname' => $lastname_r,
'login' => $login_r,
'password' => $password_r,
'email' => $email_r,
'adres' => $adres_r
);
$this->Main_model->register($data_db);
}
Model:
public function register($data_db) {
$this->db->where('login',$data_db['login']);
$query = $this->db->get('users');
$row = $query->row();
if($row->login){
$this->form_validation->set_message('rule', 'Error Message');
} else {
$this->db->insert('users', $data_db);
}
View(forms)
<?php
echo validation_errors();
echo form_open();
echo 'Imie: ' . form_input('name_r');
echo br(2);
echo 'Nazwisko: ' . form_input('lastname_r');
echo br(2);
echo 'Login: ' . form_input('login_r');
echo br(2);
echo 'Haslo: ' . form_password('password_r');
echo br(2);
echo 'Potwierdz Haslo: ' . form_password('confirm_password_r');
echo br(2);
echo 'E-mail: ' . form_input('email_r');
echo br(2);
echo 'Adres: ' . form_input('adres_r');
echo br(1);
echo form_submit('zarejestrowany','Stworz konto');
echo form_close();
?>
</div>
</div>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>
I'm not sure where you have your validation code you posted, that should be in the controller too. I'd suggest refactoring so you don't do any validation in the model:
Model:
public function get_user($login) {
$this->db->where('login',$login);
$query = $this->db->get('users');
$row = $query->row();
return $row;
}
public function register($data_db) {
$this->db->insert('users', $data_db);
}
Controller:
if ($this->form_validation->run('register') == false)
{
$this->form_validation->set_message('rule', 'Dzialaj !');
$this->load->view('content/register');
}
else
{
$this->load->view('content/index');
$name_r = $this->input->post('name_r');
$lastname_r = $this->input->post('lastname_r');
$login_r = $this->input->post('login_r');
$password_r = $this->input->post('password_r');
$email_r = $this->input->post('email_r');
$adres_r = $this->input->post('adres_r');
$user = $this->Main_model->get_user();
if($user->login) {
$this->form_validation->set_message('rule', 'Error Message');
redirect('content/register')
}
$data_db = array(
'name' => $name_r,
'lastname' => $lastname_r,
'login' => $login_r,
'password' => $password_r,
'email' => $email_r,
'adres' => $adres_r
);
$this->Main_model->register($data_db);
This still isn't great since I have to use a redirect if it $user->login is true, it would be even better to create the callback like I mentioned in the chat, but I don't really understand how your code is structured.
Your controller needs a function called "rule" (because you have a rule called "callback_rule" in your form_validation rules).
function rule($form_value)
{
if(<condition for form value is good>)
{
return TRUE;
}
else
{
$this->form_validation->set_message('login_r','your error message');
return FALSE;
}
}
Related
Hello i am building a REST API with CodeIgniter. The problemm is that i have set the validation rules but the code does not recognise them. I am using https://github.com/chriskacerguis/codeigniter-restserver.
The method put:https://github.com/alexmarton/RControl/blob/master/application/controllers/api.php and this example works. But in my case it does not.
public function properties_put(){
$property_to_update = $this->uri->segment(3);
$this->load->model('Model_properties');
$this->load->library('form_validation');
if (isset($property_to_update)) {
if (is_numeric($property_to_update)) {
$property_exist = $this->Model_properties->get_by(array('ID'=> $property_to_update));
if ($property_exist) {
$data = remove_unknown_fields($this->put(), $this->form_validation->get_field_names('property_put'));
$this->form_validation->set_data($data);
$debugdata = $this->form_validation->get_field_names('property_put');
foreach ($debugdata as $key => $value) {
log_message('debug', "Found validation data (".($key+1).")" . $value);
}
foreach ($data as $k => $val) {
log_message('debug', "Unknown field data (".($k+1).")" . $val);
}
if ($this->form_validation->run('property_put') != false) {
log_message('debug', "Passed validation data ");
}else{
$this->response(array("status" => "failure", "status_code" => "400", "response" => $this->form_validation->get_errors_as_array() ), REST_Controller::HTTP_BAD_REQUEST);
log_message('debug', "Error in validation data ");
}
} else {
$this->response(array("status" => "failure" , "status_code" => "404" , "message" => "Not Found", "response"=>"We couldn't find a property with the specified :id"), REST_Controller::HTTP_NOT_FOUND);
}
}
} else {
$this->response(array("status" => "failure" , "status_code" => "422" , "message" => "Unprocessable Entity", "response"=>"You have to specify the :id or the :name of the property that you would like to edit/update"), REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
application/form_validation:
$config = array(
'price_post' => array(
array( 'field' => 'property_id', 'label' => 'Property id', 'rules' => 'trim|required' ),
array( 'field' => '_from', 'label' => 'Timeframe from', 'rules' => 'trim|required' ),
array( 'field' => '_to', 'label' => 'Timeframe to', 'rules' => 'trim|required' ),
array( 'field' => 'price', 'label' => 'Price', 'rules' => 'trim|required|integer|min_length[2]|is_natural_no_zero' ),
),
'availability_post' => array(
array( 'field' => 'property_id', 'label' => 'Property id', 'rules' => 'trim|required' ),
array( 'field' => '_from', 'label' => 'Timeframe from', 'rules' => 'trim|required' ),
array( 'field' => '_to', 'label' => 'Timeframe to', 'rules' => 'trim|required' ),
array( 'field' => 'free', 'label' => 'Is it free or not', 'rules' => 'trim|required|integer|numeric' )
),
'image_post' => array(
array( 'field' => 'property_id', 'label' => 'Property id', 'rules' => 'trim|required' ),
array( 'field' => 'url', 'label' => 'Url', 'rules' => 'trim|required|valid_url|prep_url' ),
array( 'field' => 'sort_order', 'label' => 'Sort Order', 'rules' => 'trim|required' )
),
'property_put' => array(
array( 'field' => 'name', 'label' => 'Property Name', 'rules' => 'trim|required' ),
array( 'field' => 'village', 'label' => 'Property Village', 'rules' => 'trim|required' ),
array( 'field' => 'town', 'label' => 'Property Town', 'rules' => 'trim|required' ),
array( 'field' => 'province', 'label' => 'Property Province', 'rules' => 'trim|required' ),
array( 'field' => 'region', 'label' => 'Property Region', 'rules' => 'trim|required' ),
array( 'field' => 'type', 'label' => 'Property Type', 'rules' => 'trim|required' )
)
);
application/helpers/my_api_helper:
function remove_unknown_fields($form_fields, $expected_fields){
$new_data = array();
foreach ($form_fields as $key => $value) {
if ($value != "" && in_array($key, array_values($expected_fields))) {
$new_data[$key] = $value;
}
}
return $new_data;
}
application/libraries/MY_Form_validation:
class MY_Form_validation extends CI_Form_validation {
function __construct($rules = array()) {
parent::__construct($rules);
$this->ci =& get_instance();
}
public function get_errors_as_array() {
return $this->_error_array;
}
public function get_config_rules() {
return $this->_config_rules;
}
public function get_field_names($form) {
$field_names = array();
$rules = $this->get_config_rules();
$rules = $rules[$form];
foreach ($rules as $index => $info) {
$field_names[] = $info['field'];
}
return $field_names;
}
}
The debug info:
DEBUG - 2016-05-31 18:34:25 --> Found validation data (1)name
DEBUG - 2016-05-31 18:34:25 --> Found validation data (2)village
DEBUG - 2016-05-31 18:34:25 --> Found validation data (3)town
DEBUG - 2016-05-31 18:34:25 --> Found validation data (4)province
DEBUG - 2016-05-31 18:34:25 --> Found validation data (5)region
DEBUG - 2016-05-31 18:34:25 --> Found validation data (6)type
DEBUG - 2016-05-31 18:34:25 --> Unable to find validation rules
and still it does not display errors when i do not post data. Anyone can help me understand what is going on?
What you have to do is this:
Modify the property_put method like this:
public function properties_put(){
$property_to_update = $this->uri->segment(3);
$this->load->model('Model_properties');
$this->load->library('form_validation');
if (isset($property_to_update)) {
if (is_numeric($property_to_update)) {
$property_exist = $this->Model_properties->get_by(array('ID'=> $property_to_update));
if ($property_exist) {
$property = $this->Model_properties->update_by('primary_field_key', $property_to_update, array(
'your_field_1' => $this->put('field_1'),
'your_field_2' => $this->put('field_2')
));
if($property){
//display correct response
} else {
//display wrong response
}
} else {
$this->response(array("status" => "failure" , "status_code" => "404" , "message" => "Not Found", "response"=>"We couldn't find a property with the specified :id"), REST_Controller::HTTP_NOT_FOUND);
}
}
} else {
$this->response(array("status" => "failure" , "status_code" => "422" , "message" => "Unprocessable Entity", "response"=>"You have to specify the :id or the :name of the property that you would like to edit/update"), REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
In order for the above to work put data must have the following:
Header: Content-type: application/json
If you are using Postman you have to use raw as JSON like this
{
"field_1":"value 1",
"field_2":"value 2"
}
Hope it helps!!!
I am working on Zend framework 2. I have one form for saving shop information. I have validated the form using Zend's input filters. My issue is when I enter wrong data into the field or keep a mandatory field blank then it properly displays the error but entire form gets blank again.
I want the previously entered values as it is when the form shows errors.
Following is the function that renders the form.
public function settingsAction()
{
try {
$message = '';
$error = '';
$id = 0;
try {
$shop = $this->_getShop();
} catch (\Exception $ex) {
AppLogger::log($ex);
$error = $ex->getMessage();
}
if ($shop) {
$id = $shop->id;
}
else {
//redirect to login page
return $this->redirect()->toUrl($this->_getDomainUrl());
}
$form = new ShopForm($this->serviceLocator);
$config = $this->serviceLocator->get('config');
$apiUrls = $config['apiUrls'];
$request = $this->getRequest();
if ($request->isPost())
{
if (!$shop)
$shop = new Shop();
$form->setInputFilter($shop->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$url = $shop->url;
$token = $shop->token;
$config_id = $shop->config_id;
$password = $shop->password;
$shop->exchangeArray($form->getData(),false);
$shop->url = $url;
$shop->token = $token;
$shop->config_id = $config_id;
DAL::getShopTable($this->serviceLocator)->saveShop($shop);
$message = "Your settings has been saved successfully.";
}
else {
$error = 'There are values that need to be completed before you can save/update your preferences.';
foreach($form->getMessages() as $msg) {
$error = $error . $msg;
}
}
}
if ($shop)
{
echo "<pre>";print_r($shop);
$shop->selected_countries = unserialize($shop->selected_countries);
$form->bind($shop);
$form->get('return_address_country')->setAttribute('value', $shop->return_address_country);
}
$form->get('submit')->setAttribute('value', 'Save');
return array(
'id' => $id,
'form' => $form,
'apiUrls' => $apiUrls,
'message' => $message,
'uri' => $this->_selfURL(),
"error" => $error
);
}
catch (\Exception $ex) {
AppLogger::log($ex);
throw $ex;
}
}
I have used $form->setInputFilter($shop->getInputFilter()); for validations. A snippet from getInputFilter() is as follows:
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'ship_to_code',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'default_phone',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'max_records_per_file',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
}
And the form is
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'ship_to_code',
'type' => 'Text',
'options' => array(
'label' => 'Ship-To Code',
),
));
$this->add(array(
'name' => 'default_phone',
'type' => 'Text',
'options' => array(
'label' => 'Default Phone',
),
));
You can use the setdata() method of form in your setting action.
Here's updated code
if ($shop)
{
// echo "<pre>";print_r($shop);
// $shop->selected_countries = unserialize($shop->selected_countries);
$form->bind($shop);
$form->setData($request->getPost()); // set post data to form
}
Having a registration zend form in view looks like this :
<?php
$form = $this->form;
if(isset($form)) $form->prepare();
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'register', 'action' => 'process')));
echo $this->form()->openTag($form);
?>
<dl class="form-signin">
<dd><?php
echo $this->formElement($form->get('name_reg'));
echo $this->formElementErrors($form->get('name_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('email_reg'));
echo $this->formElementErrors($form->get('email_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('password_reg'));
echo $this->formElementErrors($form->get('password_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('confirm_password_reg'));
echo $this->formElementErrors($form->get('confirm_password_reg'));
?></dd>
<br>
<dd><?php
echo $this->formElement($form->get('send_reg'));
echo $this->formElementErrors($form->get('send_reg'));
?></dd>
<?php echo $this->form()->closeTag() ?>
And RegisterController as following.
<?php
namespace Test\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Test\Form\RegisterForm;
use Test\Form\RegisterFilter;
use Test\Form\LoginFormSm;
use Test\Form\LoginFilter;
use Test\Model\User;
use Test\Model\UserTable;
class RegisterController extends AbstractActionController
{
public function indexAction()
{
$this->layout('layout/register');
$form = new RegisterForm();
$form_sm = new LoginFormSm();
$viewModel = new ViewModel(array(
'form' => $form,
'form_sm' =>$form_sm,
));
return $viewModel;
}
public function processAction()
{
$this->layout('layout/register');
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setData($this->request->getPost());
if (!$form->isValid()) {
$model = new ViewModel(array(
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
// Creating New User
$this->createUser($form->getData());
return $this->redirect()->toRoute(NULL, array (
'controller' => 'auth' ,
));
}
protected function createUser(array $data)
{
$userTable = $this->getServiceLocator()->get('UserTable');
$user = new User();
$user->exchangeArray($data);
$userTable->saveUser($user);
return true;
}
}
Also a RegisterForm where are declared all variables shown in index. Also RegisterFilter as following:
<?php
namespace Test\Form;
use Zend\InputFilter\InputFilter;
class RegisterFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'AbstractDb',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Current Email Already registered'
),
),
),
),
));
$this->add(array(
'name' => 'name_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 140,
),
),
),
));
$this->add(array(
'name' => 'password_reg',
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' =>array(
'encoding' => 'UTF-8',
'min' => 6,
'messages' => array(
\Zend\Validator\StringLength::TOO_SHORT => 'Password is too short; it must be at least %min% ' . 'characters'
),
),
),
array(
'name' => 'Regex',
'options' =>array(
'pattern' => '/[A-Z]\d|\d[A-Z]/',
'messages' => array(
\Zend\Validator\Regex::NOT_MATCH => 'Password must contain at least 1 digit and 1 upper-case letter'
),
),
),
),
));
$this->add(array(
'name' => 'confirm_password_reg',
'required' => true,
'validators' => array(
array(
'name' => 'Identical',
'options' => array(
'token' => 'password_reg', // name of first password field
'messages' => array(
\Zend\Validator\Identical::NOT_SAME => "Passwords Doesn't Match"
),
),
),
),
));
}
}
Problem
All i need is to throw a message when somebody tries to register and that e-mail is already registered. Tried with \Zend\Validator\Db\AbstractDb and added following validator to email in RegisterFilter as following
array(
'name' => 'AbstractDb',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Current Email Already registered'
),
),
),
But that seems not to work.
Question: Is there a way to implement this validator in RegisterController?
Additional.
I've deleted from RegisterFilert validator and put inside Module.ph
'EmailValidation' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$validator = new RecordExists(
array(
'table' => 'user',
'field' => 'email',
'adapter' => $dbAdapter
)
);
return $validator;
},
And call it from RegisterController
$validator = $this->getServiceLocator()->get('EmailValidation');
if (!$validator->isValid($email)) {
// email address is invalid; print the reasons
$model = new ViewModel(array(
'error' => $validator->getMessages(),
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
And when i use print_r inside view to check for it shows.
Array ( [noRecordFound] => No record matching the input was found ).
I want just to echo this 'No record matching the input was found'.
Fixed
Modified in RegisterController as following
$validator = $this->getServiceLocator()->get('EmailValidation');
$email_ch = $this->request->getPost('email_reg');
if (!$validator->isValid($email_ch)) {
// email address is invalid; print the reasons
$model = new ViewModel(array(
'error' => 'Following email is already registered please try another one',
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
I had compared
if (!$validator->isValid($email_ch))
Before with nothing and that's why i needed to add first
$email_ch = $this->request->getPost('email_reg');
You don't have to do that in your controller, just try this in your RegisterFilter class :
First : Add $sm as parameter of the _construct() method :
public function __construct($sm) {....}
Second: Replace e-mail validation by this one :
$this->add ( array (
'name' => 'email_reg',
'required' => true,
'validators' => array(
array(
'name' => 'Zend\Validator\Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'e-mail address already exists'
),
),
),
),
)
);
When you call the RegisterFilter don't forget to pass the serviceLocator as parameter in your controller :
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
Supposing you have this in your global.php File (config\autoload\global.php) :
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
To your previous request, ("I want just to echo this 'No record matching the input was found'")
$validator = $this->getServiceLocator()->get('EmailValidation');
$email_ch = $this->request->getPost('email_reg');
if (!$validator->isValid($email_ch)) {
// email address is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
$msg = $message;
}
$model = new ViewModel(array(
'error' => $msg,
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
I have a controller and a view. I am trying to submit some details through a form, but when I submit it, no errors are displayed.
I am using only one controller to for 2 different types of users. The two users are -
User
Gym/Health Club Owner
And according to the $suertype, I have the same view being called but a different content being loaded.
This is my controller:
public function CreateProfile_Step2()
{
$data['page_title'] = 'Create Profile (Step 2)';
$loginid = $this->session->userdata('loginid');
$this->load->model('profilemodel', 'profile');
$userid = $this->profile->get_userid($loginid);
$this->session->set_userdata('userid', $userid);
$usertype = $this->profile->get_usertype($userid);
$data['usertype'] = $usertype;
if ($usertype == 'User') {
$this->load->model('activitymodel', 'activity');
$arr_activities = $this->activity->get_activities();
$data['options'] = $arr_activities;
}
else if ($usertype == 'Gym/Health Club Owner') {
$this->load->model('facilitymodel', 'facility');
$arr_facility = $this->facility->get_facilities();
$data['options'] = $arr_facility;
}
$config = array(
'User' => array(
array(
'name' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'name' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'name' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'name' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules($config);
if ($usertype == 'User') {
if ($this->form_validation->run('User') == FALSE) {
$this->load->view('create-profile-step-2', $data);
}
else {
$selected_options = $this->input->post('activities');
$this->activity->add_user_activities($userid, $selected_options);
$sex = $this->input->post('sex');
$this->profile->add_user_details($userid, $sex);
echo 'Profile Creation Completed!';
}
}
else {
if ($this->form_validation->run('Gym/Health Club Owner') == FALSE) {
$this->load->view('create-profile-step-2', $data);
}
else {
$selected_options = $this->input->post('facilities');
$this->facility->add_gym_facility($userid, $selected_options);
$website = $this->input->post('website');
$hours_of_operation = $this->input->post('hours_of_operation');
$membership_charges = $this->input->post('membership_charges');
$this->facility->add_gym_details($userid, $website, $hours_of_operation, $membership_charges);
echo 'Profile Creation Completed!';
}
}
}
This is my view:
<?php include 'user/inc/header.php'; ?>
<div id="content" class="row twelvecol">
<h1>Create Profile (Step 2 of 2)</h1>
<h2>For <?php echo $usertype; ?></h2>
<?php
echo form_open('register/CreateProfile_Step2');
if ($usertype == 'User') {
echo form_label('Sex', 'sex');
$options_sex = array(
'Male' => 'Male',
'Female' => 'Female'
);
echo form_dropdown('sex', $options_sex, 'male');
$ctr = 1;
echo form_label('Activities Interested In', 'activities');
foreach($options->result() as $option)
{
echo form_label($option->activity, 'activity-'.$ctr);
$arr_option = array(
'name' => 'activities[]',
'id' => 'activity-'.$ctr++,
'value' => $option->activity
);
echo form_checkbox($arr_option);
}
}
elseif ($usertype == 'Gym/Health Club Owner')
{
echo form_label('Website', 'website');
$arr_website = array(
'name' => 'website',
'id' => 'website',
'value' => set_value('website')
);
echo form_input($arr_website);
echo form_label('Hours of Operation', 'hours_of_operation');
$arr_hours = array(
'name' => 'hours_of_operation',
'id' => 'hours_of_operation',
'value' => set_value('hours_of_operation')
);
echo form_input($arr_hours);
echo form_label('Membership Charges', 'membership_charges');
$arr_charges = array(
'name' => 'membership_charges',
'id' => 'membership_charges',
'value' => set_value('membership_charges')
);
echo form_input($arr_charges);
$ctr = 1;
echo form_label('Facilities Available', 'facilities');
foreach($options->result() as $option)
{
echo form_label($option->facility, 'facility-'.$ctr);
$arr_option = array(
'name' => 'facilities[]',
'id' => 'facility-'.$ctr++,
'value' => $option->facility
);
echo form_checkbox($arr_option);
}
}
echo "<br/><br/>";
echo form_submit('submit', 'Create Profile');
echo form_close();
echo validation_errors();
?>
Return to previous step
</div>
<?php include 'user/inc/footer.php'; ?>
It's more likely some problem with the $config, because I have tried changing my code and used 2 separate controllers and views for the 2 cases.
Well, since no one answered my question. I was going through the code and found the errors myself. I had used the key 'name' in my configuration instead of 'field'.
INCORRECT CODE
$config = array(
'User' => array(
array(
'name' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'name' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'name' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'name' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
CORRECT CODE
$config = array(
'User' => array(
array(
'field' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'field' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'field' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'field' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
I am trying to set up validation on a simple contact form that is created using the form helper. No validation at all occurs. What is wrong?
In the code below, the “good” keyword always shows, regardless of what is entered into the form, and the saved values set via set_value are never shown.
Controller
// Contact
function contact() {
$data['pageTitle'] = "Contact";
$data['bodyId'] = "contact";
$this->load->library('form_validation');
$config_rules = array ('email' => 'required','message' => 'required');
$this->form_validation->set_rules($config_rules);
if ($this->form_validation->run() == FALSE) {
echo "bad";
$data['include'] = "v_contact";
$this->load->view('v_template',$data);
} else {
echo "good";
$data['include'] = "v_contact";
$this->load->view('v_template',$data);
}
}
View
echo validation_errors();
echo form_open('events/contact');
// name
echo form_label('Name', 'name');
$data = array (
'name' => 'name',
'id' => 'name',
'maxlength' => '64',
'size' => '40',
'value' => set_value('name')
);
echo form_input($data) . "\n<br />";
// email address
echo form_label('Email Address', 'email');
$data = array (
'name' => 'email',
'id' => 'email',
'maxlength' => '64',
'size' => '40',
'value' => set_value('email')
);
echo form_input($data) . "\n<br />";
// message
echo form_label('Message', 'message');
$data = array (
'name' => 'message',
'id' => 'message',
'rows' => '8',
'cols' => '35',
'value' => set_value('message')
);
echo form_textarea($data) . "\n<br />";
echo form_submit('mysubmit', 'Send Message');
echo form_close();
It looks like you're not setting the validation rules according to the way the new Form_validation library does it (the user guide has a section on the new syntax). That seems to be the syntax for the old Validation library.
Try this instead for your $config_rules array and see if your validation runs properly:
$config_rules = array(
array('field' => 'email', 'rules' => 'required'),
array('field' => 'message', 'rules' => 'required')
);
$this->form_validation->set_rules($config_rules);