如何在Drupal 8中将参数从hook_form_alter传递给ajax回调

问题描述 投票:0回答:1

我正在尝试实现一个hook_form_alter方法,以通过以节点形式显示的ajax回调来修改一个字段的行为。

想法是,当我从选择列表字段(field_country)中选择一个选项时,修改其他字段列表(field_laws)的值。具体来说,当我选择一个国家/地区时,hook方法通过ajax回调将此值(当前)传递给changeLawsData。此回调获得一个外部服务,该服务返回由先前选择的国家/地区过滤的一组值。

问题出在回调方法内部,我无法访问包含先前的hook_form_alter的$ form和$ form_state对象。

我的问题是:可以通过参数将此对象传递给回调吗?例如,有了这个,我就可以处理表单的状态及其字段。

类似这样的东西:

    $form['field_country']['widget']['#ajax'] = array(
        'callback' => [$this,'changeLawsData'],
        'event' => 'change',
        'disable-refocus' => FALSE,
        **'arguments' = array($form, $form_state)**
      );

这里是此实现的完整代码。

<?php

namespace Drupal\obs_urban_system\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
/**
 * Our event subscriber class.
 */
class NodeUrbanSystemFormAlterEventSubscriber implements EventSubscriberInterface {
    public static function getSubscribedEvents() {
        return [
            HookEventDispatcherInterface::FORM_ALTER => 'hookFormAlter'
        ];
    }

    /**
     * Implements hook_form_alter
     */
    public function hookFormAlter($event) {

        if($event->getFormId() == 'node_urban_system_edit_form') {
            $form = $event->getForm();
            $country = $form['field_country']['widget']['#default_value'];
            $form['field_laws']['widget'][0]['value']['#options'] = \Drupal::service('custom_services.law')->getLawsByContent($country, 'country');
            $form['field_law_articles']['widget'][0]['value']['#options'] = \Drupal::service('custom_services.law')->getLawArticlesByCountry($country);
            $form['field_country']['widget']['#ajax'] = array(
                'callback' => [$this,'changeLawsData'],
                'event' => 'change',
                'disable-refocus' => FALSE
              );
            $event->setForm($form);
        }
    }

    /**
     * @param $form
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     * @return \Drupal\Core\Ajax\AjaxResponse
     */
    function changeLawsData(&$form, FormStateInterface $form_state) {
<!--- HERE IM USING THE $form object --->
        $country = $form['field_country']['widget']['#default_value'];
<!---                                --->
        $laws = \Drupal::service('custom_services.law')->getLawsByContent($country, 'country');

        foreach ($laws as $key => $value) {
            $option .= "<option value='" . $key . "'>" . $value . " </option>";
        }

        $response = new AjaxResponse();
        $response->addCommand(new HtmlCommand('#edit-field-laws-0-value', $option));
        return $response;
    }

}

非常感谢。

drupal drupal-8 drupal-forms drupal-hooks
1个回答
0
投票

您需要在form_alter中进行所有表单操作。触发ajax回调后,将重建表单,并且该表单的当前值将在form_state中可用。您的ajax回调应仅返回前端所需的内容,而实际上不应操纵表单数组。

这里是您的代码示例(仅示例,未经测试)

<?php

namespace Drupal\obs_urban_system\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
/**
 * Our event subscriber class.
 */
class NodeUrbanSystemFormAlterEventSubscriber implements EventSubscriberInterface {
    public static function getSubscribedEvents() {
        return [
            HookEventDispatcherInterface::FORM_ALTER => 'hookFormAlter'
        ];
    }

    /**
     * Implements hook_form_alter
     */
    public function hookFormAlter($event) {

        if($event->getFormId() == 'node_urban_system_edit_form') {
            $form = $event->getForm();
            $country = $form['field_country']['widget']['#default_value'];

            // Get the form state object.
            $form_state = $event->getFormState();
            // Here we should check if a country has been selected.
            $country = $form_state->getValue('country');
            if ($country) {
              // populate the options from service here.
              $form['field_laws']['widget']['#options'] = \Drupal::service('custom_services.law')->getLawsByContent($country, 'country');
            } else {
              // Populate with default options.
              $form['field_laws']['widget']['#options'] = [];
            }


            $form['field_law_articles']['widget'][0]['value']['#options'] = \Drupal::service('custom_services.law')->getLawArticlesByCountry($country);
            $form['field_country']['widget']['#ajax'] = array(
                'callback' => [$this,'changeLawsData'],
                'event' => 'change',
                'disable-refocus' => FALSE
              );
            $event->setForm($form);
        }
    }

    /**
     * @param $form
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     * @return \Drupal\Core\Ajax\AjaxResponse
     */
    function changeLawsData(&$form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
        $response->addCommand(new HtmlCommand('#edit-field-laws', $form['field_laws']));
        return $response;
    }

}

请记住上面是一个示例...

© www.soinside.com 2019 - 2024. All rights reserved.