Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Is there a way to access the other fields when using a custom validation?
  • Hello,

    I'm now trying to use Fieldset to make a form and would like to validate in a custom way, but I have an issue on accessing some fields.

    My code is below.


    class SampleFormFieldset extends Fieldset {
    function __construct() {
    $this->validation()->add_callable('CustomValidation');
    $this->add('field_1', 'Field 1')->add_rule('custom');
    $this->add('field_2', 'Field 2');
    }
    }

    class CustomValidation {
    function _validation_custom($val) {
    // I'd like to check the value of field_2 here.
    // Ex. if the value of field 1 is 1, then 2 must be 1, and if the value of field 1 is 2, then field 2 must be 4, etc.
    }
    }

    class SampleController {
    function action_sample() {
    $form = new SampleFormFieldset();
    $val = $form->validation();
    if(Input::method() == 'POST' && Security::check_token() && $val->run()) {
    // do something
    }
    }
    }


    What I'd like to achieve is that accessing the value of field 2 from the function `_validation_custom` called through the validation process of the field 1.


    I could access the value by using Input::post('field_2') in the function `_validation_custom`, but would like to access via more appropriate way if possible. (For me it's a bit strange to access Input::post from validation function...)

    Any suggestions?

  • If you want to access another field while validation one, check rules like "match_field" or "required_with" in the Validation class. Both do that.
  • Hi Verton,

    Thanks for the comments.
    I saw the Validation class and found a way to achieve.

    Here is the change I made.


    class SampleFormFieldset extends Fieldset {
    function __construct() {
    $this->validation(CustomValidation::forge($this)); // this sets the extended validation object used for this validation
    $this->add('field_1', 'Field 1')->add_rule('custom', 'field_2');
    $this->add('field_2', 'Field 2');
    }
    }

    class CustomValidation extends Validation {
    function _validation_custom($val, $field_name) {
    $field_value = $this->input($field_name);
    // Use $field_value
    }
    }



    Connecting custom validation object with the Fieldset object did solve the problem.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion