As clearly titled I want to send a form values to js file in Drupal 8. I've made some researches and all I successfully coded was sending a PHP variable from a Controller to the JS file I'am using.
Here is the code:
library_name.libraries.yml
library_name:
version: 1.x
js:
js/<js_file_name>.js: {}
dependencies:
- core/jquery
- core/drupalSettings
controller_name.php (class)
namespace Drupal\module_name\Controller;
use Drupal\Core\Controller\ControllerBase;
class <class_name> extends ControllerBase {
public function <method>(){
return array(
'#attached' => array(
'library' => array(
'<module_name>/<library_name>'
),
'drupalSettings' => array(
'<module_name>' => array(
'<library_name' => array(
'foo' => 'bar'
)
)
)
)
);
}
js_file_name.js (under /js folder)
console.log(drupalSettings.<module_name>.<library_name>.foo);
Everything works great!
But how about using a form? I've declared a form extending from FormBase and in the submitForm() overridden method I typed the same array:
return array(
'#attached' => array(
'library' => array(
'<module_name>/<library_name>'
),
'drupalSettings' => array(
'<module_name>' => array(
'<library_name' => array(
'foo' => 'bar'
)
)
)
)
);
I know this won't work! But any ideas? I thought about using another library, point to a js file there, and use that js file to get the form values using the #attached tag like above, and then send those values to the other js file using JSON
If any one can provide me with a better Drupal Standard? that would be great! cause this my first time using Drupal.
EDIT:
I fixed this, using: the module_name.settings.yml file under module_name/config/install folder and also by using the module_name.module file where I've implemented the hook_form_alter() method.
So,
From my module_name.module file, here goes my code:
/**
* Implements hook_form_alter().
*/
function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
if($form_id === your_form_id){
$form['#attached']['library'][] = 'module_name/route_name';
// that's the route name you've defined in your module_name.libraries.yml file
// where you've located the js file you're going to use
$form['#attached']['drupalSettings']
[module_name][route_name][send_this_variable_to_js] = \Drupal::config(module_name.settings)->get(key);
return $form;
}
}
Now in your JS file, you can console.log like this:
console.log(drupalSettings.module_name.route_name.server.send_this_variable_to_js)
Hope this help!