FuelPHP Input arrays validation

After pulling some hair and digging a lot in FuelPHP core I finally discovered a litle hack that allows validation of input arrays and its re-population using FuelPHP Validation Class.

Here’s how I did it:

View simplified for the sake of the example:

<?php echo \Form::label("Price", "options[0][price]"); ?>
<?php echo \Form::input("options[0][price]", \Validation::instance()->input("options.0.price"); ?>

<?php echo \Form::label("Name", "options[0][name]"); ?>
<?php echo \Form::input("options[0][name]", \Validation::instance()->input("options.0.name"); ?>

<?php echo \Form::label("Price", "options[1][price]"); ?>
<?php echo \Form::input("options[1][price]", \Validation::instance()->input("options.1.price"); ?>

<?php echo \Form::label("Name", "options[1][name]"); ?>
<?php echo \Form::input("options[1][name]", \Validation::instance()->input("options.1.name"); ?>

Mind the options.0.name instead of options[0]name inside the Validation Input.

In my controller I did this:

$val = \Validation::factory();

if ( \Input::post("options") )
{
    $form_options = \Input::post("options");

    foreach ( $form_options as $form_id => $option )
    {
        $val->add("options.{$form_id}.price", "{$option["name"]} price")
                ->add_rule("required")
                ->add_rule("match_pattern", '/[0-9]*(\.|,)?[0-9]+/');

        $val->add("options.{$form_id}.name", "{$option["name"]} name")
                ->add_rule("required");

    }
}

 

And that’s it, this should validate the fields and repopulating them in case of errors. It’s a bit stupid that it only works like this.

FuelPHP should provide a friendlier way and a documented one to validate array input fields, it’s a common feature when dealing with dynamic built forms that have one-to-many objects in it.

 

Tested with FuelPHP 1.0.1

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>