I have a custom entity with a constructor that calls a custom method (generateCharacteristics()) to generate random values for certain fields of my entity :
public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = array()) {
parent::__construct($values, $entity_type, $bundle = FALSE, $translations = array());
$values += $this->generateCharacteristics();
foreach ($values as $key => $value)
{
$method = 'set'.ucfirst($key);
// For two-words attributes
if( strstr($method, '_') ) {
$method = explode('_', $method);
$method[1] = ucfirst($method[1]);
$method = implode('', $method);
}
if (method_exists($this, $method))
{
$this->$method($value);
}
}
}
When I log what occurs in this __construct method when I create a new entity, all works fine, attributes are well setted, but in my database I have NULL or default values (the ones I declared in baseFieldDefinitions()). That's a shame because I think that baseFieldDefinitions() is put in cache (not good for random values) and that my method using constructor is cleaner.
Maybe my error is to think that $values array is the array we send during the call of Entity::create() method because this $values array seems always empty before I add my own array to $values... Nevertheless I set my attributes correctly in the constructor. The use of a postCreate() method should be more appropriate ?
thanks !
parent::_construct
after$values += $this->generateCharacteristics();
. I don't think you even need to call those setter methods. It should get set in the parent constructor.Entity::save()
separately. Since you say it works when you inspect it, I figured this might be the cause.