2

I'm having trouble with the two ways of defining forms for entities in Drupal (the first one being in the entity field definitions and the second one being by defining a custom form class).

Now, in a classic form, all I have to do is add an element with the entity_autocomplete type and set #autocreate to array('bundle' => 'foo'). I tried replicating this in various ways in my entity, none of which worked out (I tried via BaseFieldDefinition's setSetting or in the display options for the form).

What I don't understand is why the two ways of defining forms are so different? Why can't it just be the same syntax in both places?

I'm aware of the Inline Entity Form module, but there doesn't seem to be a proper port for Drupal 8 yet, and what I'm trying to do works perfectly fine when I define the form manually as explained. I just want to be able to define all this in my entity directly to avoid unnecessary code.

1 Answer 1

3

I finally found a way to get it to work after digging through the code for the EntityReferenceAutocompleteWidget. To enable automatic creation, I needed to edit the handler settings. Here's my code:

$fields['client'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Client'))
  ->setSettings(array(
    'target_type'      => 'client',
    'handler'          => 'default',
    'handler_settings' => array(            // Added
      'auto_create'    => TRUE              // Added
    )
  ))
  ->setDisplayOptions('form', array(
    'type'     => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size'           => 60,
      'placeholder'    => ''
    ),
    'weight'   => 0
  ))
  ->setRequired(TRUE);
3
  • You probably have the same problem I had here. Try using setSetting instead of setSettings and only define the settings one by one
    – alexej_d
    Commented Apr 2, 2015 at 12:28
  • I thought so too at first, but that wasn't it. The code I posted in my answer works. I'd accept it, but apparently I need to wait another 22 hours.
    – PLPeeters
    Commented Apr 2, 2015 at 13:07
  • Yes, it works because you set all the required arguments, but you would for example drop the default value for 'handler' if you wouldn't set it. I'd recommend to switch to 2 setSetting($name, $value) calls, then you don't need to set the default value for handler.
    – Berdir
    Commented Apr 3, 2015 at 11:13

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.