Search code examples
phpcodeignitervalidationcodeigniter-2

CodeIgniter Input , and Validation


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


Solution

  • 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.