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

Written by James McDonald

March 11, 2015

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.

You May Also Like…

Clear HSTS Settings in CHrome

Open chrome://net-internals/#hsts enter the domain in the query field and click Query to confirm it has HSTS settings...

Ubuntu on Hyper-v

It boils town to installing linux-azure # as root or sudo apt-get update apt-get install linux-azure...