user198003
user198003

Reputation: 11151

CakePHP how to submit NULL value?

On web form I have select-option field. It have to submit value 'card' (without quotes), or NULL value.

Now, code looks like this:

    $options = array(NULL => 'Invoice', 'card' => 'Payment card');
    echo $this->Form->input('payment_method', array('options'=>$options));

How can I define options array, to submit NULL value in database table (and/or 'card', but that works of course), in case that Invoice option is selected?

Thank you in advance!

Upvotes: 4

Views: 5870

Answers (1)

thaJeztah
thaJeztah

Reputation: 28987

NULL is an invalid key for an associative array. Only 'integers' and 'strings' are valid array keys, see the documentation: Arrays

To send an empty value through the form, you can use an empty string. To force inserting a NULL value in the database, handle this inside your model or controller before saving

$options = array('' => 'Invoice', 'card' => 'Payment card');
echo $this->Form->input('payment_method', array('options'=>$options));

Then inside your controller;

if ('' === $this->request->data['MyModelName']['payment_method']) {
     this->request->data['MyModelName']['payment_method'] = null;
}

Alternative approach

However, why not use a value for the 'invoice' payment method? Like this:

echo $this->Form->input('payment_method', array(
    'options' => array(
        ''        => 'Select your payment method..',
        'invoice' => 'Invoice',
        'card'    => 'Payment card',
    )
));

IMO this has some advantages;

  • it's more transparent, e.g. When looking inside the database, it's clear that the payment method is 'invoice'. By using a 'special' value (null), people without knowledge of your applications inner workings will have to browse through the source code to find out
  • it's possible to check if the use has selected a payment method; e.g. If the value is empty, the use may have forgotten to select a payment method, in which case you can mark the field 'invalid' via a validation rule.

Upvotes: 4

Related Questions