1

I want to set the value of a field of a term based on a custom field set on the vocabulary. Basically if the vocabulary promote_to_index field is checked I want to the field_index_page of the term checked.

I understand I have to write a hook like but I don't understand how to get the value of the vocabulary custom field

function polaris_drupal_taxonomy_form_alter(&$form, FormStateInterface &$form_state, $form_id) {

  switch ($form_id) {

    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['field_index_page']['widget']['value']['#default_value'] = true;
  }
}
1

You can add an extra validation step to those forms that checks and changes the value accordingly like so.

function polaris_drupal_taxonomy_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['#validate'][] = '_polaris_drupal_add_field_index_page';
  }
}

function _polaris_drupal_add_field_index_page(&$form, FormStateInterface $form_state) {
  $promote_to_index = $form_state->getValue('promote_to_index');
  if ($promote_to_index['value']) {
    $form_state->setValue('field_index_page', [ 'value' => TRUE ]);
  }
  else {
    $form_state->setValue('field_index_page', [ 'value' => FALSE ]);
  }
}

This will check the field promote_to_index of the form and set the field field_index_page before executing the submit handlers of the 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.