0

I'm building a block plugin that allows users to specify a menu to appear in a block plugin. I'm taking advantage of the EntityAutocomplete form element.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/class/EntityAutocomplete/8.2.x

Here is how the form is built.

public function blockForm($form, FormStateInterface $form_state) {
    $form['menu'] = [
        '#type'          => 'entity_autocomplete',
        '#target_type'   => 'menu',
        '#default_value' => $this->configuration['menu'],
    ];
    return $form;
}

It's able to display the form element just fine. And it allows users to select menus as well. I then save the item on submit like this.

public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['menu'] = $form_state->getValue('menu');
}

However after saving it and opening it again I receive this error

InvalidArgumentException: The #default_value property has to be an entity object or an array of entity object

How do I successfully save or retrieve the menu? Do I need to put something like $this->configuration['menu']['value']?

Update: When I perform

die(print_r($this->configuration['menu']));

It just prints the machine name of the menu I selected. So maybe the issue is that the default value it's being supplied is just a string instead of the actual entity? But if so how would I get the entity from the machine name?

Update 2: I tried using

$menu = Entity::load($this->configuration['menu']);
die(print_r($menu));

But that didn't produce anything.

1 Answer 1

4

I was able to resolve the issue by loading the entity first like so

$menu = \Drupal::entityTypeManager()->getStorage('menu')->load($this->configuration['menu']);
    $form['menu'] = [
    '#type'          => 'entity_autocomplete',
    '#target_type'   => 'menu',
    '#default_value' => $menu,
];

The value of $this->configuration['menu'] was only the machine name, not the actual entity. So the entity had to be loaded and stored in a variable first.

Your Answer

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

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