Kohana 3.1 ORM: empty model property value stored as 0 (zero) instead of NULL

I have two models: Product and Product_Methodology. In my view of product editing, I have a selection box for choosing one of many methodologies or not (empty first option). In my product table, I have a property INT(10) methodology_idthat is saved with the identifier of the methodology selected from the selection form field. Until today, everything worked fine, and I had to make adjustments to the system, in which now the choice of methodology may be additional. Therefore, I changed the field of methodology_idthe product table to resolve the value NULLand deleted not_emptythe model validation rule .

The problem is that now, when I save the model that selects an empty parameter, instead of the expected one NULL, I get a value 0(zero).

Any clue to this? Thank you very much and let me know if this is not so clear.

+3
source share
4 answers

What input form do you use to select a methodology? is it <select>? If so, the choosen parameter value is probably set to 0 when no methodology is selected, and submit with other form data.

In such cases, I create my own filter with a model method filters()to set the value to NULL (since PHP refers to it) when it is empty(), something like this:

public function filters()
{
    return array(
        'methodology_id' => array(
            array('Filter::null', array(':value')),
        ),
    );
}

- . ...

class Kohana_Filter {

    public static function null($value)
    {
        return (empty($value) ? NULL : $value);
    }

}

, :)

+6

, - NULL. 0 INT ( , mysql). , :

$methodology_id = (empty($methodology_id) ? NULL : $methodology_id);
+1

NULL, :

public function filters()
{
    return array(
        // Return a NULL value if empty string.
        'field_name' => array(
            array(function($value){
                return ($value === '') ? NULL : $value;
            }, array(':value')),
        )
    );
}
+1

, 0.

not_empty . , , product_methodology, .

ORM :

public function exists_or_zero(Validation $validation, $field, $model, $pk)
{
    // The exists() function is only called if the field has a non-zero value
    if ($validation[$field]) {
        $this->exists($validation, $field, $model, $pk);
    }
}

public function exists(Validation $validation, $field, $model, $pk)
{
    if ( ! ORM::factory($model, $pk)->loaded()) {
        $validation->error($field, 'exists', array($validation[$field]));
    }
}

If you use these functions, you will be in the product class :

public function rules()
    return array(
        'product_methodology_id' => array(
            array('not_empty'),
            array(array($this, 'exists_or_zero'), array(':validation', ':field', 'product_methodology', ':value')),
        ),
    );
}
0
source

All Articles