【问题标题】:How do you modify entity references on a form in a custom ajax action in Drupal 8?如何在 Drupal 8 的自定义 ajax 操作中修改表单上的实体引用?
【发布时间】:2018-05-15 23:43:21
【问题描述】:

我在表单中添加了一个自定义按钮:

    $form['actions']['autotag_content'] = [
     '#type' => 'button',
     '#value' => 'Autotag Content',
     '#ajax' => [ 
       'callback' => ['\Drupal\taxonomy_migrate\taggerService', 'tagContent'],
       'wrapper' => ['block-adminimal-theme-content'],
       'progress' => [ 
         'type' => 'throbber',
         'message' => 'Tagging content',
       ],
     ],
   ];

然后在回调中,我想在表单上的实体引用字段中添加或删除实体。然后,这将被发送回浏览器并重新呈现。我不想保存更改,我只想将它们填充到表单中,然后用户可以接受更改。

为了这个例子,我已经简化了这个只是为了说明这一点。我想向 field_tax_subjects 添加两个实体引用并重新呈现前端表单。目前,前端表单重新呈现,但不反映更改

public static function tagContent(array &$form, FormStateInterface &$form_state) {
  $node = $form_state->getFormObject()->getEntity();

  $node->field_tax_subjects[] = 12345;
  $node->field_tax_subjects[] = 23456;

  $form = \Drupal::service('entity.form_builder')->getForm($node);
  $form_state->setRebuild();

  return $form;
}

【问题讨论】:

    标签: drupal drupal-8 drupal-forms drupal-form-submission


    【解决方案1】:

    我的回答只是为了以防你的 ajax 工作正常 因为在你的问题中你没有完整的表格代码 也不清楚它的节点形式或其他东西 任何方式

    如果您的 ajax 工作正常,您只需更正如何为实体引用字段和术语引用字段设置值

    用于实体引用和术语引用

    public static function tagContent(array &$form, FormStateInterface &$form_state) {
      $node = $form_state->getFormObject()->getEntity();
    
      // for entity refrence
      $node->field_tax_subjects[]['target_id'] = 12345;
      $node->field_tax_subjects[]['target_id'] = 23456;
    
      // for term reference
      //$node->field_tax_subjects[]['tid'] = 12345;
      //$node->field_tax_subjects[]['tid'] = 23456;
    
      $form = \Drupal::service('entity.form_builder')->getForm($node);
      $form_state->setRebuild();
    
      return $form;
    }
    

    希望对您有所帮助

    谢谢

    【讨论】:

    • 感谢您的评论,但我认为语法不正确。当我使用该语法时,我得到“发生致命错误:无法在列表中获取具有非数字增量的值。”
    • $node->field_tax_subjects[]['target_id'] = 12345;这是 100% 测试的,但现在你的错误是关于获取价值而不是关于设置价值我告诉你你的代码不完整
    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多