2

I am using codeIgniter 2.2.2. In a Controller I captured the input so that I pass it back to the view in case the validation is failed, so that user is not forced to fill all the fields from the start, I set the following variable through $data array

$data['fullname'] = $this->input->post('fullName');

But when the user access the form at first it gives as error as follows.

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: fullname

If I use $this->input->post('fullName'); directly inside the view than no error is triggered, but I want to pass it from the Controller.

The second issue is when I set form validation rule for this input as $this->form_validation->set_rules('fullName', 'Full Name', 'required|alpha'); the validation rule alpha doesn't even allow spaces which in this case I require, because the form field is full name, where there must be a space e.g., "Albert Einstein".

I can solve this problem by setting two different form input fields as "First Name" and "Last Name", but I don't like that, because I think a framework should make my life easier not harder.

Here is an example gist showing the example code, which will trigger the errors I said. Example Gist

6
  • What your view say? Edit your post with view if possible and controller Commented Apr 28, 2015 at 4:03
  • Please provide your controller method and view if possible ! Commented Apr 28, 2015 at 4:05
  • Let me put that code at my github and than provide the link, please wait for a while. Thank You for your time ! I can't provide the whole code, but I'll provide the controller for this view and the view where form is located. Commented Apr 28, 2015 at 4:07
  • Only your controller method and view is enough, not the whole project ! Commented Apr 28, 2015 at 4:08
  • Dear @ArkarAung , I added the example gist's link. I know I didn't use good practices, but still the code is valid according to PHP and CodeIgniter. :) Commented Apr 28, 2015 at 4:15

4 Answers 4

2

Try this.

public function contact() {
    $this->load->library("session");
    $data['message'] = $this->session->flashdata("message");
    $data['fullname'] = $this->session->flashdata("fullname");
    $this->load->view('site_header');
    $this->load->view('site_nav');
    $this->load->view('content_contact', $data);
    $this->load->view('site_footer');
} 

public function send_email() {
    $this->load->library('form_validation');
    $this->form_validation->set_rules('fullName', 'Full Name', 'required|callback_fullname_check');
    $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    $this->form_validation->set_rules('message', 'Message', 'required');

    if ($this->form_validation->run() == false) {
        $this->session->set_flashdata("message", validation_errors());
        $this->session->set_flashdata("fullname", $this->input->post('fullName'));
    } else {
        $this->session->set_flashdata("message", "The email has successfully been sent!");
    }
    redirect("site/contact");
}

public function fullname_check($str) {
    if (! preg_match("/^([a-z0-9 ])+$/i", $str)) {
        $this->form_validation->set_message('fullname_check', 'The %s field can only be alpha numeric');
        return FALSE;
    } else {
        return TRUE;
    }
}

Please avoid loading view repeatedly as DRY (Don't Repeat Yourself)

Edit

Try to use custom validation rule to achieve alpha numeric string with space.

Hope it will be useful for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the nice tip on how to do it the DRY way ! But its still not working :( Only when I used $this->input->post('fullName') directly in the view it works. And how will you address the second issue? the form validation rules alpha / alpha_numeric / alpha_dash none of them allow spaces, is there a rule which allow spaces ?
Thank You bro ! Actually I wanted to see if there is some builtin way inside codeIgniter instead of using workarounds, but I think there is not built in way sadly.
Yes, only three built-in methods that are alpha, alpha-numeric and alpha-dash. Need to create custom rule to achieve alpha-space.
1

You had missed the $data['fullname'] = "" on the sucess part of the form but you have doubled up code try and make it lean as possible.

How I would do it.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Contact extends CI_Controller {

  public function index() {

    $this->load->library('form_validation');
    // Double check spelling of set rules make sure matches the input on the view name="" area
    $this->form_validation->set_rules('fullname', 'Full Name', 'required'); // Removed |alpha no need I think
    $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    $this->form_validation->set_rules('message', 'Message', 'required');

    $fullname = $this->input->post('fullname');

    if (isset($fullname)) {
        $data['fullname'] = $fullname;
    } else {
        $data['fullname'] = "";
    }

    $data['message'] = "";

    if ($this->form_validation->run() == false) {

        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');

    } else {

        $data['message'] = "The email has successfully been sent!";
        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');
    }
  }
}

View: Note might need to set some routes.

<form action="<?php echo base_url('contact');?>" method="post">
<input type="text" name="fullname" value="<?php echo $fullname;?>" placeholder=""/>
</form>

Your Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Site extends CI_Controller {

public function contact() {
    $data['message'] = '';

    $this->load->view('site_header');
    $this->load->view('site_nav');
    $this->load->view('content_contact', $data);
    $this->load->view('site_footer');
}

public function send_email() {
    $this->load->library('form_validation');

    $this->form_validation->set_rules('fullName', 'Full Name', 'required|alpha');
    $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    $this->form_validation->set_rules('message', 'Message', 'required');

    if ($this->form_validation->run() == false) {
        $data['message'] = '';

        $data['fullname'] = $this->input->post('fullName');

        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');
    } else {
        $data['fullname'] = "";

        $data['message'] = 'The email has successfully been sent!';

        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');
    }
}

}

Comments

0

I came across this question (my own question) after a long time. I asked this question when I started learning CodeIgniter.

I asked about two things in the question, and following are the best answers to those two (then) issues.

  1. The best way to capture input value and show back to the user is setting input's 'value' attribute to set_value(), as value="<?= set_value('fieldName') ?>", in case the form isn't submitted successfully and you want to save user from filling the form fields again.
  2. I tried to add a rule alpha_spaces to CodeIgniter's core for the (full name validation) functionality, but the pull request wasn't merged, so I think the better way to get that functionality is to use the method @arkar-aung mentioned in his answer.

The code I used that time looked weird to me when I saw it today, its against the best practices. Look at my answer at Quora about how to better manage views in CodeIgniter.

Comments

0

<!-- form validation -->
	<!-- form validation controller-->	
		class Securities_Controller extends CI_Controller {
		    /**
		     * load the add security page
		     */
		    public function index() {
		        $this->load->model('securities/Security_Model');
		        $data['security'] = $this->Security_Model->get_new();
		        $this->load->view('securites_view/index', $data);
		    }

		    public function add() {
		        echo 'add';
		        $this->load->model('securities/Security_Model');
		        $data['security'] = $this->Security_Model->get_new(); //create empty fields
		        $rules = $this->Security_Model->rules;
		        $this->form_validation->set_rules($rules);
		        if ($this->form_validation->run() == TRUE) {
		            
		        }
		        $this->load->view('securites_view/index', $data);
		    }
		}
	<!-- //form validation controller-->
	<!-- form validation model-->
		class Security_Model extends CI_Model {
		    //put your code here
		    function __construct() {
		        parent::__construct();
		    }
		    //validation rules
		    public $rules = array(
		        'cdsaccid' => array(
		            'field' => 'cdsaccid',
		            'label' => 'CDS Account',
		            'rules' => 'trim|required'
		        ),
		        'comid' => array(
		            'field' => 'comid',
		            'label' => 'Company Name',
		            'rules' => 'trim|required'
		        )
		    );
		    //the standered class for security 
		    function get_new() { 
		        $Security = new stdClass();
		        $Security->cdsaccid = '';
		        $Security->comid = '';
		        return $Security;
		    }
		      public function array_from_post($fields) {
		        $data = array();
		        foreach ($fields as $field) {
		            $data[$field] = $this->input->post($field);
		        }
		        return $data;
		    }
		}
	<!-- //form validation model-->
	<!-- form validation view-->
		<?php echo form_open('Securities_Controller/add') ?>
                                   <?php echo validation_errors();?>
                                        <div class="form-group">
                                            <label for="exampleInputEmail1">CDS Acc</label>
                                            <input type="text" name="cdsaccid" class="form-control" value="<?=set_value('cdsaccid', $security->cdsaccid);?>" >
                                        </div>
                                        <div class="form-group">
                                            <label for="exampleInputPassword1">Company</label>
                                            <input type="text" name="comid" class="form-control" id="exampleInputPassword1">
                                        </div>
                                        <button type="submit" class="btn btn-default">Submit</button>
        <?php echo form_close() ?>
	<!-- //form validation view-->
<!-- //form validation -->	

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.