0

How do I autopopulate fields in a node form in drupal 8?

Basically, what I'm trying to do is create an ajax callback to autopopulate fields based on a call to a 3rd party service.

So I'm using hook_form_alter and a custom validate function, and I'm trying to update form values.

function mymodule_validate($form, FormStateInterface &$form_state) {

  $form_state->setValue('title', [['value' => 'testing 123']]);

  $form_state->setRebuild();

}

But this doesn't update the node title.

What's the correct way to alter values in a node form in an ajax callback?

0

You can hide the field_teaser_title from the node from (set its widget to hidden) then use hook_entity_presave to update its value. Finally show this field in teaser mode.

  • I updated the question. This questions is out of date. – oknate Dec 13 '16 at 22:46
0

I was able to get a basic autopopulation callback working based on this question:

How do I modify a core field to use Ajax and add markup?

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Implements hook_form_alter() on behalf of mymodule.module.
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_publication_form') {

    $form['title']['widget'][0]['value']['#value'] = 'enter title here';

    $form['import_from_third_party_service_id'] = [
      '#type' => 'textfield',
      '#title' => t('Import from third_party_service Id'),
      '#description' => t('To autopopulate fields from third_party_service, enter the third_party_service ID above in the textfield above and hit the import key below'),
      '#maxlength' => 64,
      '#size' => 8,
      '#weight' => '-10',
    ];

    $form['import_from_third_party_service_submit'] = array(
      '#name' => 'custom',
      '#type' => 'submit',
      '#value' => t('Import'),
      '#weight' => -9,
      '#ajax' => [
        'callback' => 'mymodule_import_ajax_callback',
        'wrapper' => 'import-wrapper',
      ],
    );

    $form['#prefix'] = '<div id="import-wrapper">';
    $form['#suffix'] = '</div>';

  }
}

function mymodule_import_ajax_callback($form, &$form_state) {

  // replace with code to get value from third party service
  $new_title = 'hello world';

  $form['title']['widget'][0]['value']['#value'] = $new_title;

  return $form;
}

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.