首页 > 解决方案 > 如何将javascript文件添加到自定义表单并将数据传递给js文件

问题描述

我正在使用 Drupal 8,并且我有自定义 ajax 表单,当我使用 [Ajax htmlCommands] 对其进行测试时,它可以正常工作。但现在我想将数据发送到 javascript 文件以在 div 中显示它并做一些其他的事情。我所做的是在下创建 js 文件,themes/custom/myform/assets/js/simple-form.js但单击元素时控制台中没有显示任何内容。

Drupal.behaviors.simple_form = function(context) {
$('.btn-primary').click(function() {
console.log('clicked');
  });
};

并将其添加到themes/custom/myform/myform.libraries.yml

simple-form-js:
  js:
    assets/js/simple-form.js: {}

我的自定义表单模块/custom/my_module/src/Form/SimpleForm.php

<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
/**
 * Our simple form class.
 */
class SimpleForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_module';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
//$form = parent::buildForm($form,  $form_state);
$form['#theme'] = 'simple_form';

   $form['massage'] = [
      '#type' => 'markup',
      '#markup' => '<div class="result_message"></div>',

    ];
   $form['number_1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('number 1'),
      '#attributes' => ['class' => ['form-control ml-sm-2 w-100']],
      '#required' => TRUE,
    ];

    $form['number_2'] = [
      '#type' => 'textfield',
      '#title' => $this->t('number one'),
      '#attributes' => ['class' => ['form-control ml-sm-2 w-100']],
      '#required' => TRUE,

];




    $form['actions'] = [
      '#type' => 'button',
      '#value' => $this->t('Calculate'),
      '#attributes' => ['onclick'=>'return false;','class' => ['mt-3 btn btn-primary btn-me2']],
      '#attached' =>  [
         'library'=>[
         'simple-form',
       ]
      ],
      '#ajax' => [
        'callback' => '::setMessage',
      ]
    ];


return $form;
  }
public function setMessage(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$letter = $form_state->getValue('number_1');
$code = $form_state->getValue('number_2');
$fetchUrl = 'http://example.com/api';
$responseAPI = \Drupal::httpClient()->get($fetchUrl, array('headers' => array('Accept' => 'text/plain')));
$data = (string) $responseAPI->getBody();
//drupal_set_message($data);
    $response->addCommand(
      new HtmlCommand(
        '.result_message',
        '<div class="my_top_message">' . $this->t('The result is @result', ['@result' => ($data)])
        )
    );
    return $response;

}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
  /**
   * {@inheritdoc}
   */
public function submitForm(array &$form, FormStateInterface $form_state) {
}


}

themes/custom/myform/myform.theme

        if($route_namee=="my_module.simple_form"){
                $variables['#attached']['library'][] = 'myform/simple-form-css';
                $variables['#attached']['library'][] = 'myform/simple-form-js';
        }

标签: javascriptformsdrupal

解决方案


您可以使用HOOK_form_alter附加库

*/**
* Implements hook_form_alter().
*/

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_id == "my_module") {
    $form['#attached']['library'][] = 'myform/simple-form-js';
    $form['#attached']['library'][] = 'myform/simple-form-css';
    $form['#attached']['drupalSettings']['my_module']['variable'] = 'Your Custom values to JS';
    return $form;
  }
}

推荐阅读