Andreas Witte
Andreas Witte

Reputation: 291

Cakephp3: Using NULL in Form input as options

I am trying to get null inserted into my database by using a FormHelper input.

Options should be:

<?= $this->Form->input('preferedtimeformat', [
        'label' => __('prefered representation of date and time'),
        'options' => [
            NULL => __('standard of your locale'),
            'yyyy-MM-ddThh:mm:ss.sTZD' => __('ISO 8601 (yyyy-MM-ddThh:mm:ss.sTZD)'),
            'eee, dd MMM yyyy hh:mm:ss xx' => __('RFC 2822 (eee, dd MMM yyyy hh:mm:ss xx)'),
            'h:m:s d.M.yyyy' => __('german style (h:m:s d.M.yyyy)'),
            'd.M.yyyy h:m:s' => __('invers german style (d.M.yyyy h:m:s)')
            ...some more options...
        ]
    ]) ?>

This should help the user specifying another Datetimeformat if he wants or needs to. Time::i18nFormat() accepts null as Datetimeformat and then uses the presets of the locale you give to it.

But creating a user with the NULL option from a form doesn't work, so I get an empty string ant not null saved into the database.

Is there any better solution than checking in the controller for an empty string and replacing it by NULL?

Upvotes: 0

Views: 541

Answers (1)

ndm
ndm

Reputation: 60453

Of course you'll end up a string in the database, HTML can only "send" strings, all input received by PHP is of type string, and your database column is a string type too.

If you want an empty string to be treated as NULL, you should use a mutator in the correspending entity, which turns '' into null, for example something like

class Xyz extends Entity
{
    protected function _setPreferedtimeformat($value)
    {
        if (empty($value)) {
            return null;
        }
        return $value;
    }
}

See also Cookbook > Database Access & ORM > Entities > Accessors & Mutators

Upvotes: 2

Related Questions