In Phalcon2, is it possible to allow a null value for the default selection in a select box? (Keep in mind I've read multiple forum posts and still don't have a clear understanding.)
For example, let's say I have a concept of a News Post in my system, and each News Post has one Category asssociated with it. So I can initialize a Select element and show a list of Categories with a default "None" selection at the top.
$el = (new Select('category_id', Category::find(), [ 'using' => ['id', 'name'], 'useEmpty' => true, 'emptyText' => 'None', 'emptyValue' => null, ]))
Ideally, this would have been all I needed so that if a user selected the "None" option, a NULL would be placed in the database for the "categoriy_id" column.
Here is some code I have in the News Post model. The beforeValidation method fixes my problem but I don't want to have to add this to every model that has this sort of case.
public function initialize() { $this->belongsTo('category_id', 'Category', 'id', [ 'reusable' => true, 'foreignKey' => [ 'allowNulls' => true, 'message' => 'Bad Category ID', ] ]); } public function beforeValidation() { if ($this->category_id == '') { $this->category_id = null; } }
Any ideas on how I can fix this on a more general level? Perhaps something I could add to my Base Model class that would solve this problem for foreign keys that I will allow to be NULL.