CakePHP 4: 'Column' cannot be null, but default value defined in database

I have a number of non-nullable fields in my database, for which I have provided default values. For example:

invest_poc_id int(11) NOT NULL DEFAULT 0

When I debug in my edit method, I see the default value upon page load.

'invest_poc_id' => (int) 0`

Field is marked dirty after post.

However, upon POST, the value is null and the default value of the field is ignored. I don’t want to make this field nullable, nor do I want to disable strict mode in my application. What can I do to make my app recognize the default value of these fields?

This isn’t the answer to your question, but more of a design approach. You’re mixing your technologies, in that using CakePHP for some default fields, and your Database for others. So I would be setting all default values in the CakePHP, in the Model/table. That way I only have one place to look and to check for those fields value.

A classic example is the timestamp where in your table you put created and modified fields, but you use your initialize(} $this->addBehavior('Timestamp'); for the “default” values. This allows your app to work on different database paradigms, and someone else if they ever need to maintain it should follow your thinking.

But, as your question asks, I don’t know why it wouldn’t pull the table’s defaults - maybe track down the INSERT query CakePHP is creating to see if it is populating those fields will a null value.

Upon form submission, debug shows that the value of the field is null instead of 0. I even have default => 0 configured on the form control and I still get the error.

Any chance that this is just a result of not clearing your ORM cache?

Ah Zuluru beat me to it! If you changed your table structure it’ll be the cache. Also check your spelling of variable/field name is correct.

Clearing the cache using cake cache clear_all didn’t help. Should I try something else?

Just sometimes seems like 50% of the posts on here could be skipped if there was a “did you clear your ORM cache?” question before posting. :slight_smile:

The cache clear command doesn’t always work for me, make sure that tmp/cache/models is empty after doing it.

1 Like

I logged out of my app, closed/reopened the browser, ran cake cache clear_all again, looked in tmp/cache/models and confirmed that the directory was empty. Problem persists. No matter what I do, Cake always makes that field null instead of 0 on submit if it doesn’t have a value.

I know this is a big ask, but maybe we are at the stage where you can put together a small project which duplicates this behaviour? Just that table and its controller/model/view files; so with the problem running and with full source the solution will be found. You may even find what is causing it by putting that demo together. Like, it could be a bug in the validator or anything! If you host it do not turn on debugging!