Form alter + Unlimited Values + Entity Reference Field

by Techd   Last Updated May 22, 2020 18:07 PM - source

  • There are two fields, News Type (Selectbox), News (Reference Entities, Unlimited option, autocomplete)
  • When user select a news type, options of News fields needs to revised.
  • Example: Selecting World needs to display the News related to World.
  • I have added the ajax callback to get the revised data
  • I received the options
  • But when i submit the form or click on add more it says "This entity (node: 6) cannot be referenced. "
function featured_news_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['field_featured_news']['#prefix'] = '<div id="news-wrapper">';
  $form['field_featured_news']['#suffix'] = '</div>';

  $form['field_news_type']['widget']['#ajax'] = [
    'callback' => 'updateNews',
    'disable-refocus' => FALSE,
    'event' => 'change',
    'wrapper' => 'news-wrapper',
    'progress' => [
      'type' => 'throbber',
      'message' => t('Loading...'),
    ],
  ];

  if (!empty($values) && !empty($values['field_news_type'])) {
    $type = $form_state->getValue('field_news_type')[0]['value'];
    foreach ($form_state->getValue('field_featured_news') as $key => $value) {
      $form['field_featured_news']['widget'][$key]['target_id']['#selection_settings']['view']['arguments'][0] = $type;
    }
  }
}

function updateNews(&$form, FormStateInterface $form_state) {
  return $form['field_featured_news'];
}
Tags : forms ajax


Related Questions



Access Denied when Menu CallBack Function is Called

Updated April 20, 2015 06:03 AM