在 Drupal 8 中,如何在保存节点之前操作值?

O C*_*nor 5 php drupal drupal-8

我有一个编辑节点表单。当用户输入新值并单击提交来编辑节点时,我首先想取回旧节点,操作该值,然后保存/更新节点。

以下是我的解决方案,但它不起作用。

function custom_module_form_node_form_alter(&$form, FormStateInterface $form_state) {
    $editing_entity = $form_state->getFormObject()->getEntity();

    if (!$editing_entity->isNew()) {
        $form['actions']['submit']['#submit'][] = 'custom_module_node_form_submit';
    }
}

function custom_module_node_form_submit($form, FormStateInterface $form_state) {
   $editing_entity = $form_state->getFormObject()->getEntity();

   $entity = Drupal::entityTypeManager()->getStorage('node')->load($editing_entity->id());
}
Run Code Online (Sandbox Code Playgroud)

在 form_submit 钩子中,我尝试取回旧节点,但已经太晚了,节点已经更新/保存。在 Drupal 8 中更新/保存节点之前,如何取回旧节点并操作该值?

O C*_*nor 5

我决定按如下方式操作表单验证挂钩中的值。

function custom_module_form_node_form_alter(&$form, FormStateInterface $form_state) {
    $editing_entity = $form_state->getFormObject()->getEntity();

    if (!$editing_entity->isNew()) {
        $form['#validate'][] = 'custom_module_node_form_validate';
    }
}

function custom_module_node_form_validate(array &$form, FormStateInterface $form_state) {
    $old_entity = $form_state->getFormObject()->getEntity();
    $old_values = $old_entity->get('field_name')->getValue()

    $new_values = $form_state->getValue('field_name');

    // Manipulate and store desired values to be save here.
    $to_save_value = ['a', 'b', 'c'];
    $form_state->setValue('field_name', $to_save_value);
}
Run Code Online (Sandbox Code Playgroud)


Mil*_*anG 4

尝试使用hook_entity_presave()

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  switch ($entity->bundle()) {
    // Here you modify only your day content type
    case 'day':
      // Setting the title with the value of field_date.
      $entity->setTitle($entity->get('field_date')->value);
     break;
  }
}
Run Code Online (Sandbox Code Playgroud)

从这里获取的解决方案:https://drupal.stackexchange.com/questions/194456/how-to-use-presave-hook-to-save-a-field-value-as-node-title

您还可以获得旧值,例如:$entity->original。在这里查看:

https://drupal.stackexchange.com/questions/219559/how-to-get-the-original-entity-on-hook-entity-presave