# Question
Title: How to disable form button on ajax callback?
I have a button with ajax callback and I want to disable it on button click without page reload. Preferably inside `ajax_function` but it's not obligatory.

```
$form['my_button'] = [
  '#type' => 'button',
  '#ajax' => [
    'callback' => '::ajax_function',
    'wrapper' => 'my-button-wrapper',
  ],
  '#attributes' => array(
    'class' => array('glyphicon', 'glyphicon-shopping-cart'),
  ),
  '#submit' => ['::ajaxButtonSubmit'],
];

```

# Answer
> 1 votes
In your ajax callback function write the code to disable button. like:

```
public function ajax_function(array &$form, FormStateInterface $form_state) {
    $form['my_button']['#attributes']['disabled'] = true;
    return $form['my_button'];
}

```

Hope it helps!

---
Tags: 8, forms
---


# Question
Title: How to duplicate nodes programmatically?
I want to create duplicate nodes of a content type programmatically.

Is there any way to do this?

*Note: I don't want to use any module to do this.*

# Answer
> 9 votes
In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned\_node = $node-\>createDuplicate(). Calling $cloned\_node-\>save() will save a new node with a different ID.

Answer from here

# Answer
> 7 votes
You can read the values from the original node in an array and create a new node with the data:

```
$storage = \Drupal::entityTypeManager()->getStorage('node');

$node = $storage->load($nid);

$original_values = $node->toArray();

// assign content type as string, the array causes an error when creating a new node
$original_values['type'] = $node->bundle();

// change title
$original_values['title'] = $node->label() . ' (cloned)';

// remove nid and uuid, the cloned node is assigned new ones when saved
unset($original_values['nid']);
unset($original_values['uuid']);

// remove revision data, the latest revision becomes the only one in the new node
unset($original_values['vid']);
unset($original_values['revision_translation_affected']);
unset($original_values['revision_uid']);
unset($original_values['revision_log']);
unset($original_values['revision_timestamp']);

$node_cloned = $storage->create($original_values);
$node_cloned->save();

```

# Answer
> 1 votes
Yes, we can duplicate a node in Drupal 8 as well. Check example below:

***NOTE: I've not tested this code thoroughly, and not sure if this will affect on node being cloned as well.***

```
use Drupal\node\Entity\Node;

$node_clone = Node::load($id);
$node_clone->nid = NULL;
$node_clone->vid = NULL;
$node_clone->tnid = NULL;
$node_clone->log = NULL;
// Also handle modules that attach a UUID to the node.
$node_clone->uuid = \Drupal::service('uuid')->generate();
$node_clone->vuuid = NULL;

// Anyonmymous users don't have a name.
$node_clone->name = 'Anonymous';
$node_clone->uid = 0;

$node_clone->created = time();
$node_clone->path = NULL;
$node_clone->files = array();
$node_clone->setTitle('Clone Node');
$node_clone->save();

```

---
Tags: nodes, 8, migrations
---


# Question
Title: Local simpletest drupalGet() always gives "returned 0 (0 bytes)"
I want to run tests locally with simpletest module.

I tried this with the cli scripts/run-tests.sh, and also in the admin UI. I tried different tests shipped with Drupal 7 core, such as the ContactSitewideTestCase test.

Whenever a test wants to make a http request with $this-\>drupalGet(), the test reports a fail saying e.g. "GET http://d7git.localhost/user returned 0 (0 bytes)."

I think to remember that something needs to be configured for simpletest to make http requests. But I cannot remember what it is, and cannot find documentation that would explain it.

# Answer
> 1 votes
Drupal 7 configuration. You need to get nginx container IP first:

`docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <nginx container name or ID>`

Then add this IP Address to hosts file of PHP-container:

`docker exec --user root -it <php container ID or name> /bin/bash;
echo "172.22.0.8 <your domain name>" >> /etc/hosts; cat /etc/hosts`

Here '172.22.0.8' is an IP Address of nginx container.

# Answer
> 0 votes
This error means that your test cannot reach your website.

I had a similar issue using something based on docker for drupal. For me the solution or hack the hosts file on the php container and change to point the domain you want to test to to the ip of the proxy server, in my case traeffik.

So in my host file I had something like this:

172.18.0.5 domain.internal

once that is done you can use curl to test the connection:

curl -v domain.internal

In my case I had an issue with a self signed certificate.

* Rebuilt URL to: https://domain.internal/
* Trying 172.18.0.5...
* TCP\_NODELAY set
* Connected to domain.internal (172.18.0.5) port 443 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS alert, Server hello (2):
* SSL certificate problem: self signed certificate
* Closing connection 0 curl: (60) SSL certificate problem: self signed certificate More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above.

However this should allow you to run your simpletest(s) in your browser.

Ideally there should be a way to configure this in your docker-compose file but I am not sure how?

---
Tags: 7, testing
---


title: Ajax add command to open a new URL

text:
# Question
Title: Ajax add command to open a new URL
in a custom module, I created a custom form. On this form, I have an ajax button to open a specific file (.pdf).

Here is my code in a custom submit function :

```
  $url = 'myfileUrl';
  $response = new AjaxResponse();
  $command = new RedirectCommand($url);
  $response->addCommand($command);

```

It's ok and the file is opened when I click on the button. But, the page is closed to open the file. How can I specify an attribute "target" to open the file in a new window? If not possible, is there another ajax command to open an external URL?

Thanks.

# Answer
I found a solution to resolve my problem. After having readed several posts, i have decided to create a custom Ajax Command to open my files (pdf/csv).

Create a custom command - link

In my custom module, I have built the required files for this and call in my CallBack function this new ajax command ('OpenFileCommand') :

```
    $ajax_response = new AjaxResponse();
    $command = new OpenFileCommand($file_url);
    $ajax_response->addCommand($command);

```

Here is the simple code for this command:

```
use Drupal\Core\Ajax\CommandInterface;

/**
 * Class OpenFileCommand.
 */
class OpenFileCommand implements CommandInterface {

  // Create a new property.
  protected $file_url;

  // Construct the File Url property.
  public function __construct($file_url) {
    $this->file_url = $file_url;
  }

  /**
  * Render custom ajax command.
  *
  * @return ajax command function
  */
  public function render() {
    return [
      'command' => 'OpenFileCommand',
      'file_url' => $this->file_url
    ];
  }

}

```

Now, I can open a file when I click on a ajax button.

Thanks for all for your help. This solution can help someone...
> 1 votes

# Answer
You can open a new window which can be achieved using javascript. Call function like below using on click method. You have to pass the URL to open and title for the window.

```
    function openWindow(url, title){
      var left = (screen.width/2)-(700/2);
      var top = (screen.height/2)-(500/2);
      var win = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=700, height=500, top='+top+', left='+left);
      //setTimeout(function () { win.close(); }, 10000); <- You can give timeout also so window will get automatically closed
    }

```

Hope this will help to open your pdf file in new window, I will post another answer if I found to open a new tab on redirect.
> 0 votes

---
Tags: ajax
---


# Question
Title: How do I use hook_update_N() to create a vocabulary?
I want to create a standard vocabulary (no extra fields) in Drupal 8.7.5 programatically, using hook\_update\_N. I've never used this function before. So I'm a complete newbie.

I've modified a simple delete script I was shown, but something tells me it can't possibly be this simple.

Here's my starting point:

```
<?php

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * create vocabulary testname.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';
  $vocabulary = Vocabulary::load($vid);
  if (!$vocabulary) {
    $vocabulary->create();
  }
}

```

I assume that, once the script is created correctly, I simply run `drush entup`.

# Answer
Using the following code, you should be able to create a new vocabulary.

```
use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Create the testname vocabulary.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';

  if (!$vocabulary = Vocabulary::load($vid)) {
    $vocabulary = Vocabulary::create([
      'vid' => $vid,
      'description' => '',
      'name' => 'The vocabulary name',
    ]);

    $vocabulary->save();
  }
}

```

The correct hook to use to create or change entities is not `hook_update_N()`, though, but `hook_post_update_NAME()`.

The hook must be added to the *ent.post\_update.php* file, not the *ent.install* file. For the rest, the code is pretty much similar.

```
/**
 * Create the testname vocabulary.
 */
function ent_post_update_create_vocabulary(&$sandbox) {
  $vid = 'testname';

  if (!$vocabulary = Vocabulary::load($vid)) {
    $vocabulary = Vocabulary::create([
      'vid' => $vid,
      'description' => '',
      'name' => 'The vocabulary name',
    ]);

    $vocabulary->save();
  }
}

```
> 2 votes

---
Tags: 8, taxonomy-terms, hooks
---


title: Routing match everything

text:
# Question
Title: Routing match everything
i want to match in a route a 'random' URL with a random sub path, fox example:

* `/example/1/a/b/c`
* `/example/c3/s`
* ...

i implement this route in my `.routing.yml` file

```
modulo.validator:
  path: '/example/{path}'
  defaults:
    _controller: '\Drupal\modulo\Controller\Controller::check'
  requirements:
    _permission: 'TRUE'
    path: '.+'

```

I write it following Symfony2 standard but it doesn't works, seems Drupal override requirements in path.

Take look to `system.routing.yml`

```
system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

```

why this doesn't work for me?

Any suggestion?

# Answer
The reason that the route in system.routing.yml works is that it gets help by an inbound path processor service, which stores the filepath to a query parameter in the request:

**PathProcessorFiles.php**

```
<?php

namespace Drupal\system\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines a path processor to rewrite file URLs.
 *
 * As the route system does not allow arbitrary amount of parameters convert
 * the file path to a query parameter on the request.
 */
class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

```

This service is registered in system.services.yml:

**system.services.yml**

```
  services:

    path_processor.files:
      class: Drupal\system\PathProcessor\PathProcessorFiles
      tags:
        - { name: path_processor_inbound, priority: 200 }

```

And the controller gets the file path from the query parameter added by the processor:

**FileDownloadController.php**

```
  public function download(Request $request, $scheme = 'private') {
    $target = $request->query->get('file');
    ...

```

You can implement the same approach for your route to match everything after `/example/`.
> 8 votes

# Answer
The accepted answer may be appropriate for the intended use case of the OP, however, the title of this question is "Routing match everything".

As this is the closest question I've found from searching the interwebs, I'll just share my discovery here on how to accomplish this for SPAs where all paths that start with "/app" need to be redirected to a single route.

In `./my_module/my_module.routing.yml`:

```
my_module.app:
  path: '/app'
  defaults:
    _controller: '\Drupal\my_module\Controller\App::content'
  requirements:
    _access: 'TRUE' # Access is handled by app.

```

In `./my_module/my_module.services.yml`:

```
  my_module.request_subscriber:
    class: Drupal\my_module\EventSubscriber\RequestSubscriber
    arguments: ['@router.route_provider', '@controller_resolver', '@http_kernel.controller.argument_resolver']
    tags:
      - { name: event_subscriber }

```

In `./my_module/src/EventSubscriber/RequestSubscriber.php`:

```
<?php

namespace Drupal\my_module\EventSubscriber;

use Drupal\Core\Controller\ControllerResolverInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class RequestSubscriber.
 */
class RequestSubscriber implements EventSubscriberInterface  {

  /**
   * The Argument Resolver service.
   *
   * @var \Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface
   */
  protected $argumentResolver;

  /**
   * The Controller Resolver service.
   *
   * @var \Drupal\Core\Controller\ControllerResolverInterface
   */
  protected $controllerResolver;

  /**
   * The Route Provider service.
   *
   * @var \Drupal\Core\Routing\RouteProviderInterface
   */
  protected $routeProvider;

  /**
   * RequestSubscriber constructor.
   *
   * @param \Drupal\Core\Routing\RouteProviderInterface $routeProvider
   * @param \Drupal\Core\Controller\ControllerResolverInterface $controllerResolver
   * @param \Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface $argumentResolver
   */
  public function __construct(RouteProviderInterface $routeProvider, ControllerResolverInterface $controllerResolver, ArgumentResolverInterface $argumentResolver) {
    $this->routeProvider = $routeProvider;
    $this->controllerResolver = $controllerResolver;
    $this->argumentResolver = $argumentResolver;
  }

  /**
   * The request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The event.
   */
  public function checkAppRequest(GetResponseEvent $event) {
    $request = $event->getRequest();
    $path = $request->getPathInfo();

    // Redirect all requests that start with "/app" requests to a single
    // route. Note: this is necessary because core doesn't have any other
    // way to really handle "wildcard/catch all" routes.
    if (strpos($path, '/app') === 0
      // Ignore CSS/JS (if it reaches here, it means the file doesn't exist).
      && !in_array(substr($path, -3), ['.css', '.js'])
      && !in_array(substr($path, -4), ['.map'])
    ) {
      $route = $this->routeProvider->getRouteByName('my_module.app');
      $definition = $route->getDefault('_controller');
      $controller = $this->controllerResolver->getControllerFromDefinition($definition, $path);
      $arguments = $this->argumentResolver->getArguments($request, $controller);
      $response = \call_user_func_array($controller, $arguments);
      if ($response instanceof Response) {
        // Set the response, necessary so the kernel knows it got something
        // which will also prevent any other event handler from running.
        $event->setResponse($response);
        return;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Check for /app requests.
    $events[KernelEvents::REQUEST][] = ['checkAppRequest', 1000];
    return $events;
  }

}

```
> 2 votes

# Answer
The Drupal 8 example modules has a few examples of this functionality.

For example in the page\_example module you'll see a page\_example.routing.yml file with the following

```
page_example_arguments:
   path: 'examples/page-example/arguments/{first}/{second}'
   defaults:
       _controller: '\Drupal\page_example\Controller\PageExampleController::arguments'
   requirements:
       _permission: 'access arguments page'

```

And in the controller you have the arguments function that is called:

```
public function arguments($first, $second) {
    // Make sure you don't trust the URL to be safe! Always check for exploits.
    if (!is_numeric($first) || !is_numeric($second)) {
       // We will just show a standard "access denied" page in this case.
       throw new AccessDeniedHttpException();
    }

    $list[] = $this->t("First number was @number.", array('@number' => $first));
    $list[] = $this->t("Second number was @number.", array('@number' => $second));
    $list[] = $this->t('The total was @number.', array('@number' => $first + $second));

    $render_array['page_example_arguments'] = array(
       // The theme function to apply to the #items.
       '#theme' => 'item_list',
       // The list itself.
       '#items' => $list,
       '#title' => $this->t('Argument Information'),
     );

     return $render_array;
}

```
> -1 votes

---
Tags: 8, routes
---


# Question
Title: How to remove a taxonomy vocabulary via database query
To manually remove a taxonomy vocabulary in the database, what tables/columns etcetera do I need to delete or modify?

I have a "ghost" taxonomy - it shows up in the list, but doesn't exist anywhere else. I cannot edit it through the website admin - it says page doesn't exist. I can't delete it by using `drush entup`

But I must remove this somehow, as it's disrupting the website with errors...

> LogicException: Missing bundle entity, entity type taxonomy\_vocabulary, entity id Regions

As a **hook\_update\_n** solution didn't work, and installing a module to do '**drush entup**' didn't work... where can I remove this from the database? I had the team in charge of the database itself do a search and pull this result:

I'm assuming that first result is for the block structure, and unrelated to my taxonomy. But maybe someone sees an issue with the results below it, or if we can safely delete those to get rid of this 'ghost' taxonomy?

# Answer
> 1 votes
From the world of weird solutions that work...

* I tried using a module and 'drush entup' ... didn't work
* I tried creating a module to use 'hook\_update\_N' to delete it ... didn't work
* I tried using hook\_update\_N to Create it, so I could then delete it ... didn't work.

On a whim, I went to the admin page, listing taxonomies. I dragged the 'ghost' taxonomy to rearrange the list. Then I saved. Suddenly, all the options to edit it had returned. I was finally able to delete the taxonomy using the usual dropdown field.

# Answer
> 0 votes
Take any existing custom module or create one and install it. Then let this module have an `.install` file and in there implement `hook_update_N` with the following code to delete the vocabulary when you run database updates the next time, for example via `$ drush updb`.

```
<?php

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Delete vocabulary MY_VOCABULARY.
 */
function MYMODULE_update_8101(&$sandbox) {
  $vid = 'MY_VOCABULARY_MACHINE_NAME';
  $vocabulary = Vocabulary::load($vid);
  if ($vocabulary) {
    $vocabulary->delete();
  }
}

```

---
Tags: 8, taxonomy-terms
---


title: How to get my button in a dialog click?

text:
# Question
Title: How to get my button in a dialog click?
I have added the following JS to a node form, it clones the submit button but clicking it inside the dialog (which does show up) doesn't submit the form in the browser, just nothing happens when the button is clicked. I also tried adding the button server side, same results:

```
(function (window, Drupal, $) {
  Drupal.behaviors.drafter = {
    attach: function attach(context) {
      var button = $('#edit-submit');
      var newbutton = button.clone().prop('id', 'edit-submit-drafter');
      button.click(function () {
        $('#drafter-elements').toggle();
        var confirmationDialog = Drupal.dialog('#drafter-elements', {
          resizable: false,
          closeOnEscape: false,
          create: function () {
            $(this).append(newbutton);
          },
          beforeClose: false,
          close: function (event) {
            $(event.target).remove();
          }
        });
        confirmationDialog.showModal();
        return false;
      })
    }
  }
})(window, Drupal, jQuery);

```

Where `drafter-elements` come from:

```
$form['drafter'] = [
  '#prefix' => '<div id="drafter-elements">',
  '#suffix' => '</div>',
  '#attached' => ['library' => ['drafter/drafter']],
];
$form['drafter']['save_in_place'] = [
  '#title' => 'Confirm',
  '#type' => 'checkbox',
  '#description' => t('By default a new draft will be created.'),
];

```

With a tiny CSS:

```
#drafter-elements {
  display: none;
}

```

(Here's the drafter repository should someone want to try it / fix it.)

# Answer
for me that submits the node:

```
(function (window, Drupal, $) {
  Drupal.behaviors.drafter = {
    attach: function attach(context) {
      var button = $('#edit-submit');
      var newbutton = button.clone().prop('id', 'edit-submit-drafter');
      var confirmationDialog = Drupal.dialog('#drafter-elements', {
        resizable: false,
        closeOnEscape: false,
        create: function () {
          $(this).append(newbutton);
        },
        beforeClose: false,
        close: function (event) {
          $(event.target).remove();
        }
      });
      newbutton.click(function (e) {
        button.click();
        confirmationDialog.close();
        return true;
      });
      button.click(function () {
        if (!confirmationDialog.open) {
          confirmationDialog.showModal();
          return false;
        }
      });
    }
  }
})(window, Drupal, jQuery);

```
> 3 votes

---
Tags: 8, javascript, modal-dialogs
---


title: How to remove welcome to message?

text:
# Question
Title: How to remove welcome to message?
I changed the:

```
configuration: Site Name --> 'my site name'

```

But it shows in title bar like this:

> Welcome to 'my site name'

So, how can I remove the "Welcome to" in the title bar, so that the result would be just:

`'my site name'`

---

When I inspected the html I found like this:

```
Welcome to my stie name | my site name

```

But I wanted to be :

```
my site name

```

And I'm using zen base theme and zenophile sub-theme.

# Answer
Try Page Title module and configure the Page title for Front Page.
> 3 votes

# Answer
in your template.php

```
function THEME_preprocess_page(&$vars) {
  if (drupal_is_front_page()) {
    drupal_set_title(''); //removes welcome message (page title)
  }
}

```

dont forget to clear cache.
> 1 votes

# Answer
if you want to remove for all your project so you can comment this line in node module. in this address : Drupal core/modules/node/node.module and comment line for default message.
> -1 votes

---
Tags: 7
---


title: Let a user select the theme

text:
# Question
Title: Let a user select the theme
For a few weeks, I have been developing a site based on Drupal 8 and so far, everything's working fine. Only recently I found a functionality that I had expected to be there, but that now seems to be missing.

In a nutshell, I would like to allow registered users to select the site theme (out of a small pre-defined set). This was a functionality that I was present in Drupal 6, but that seems to have been dropped in Drupal 7 (see the thread here and the discussion here). In that thread, the ThemeKey module was suggested as an alternative, but that hasn't been ported to Drupal 8 yet. I also found two more modules (Theme Change and Clever Theme Switcher) that are capable of changing themes in Drupal 8, but not based on a user selection.

So, lacking a suitable module (I'm open for suggestions, though), I guess I will have to implement this myself, maybe even code a simple module or extend the Clever Theme Switcher. Unfortunately, I'm at a loss as to how to proceed. Can anybody offer any help?

# Answer
You can solve this in code by implementing ThemeNegotiatorInterface. This is a tagged service, for which you can set a priority. So you can let AdminNegotiator (priority -40) choose the theme first, before you set the theme for non admin pages, but no later than -100, the priority of DefaultNegotiator.
> 2 votes

---
Tags: 8
---


# Question
Title: How to set different form displays for creating and editing an entity?
I see we can configure multiple form modes for an entity bundle.

We want to utilize that to create two form modes for Image bundle of Media entity. One to use while creating a new Image media and other to use while editing existing one.

How can we achieve that? Are there exist configuration ways to do it?

# Answer
The media entity has already specific form handlers `add` and `edit`, so you can configure them right away.

Add both form modes to the media entity at */admin/structure/display-modes/form* and enable them for the media type at */admin/structure/media/manage/image/form-display* in CUSTOM DISPLAY SETTINGS.
> 2 votes

---
Tags: 8
---


# Question
Title: How to grant permission to FileSystem.php file
I navigate to `admin/config/media/file-system` in the drupal admin interface. I get this error

> Warning: mkdir(): Permission denied in Drupal\Core\File\FileSystem-\>mkdirCall() (line 244 of core/lib/Drupal/Core/File/FileSystem.php) .

I granted the permission to sites folder using the following commands `chown -R www-data:www-data sites` and `chmod -R g+rw sites`.
But still the error appears.

Any advice?

# Answer
> -1 votes
First of all make sure that the files directory (*sites/default/files* by default) has the right owner and permissions.
And also directory of temporary files, in general */tmp* if you don't have create one and give it the right permissions.

---
Tags: 8
---


# Question
Title: What is the ID or class for the Wizard Page name?
In Webform 8 I am using the Attachment PDF / Entity Print to send a PDF of the submission via e-mail.

I am able to target the field labels, fieldset and webform-elements to add CSS but cannot find the correct ID or class for the wizard page titles.

Where do I find it?

# Answer
> 2 votes
Each wizard page is rendered as details element.

Below is the Entity Print markup from the webform\_example.module's 'Example: Wizard'.

```
<details
 class="webform-container webform-container-type-details js-form-wrapper form-wrapper"
 data-webform-element-id="example_wizard--information"
 id="example_wizard--information"
 open="open">
   <summary
     role="button"
     aria-controls="example_wizard--information"
     aria-expanded="true"
     aria-pressed="true">
     Your Information
     </summary>
   <div class="details-wrapper">
   ...
   </div>
</details>

```

---
Tags: 8, webforms
---


# Question
Title: Unable to run update.php or update modules from web interface
I would really like to be able to install module updates through the web interface or run update.php when needed without changing settings.php, but something seems to be broken in my setup because it tells me I am not authorized to do so when I try.

In all attempts to make this work, I am using UID1, which besides any special properties that user has, it is an administrator which has the "Administer software updates" permission. In settings.php I have: `$settings['allow_authorize_operations'] = TRUE;` set explicitly, but I have also tried it in the default, not set, state which is also TRUE.

If I set `$settings['update_free_access'] = TRUE;` then I can run update.php, but that doesn't seem to help with the module updates and I would rather not have to change that setting every time I need to do an update.

I have tried all of the usual things I have seen mentioned including:

* Rebuild the user permissions
* Cleared the session table in the db
* Verified correct permissions on relevant files/directories
* Looked through various server logs for any obvious failures

My first real clue came from looking at the log an noticing that the "access denied" entry is tied to the anonymous user instead of the user I was logged in as. I have tried digging through the code a bit to see if I could track down where it is losing track of my user, but I am in a little over my head at that point. Obviously, the authentication is working in general because I am able to log in the admin site and do most things.

Has anyone had any idea why Drupal would lose knowledge of the logged in user just while trying to do update type operations?

Version: Drupal 8.7.6

Note: I have looked a little more into the code to try to track down my problem. As seen from the logs, the problem is not that my user doesn't have permission but rather that when I run those specific actions, drupal momentarily doesn't see me as being logged in. In the file `core\authorize.php` there is a method that gets called: `authorize_access_allowed(Request)` which is mostly checking to see if the logged in user has the 'administer software updates' permission. In that method, it doesn't believe I am logged in. As far as I can tell, there are two ways it might pull the user out of that passed in Request (reading PHP\_AUTH\_USER out of the get headers or getting the UID out of a cookie). The get headers are definitely not there, and while there is a session cookie, it doesn't seem to be able to pull a UID out of it. I have not been able to find the code that parses the Session string.

# Answer
> 0 votes
`update.php` does not update modules. It updates the database state if needed (after installing module updates, aka db-update).

Did you check the permissions of your /modules/contrib/\* filesystem? When you update your modules with the admin UI, your webserver's user (apache or www-run...) needs to have write permission there.

Did you install your instance with composer? If so, do not use the admin UI.

Maybe, check the docs again: https://www.drupal.org/docs/user\_guide/en/security-update-module.html

---
Tags: 8, users, authentication-authorization, maintenance-mode
---


# Question
Title: Add new field to custom content entity type
I have created a custom content entity type called `Course`. When I installed my module, Drupal automatically created the table schema for my entity, so all the fields I defined in `Course::baseFieldDefinitions()` had their column in the database table `course`, as specified in the `base_table` annotation of my class.

Now I want to add an extra field to my entity. I edited the `Course::baseFieldDefinitions()` method to define my new field in the same way as I did with the previous ones. The problem is that I don't know how can I create the appropiate column in the database.

The relevant part of my `Course` entity is:

```
class Course extends ContentEntityBase implements CourseInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference');
      // Settings and constraints for this field

    $fields['name'] = BaseFieldDefinition::create('string');
      // Settings and constraints for this field

    $fields['price'] = BaseFieldDefinition::create("float");
      // Settings and constraints for this field

    $fields['status'] = BaseFieldDefinition::create('boolean');
      // Settings and constraints for this field

    $fields['created'] = BaseFieldDefinition::create('created');
      // Settings and constraints for this field

    $fields['changed'] = BaseFieldDefinition::create('changed');
      // Settings and constraints for this field

    // New field being added
    $fiels["place"] = BaseFieldDefinition::create("string")
      ->setLabel(t("Place"))
      ->setDescription(t("The place of the course"))
      ->setSettings(["max_length" => 255, "text_processing" => 0])
      ->setDefaultValue("")
      ->setDisplayOptions("view", ["label" => "above", "type" => "string", "wegith" => -3])
      ->setDisplayOptions("form", ["type" => "string_textfield", "wegith" => -3]);

    return $fields;
  }

}

```

I've tried using the Drupal console command `update:entities` but it is not updating my database schema.

How could I add the `place` field to my database table?

# Answer
After installation, you need to handle updating the schema yourself. There are some different scenarios, some are more easy to deal with than others. The most complex is moving data from one field type to another which means you would have to do a migration of data.

Anyways Drupal core has the `entityDefinitionUpdateManager()` which can be accessed doing `\Drupal::entityDefinitionUpdateManager()`. This manager can do a lot of the things you need to do when you change the base fields of content entities.

Creation of a new field is pretty easy, and all you need to make your own update hook:

```
function hook_update_8xxx() {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

```

This will apply all updates to all entities. This can generally be used for most things, but if there are data in Drupal has a failsafe that throws an exception to make sure it doesn't accidentally mess data up. During the beta the system attempted to handle data migration as well, but it didn't work well so it was decided that this is something module maintainers should do themselves.
> 8 votes

# Answer
As described in Write update functions for entity schema updates, automation removed (created on August 2015), which describes a change introduced on the 8.0.x branch, if you need to update the database schema used for an entity, you need to also implement `hook_update_N()` with code similar to the following one.
Since the class implementing the entity is `Course`, I assume the module machine name is *course*. Change the update number to the correct one for your module.

```
use Drupal\Core\StringTranslation\TranslatableMarkup;

function course_update_8110() {
  $storage_definition = BaseFieldDefinition::create("string")
    ->setLabel(new TranslatableMarkup("Place"))
    ->setDescription(new TranslatableMarkup("The place of the course"))
    ->setSettings(["max_length" => 255, "text_processing" => 0])
    ->setDefaultValue("")
    ->setDisplayOptions("view", ["label" => "above", "type" => "string", "weigth" => -3])
    ->setDisplayOptions("form", ["type" => "string_textfield", "weigth" => -3]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('place', 'course', 'course', $storage_definition);
}

```

I also fixed a typo in your code: Instead of `"weight"`, you wrote `"wegith"`.

The code I am showing is for adding a new field. The change record I linked shows also the code to use when existing fields are promoted to entity keys,or when the cardinality of a field with existing data is changed from single to multiple (or from multiple to single).

Before Automatic entity updates can fail when there is existing content, leaving the site's schema in an unpredictable state (one of the issues linked from the change record) was fixed, update.php had an automated system to fix the entity schema, which didn't make the entity schema state predictable for module updates.
Given the branch that removed the automatic updates, I would say that practically all the modules need to use code similar to the one I show in this answer.
> 8 votes

# Answer
Starting from **Drupal 8.7.0** you need to use the Update API for that task, like so:

In `modulename.install` add a function like this:

```
function modulename_update_8001() {
  $field_storage_definition = BaseFieldDefinition::create('timestamp')
    ->setLabel(t('Start'))
    ->setDescription(t('The first day'))
    ->setRevisionable(FALSE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('start', $entity_type_id, $entity_type_id, $field_storage_definition);
}

```

Then run `drush updatedb` or go to Database Updates on the status report.

See https://www.drupal.org/node/3034742 for deeper understanding.
> 4 votes

# Answer
You should execute the command with drush drush updatedb --entity-updates
> 2 votes

# Answer
The code for an individual update is similar to the following one.

```
function my_module_update_8400() {
  $entity_manager = \Drupal::entityManager();
  $reserved = $entity_manager->getFieldStorageDefinitions('table_name')['column_name'];
  $entity_manager->onFieldStorageDefinitionCreate($reserved);
}

```
> 1 votes

---
Tags: entities, 8, database
---


# Question
Title: on click popup load another popup and close other popup
I'm having a requirement where I have to show popup on the click link. and then after that pop up open need to show related content on that pop-up. this part is working. by doing this

```
<a class="use-ajax" data-dialog-type="modal" href="/node/{{ nid }}">
Click
    </a>

```

so when I click related content I again need to show a popup and close the old one. this case not working

I know there is CloseModalDialogCommand but how to use in this case as I have

```
    <a class="use-ajax" data-dialog-type="modal" href="/node/{{ nid }}">
Click
    </a>

```

this link for related content also

# Answer
> 1 votes
As per my understanding you want to open a new modal from an existing open modal. I have checked the same case in latest drupal 8.7.5 and it works without a problem. You don't have to add any additional script to do this. I would recommend you to debug it and check the exact problem that is preventing popup to open and close existing one. You can follow the below steps to debug it-

1. Create any of 2 dummy articles like below and link one with another one.

> First Article:-
>
> ```
> Title - Dummy Article 1
> Body - <a class="use-ajax" data-dialog-type="modal" href="/node/2">Click Article 2</a>
> Text Format - Full HTML
> URL - node/1
>
> ```
>
> Second Article:-
>
> ```
> Title - Dummy Article 2
> Body - <a class="use-ajax" data-dialog-type="modal" href="/node/1">Click Article 1</a>
> Text Format - Full HTML
> URL - node/2
>
> ```

Open/View any of the above created article to check if the problem is with the modal or related with any other issue. Check browser console if in case modal doesn't open.

---
Tags: 8, modal-dialogs
---


# Question
Title: How to specify the file path for the private file system?
Environment: Shared hosting, Apache.

Home directory: **/home/someuser**

Website at: **/home/someuser/public\_html/stuff**

I've spent 2 days trying to get this to work, and realise that as soon as I'm answered it will be blindingly obvious, but I'm failing miserably right now.

I have created a directory in my public\_html directory called **private\_files** with a sub-directory called **stuff**. Both have access rights 755.

I have edited settings.php to include the line:

```
# $settings['file_private_path']
= '/home/someuser/public_html/private_files/stuff';

```

I have cleared all caches.

The file system configuration page shows:

> Private file system path
>
> Not set

What stunningly stupid mistake am I making? Why is what I'm doing wrong?

# Answer
In order for this question to be marked as answered, @Clive pointed out here that the problem was the leading `#` character, which made the 1st line a comment, meaning that the `file_private_path` was never set.

The correct line should be

```
$settings['file_private_path'] = '/home/someuser/public_html/private_files/stuff';

```
> 4 votes

---
Tags: 8
---


# Question
Title: What are configuration entities used for?
I’m trying to wrap my head around D8 Configuration Entities (CFE). The concept of a Content Entity (CTE) seems easy – if you want an application that keeps the information for a CD music collection you can build a content entity that creates a table and stores the fields of your CDs (e.g. *Artist* and *Title*).

What is a CFE is used for? When the CFE example in the “examples” module is installed the result is a link to a page that shows a table that contains one default “robot” (Marvin) and a button to "Add A Robot". How is this different from creating a robot entity via a CTE?

I do appreciate that there is a structural database difference. The data for each robot gets stored in the *config* table.

# Answer
> 5 votes
I would like to add some additional general thoughts on the differences…

Content entities are generally external facing, meaning your site viewers will interact with your content – ie. they will read your pages & articles; they will look at your images, they will browse thru your product catalog, they will post comments and reviews, etc.

Config entities are generally internal facing, normally only site administrators & content editors interact with a config entity such as setting up a new view or adding a block to a page.

There are many, many, instances of content entities – think of a news website and how many hundreds or thousands of articles there are, but there are only a few instances of config entities – with the article, there may just be one content type (content types are config entities) needed for all those articles.

Content entities generally store data in their own database tables and fields though you don’t have to use hook\_schema to create them, they are more often instantiated in the class annotations, with yaml files or by using the UI. Config entities can have database fields, but by default they do not. That is not to say they don’t have fields, they do have fields. The content type entity has fields, such as name and description (you just won’t find them in the database as such).

# Answer
> 4 votes
The configuration entity is used to create configuration items. Entities allow you to store more complex configuration structures, which can be listed, edited, deleted, etc., but, above all, can be instantiated multiple times.

Examples of configuration entities include date formats, vocabularies, image styles, roles, menus, views, Pathauto URL patterns, and text formats. All have in common that you can create multiple such elements, and perform other common operations like edit and delete. They also have in common that they are entities that are only managed from the configuration or administration of the site, without exposing them to the end user.

Configuration entities are translatable and can provide default values that will be taken into account during installation. Configuration entities can not have fields.

Content Entity. Content entities are used to create content items. They differ mainly because they have fields. The Manage fields, Manage presentation, etc. options are common in content entities. They are also translatable and, optionally, may have revisions.

Examples of content entities are nodes, comments, taxonomy terms, users, files, custom block types, etc.

A fundamental difference between the two variants is that the configuration entities use the configuration system to store the information, instead of the database, which is the storage used by the content entities.

# Answer
> 1 votes
Configuration entities are useing the entity API in order to keep configuration in the database, not content.

Differences compared to Content Entity

1. Integrates with CMI API for exportability (yml files)
2. No fields
3. Schema file (Content Entity uses hook\_schema())

If you create a module that needs to store some configuration per "whatever" (i.e. role), use config entities.

More about this on Drupal.org

# Answer
> 1 votes
Another way to ask and answer this question is "why".

If you look at some contributed modules in Drupal 7, and particularly if you look at their uninstall code, you'll see some pretty ugly stuff getting jammed into the variables table, because this was the easy and default way to store "user" configuration from a module (if you want a random example, try "fivestar").

So if you start thinking about how to handle these "dynamic" kinds of configuration, and you've got this nice "entity" abstraction sitting around, you'll appreciate that it's a great fit - you get stuff like CRUD and listings sort of for free which is typically what you want for this kind of configuration-type thingy.

The hardest part (IMHO) is updating your brain to separate entities from content, which is what entities are often used for. The real key is to understand "user configuration with multiple entries" - that's the thing that is such a nice match to entities and why configuration entities were developed.

---
Tags: 8, entities
---


title: Error during config export

text:
# Question
Title: Error during config export
I have added one field in the content type. So when trying to export configuration it gives an error

```
$ pwd
$ /c/xampp/htdocs/Test/docroot/sites/testone.com
$ ../../../vendor/bin/drush config:export --uri=test.com

```

> Command config:export was not found. Drush was unable to query the database. As a result, many commands are unavailable. Re-run your command with --debug to see relevant log messages.

Other Information are below:

```
/c/xampp/htdocs/Test/docroot/sites/testone.com
$ ../../../vendor/bin/drush status --uri=test.com
Drupal version : 8.6.17
Site URI       : test.com
DB driver      : mysql
DB hostname    : xxx
DB port        : xxxx
DB username    : xxxxxx
DB name        : xxxxxx
PHP binary     : C:\xampp\php\php.exe
PHP config     : C:\xampp\php\php.ini
Drush script   : C:/xampp/htdocs/Test/vendor/drush/drush/drush
Drush version  : 9.4.0
Drush temp     : C:\Users\xxxx\AppData\Local\Temp
Drush configs  : C:\xampp\htdocs\Test\vendor\drush\drush/drush.yml
Drupal root    : C:\xampp\htdocs\Test/docroot
Site path      : sites/testone.com

```

DEBUG Details

```
 /c/xampp/htdocs/Test/docroot/sites/testone.com
$ ../../../vendor/bin/drush cex -l testone.com --uri=test.com --debug
 [preflight] Config paths: C:\xampp\htdocs\Test\vendor\drush\drush/drush.yml
 [preflight] Alias paths: C:\xampp\htdocs\Test\docroot/drush/sites,C:/xampp/htdocs/Test/drush/sites
 [preflight] Commandfile search paths: C:\xampp\htdocs\Test\vendor\drush\drush\src
 [debug] Bootstrap further to find cex
 [debug] Trying to bootstrap as far as we can
 [bootstrap] Drush bootstrap phase: bootstrapDrupalRoot()
 [bootstrap] Change working directory to C:\xampp\htdocs\Test/docroot
 [bootstrap] Initialized Drupal 8.6.17 root directory at C:\xampp\htdocs\Test/docroot
 [bootstrap] Drush bootstrap phase: bootstrapDrupalSite()
 [bootstrap] Initialized Drupal site test.com at sites/testone.com
 [bootstrap] Drush bootstrap phase: bootstrapDrupalConfiguration()
 [debug] Add service modifier
 [info] sql-query: SELECT 1;
 [info] Executing: mysql --defaults-file="C:\\Users\\XXXXXXXX\\AppData\\Local\\Temp\\dru3652.tmp" --database=XXXX --host=XXXX --port=3306 --silent  < "C:\\Users\\XXXXXXXX\\AppData\\Local\\Temp\\dru3641.tmp" > nul
 [bootstrap] Drush was not able to start (bootstrap) the Drupal database.
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.
More information may be available by running `drush status`
 [debug] Bootstrap phase bootstrapDrupalDatabase() failed to validate; continuing at bootstrapDrupalConfiguration()
 [debug] Done with bootstrap max in Application::find(): trying to find cex again.

In Application.php line 238:

  [Symfony\Component\Console\Exception\CommandNotFoundException]
  Command cex was not found. Drush was unable to query the database. As a result, many commands are unavailable. Re-r
  un your command with --debug to see relevant log messages.

Exception trace:
 () at C:\xampp\htdocs\Test\vendor\drush\drush\src\Application.php:238
 Drush\Application->bootstrapAndFind() at C:\xampp\htdocs\Test\vendor\drush\drush\src\Application.php:191
 Drush\Application->find() at C:\xampp\htdocs\Test\vendor\symfony\console\Application.php:236
 Symfony\Component\Console\Application->doRun() at C:\xampp\htdocs\Test\vendor\symfony\console\Application.php:148
 Symfony\Component\Console\Application->run() at C:\xampp\htdocs\Test\vendor\drush\drush\src\Runtime\Runtime.php:112
 Drush\Runtime\Runtime->doRun() at C:\xampp\htdocs\Test\vendor\drush\drush\src\Runtime\Runtime.php:41
 Drush\Runtime\Runtime->run() at C:\xampp\htdocs\Test\vendor\drush\drush\drush.php:66
 require() at C:\xampp\htdocs\Test\vendor\drush\drush\drush:4

```

But when I run drush status command, it works. Is there any step m missing?

# Answer
You are targeting a multisite instance. So you need to add the `-l` option to tell Drush what site you are targeting at. Otherwise Drush will try to target the default site.

```
drush cex -l testone.com --uri=test.com

```

The `--uri` option is to tell Drush what base path to use, for example for generating the sitemap, which isn't known to PHP when triggering code from the command line instead of from within a browser.
> 1 votes

# Answer
Finally, I found the solution for the above "\** ERROR: Drush was not able to start (bootstrap) the Drupal database\**". In short, drush was not able to communicate with MySQL.

**Solution**: Add a new system environment variable in the path "C:\xampp\mysql\bin" and restart gitbash. Then try to run above command. It works properly :) . Hope it may help someone.
> 0 votes

# Answer
The command `config:export` only works if Drush is able to connect to your site or your site's database to be 100% correct. If you aren't connected, the command is reported as not found.

Added: I missed the part about multisite. leymannx's answer is much better.
> -1 votes

---
Tags: 8, drush
---


# Question
Title: What is the appropriate way to store arrays of information with configuration API?
In Drupal 7 with custom forms and variables, one could easily store arrays of information in the 'variables' table. I would sometimes construct configuration forms that provided a setting per say user role. Then I could either store the setting for each role in a separate variable, or pack all the settings into one array and store it that way.

I am wondering what the standard best practices way of doing a similar thing in Drupal 8.

in Drupal 7 I would have something like this for a form code:

```
// build list of roles
  $user_roles = user_roles(TRUE);
  // remove authenticated user role from options
  if (isset($user_roles[2])) {
    unset($user_roles[2]);
  }
$role_settings = variable_get('MYMODULE_role_type_mapping', $role_settings);
foreach ($user_roles as $rid => $role) {
      $form['roles']['other_roles']['MYMODULE_role_' . $rid . '_type_mapping'] = [
        '#title'         => $role,
        '#type'          => 'select',
        '#options'       => $membership_types,
        '#default_value' => !empty($role_settings[$rid]) ? $role_settings[$rid] : '',
      ];
    }

```

and then something like this in the form submit callback:

```
    // build list of roles
      $user_roles = user_roles(TRUE);
      // remove authenticated user role from options
      if (isset($user_roles[2])) {
        unset($user_roles[2]);
      }
      foreach ($user_roles as $rid => $role) {
        $role_settings[$rid] = !empty($form_state['values']['MYMODULE_role_' . $rid . '_type_mapping']) ? $form_state['values']['MYMODULE_role_' . $rid . '_type_mapping'] : '';
      }
variable_set('MYMODULE_role_type_mapping', $role_settings);

```

This type of thing is necessary when you install the custom module on multiple sites, where there could be different number of roles on each site.

So now with Drupal 8 we have this new Configuration API. I can't assume I know the roles in advance.

I was hoping to achieve this with "Simple Configuration" but I realize it may be necessary to create a custom configuration entity, although if it can be done without that that would be nice and "simple".

According to this resource: https://www.drupal.org/node/1905070#types There are just a few schema types for configuration fields, none of which seem intuitively appropriate to this case.

Reading that page, it is not obvious even how one would store the value of a multi-valued select list in configuration, let alone variable that could be an array of all kinds of different information. In D7 a multi-valued select list would return an array. In D7 variables are stored as serialized variables. Even D7's "simple\_settings\_form" would handle this no problem.

Surely this type of problem has been solved many times, but it is not "simple" to find any information.

So the problem is two-fold 1) Just storing an array of values into configuration, with unknown number of array elements, number depending on custom site conditions (like user roles on a site) 2) Unpacking this array and setting up form elements for it, which on submit, packs it all up into one variable.

Similar question, simpler question is: If one is defining configuration schema for a multi-valued select list, what data type does one use? String?

Is the model I used here for D7 even portable to D8, there's probably some better way to go no doubt, but making a configuration entity for each role in the site and all of that doesn't seem simple and definitely not as simple as could be done in D7. I do want to give a thought to config export / import between sites. dev/staging/production versions of the site may all have the same user roles, but definitely not separate websites altogether.

Although I ask several questions in this post, the common theme is how to store arrays of information as configuration appropriately in Drupal 8? Simple case is the value of a multi-valued select list, more complex scenario of the setting per user role like I describe.

Thanks in advance!

# Answer
> 7 votes
You define a schema type `sequence`:

Example: */core/modules/options/config/schema/options.schema.yml*

```
# Schema for the configuration files of the Options module.

field.storage_settings.list_integer:
  type: mapping
  label: 'List (integer) settings'
  mapping:
    allowed_values:
      type: sequence
      label: 'Allowed values list'
      sequence:
        type: mapping
        label: 'Allowed value with label'
        mapping:
          value:
            type: integer
            label: 'Value'
          label:
            type: label
            label: 'Label'

```

You'll find the form for this example in */core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php*

More info https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata

# Answer
> 4 votes
I was recently struggling how to store data with a nested array of strings,

```
allowed_view_modes:
  image:
    embed: embed
    full: full

```

The only way I could figure out how to validate it was by running functional tests, where it validates the configs when you save a config entity.

I was able to save data like the above data by nesting 'sequences':

```
ckeditor.plugin.drupalmedia:
  type: mapping
  label: 'Media Embed'
  mapping:
    allowed_view_modes:
      type: sequence
      label: 'Allowed View Modes'
      nullable: true
      sequence:
        type: sequence
        nullable: true
        label: 'View Mode'
        sequence:
          type: string

```

This worked and passed the config linter.

The top level sequence is for the media type, the inner sequence is for each view mode. There are lots of complex examples in drupal core. Unfortunately, I don't know where to point you for the documentation. I've mostly been learning this by trial and error.

# Answer
> 4 votes
This was custom openid\_connect plugin I was working on, so a bit different than a ConfigFormBase normal configuration form, but I hope this methodology applies and is helpful to someone in the future. I used a schema like so (snippet):

```
# Schema for the configuration files of the OpenID Connect module.
openid_connect.settings.nimble:
  type: config_object
  label: 'OpenID Connect Nimble settings'
  mapping:
    enabled:
      type: boolean
      label: 'Enable client'
    settings:
      type: mapping
      mapping:
        roles_membership_types:
        type: sequence
        label: 'Role Membership Types'
        sequence:
          type: mapping
          label: 'Roles mapped to membership types'
          mapping:
            role:
              type: string
              label: 'Role id'
            membership_type:
              type: string
              label: 'Membership Type'

```

FAPI setup like so (I had NO form index for the actual name of the config item, roles\_membership\_types:

```
    $roles = user_role_names(TRUE);
    if (isset($roles['authenticated'])) {
      unset($roles['authenticated']);
    }
    $membership_types = ['' => 'None'] + $this->getMembershipTypes($this->configuration['instance']);
    $roles_membership_types = $this->configuration['roles_membership_types'];
    if (!empty($roles_membership_types)) {
      foreach ($roles_membership_types as $type) {
        $roles_membership_types_default_values[$type['role']] = $type['membership_type'];
      }
    }
    foreach ($roles as $rid => $role) {
      $form['roles_mapped_membership_types'][$rid] = [
        '#title'         => $role,
        '#type'          => 'select',
        '#options'       => $membership_types,
        '#default_value' => !empty($roles_membership_types_default_values[$rid]) ? $roles_membership_types_default_values[$rid] : '',
      ];
    }

```

Little bit of code in the submit handler to get the values from the role form elements, and put it together in the format necessary to map the config.

```
$values = $form_state->getValues();
if (!empty($values['roles_mapped_membership_types'])) {
  foreach ($values['roles_mapped_membership_types'] as $rid => $membership_type) {
    $roles_to_membership_type_value[] = ['role' => $rid, 'membership_type' => $membership_type];
  }
$form_state->setValue('roles_membership_types', $roles_to_membership_type_value);
}

```

So eventually this code would work:

```
// Save plugin settings.
$this->configFactory()
  ->getEditable('openid_connect.settings.' . $plugin_id)
  ->set('settings', $subform_state->getValues())
  ->save();

```

---
Tags: 8, configuration
---


title: Error is not catching properly

text:
# Question
Title: Error is not catching properly
I have a `try... catch` error handling while saving a custom form in the submit handler, but it is not going to the catch block nor throwing any error to the front end. Instead, it is throwing a fatal error and logging into the Apache error log. How could I force the error to appear on the front end?

```
   public function approve_button_handler(array &$form, FormStateInterface $form_state){
          $nid = $form_state->getValue('nid');
          try {
            $terra_node = Node::load($nid);
            $terra_node->set('field_number_of_cpu_s', $number_of_cpus);
            $terra_nodess->set('field_memory', $memory); //this is wrong
            //as i given $terra_nodess as the loaded entity type node,
            //or I could give a wrong field name.

            $terra_node->save();
          } catch (Exception $e) { //Not catching here
              drupal_set_message(t($e), 'error');
          }
    }

```

# Answer
This is not a Drupal question, but a general PHP question. If your site is running PHP7, you can use the new `Throwable` instead of the `Exception`

```
   public function approve_button_handler(array &$form, FormStateInterface $form_state){
          $nid = $form_state->getValue('nid');
          try {
            $terra_node = Node::load($nid);
            $terra_node->set('field_number_of_cpu_s', $number_of_cpus);
            $terra_nodess->set('field_memory', $memory); //this is wrong

            $terra_node->save();
          } catch (Throwable $e) { // Use Throwable instead of Exception here
              drupal_set_message($e->getMessage(), 'error');
          }
    }

```

Remember, PHP7 only! And I fully agree with Clive's comment, showing Exceptions in the UI is a bad idea.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How do I migrate content to a field added with UI to an existing custom content entity?
In a custom module (assoc), I have a custom Content Entity (Person) with these fields:

```
$fields['lastname'] = BaseFieldDefinition::create('string')
$fields['firstname'] = BaseFieldDefinition::create('string')
$fields['email'] = BaseFieldDefinition::create('email')
$fields['cellphone'] = BaseFieldDefinition::create('telephone')

```

I migrated Person content from a Drupal 6 site using Migrate Source CSV, Migrate Plus, Migrate Tools and this migration file:

```
id: migration_persons
migration_tags: null
migration_group: null
label: 'Person migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Persons.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  lastname: lastname
  firstname: firstname
  cellphone: cellphone
  email: mail
  iscontact: iscontact
  isactive: isactive
  member_id: member_id
  user_id: user_id
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:person'
migration_dependencies:
  required: {}
  optional: {}

```

I added a field to this entity using the UI:  The corresponding config files are `field.storage.person.field_sel_initial_credit.yml` and `field.field.person.person.field_sel_initial_credit.yml` I tried to migrate some content to this field using

```
id: migration_sel_initial_credit
migration_tags: null
migration_group: null
label: 'Sel initial credit migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Sel_initial_credit.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - uid
process:
  bundle: "person"
  entity_id: uid
  revision_id: uid
  field_sel_initial_credit_value: value
destination:
  plugin: 'entity:field_storage_config'
migration_dependencies:
  required: {}
  optional: {}

```

and I got this error when executing the migration:

```
[error]  Attempt to create a field storage without a field name. (/Users/efalzon/Sites/JdP8M7b/web/core/modules/field/src/Entity/FieldStorageConfig.php:252)

```

What am i missing?

# Answer
> 0 votes
In fact, it was easier than I thought. I just had to add the field to the Person migration file:

```
id: migration_persons_with_sel
migration_tags: null
migration_group: null
label: 'Person migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Persons.csv
  delimiter: ;
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  lastname: lastname
  firstname: firstname
  cellphone: cellphone
  email: mail
  iscontact: iscontact
  isactive: isactive
  member_id: member_id
  user_id: user_id
  field_sel_initial_credit: credit <----------
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:person'
migration_dependencies:
  required: {  }
  optional: {  }

```

---
Tags: 8, entities, migrations
---


# Question
Title: How do I enable users to submit sessions in "Conference Organizing Distribution"?
I don't see any configuration item or link that would enable logged-in users to submit sessions in the Conference Organizing Distribution module. How can I enable this? What link should I use?

I'm using the latest module version for Drupal 7.

# Answer
> 0 votes
Okay, I figured this out. It's as simple as going here as a logged in user: https://example.com/node/add/session

---
Tags: 7
---


# Question
Title: Display Jalali (Shamsi) Date in Archive View
I have a Persian language website and I need to a archive block in my site. but date of default archive view is Gregorian. I install Datex module and it convert all date of nodes to Jalali(Shamsi) Date but can't convert Gregorian date to Jalali Date in archive view. I want to archive content in year+month format. any one has another idea for convert date in archive view?

# Answer
> 0 votes
you can use of persoanTools module persian Tools change calender to jalali and you can use of it in archive and views pages

# Answer
> 0 votes
to display jalali date in drupal, you can do one of the following :

1. install persian tools and Calendar Systems and in node.tpl file write the following:

> ```
> <time datetime="<?php print date('Y-m-d H:i:s', $node->created) ?>"><?php print $date ?></time>
>
> ```

2. get timestamp from php, convert it to javascript timestamp and display it using toLocalDateString():

> ```
> <time datetime="<?php print date('Y-m-d H:i:s', $node->created); ?>">
>     <span class="publishedon">
>         <script>let pdate = new Date(<?php print $node->created.'000'; ?>).toLocaleDateString('fa-IR');  jQuery('.publishedon').text(pdate);</script>
>     </span>
> </time>
>
> ```

---
Tags: views, datetime
---


# Question
Title: Endless redirect on paths containing question marks
A similar question was posted here: EventSubscriber endless redirect

But I haven't quite been able to implement a workable solution.

On Drupal 8.73: Basically we have a custom module that is redirecting to clean urls (so that /node/42 doesn't get indexed by google). I didn't write the module and I'm a little fuzzy on what it's doing and why. The module works fine except that urls with `?` in them endlessly redirect and get caught in a redirect loop. The browser eventually returns an error that the page is redirecting and will never load properly. Here is the module:

```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\EventSubscriber\MyModuleSubscriber.
 */

namespace Drupal\sjwc_tweaks\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Event subscriptions for events dispatched by SimpleFbConnect.
 */
class TweaksSubscriber implements EventSubscriberInterface {

  public function onRequest(GetResponseEvent $event) {
    $baseUrl = $event->getRequest()->getBaseUrl();
    $attr = $event->getRequest()->attributes;
    if (null !== $attr && null !== $attr->get('node') && $attr->get('_controller') == '\Drupal\node\Controller\NodeViewController::view') {
      $node = $attr->get('node');
      $nid = $node->id();
      $current_uri = \Drupal::request()->getRequestUri();
      if (\Drupal::service('path.matcher')->isFrontPage()) {
        $redirect_uri = '/';
      } else {
        $url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
        $redirect_uri = $url->toString();
      }
      if ($redirect_uri != $current_uri) {
        $event->setResponse(new RedirectResponse($redirect_uri));
      }
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onRequest'];
    return $events;
  }

}

```

---

I believe this line is the issue:

```
$event->setResponse(new RedirectResponse($redirect_uri));

```

At the issue linked above, a kind user suggested a solution that I do not quite understand, they said:

> The problem is, you should never send a response inside of a StackPHP application. Drupal continues to build its own response (the real frontpage) and stores this in the cache. Set the response in the event instead: $event-\>setResponse($response);

I'm not sure exactly where he means by setting the response "in the event" instead.

Now, as this issue only is a problem on urls with `?` in them, I did find I could correct the issue by wrapping the line above, line 37 thusly:

```
if (strpos($current_uri, '?') != TRUE) {
  $event->setResponse(new RedirectResponse($redirect_uri));
}

```

However I worry this might cause unpredictable behavior and I prefer to fix this the right way the first time. Can someone tell me what I'm doing wrong or overlooking or explain how I can "set the response in the event" instead?

# Answer
You can try to manually add the query parameters to the redirect URL.

Add this code:

```
$query = [];
parse_str($current_uri, $query);

```

just below this code:

```
$current_uri = \Drupal::request()->getRequestUri();

```

And then change this line:

```
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);

```

To this:

```
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid], ['query' => $query]);

```
> 0 votes

---
Tags: 8, redirection
---


# Question
Title: View is removing iframe from custom text
I'm using a global custom text field within a view that is meant to display an embedded youtube video.

However in the actual render of the view it's completely removed from the dom.

My first assumption was that ckeditor was not allowing the iframe tag and removing it itself. However I have it setup to allow iframe tags, and if I go back and edit the Global Custom text it still appears. If it didn't allow it I'm assuming it would not appear in the editor the next time I open and edit the field.

Also I'm able to embed iframes in the body text of nodes just fine. It's specifically in views.

I also attempted creating iframes with different src's in different divs but I still had the same behavior.

Are there other possible causes of Drupal removing iframes from custom text in views? Is this the expected behavior? If this is the expected behavior is there away around this?

EDIT: Forgot to mention that 'Strip HTML tags' is also turned off.

# Answer
> 1 votes
This is not the expected behavior of drupal views, Drupal Views usually not doing this. I have done this before, and global text with iframe is working with no issue. Maybe you have another issue like some javascript issue to prevent the load iframe form another site, see the console of your webpage maybe you got some error.

You can debug also by putting that iframe into any page Textarea field where you already use the HTML content of your website.

# Answer
> 0 votes
Check in the view preview whether the iframe shows there. If it does, your issue is with your theme, most likely, or some module, but not Views.

---
Tags: 7, views
---


title: Export menu configuration

text:
# Question
Title: Export menu configuration
Looking for a way to export menu configuration. The Configuration management system will export the menu itself, but not the menu links configuration. I am looking for a way to put one of those mega menus into version control to import/export through multiple environments.

If anyone has found a good way to do this. I would be greatly appreciative.

# Answer
Menu links can come from 3 sources:

* Views module (these can be exported when the view config is exported)
* `.links.yml` file in a module (not possible to export)
* Created menu links (Is content entities, like nodes, users, etc and is not possible to export)

I'm guessing you are creating menu links via interface, which is content. The config system can't export content, which is by design. If you wanted to synchronize content, you would need to look at the Deploy module suite. I'm not sure how well this is working atm, since it's still in alpha.
> 8 votes

# Answer
My experience with Drupal 8 step by step

First of all, you need to install Menu Export module and activate it. After that, you will have Export Menu in the Structure part.

> **Steps to Export & Import**

1- In the Export Menu page `domain.com/admin/config/development/menu_export`, you have three option, at **Menu list** select which menus you want to export.

2- On the Export section, export your menus.

**(In this step menu setting will not be exported on YML file then you need to continue.)**

3- Now you need to export system configuration from `domain.com/admin/config/development/configuration/full/export` or `drush cex`

**Note: after export, you will have `menu_export.export_data.yml` file that contains your menu settings**

4- Transfer configuration anywhere you want, then you need to import them from `domain.com/admin/config/development/configuration/full/import` or `drush cim`

5- Then you need to import menus to your system from UI `domain.com/admin/config/development/menu_export/import`

> **Important Note**
>
> Clear your cache
>
> In some cases, mostly with **Administration** menu you need do and **extra step**. That you need to just open the edit Administration menu page and just saving it without any changes after this you should see your updated menu on administration as well.
> 3 votes

# Answer
Check the Config Menu Link module.
> 2 votes

# Answer
There's also Menu Import and Export:

> This module helps in exporting and importing Menu Items among cloned sites which is not possible using CMI.
>
> This module exports the menu entity as config YAML and will be imported on subsequent instances.
> 2 votes

---
Tags: 8, navigation, configuration
---


# Question
Title: Form is not submitting after ajax callback
I have a form which has a checkboxes field.

This field has an ajax callback attached

```
$form['checkboxes'] = array(
  '#type' => 'checkboxes',
  '#title' => 'test',
  '#ajax' => array(
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'test-wrapper',
    'method' => 'replace'
  );
);

function mymodule_ajax_callback(&form, &$form_state) {
  return $form['another-field'];
}

```

When I check a checkbox, the ajax callback is executed. Then when I try to submit the form through form submit button, it reloads the same page with values in the fields, but the form is not submitted.

I have tried `$form_state['rebuild'] = TRUE` in the ajax callback also but it did not help.

I have added the `#name` and `#id` properties also to the submit button but no luck.

Is there any other solution which I can try?

# Answer
I think the problem is that you only return the `another-field` in the ajax callback.

You probably have to make a wrapper for the submit and the `another-field`.

So you willl have:

```
$form['ajax_wrapper'] = array(
  'submit' => array(
    // Submit button...
  ),
  'another-field' => array(
    // Another field...
  ),
);

```

And then return `$form['ajax_wrapper']` in your ajax callback. Make sure to use `$form_state['rebuild'] = TRUE`;
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: How to add additional information to shipping methods?
I have a list of shipping methods added via the UI `admin/commerce/config/shipping-methods`.

I need to have an accompanying description added to each shipping method.
First I thought that I could add an additional field under the settings for shipping types, but this didn't work (Added the field, but it never shows up when adding or editing a shipping method).

I'm fine if this is only doable programmatically, but I have found absolute zero information on how to do this on drupal 8.
I would actually prefer if I can do it programmatically, as I will be adding my own shipping method plugin in the future.

**Question**
How do I add an additional field to each shipping method?

# Answer
I know this is an old thread, but I encountered the same problem. So in case you have the same issue:

This isn't really a commerce question, rather a general one.

There is a hook, where you can simple add new fields to an existing entity: HOOK\_entity\_base\_field\_info

So in this case:

```
/**
 * Implements hook_entity_base_field_info().
 */
function yourmodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'commerce_shipping_method') {
    $fields['shipment_description'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Description'))
      ->setDescription(t('The shipping method description.'))
      ->setRequired(FALSE)
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
    }
}

```

This will add a simple textarea field type, but you can add any field type you like.

This will only add the field visually, you must also do an update to your database table. In a .install file, do something like this:

```
/**
 * Implements hook_install().
 */
function hartmann_add_field_install() {
  $entity_manager = \Drupal::entityManager();

  $desc_definition = $entity_manager->getFieldStorageDefinitions('commerce_shipping_method')['shipment_description'];
  $entity_manager->onFieldStorageDefinitionCreate($desc_definition);
}

/**
 * Implements hook_uninstall().
 */
function hartmann_add_field_uninstall() {
  $entity_manager = \Drupal::entityManager();

  $desc_definition = $entity_manager->getLastInstalledFieldStorageDefinitions('commerce_shipping_method')['shipment_description'];
  $entity_manager->onFieldStorageDefinitionDelete($desc_definition);
}

```

Then reinstall your module. In more recent versions of Drupal 8, entitymanager is deprecated. I don't now the updated code for .install, but some research and you will find it.
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: chmod() and touch() operations not permitted
After updating drupal8 for 8.7.0 and then to 8.7.1 versions i have next errors:

> Warning: chmod(): Operation not permitted in Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage-\>save() (line 76 of core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php).
>
> Warning: touch(): Utime failed: Operation not permitted in Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage-\>save() (line 100 of core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php).

This errors appears for all twig templates and only at first time page loaded. For second and other times no errors and template created in cache folder.

I set 777 permission for all files. Checked files owner. Was Reading many forums and nothing ...

# Answer
> 2 votes
I fixed this problem by updating the file owner; changing the group only is not enough. Before I had *vagrant* as owner, and *www-data* as group. Now *www-data* is both the owner and the group.

But it's still strange for me. If I refresh the page, sometimes files are generated and the warnings go away.

---
Tags: 8, files, caching
---


# Question
Title: Composer update - Your requirements could not be resolved to an installable set of packages
when I run a composer update --with-dependencies, I get the following error message:

```
Problem 1
    - don't install drupal/core 8.6.0|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.0-alpha1|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.0-beta2|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.1|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.10|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.11|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.12|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.13|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.14|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.15|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.16|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.17|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.2|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.3|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.4|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.5|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.6|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.7|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.8|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.9|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.0|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.0-alpha1|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.0-alpha2|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.0-beta2|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.1|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.2|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.3|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.4|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.5|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.6|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.8.x-dev|remove drupal/drupal dev-master
    - remove drupal/drupal dev-master|remove drupal/core 8.7.6
    - Installation request for drupal/drupal dev-master -> satisfiable by drupal/drupal[dev-master].
    - Installation request for drupal/core ~8.6 -> satisfiable by drupal/core[8.6.0, 8.6.0-alpha1, 8.6.0-beta1, 8.6.0-beta2, 8.6.0-rc1, 8.6.1, 8.6.10, 8.6.11, 8.6.12, 8.6.13, 8.6.14, 8.6.15, 8.6.16, 8.6.17, 8.6.2, 8.6.3, 8.6.4, 8.6.5, 8.6.6, 8.6.7, 8.6.8, 8.6.9, 8.6.x-dev, 8.7.0, 8.7.0-alpha1, 8.7.0-alpha2, 8.7.0-beta1, 8.7.0-beta2, 8.7.0-rc1, 8.7.1, 8.7.2, 8.7.3, 8.7.4, 8.7.5, 8.7.6, 8.7.x-dev, 8.8.x-dev].

```

I have tried:

```
composer clearcache
rm composer.lock
rm -R vendor
rm -R core

```

and then one again:

```
composer update --with-dependencies

```

but still this error!!!

My composer.json:

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/address": "^1.2",
        "drupal/admin_toolbar": "^1.20",
        "drupal/commerce": "^2.0",
        "drupal/commerce_variation_cart_form": "^1.0",
        "drupal/config_update": "^1.4",
        "drupal/ctools": "^3.0",
        "drupal/devel": "^2.0",
        "drupal/features": "^3.7",
        "drupal/imce": "^1.6",
        "drupal/pathauto": "^1.1",
        "drupal/votingapi": "^3.0",
        "drupal/views_flipped_table" : "^1.2",
        "drupal/field_group": "^1.0",
        "drupal/entity_browser": "^2.0",
        "drupal/shortcode": "^1.0",
        "drupal/dropzonejs": "^2.0@alpha",
        "drupal/embed": "^1.0",
        "drupal/token": "^1.0",
        "drupal/webform": "^5.0",
        "drupal/core": "~8.6",
        "drush/drush": "~9.0"
    },
    "replace": {

    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "drupal-phpunit-upgrade-check": "Drupal\\Core\\Composer\\Composer::upgradePHPUnit",
        "drupal-phpunit-upgrade": "@composer update phpunit/phpunit --with-dependencies --no-progress",
        "phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --",
        "phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    }
}

```

What's wrong? Would be grateful for any help?

Thanks

# Answer
You are using drupal/drupal that is deprecated (because upgrading is very hard / impossible). After you have fixed the drupal/drupal problem, follow the normal update instructions.
> 2 votes

# Answer
You are using the tilde here: `"drupal/core": "~8.6",`

From experience I know it is better to pinpoint drupal/core to a certain version. FE `"drupal/core": "8.6.17",` This leaves composer with no other choice than going for that version of core.

In case you are using the webflo template you have to run another command: composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

Or find this package in the composer.json and also pinpoint it to the core version you want.
> 1 votes

---
Tags: updating, composer
---


title: How can I get the module path in twig?

text:
# Question
Title: How can I get the module path in twig?
I have a module and created twig templates there. I just followed the documentation here: https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-for-custom-module

I want to include a JS file from the twig. And the JS file is located inside the module folder. I have this code in the twig:

```
<script src="/{{ directory }}/js/script.js"></script>

```

But the `directory` is returning the theme path NOT the module path. How can I get the module path inside the twig?

# Answer
There is a solution that can work for your problem without going into php and this solution will work only in case if twig template is under module directory.

Suppose my module structure is like below:

* modules
    + custom\_module
        - templates
            * my-template.html.twig
        - js
            * script.js

To include **script.js** in **my-template.html.twig** file. Use below code in **twig** file -

```
{% set module_path = _self|split('/templates') %}
<script src="/{{ module_path[0] }}/js/script.js"></script>

```

In above script `_self` returns the path upto twig file and `split('/templates')` splits the string from `/templates` AND

```
module_path[0] = /modules/custom_module/
module_path[1] = /my-template.html.twig

```

However, this is not the appropriate way. This is only a solution for your problem. Appropriate way is to set module path in a variable in preprocess hook and use that variable in twig.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to use an image with Responsive Image style as a background?
We have a need to use the Responsive Image module. The key is that we want to be able to use the image (field\_image) field with Responsive Image styles as a background and put the node's title on top of them.

How can we achieve this?

We have tried the following but this only fetches the original photo in a twig template. In other words, when i use Chrome Dev tools to see if it fetched the other images as part of the Responsive Image style settings, it does not fetch them.

```
<div class="wrapper">
    <div class="wrapper__image" style="background-image: url('{{file_url(content.field_image.0['#item'].entity.uri.value)}}>
    </div>
    <div class="wrapper__content"> {# title goes here #} </div>
</div>

```

Sample image:

Currently we are using the out of the box Responsive Image twig template

```
{% if output_image_tag %}
  {{ img_element }}
{% else %}
  <picture>
    {% if sources %}
      {#
      Internet Explorer 9 doesn't recognise source elements that are wrapped in
      picture tags. See http://scottjehl.github.io/picturefill/#ie9
      #}
      <!--[if IE 9]><video style="display: none;"><![endif]-->
      {% for source_attributes in sources %}
        <source{{ source_attributes }}/>
      {% endfor %}
      <!--[if IE 9]></video><![endif]-->
    {% endif %}
    {# The controlling image, with the fallback image in srcset. #}
    {{ img_element }}
  </picture>
{% endif %}

```

# Answer
> 0 votes
What you're trying isn't going to work on a background image. You'd need to do this yourself with javascript. How i've done it previously is added data attributes to the div for each breakpoint e.g.

```
<div data-mobile-image="mobilestylename/aaa.jpg" data-desktop-image="desktopstylename/aaa.jpg">

```

Then in javscript use matchmedia or a body class if its already being added by your theme to know which breakpoint you are in and then do

```
var mobile_image = $('.mydiv').data('mobile-image');
$('.mydiv').css('background-image',mobile_image);

```

# Answer
> 0 votes
You can let the responsive image markup from the core :

```
<div class="wrapper">
  <div class="wrapper__image">{{ content.field_image }}</div>
  <div class="wrapper__content"> {# title goes here #} </div>
</div>

```

And use the CSS property object-fit on your responsive image :

```
.wrapper__image {
  position: relative;
  width : 100%
  height : 100vh
}

.wrapper__image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.wrapper__image img {
  object-fit: cover;
  object-position: center;
  width: 100%;
  height: 100%;
}

```

You can easily find JavaScript polyfills to enable this feature on IE.

---
Tags: 8, media, theming
---


# Question
Title: How do I reference a file field and node title from another content type & node?
I need to add a link to a file, added through a file field on its own content type called "Document" from another content type and node call "plan information".

The idea is that the "document" nodes are displayed to provide access to a collection of "documents" throughout the entire site. This content type simply has a title and a file field. That cannot change.

What I need to do is to add a LINK to a user-selected document on the "plan information" content type that links the "document" to the appropriate "plan information" node as selected by the content manager.

On the "plan information" nodes, I want to simply create a UL of the document(s) attached using the title of the "document" node as the anchor text.

We've had a big problem with updating documents where associating the right "document" link on the correct "plan information" node has been problematic at best.

I've tried entity reference but couldn't get that to work. It would either bring in the entire document node, or nothing at all.

I tried node reference but it wants to behave in a similar way as the entity reference did, pulling in the whole node.

I tried field reference, but again, no success.

Most grateful for any guidance/insight on this.

# Answer
> 1 votes
Ok - I got it figured out.

All I needed was the entity reference field.

I then followed the steps in the article posted below which allowed me to then be able to attach my document entities to my plan info nodes.

https://www.ostraining.com/blog/drupal/entity-reference-view/

Then i was able to create a view of the plan info nodes by creating a relationship in views to the referenced entity on the nodes, then I had the necessary fields available to me as fields for my view, and that solved everything.

---
Tags: 7, nodes, files
---


# Question
Title: Blocking JS from being executed more than once
JS lines of code are often executed more than once. How can this ( annoying ) behaviour be blocked?

```
    (function ($, Drupal) {
  'use strict';

  Drupal.behaviors.recherche = {
    attach: function (context) {

      var filters = $('.block-facets-ajax');
      filters.wrapAll('<div class="facets-wrap"></div>');
...........

```

what's expected:

```
<div class="facets-wrap">
   <div class="block-facets-ajax></div>
   <div class="block-facets-ajax></div>
</div>

```

what's happening:

```
<div class="facets-wrap">
<div class="facets-wrap">
<div class="facets-wrap">
<div class="facets-wrap">
<div class="facets-wrap">
<div class="facets-wrap">
      <div class="facets-wrap">
           <div class="block-facets-ajax></div>
           <div class="block-facets-ajax></div>
        </div>
</div></div></div></div></div></div>

```

EDIT: trying to apply the doc given in comments, unsuccesfully

```
Drupal.behaviors.recherche = {
    attach: function (context) {

      var filters = $('.block-facets-ajax',context);
      filters.once('behave').each(function () {
        $(this).wrapAll('<div class="facets-wrap"></div>');
      });

```

EDIT2 : dependancies added to the library. It is not working as it is not entering the .each :

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {

      console.log('this is logged');
      $('.block-facets-ajax', context).once('myModuleBehavior').each(function () {
        console.log('this is not logged');
        // Apply the myModuleBehavior effect to the elements only once.
        $(this).wrap('<div class="facets-wrap"></div>');
      });

    }
  };
})(jQuery, Drupal);

```

EDITED 3 : if i remove context in the selector then .each is executed but instead of wrapping all elt together it 's wrapping each element individually. This is the case no matter i use wrapAll or wrap method.

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {

      $('.block-facets-ajax').once('myModuleBehavior').each(function () {
          $(this).wrap('<div class="facets-wrap"></div>');
      });

    }
  };
})(jQuery, Drupal);

```

what i am trying to achieve :

```
  <div class="facets-wrap">
       <div class="block-facets-ajax></div>
       <div class="block-facets-ajax></div>
   </div>

```

what's the outcome:

```
  <div class="facets-wrap">
       <div class="block-facets-ajax></div>
  </div>
   <div class="facets-wrap">
       <div class="block-facets-ajax></div>
   </div>

```

# Answer
I adjusted your code to match the one from the docs.

### MYMODULE/js/myscripts.js:

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {

      $('.block-facets-ajax', context).once('myModuleBehavior').each(function () {
        // Apply the myModuleBehavior effect to the elements only once.
        $(this).wrapAll('<div class="facets-wrap"></div>');
      });

    }
  };
})(jQuery, Drupal);

```

---

To get that working properly you also need to require `core/jquery.once` for this script.

### MYMODULE.libraries.yml:

```
myscripts:
  version: VERSION
  js:
    js/myscripts.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

```
> 3 votes

---
Tags: 8, javascript
---


title: Is Webform using datepicker.js?

text:
# Question
Title: Is Webform using datepicker.js?
I am trying to create an alert when a date is selected that falls within 30 days of today using the following script:

```
(function ($) {
  $('#edit-select-date').datepicker({

    onSelect: function () {
      var date = $(this).datepicker('getDate');
      var today = new Date();

      if ((new Date(today.getFullYear(), today.getMonth(), today.getDate() + 30)) > date) {
        // Do something here.
        alert(123);
      }
    }
  });
}(jQuery));

```

Unfortunately this is not working and am getting a $(...).datepicker is not a function in dev console. If datepicker.js is not being used is there a way I can have an alert trigger when the date select is +30 days from today?

# Answer
Webform provides a fieldable form entity type. And when you add a date field to it (you didn't specify what date field exactly, core, contrib, custom), this date field may make use of a datepicker library.

Speaking of core it most likely is core's `core/jquery.ui.datepicker` library. Which is used for `#type => 'date'` form elements for example.

When you in your custom script want to make use of this datepicker library you need to add it as a dependency. Same as core does:

> ```
> drupal.date:
>   version: VERSION
>   js:
>     misc/date.js: {}
>   dependencies:
>     - core/drupal
>     - core/modernizr
>     - core/jquery.once
>     - core/jquery.ui.datepicker
>
> ```

See https://git.drupalcode.org/project/drupal/blob/8.8.x/core/core.libraries.yml#L142-150.

---

And maybe you also make your JavaScript look more like in the examples in the docs.
> 1 votes

---
Tags: 8, webforms
---