fuelCMS way to add form validation to form_builder generated forms

FuelCMS documentation regarding construction of forms using form_builder is extensive, but it is not quite clear how to add validation to the form in the proper way (so that the error messages be included in the generated form code).

Could someone provide/point to an example of how it is to be done? Can the Codeigniter form validation class be used, or only the fuelCMS's own validator class? (I know CI form validation class can be used in the standard codeigniter way, but then the error messages are produced outsite of the form_builder functionality (and therefore need a separate piece of code to be shown in the view)).

Comments

  • edited April 2018

    You can use CI's own form validation, however, Form_builder has a "set_validator" and "get_validator" methods on it that return FUEL's Validator class instance. You can do something like the following:
    http://docs.getfuelcms.com/libraries/validator

    So in your

    if (!empty($_POST))
    {
         $validator = $this->form_builder->get_validator();
         $validator->add_rule('name', 'required', "This is required", array($this->input->post('name')));
         if ($validator->is_valid()) {
            redirect('success_page');
         }
    }
    

    The form_builder will automatically highlight each field with an error and print the errors at the top of the page if the page doesn't redirect and is posted to itself with errors.

  • Thank, you, I will try it out tonight. I understand there is no way to use the default CI form validation class and get the form_builder functionality of "highlighting each field with an error" at the same time?

  • Hm, I get an error with the suggested code:

    Fatal error: Call to a member function add_rule() on null

    What could be wrong? I did load the Validator library, though the error does not change if I do not load it (so I guess the Form_builder loads it for me).

  • Try loading the validator library before that:

    $this->load->library('validator');
    
  • This does not help. In my controller function create() that I run I currently have this:

    $this->load->module_language('fuel', 'fuel');//turi būti prieš form_builder
    $this->load->library('form_builder');
    $this->load->model('Dearones_model');
    echo '<pre>'; var_dump($this);exit;
    

    and if I add $this->load->library('validator'); before var_dump, the output does not change at all - it includes numerous references to the validator object, see here: https://pastebin.com/u6K0Czgq

    Here is the complete class: https://pastebin.com/Dax6ht9F

  • Try loading the validator first. I'm wondering if it's an ordering thing. Form_builder uses the Form class which on initialization will grab a reference to the validator object if it's loaded, but if it's not then it will be null.

  • If I raise

    $this->load->library('validator'); 
    

    above

    $this->load->library('form_builder');
    

    I get a blank page (and I have

    error_reporting(-1);

    at the top of index.php file.

    Could it be that the form_builder functionality is sort of abandoned since there is module able to do more than the form_builder?

  • The form module actually uses the form_builder library. Do you have the following set too?

    ini_set('display_errors', 1);
    
  • yes, I have ini_set('display_errors', 1) in case of development environment, and echo ini_get('display_errors'); echoes 1

    Anyway, I have reduced the controller class to bare minimum, with no dependencies in the code, and still get the same error. Could you try it out and see what you get? It drives me nuts... (on pastebin (https://pastebin.com/pH7NxsPp) or below):

    <?php
    require_once(FUEL_PATH.'/libraries/Fuel_base_controller.php');
    
    error_reporting(-1);
    ini_set('display_errors', 1);
    class Testas extends CI_controller {
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function index()
        {
            $this->load->module_language('fuel', 'fuel');
            $this->load->library('form_builder');
            $this->load->library('validator');
    
            $fields['email'] = array('type' => 'email', 'label'=>'Email', 'required' => TRUE);
            $fields['name'] = array('type' => '','label'=>'Your name');
            $this->form_builder->set_fields($fields);
    
            $validator = $this->form_builder->get_validator();
    
            //var_dump($validator);exit; //If I uncomment it, it echoes NULL
    
            $validator->add_rule('name', 'required', "This is required", array($this->input->post('name')));
    
            if (!empty($_POST)) 
            {
                if ($validator->is_valid()) 
                {
                    echo "validation succeeded";
    
                }
                else
                {
                    echo "validation failed";
                }
            }
        }
    } 
    
  • You need to move $this->load->library('validator'); above $this->load->library('form_builder');. The reason you are seeing a blank screen after that is because the code is working. You are checking for a $_POST variable which will be empty if you are just browsing to that page. You will need to submit a form that has a method of POST for that controller method to echo out anything.

  • edited April 2018

    Thank you, really so.

    I finally figured out how validator works (outside of the form_builder thus far). Here is a pure validator example, without dependencies on any other code. Would you consider to include an example like this in the documentation? I think it would make things so much clearer for the beginners of programming.

    <?php
    
    class Test2 extends CI_controller {
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function index()
        {
            //self-made function to validate against
            function is_ten($string){
                if ($string == 10) return TRUE;
                return FALSE;
            }
            $namevar = 'My Name';
            $emailvar = 'dd@dd.lt';
            $stringvar = 'TooLongAWordItIs';
            $datevar = date('Y-m-d',strtotime("+1 days")); //that is tomorrow; today date("Y-m-d") - would be considered past date
            $numbervar = '11';
    
            $this->load->library('validator');
    
            $this->validator->add_rule('name_key', 'required', "This is required", $namevar);
            $this->validator->add_rule('email_key', 'valid_email', "This should be a valid email address", $emailvar);
            // second array element of the last element of the method is the parameter that the method validates against:
            $this->validator->add_rule('string_key', 'length_max', "String should be shorter than 10 symbols", array($stringvar,10));
            $this->validator->add_rule('date_key', 'is_past_date', "It should be a past date (today is past as well)", $datevar);
            //in this case the second and third elements of the array are the parameters of function to validate against:
            $this->validator->add_rule('number_key', 'is_between', "Number should be between 10 and 20", array($numbervar,10,20));
            //now let us use self-made function; it could also be any php function returning TRUE or FALSE
            $this->validator->add_rule('number_key2', 'is_ten', "Should be 10", $numbervar);
    
            $this->validator->validate();
    
            if ($this->validator->is_valid()) 
            {
                echo "Validation succeeded";
            }
            else
            {
                $errors = $this->validator->get_errors();
                echo "Validation failed: <br><pre>";
                var_dump($errors);
            }
        }
    } 
    /* end of file ./fuel/application/controllers/Test2.php */
    
  • By the way, the http://docs.getfuelcms.com/libraries/validator definition of add_rule incorrectly explains (mixes up) the parameters thus:

    (string) $func error message
    (string) $msg function for processing
    
  • Below is a working example of a form with validation. I got the errors to display above the fields with $this->form_builder->display_errors = TRUE;

    The only thing I have not yet figured out is - how do I get the form to highlight the fields with errors?

    The controller file:

    <?php
    
    class Test3 extends CI_controller {
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function index()
        {
            /**** LOADING LIBRARIES ****/
            $this->load->library('validator');
            $this->load->module_language('fuel', 'fuel');//language should be loaded before form_builder class
            $this->load->library('form_builder');
            $this->form_builder->display_errors = TRUE;
    
            /**** CONSTRUCTING FORM ****/
            $fields['name'] = array('type' => '','label'=>'Name');
            $fields['email'] = array('type' => 'email', 'label'=>'Email');
            $fields['age'] = array('type' => '','label'=>'Age');
    
            $this->form_builder->set_fields($fields);
    
            /**** GETTING VALIDATION OBJECT ****/
            $validator = $this->form_builder->get_validator();
    
            $validator->add_rule('name', 'required', "The Name field is required", $this->input->post('name'));
            $validator->add_rule('email1', 'required', "The Email field is required", $this->input->post('email'));
            $validator->add_rule('email2', 'valid_email', "Field Email should contain a valid email address", $this->input->post('email'));
            $this->validator->add_rule('age', 'is_between', "Field Age should contain numbers in the interval from 10 to 20", array($this->input->post('age'),10,20));
    
            if (!empty($_POST))
            {
                $validator->validate();
    
                if ($validator->is_valid())
                {
                    $vars['valid']= "<p>Data validates!</p>"; 
                }
    // //             else
    // //             {
    // //               $errors = $this->validator->get_errors();
    // //               echo "Validation failed: <br><pre>";
    // //               var_dump($errors);
    // //               echo "</pre>";
    // //             }
            }
            $this->form_builder->set_field_values($this->input->post());
            $vars['form'] = $this->form_builder->render();
            $this->fuel->pages->render('test3', $vars);
        }
    }
    /* end of file ./fuel/application/controllers/Test3.php */
    

    The view file:

    <?php 
    if(isset($vars['valid'])) echo $vars['valid'];
    echo $vars['form'];
    /* end of file ./fuel/application/views/test3.php */
    
  • Is it perhaps a styling thing and are there classes being applied to the fields already and it just needs to be styled?

  • Thank you, it really is a styling thing: the fields with errors have a span element with class error_highlight. Once you add css

     .error_highlight {
         border-top: #FF0000 1px solid;
     }
    

    the fields get highlighted.

Sign In or Register to comment.