1

I have a custom form that I created programmatically.

    $target_type = 'node';
    $selection_handler = 'default';

    $selection_settings = ['page'];
    $data = serialize($selection_settings) . $target_type . $selection_handler;
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    $key_value_storage = \Drupal::keyValue('entity_autocomplete');
    if (!$key_value_storage->has($selection_settings_key)) {
      $key_value_storage->set($selection_settings_key, $selection_settings);
    }


    $form['terms_default_node'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Terms of Business - default page'),
      '#autocomplete_route_name' => 'system.entity_autocomplete',
      '#autocomplete_route_parameters' => [
        'target_type' => $target_type,
        'selection_handler' => $selection_handler,
        'selection_settings_key' => $selection_settings_key,
      ],
      '#default_value' =>  \Drupal\node\Entity\Node::load(1)->value, // What do I put here?
    ];

I don't get how to make the default value of the field be "Terms of Business (1)".

Autocomplete works, saving works, but I don't know how to recall that saved value again and make it as default_value when I open this form again.

This field doesn't have any widgets, etc. And I can't find anything in Google

2

1 Answer 1

1

This whole approach of entity autocomplete is not okay. Here is the correct way, and also it accepts Node Object as the default value well.

    $form['terms_default_node'] = [
      '#title' => $this->t('Terms of Business - default page'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#selection_handler' => 'default',
      '#selection_settings' => [
        'target_bundles' => ['article', 'page'],
      ],
      '#default_value' => $this->entityTypeManager->getStorage('node')->load($id), // Dependency injection.
    ];

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.