4

I need change a value to element on form validation.

I have this code:

/**
 * Implements hook_form_FORM_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'block_content_MY_BLOCK_form' || $form_id == 'block_content_MY_BLOCK_edit_form') {
    $form['#validate'][] = '_custom_validate';
  }
}

I want change the value of field field_test. This field is plain text.

function _custom_validate($form, FormStateInterface $form_state) {
  $form_state->setValueForElement($form['field_test'], 'changed');
}

But when I saved this block, the field field_test doesn't change its value.

What I am doing wrong?

6
+50

Please insert the validate method inside the #element_validate function and then change the element value.

/**
 * Implements hook_form_FORM_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'block_content_MY_BLOCK_form' ||  $form_id =='block_content_MY_BLOCK_edit_form') {
       $form['field_test']['widget'][0]['#element_validate'][] = '_custom_validate';
      }
    }

function _custom_validate(&$element, FormStateInterface $form_state, &$complete_form) {
  $form_state->setValueForElement($element,['value' => 'See the change']);
}
0

Use setValue function to change textfield value.

function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'block_content_MY_BLOCK_form' || $form_id == 'block_content_MY_BLOCK_edit_form') {
    $form['#validate'][] = '_custom_validate';
  }
}

function _custom_validate(&$form, FormStateInterface $form_state) {
  $form_state->setValue('field_test', 'changed');
}
0

Your code looks like it should work, according to the docs for setValueForElement(). I couldn't get it to work that way, either.

There's what eventually worked:

$title = t(
  '@user enrolled in @class',
  ['@user' => $userName, '@class' => $classTitle]
);
$formState->setValue('title', [['value'=>(string) $title]]);

If the field has other attributes, like a format name for a rich text field, you might have to add the attributes, too:

$formState->setValue('field_notes', [['value'=>'Dogs are great!', 'format'=>'skilling']]);

Something else that might help. In hook_alter, my code hides the field that will have its value computed. However, the field needs a value to keep Drupal happy:

// Hide the title. Compute it from other elements.
$form['title']['#type'] = 'hidden' ;
// Need to give the field a default value, for Drupal's validation code
// to get to the point where a value for the field can be computed. 
$form['title']['widget'][0]['value']['#default_value'] = 'Dogs are the best!';

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.