Dear Forum,

i want to add a javascript to form, which is build with ContentEntityForm and used for a custom entity.

I´ve added the javascript to the libraries.yml:

drupal-addlayer:
    version: VERSION
    js:
      js/addLayer.js: {}
    dependencies:
      - core/jquery
      - core/jquery.once
      - core/drupal

I´ve created the javascript:

(function ($) {
  'use strict';
  console.log("JS Drupal AddLayer");
  Drupal.behaviors.addLayer = {
    attach: function (context, settings) {
        console.log("works");
    }
  }
  })(jQuery);

I want to add thes javascript to the following form, which is using ajax by default:

<?php
/**
 * @file
 * Contains \Drupal\openlayers\Form\LayerForm.
 */

namespace Drupal\openlayers\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\openlayers\Controller\ExternalLayerTree;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form controller for the content_entity_example entity edit forms.
 *
 * @ingroup content_entity_example
 */
class LayerForm extends ContentEntityForm {

   
    
  /**
   * {@inheritdoc}
   */
  private $sourcelayerrelation = [];
  
  /**
   * @var \Drupal\Core\Entity\EntityTypeManager
   */
  protected $entityTypeManager;
  
  /**
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;
  
  /**
  * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
  * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
  * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
  */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityRepositoryInterface $entity_repository) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityRepository = $entity_repository;
  }
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('entity.repository')
    );
  }
  
  public function buildForm(array $form, FormStateInterface $form_state) {
    /*
     * kind of source => kind of layer
     * OSM, XYZ => tile
     * ImageWMS => image 
     * vector => view, node
     */
    
    $this->sourcelayerrelation['tile'][0] = 'osm';
    $this->sourcelayerrelation['tile'][1] = 'XYZ';
    $this->sourcelayerrelation['image'][0] = 'imagewms';
    $this->sourcelayerrelation['node'][0] = 'vector';
    $this->sourcelayerrelation['view'][0] = 'vector';
    
    $form['wrapper'] = array(
      '#type' => 'container',
      '#attributes' => array('id' => 'data-wrapper'),
    );
    /* @var $entity \Drupal\openlayers\Entity\OpenLayersLayer */
    $form['wrapper'][] = parent::buildForm($form, $form_state);

    $form['#attached'] = array(
      'library' => array('openlayers/addlayer'),
      'drupalSettings' => array(),
    );
    $form['wrapper'][0]['layer_type']['widget']['#ajax'] = [
      'callback' => '::rebuildLayerForm',
      'event' => 'change',
      'wrapper' => 'data-wrapper',
      'progress' => [
        'type' => 'throbber',
        'message' => $this->t('...'),
      ],
    ];   
       
    switch ($layerType) {
      case 'none':
        dsm($layerType);
        $form['wrapper'][0]['layer_source_ref']['#access'] = FALSE;
        $form['wrapper'][0]['layer_name']['#access'] = FALSE;
        $form['wrapper'][0]['layer_view_ref']['#access'] = FALSE;
        $form['wrapper'][0]['layer_node_ref']['#access'] = FALSE;
        $form['wrapper'][0]['layer_machinename']['#access'] = FALSE;
        break;
      case 'image':
        dsm($layerType);
        $form['wrapper'][0]['layer_source_ref']['widget']['#options'] = $this->buildSourcesforLayerType('image');
        $form['wrapper'][0]['layer_source_ref']['widget']['#ajax']= [
          'callback' => '::rebuildLayerForm',
          'event' => 'change',
          'wrapper' => 'data-wrapper',
          'progress' => [
            'type' => 'throbber',
            'message' => $this->t('...'),
          ],
        ];   
        
        if(isset($tmp_sourceid)) {
          $options = $this->buildLayerOptions($tmp_sourceid);
          $form['wrapper'][0]['layer_machinename']['widget']['#default_value'] = TRUE;
          $form['wrapper'][0]['layer_machinename']['#access'] = TRUE;
          $form['wrapper'][0]['layer_machinename']['#suffix'] = '<a class="button button--primary" >Clear</a><div id="layeroptions"><br>' . $options . '</div>';
        }
        $form['wrapper'][0]['layer_source_ref']['#access'] = TRUE;
        $form['wrapper'][0]['layer_name']['#access'] = TRUE;
        $form['wrapper'][0]['layer_view_ref']['#access'] = FALSE;
        $form['wrapper'][0]['layer_node_ref']['#access'] = FALSE;
        
        break;
    }
    return $form;
  }

public function rebuildLayerForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild(true); 
    return $form['wrapper'];
  }

In the code below, i´ve tested to add the javascript directly to the $form element, but nothing happen, none of the console log is printing.

best regards

Comments

wombatbuddy’s picture

If your library name is 'drupal-addlayer' then the code should be like this: 

$form['#attached']['library'][] = 'openlayers/drupal-addlayer';
wombatbuddy’s picture

Also take a note, that you need to use two spaces for indentation in 'openlayers.libraries.yml': 

drupal-addlayer:
  version: VERSION
  js:
    js/addLayer.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

For more details see: 'Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module'

AndyLicht’s picture

Thanks so lot,

I´ve changed 

 $form['#attached'] = array(
      'library' => array('openlayers/addlayer'),
      'drupalSettings' => array(),
    );

to

 $form['#attached'] = array(
      'library' => array('openlayers/drupal-addlayer'),
      'drupalSettings' => array(),
    );

and everything works fine.

thanks a lot.