简体   繁体   中英

How to add javascript file to custom form and pass the data to the js file

I'm working with Drupal 8 and I have custom ajax form it works fine when I test it using [Ajax htmlCommands]. but now I want to send the data to the javascript file to show it in a div and do some other things. what I did is create js file under themes/custom/myform/assets/js/simple-form.js but nothing shows in the console when the element clicked.

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

and add it to themes/custom/myform/myform.libraries.yml

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

my custom form modules/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) {
}


}

and 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';
        }

You can use HOOK_form_alter to attach libraries

*/**
* 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;
  }
}

What you are looking for is a ajaxCommand and not a behavior. Create a custom ajaxCommand and pass your variables to it when creating the ajax response.

Here is help https://weknowinc.com/blog/creating-custom-ajax-command-drupal-8 And get Inspired with how Drupal Cores InvokeCommand is working

To attach library you dont need theme or module files for example :

$form['#attached']['library'][] = 'core/drupal.dialog.ajax';

is enough to attach a library in your case you should call your js file like :

$form['#attached']['library'][] = 'simple-form-js';

Then files under your library will loaded with your form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM