For Drupal 7, I wrote a very simple module to implement the Dirty Forms jQuery library with specific customizations to support the CKEditor module. This was, all told, about 8 lines of PHP code.

I've spent several hours reading through documentation and experimenting today, and I still am no closer to making this work for Drupal 8.

Drupal 7 has a relatively simple manner for doing this:

$form['#attached']['js'] = array();

When I first did this in Drupal 8, I got the error:

LogicException: You are not allowed to use js in #attached in drupal_process_attached() (line 661 of /core/includes/common.inc).

despite the fact that the Drupal 8 form api documentation seems to believe I can https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.h...

Then, I googled my error and came across this: https://www.drupal.org/node/2391025 and it sounds like you can no longer #attach js. Ok.

https://www.drupal.org/node/2274843 explains fairly verbosely how to add javascript all over the place. However, I absolutely cannot get things working the way I expect them to.

Right now, I have a custom module that includes a libraries file:

dirty_forms:
  version: VERSION
  js:
    js/jquery.dirtyforms.js: {}
dirty_forms_ckeditor:
  version: VERSION
  js:
    js/jquery.dirtyforms.ckeditor.js: {}

and I have a .module file that includes:

function dirty_forms_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['#attributes']['class'][1]) && $form['#attributes']['class'][1] == 'node-form') {
    $form['#attached']['library'][] = 'dirty_forms/dirty_forms';
    $form['#attached']['library'][] = 'dirty_forms/dirty_forms_ckeditor';
  }
}

my site doesn't throw errors, I can dpm out the $form and see the attached libraries along with node/form, and yet my javascript doesn't load on the page.

the documentation I've found talks a lot about doing this various places, but there isn't anything at all for adding javascript onto a form (at least, not that I've found that is current for Beta 15).

I understand that there are massive changes to the API, but surely, this should not be taking hours to figure out. Does anyone have any hints they can help with?

Comments

swentel’s picture

This fix is depressing:

change

    js/jquery.dirtyforms.js:{}

to

    js/jquery.dirtyforms.js: {}

Yes - a space ...

fubarhouse’s picture

FYI YML is very explicit in its syntax.

eclipsegc’s picture

I had a similar experience and it took quite a while (and other people's expertise, thx tic2000) to figure out that I'd failed to put:
(jQuery, Drupal, drupalSettings)
at the end of my js file. If this isn't there, your js won't even be included in the page.

Hope that helps!

Eclipse

Eclipse

RealityBitesYou’s picture

Felt the need to update this documentation.

Actually, these days, (jQuery) at the end is now sufficient unless you need the imports.

mhmd’s picture

Not working all the tries above failed to load a js file, I consider this situation very bad for Drupal Architects they make developers suffer digging in drupal 8 and upgrade modules.

libraries.yml

taarikh: 
  version: VERSION
  js: 
    js/taarikh.js: {}
  dependencies: 
    - core/jquery

.module

function taarikh_page_attachments(array &$page) {
  $page['#attached']['library'][] = drupal_get_path('module', 'taarikh').'/js/taarikh.js';
}

I could see the file path present in the page array but not loaded

why not working?
why I have to attach the file in code why not just put in .yml file and the system itself load it?

jaypan’s picture

I believe the problem is that you are trying to attach a file, when you need to attach a library, which will in turn attach that file.

Try this:

  $page['#attached']['library'][] = 'taarikh/taarikh';

Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
mhmd’s picture

It matches the PSR-4 standard Drupal 8 implements PSR-4.

rishabh318’s picture

Hi All,

I am facing problem with "#markup" in form API.

In Drupal 7 we can use "#markup" form element which look like this:

<?php
$form['test'] = array(
    '#type' => 'markup',
    '#markup' => '<div><script src="http://localhost/drupal7/sites/all/libraries/test.js"></script></div>',
  );
?>
//Here is my custom test.js
(function($) {
    Drupal.behaviors.test = {
        attach: function(context, settings) {
            console.log('testttt');
            document.write('*Hello, there!*');
        }
    };
})(jQuery);

and above code will print "*Hello, there!*" when form will be render.

Now in Drupal 8 I am using below code but it prints nothing.

<?php
$form['test'] = array(
      '#markup' => '<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>',
    );
?>

So how can implement this functionality in Drupal 8, which is already working in Drupal 7 .
Under script tag it can be local script or external script..
Please help...

Thanks

Jeff Burnz’s picture

Your problem is that #markup was never designed to do such a thing as insert a script tag!

In D7 you #attached files directly to the form array.

    '#attached' => array(
      'css' => array(drupal_get_path('theme', 'adaptivetheme') . '/css/at.settings.form.css'),
    ),

In D8 you #attached libraries to the form array:

$form['#attached']['library'][] = 'at_core/at.appearance_settings';

The Form API is fine, use it properly. Read the manual dude, that's what real developers do.

mester9’s picture

I can't seem to make it work on admin forms, like node create or edit, even though I can debug and get the form_id and everything, my javascript won't launch if it's an admin form? It shouldn't make any difference right?

jaypan’s picture

Depends - are you trying to do it in a theme? If so, it probably won't work unless the theme you are working on is the admin theme.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
Jeff Burnz’s picture

why I have to attach the file in code why not just put in .yml file and the system itself load it?

Because there are many ways to attach libraries and it's up to you to choose one. For example you might want to attach in a template, or preprocess, or a form, set conditions on the attachments and so on. See this docs page - https://www.drupal.org/developing/api/8/assets

Please note that page has existed for approx. 2 years, with the attach stuff added at least 1 year ago.

mhmd’s picture

The drupal 8 assets must mention and reference that article Drupal 8 implements PSR-4 to clear any misconceptions about paths and how files are being discovered by drupal 8.

Besides that I see the documentation pages must be structured to give first page for quickly how to do stuff and another detailed pages like other frameworks and cms write getting started quickly

mikemadison’s picture

A bit late, but thank you for the information. This is now working as expected.