1

Hello everyone how are you?

I created a new configEntity called Modal with 3 fields:

  1. Label
  2. Body
  3. Auto Open

To create a new Modal I'm using this code:

$modal = \Drupal::entityTypeManager()->getStorage('modal')->create();

$modal->setLabel('Modal Title');
$modal->setBody('Modal Content');
$modal->setAutoOpen(TRUE);
$modal->save();

OK! It works!

But now I don't want to pass "auto-open" and I this value with TRUE as default. Like this:

$modal = \Drupal::entityTypeManager()->getStorage('modal')->create();
        
$modal->setLabel('Modal Title');
$modal->setBody('Modal Content');
$modal->save();

Note that there is no "Auto-Open" and it inserts a new Modal with "auto-open" = FALSE

My goal is; if you don't pass "auto-open" this field is filled with TRUE by default.

Do you know how can we do this? 🤔

Thank you so much, everyone

2
3

For entities in general, set default values by adding preCreate() to your entity class:

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'auto_open' => TRUE,
    ];
  }

In this specific case, define a class property with the same name as the field, which defaults to TRUE:

  /**
   * Auto Open.
   *
   * @var bool
   */
  protected $auto_open = TRUE;
2
  • And that it gets set to FALSE as in the OP when omitted is because it's a Boolean and it simply is the default for Booleans? – leymannx Nov 9 '20 at 15:52
  • 1
    @leymannx, I did answer to the question title in general, for all entities. But I'm now seeing what you are referring to. In the linked code example of a config entity class the properties look a bit weird. Camel case for snake cased fields and without default, so initializing as NULL. So there are two reasons the boolean probably doesn't start with FALSE. – 4k4 Nov 9 '20 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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