-1

How do I change a value, in this case the title field of a node object form, in the preprocess function of the form_alter hook.

$form['actions']['publish']['#submit'][] = MODULE_submit_preprocess';

function MODULE_submit_preprocess($form, FormStateInterface $form_state) {

   $form_state->setValue('title', 'Updated Title'); //not working...

   $fstate = $form_state->getFormObject()->getEntity();
   dsm($fstate);
}

dsm result

stdClass Object
(
    [__CLASS__] => Drupal\node\Entity\Node
    [in_preview] =>
    [values] => Array
        (
            [title] => Array
              (
                  [x-default] => Array
                    (
                         [0] => Array
                          (
                             [value] => Old Title
  • In this case, maybe it is better use MODULE_ENTITY_presave() function. After submit and before save in db, Drupal call this function then you can change something in your entity. If you want to change a node, then use MODULE_node_presave(). And will be called when you create and update. – Vagner May 10 '16 at 18:19
  • That is a viable answer and accomplishes the task. – Jeff W Petersen May 10 '16 at 18:41
1

To change Entities fields its better use MODULE_ENTITY_presave() function (more info in docs).

In this case that you need change a node field use this function:

function hook_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->set('title', 'Updated title');
}
  • Then to change the title before saving to database: $entity->title='Updated Title'; – Jeff W Petersen May 10 '16 at 18:54
  • I have a utility field, populated via javascript, that was added in the form_alter hook that I use to set the field_date before submitting. The field only exists in $form_state and is not available to hook_presave. So I still need to know how to alter a value in the preprocess callback. I can add the field to the entity, but it would be nice to be able to do it in code. – Jeff W Petersen May 11 '16 at 14:26
  • I think that you can overthinking a problem, maybe there is another way much easier to do what you need. Back to your situation, maybe you can use $fstate that actually is your Node, and use Node::setTitle. In your question shows 'old value' because you just changing FormState object instead your Node. – Vagner May 11 '16 at 15:00

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.