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))


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 !

  • There's a lot happening in the parent constructor (You should take a look). Try running 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.
    – Beebee
    Commented Oct 24, 2017 at 15:18
  • 1
    You do save the entity right? Just creating it only instantiates the entity, but it is gone once the request ends. You have to call Entity::save() separately. Since you say it works when you inspect it, I figured this might be the cause. Commented Oct 25, 2017 at 18:44

1 Answer 1


Entity::create gets the storage for the entity type and calls EntityStorage::create. What you are looking for is probably the method Entity::preCreate, which is the first entity event invoked by EntityStorage::create.

Place it as public static function in the custom entity class to change the values before the entity is created:

class CustomEntity extends ContentEntityBase {

   * {@inheritdoc}
  public static function preCreate(EntityStorageInterface $storage, array &$values) {
    // modify $values


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.