How to supress required column in phalcon's model when saving an empty string
lang_of_article_differ
want_proper_trans
When using phalcon's models there are situations when model won't to save into database and there is no exceptions raised.
Example
Lets assume we have model Post
in our project:
class Post extends \Phalcon\Mvc\Model {
public $id;
public $title;
public $body;
}
Fields title
and body
in database are NOT NULL
. Presumably there shoudn't be a problem by executing following code, because we provide an empty string to those columns and they are not null in fact:
$newPost = new Post();
$post->title = '';
$post->body = '';
$post->save(); // object is not saved actually
But we got next errors from $post->getMessages()
:
Array
(
[0] => Phalcon\Mvc\Model\Message Object
(
[_type:protected] => PresenceOf
[_message:protected] => title is required
[_field:protected] => title
[_model:protected] =>
)
)
Phalcon says that we didn't provide value to the field and it can't be blank, because structure in database doesn't allow NULL
.
It seems horrible to me when model doesn't save and says nothing, but it can be solved.
Solution
-
The very naive solution is to change the columns structure in the database to allow
NULL
values on that column. -
The another solution is within phalcon. You can easily say to the model that you allow empty strings on some columns by
allowEmptyStringValues
method. You can set it in model'sinitialize
:public function initialize() { $this->allowEmptyStringValues(['title','body']); }