CakePHP: Submit 0 instead of NULL for a database column that doesn’t allow NULLs

Problem: Error: SQLSTATE[23000]: Integrity constraint…

Login

Blog History

Problem: Error: SQLSTATE[23000]: Integrity constraint violation: 1048 column 'inventory_status_id' cannot be null

cakephp_error_empty_post_value

Cakephp returns the above error when I'm trying to POST a removal of an integer from a field.

Cause: The form was sending a blank value back to the cakephp, this was making the value into NULL and so causing the database to object with the above error.

Resolution: Instead of specifying empty => true which would make the control look like:

<select name="data[Label][inventory_status_id]" id="LabelInventoryStatusId">
    <option value="" selected="selected"></option>
    <option value="1">HOLD</option>
</select>

Change the view code for the control to specify the 'empty' value as something the database will not choke on

# before this would send "" nothing back
echo $this->Form->input(
    'inventory_status_id', 
    array(
        'options'=> $inventory_statuses, 
        'empty' => true
    )
);

# after the empty option is assigned a value of '0'
echo $this->Form->input(
    'inventory_status_id', 
    array(
        'options'=> $inventory_statuses, 
        'empty' => array(0 => '(no status)')
    )
);

The change will then output:

<select name="data[Label][inventory_status_id]" id="LabelInventoryStatusId">
    <option value="0" selected="selected">(no status)</option>
    <option value="1">HOLD</option>
</select>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.