Form validation not working in CodeIgniter, controller issue - php

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'
))
);

Related

How to send validation error massage? Codeigniter

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;
}
}

Problemm with REST Api Validation

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!!!

How to get posted data from from to email in SocialEngine?

I edited standard contact form in SocialEngine. Added new 4 fields to it - BirthDate, address, country & postal code field.
First question - how to properly set the default value of Country Select = "USA"?
Second question - how to get posted data from new form's fields (BirthDate, address, country & postal code) to user's email? How need to edit my controller?
My code:
class Pagecontact_Form_Contact extends Engine_Form
{
private $page_id;
public function __construct($page_id)
{
$this->page_id = $page_id;
parent::__construct();
}
public function init()
{
parent::init();
$this
->setTitle('Send Message to Apply for Sponsorship')
->setAttrib('id', 'page_edit_form_contact')
->setAttrib('class', 'global_form');
$topicsTbl = Engine_Api::_()->getDbTable('topics', 'pagecontact');
$topics = $topicsTbl->getTopics($this->page_id);
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
$options[0] = '';
foreach($topics as $topic)
{
$options[$topic['topic_id']] = $topic['topic_name'];
}
$this->addElement('Date', 'birthdate', array('label' => 'Birthdate:',
'class' => 'date_class', 'name' => 'birthdate'));
$this->addElement('Text', 'address', array('label' => 'Address:',
'class' => 'address_class', 'name' => 'address'));
$this->addElement('Select', 'country', array('label' => 'Country:',
'class' => 'country_class', 'name' => 'country')); //->setValue("USA");
$this->addElement('Text', 'postal', array('label' => 'Postal Code:',
'class' => 'postal_class', 'name' => 'postal'));
$this->addElement('Select', 'topic', array(
'label' => 'PAGECONTACT_Topic',
'class' => 'topic_class',
'multiOptions' => $options,
));
$this->getElement('topic')->getDecorator('label')->setOption('class','element_label_class topic_label_class');
$this->addElement('Hidden', 'visitor', array(
'value' => 0,
'order' => 3,
));
if ($viewer_id == 0)
{
$this->addElement('Text', 'sender_name', array(
'label' => 'PAGECONTACT_Full name',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('sender_name')->getDecorator('label')->setOption('class','element_label_class sender_name_label_class');
$this->addElement('Text', 'sender_email', array(
'label' => 'PAGECONTACT_Email',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('sender_email')->getDecorator('label')->setOption('class','element_label_class sender_email_label_class');
$this->addElement('Hidden', 'visitor', array(
'value' => 1,
'order' => 3,
));
}
$this->addElement('Text', 'subject', array(
'label' => 'PAGECONTACT_Subject',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('subject')->getDecorator('label')->setOption('class','element_label_class subject_label_class');
$this->addElement('Textarea', 'message', array(
'label' => 'PAGECONTACT_Message',
'maxlength' => '512',
'class' => 'message_class',
'filters' => array(
new Engine_Filter_Censor(),
new Engine_Filter_Html(array('AllowedTags' => 'a'))
),
));
$this->getElement('message')->getDecorator('label')->setOption('class','element_label_class message_label_class');
$this->addElement('Hidden', 'page_id', array(
'value' => $this->page_id,
'order' => 7,
));
$this->addElement('Button', 'send', array(
'label' => 'Send',
'type' => 'button',
'class' => 'btn_send_class',
'name' => 'submitted'
));
}
}
Controller:
public function sendAction()
{
$page_id = $this->_getParam('page_id');
$topic_id = $this->_getParam('topic_id');
$subject = $this->_getParam('subject');
$message = $this->_getParam('message');
$senderName = $this->_getParam('sender_name');
$senderEmail = $this->_getParam('sender_email');
$birthDate = $this->getRequest()->getPost('birthdate'); // Empty set
$address = $this->getRequest()->getPost('adress'); // Empty set
$country = "USA"; // Works
$postal = $this->getRequest()->getPost('postal'); // Empty set
$pagesTbl = Engine_Api::_()->getDbTable('pages', 'page');
$select = $pagesTbl->select()
->from(array($pagesTbl->info('name')), array('displayname'))
->where('page_id = ?', $page_id);
$query = $select->query();
$result = $query->fetchAll();
$pageName = $result[0]['displayname'];
$viewer = $this->_helper->api()->user()->getViewer();
$user_id = $viewer->getIdentity();
$topicsTbl = Engine_Api::_()->getDbTable('topics', 'pagecontact');
$emails = $topicsTbl->getEmails($page_id, $topic_id);
$i = 0;
$emails = explode(',',$emails);
foreach($emails as $email) {
$emails[$i] = trim($email);
$i++;
}
if ($user_id != 0) {
$senderName = $viewer['displayname'];
$senderEmail = $viewer['email'];
}
foreach($emails as $email) {
// Make params
$mail_settings = array(
'date' => time(),
'page_name' => $pageName,
'sender_name' => $senderName,
'sender_email' => $senderEmail,
'subject' => $subject,
'message' => $message." ".$birthDate." ".$address." ".$country." ".$postal,
);
// send email
Engine_Api::_()->getApi('mail', 'core')->sendSystem(
$email,
'pagecontact_template',
$mail_settings
);
};
}
}
Eugene,
There is not country field in the your form. But you can do in controller where you are calling the form function like.
{
$form->getElement('country')->setvalue('USA');
}
Please feel free to ask your questions.

ERRORS Zend\InputFilter\Exception\RuntimeException

I am trying use zf2 to validate form, but have errors:
An error occurred
An error occurred during execution; please try again later.
Additional information:
Zend\InputFilter\Exception\RuntimeException
File:
C:\xampp\htdocs\ZEND\Users\Users\vendor\ZF2\library\Zend\InputFilter\Factory.php:395
Message:
Invalid validator specification provided; was neither a validator instance nor an array specification
Code:
<?php
namespace Users\Form;
use Zend\InputFilter\InputFilter;
class RegisterFilter extends InputFilter{
public function __construct(){
$this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
));
$this->add(array(
'name' => 'user',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringLength'),
),
'validators' => array(
array(
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 32,
),
),
),
));
}
}
RegisterForm
<?php
namespace Users\Form;
use Zend\Form\Form;
class RegisterForm extends Form {
public function __construct($name = null){
parent::__construct('Register');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$this->add(array(
'name' => 'user',
'attributes' => array(
'type' => 'text',
'required' => 'required'
),
'options' => array(
'label' => 'UserName',
),
));
$this->add(array(
'name' => 'pwd',
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'options' => array(
'label' => 'Password',
)
));
$this->add(array(
'name' => 'cpwd',
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'options' => array(
'label' => 'Comfirm Password',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Register',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
),
'options' => array(
'label' => 'Email',
),
'attributes' => array(
'required' => 'required',
),
'filters' => array(
array('name' => 'StringTrim')
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email Address Format is invalid'
)
)
)
)
));
}
}
RegisterController
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
class RegisterController extends AbstractActionController{
public function indexAction(){
$form = new RegisterForm();
$viewmodel = new ViewModel(array('form' => $form));
return $viewmodel;
}
public function processAction(){
if(!$this->request->isPost()){
return $this->redirect()-> toRoute(NULL,
array( 'controller' => 'register',
'action' => 'index',
));
}
$post = $this->request->getPost();
$form = new RegisterForm();
$inputFilter = new RegisterFilter();
$form->setInputFilter($inputFilter);
$form->setData($post);
if(!$form->isValid()){
$model = new ViewModel(array(
'error' => true,
'form' => $form,
));
$model ->setTemplate('users/register/index');
return $model;
}
return $this->redirect()->toRoute(NULL,array(
'controller' => 'register',
'action' => 'confirm',
));
}
public function confirmAction(){
$viewmodel = new ViewModel();
return $viewmodel;
}
}
index.phtml
<section class = 'register'>
<h2> Register </h2>
<?php if($this -> error): ?>
<p class='error'> have errors </p>
<?php endif ?>
<?php
$form = $this->form;
$form -> prepare();
$form -> setAttribute('action', $this->url(NULL,
array('controller' => 'Register', 'action' => 'process')));
$form -> setAttribute('method','post');
echo $this->form()->openTag($form);
?>
<dl class='zend_form'>
<dt><?php echo $this->formLabel($form -> get('user')) ;?> </dt>
<dd> <?php echo $this->formElement($form->get('user')) ;?>
<?php echo $this->formElementErrors($form->get('user')) ;?>
</dd>
<dt><?php echo $this->formLabel($form -> get('email'));?></dt>
<dd><?php echo $this->formElement($form-> get('email')) ;?>
<?php echo $this->formElementErrors($form -> get('email')) ;?>
</dd>
<dt><?php echo $this->formLabel($form -> get('pwd')) ;?></dt>
<dd><?php echo $this->formElement($form->get('pwd')) ;?>
<?php echo $this->formElementErrors($form->get('pwd')) ;?>
</dd>
<dt><?php echo $this->formLabel($form ->get('cpwd'));?></dt>
<dd><?php echo $this->formElement($form->get('cpwd'));?>
<?php echo $this->formElementErrors($form->get('cpwd'))?>
</dd>
<dd><?php echo $this->formElement($form->get('submit'));?>
<?php echo $this->formElementErrors($form->get('submit'));?>
</dd>
</dl>
<?php echo $this->form()->closeTag()?>
</section>
Your validator structure is wrong.
The validators key is expecting an array of validators. You are supplying the validator name and options directly.
Change this:
this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
));
To:
this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
)
//Another validator here ..
),
));

Index value is also shown with database value

I have dropdown with database values.But,dropdown also shows database value's index and i want to remove index.I have searched in google and other forums,but not getting expected solution.
function products_edit($product_id) {
$this->load->helper('form');
$this->load->helper('html');
$this->load->library('form_validation');
$this->load->model('products_model');
$data=$this->products_model->general();
$category['categories']=$this->products_model->get_category();
$product = $this->products_model->get_product($product_id);
$this->data['title'] = 'Edit Product';
//validate form input
$this->form_validation->set_rules('name', 'Product name', 'required|xss_clean');
$this->form_validation->set_rules('description', 'Product Description', 'required|xss_clean');
$this->form_validation->set_rules('category', 'Category', 'required|xss_clean');
//$this->form_validation->set_rules('extras', 'Extras', 'required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
$this->form_validation->set_rules('is_featured', 'Is Featured', 'required|xss_clean');
$this->form_validation->set_rules('prorder', 'prorder', 'required|xss_clean');
if (isset($_POST) && !empty($_POST)) {
$data = array(
'product_name'=> $this->input->post('name'),
'product_desc'=> $this->input->post('description'),
'product_category' => $this->input->post('category'),
'extras' => $this->input->post('extras'),
'price' => $this->input->post('price'),
'is_featured' => $this->input->post('is_featured'),
'prorder' => $this->input->post('prorder'),
);
if ($this->form_validation->run() === true) {
$this->products_model->updateproducts($product_id, $data);
$this->session->set_flashdata('message', "<p>Product updated successfully.</p>");
redirect('products_controller/products_edit/'.$product_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['product'] = $product;
//display the edit product form
$this->data['name'] = array(
'name' => 'name',
'id' => 'name',
'type' => 'text',
'style' => 'width:300px;',
'value' => $this->form_validation->set_value('name', $product['product_name']),
);
$this->data['description'] = array(
'name' => 'description',
'id' => 'description',
'type' => 'text',
'cols' => 60,
'rows' => 5,
'value' => $this->form_validation->set_value('description', $product['product_desc']),
);
$cat=array();
$test = array();
for($i=0;$i<=3;$i++) {
$test[$i] = array($category['categories'][$i] => $category['categories'][$i]);
}
$this->data['category'] = $test;
$this->data['extras'] = array(
'name' => 'extras',
'id' => 'extras',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('extras', $product['extras']),
);
$this->data['price'] = array(
'name' => 'price',
'id' => 'picture',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('price', $product['price']),
);
$this->data['is_featured'] = array(
'name' => 'is_featured',
'id' => 'is_featured',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('is_featured', $product['is_featured']),
);
$this->data['prorder'] = array(
'name' => 'prorder',
'id' => 'prorder',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('prorder', $product['prorder']),
);
$this->load->view('products_edit', $this->data);
}
The error occurs in this line.
for($i=0;$i<=3;$i++) {
$test[$i] = array($category['categories'][$i] => $category['categories'][$i]);
}
The error is due to $i in the test array. If I remove it, causing an error. I don't have solution for this error.
The screen shot http://i.share.pho.to/f4a24cc3_o.png
Is there a particular reason why you're using a for loop to build your categories dropdown list?
The $test array needs to look something like this:
$test = array(
1 => 'Pizza',
2 => 'Sandwich',
3 => 'Dessert',
4 => 'Salad'
);
Where the key is the associated id to the category and the value is the category name. At the minute you are loading both the key and value of the array with the whole category (based on it's index).
If you are wanting to pull out all the categories into a dropdown box, I would suggest something similar to the below, as this would allow you to add additional categories in future and them appear in the dropdown box:
foreach($category['categories'] as $category) {
$test[$category['id']] = $category['name'];
}
$this->data['category'] = $test;
This would require the categories (which I assume are being pulled out of a database table?) to have an id and name field.
Hope that helps...

Categories