# Question
Title: Destination property uri not provided migrating uri
I'm working on a file migration from D6 -\> D8, and in my case, all the files are already on S3, and they don't need to move, so all I need to do is migrate the URL to a new fid. Based on direction from mikeryan1 in IRC, in my config file I'm just doing

```
uri: uri

```

However, when I try to migrate, I get a `'Destination property uri not provided'` error. I tracked down the code to EntityFile::getEntity():

```
// By default the entity key (fid) would be used, but we want to make sure
// we're loading the matching URI.
$destination = $row->getDestinationProperty('uri');
if (empty($destination)) {
  throw new MigrateException('Destination property uri not provided');
}

```

where getDestinationProperty() is

```
  public function getDestinationProperty($property) {
    return NestedArray::getValue($this->destination, explode(static::PROPERTY_SEPARATOR, $property));
  }

```

Tracking the code all the way through to NestedArray::getValue(), I find that the problem is my `$ref` array does not contain a `uri` key, so getValue() returns NULL.

```
  public static function &getValue(array &$array, array $parents, &$key_exists = NULL) {
    $ref = &$array;
    foreach ($parents as $parent) {
      if (is_array($ref) && array_key_exists($parent, $ref)) {
        $ref = &$ref[$parent];
      }
      else {
        $key_exists = FALSE;
        $null = NULL;
        return $null;
      }
    }
    $key_exists = TRUE;
    return $ref;
  }

```

Here is my migration config file.

```
id: file_s3
label: Files - S3
migration_group: file
migration_tags:
  - Drupal 6
source:
  plugin: file_s3_source
  constants:
    # source_base_path must be set by the tool configuring this migration. It
    # represents the fully qualified path relative to which URIs in the files
    # table are specified, and must end with a /. See source_full_path
    # configuration in this migration's process pipeline as an example.
    source_base_path: ''
process:
    # If you are using both this migration and d6_user_picture_file in a custom
    # migration and executing migrations incrementally, it is recommended that
    # you remove the fid mapping here to avoid potential ID conflicts.
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  destination_full_path:
    plugin: file_uri
    source:
      - filepath
      - file_directory_path
      - temp_directory_path
      - is_public
  uri: uri
  filemime: filemime
  filesize: filesize
  status: status
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file

```

So what do I need to do to my config file to avoid this error?

Thanks.

# Answer
> 2 votes
It turns out that the problem was that the source data from D6 doesn't have a uri field (it's filename and filepath), so just using a custom plugin to create the uri in the source row gets around it.

---
Tags: 8, files, uri, migrations
---


# Question
Title: Views autocomplete with aggregation (and panels)
I have panel that displays data from two custom content types, Funding and Partners. There are various attributes of Funding and Partners that I have exposed as filters.

There are two types of views I'm using to display data in the panel. The first type is simply a list of Funding instances. This is working just fine (I have the relationship setup between Funding and Partners, I'm using Content: title with the relationship, the autocomplete field points to this Content: title field, etc.).

The second type of view is giving me trouble. I'm using Aggregation to display the total number of Funding instances and the total amount of Funding, based on the exposed filters. This works just fine for most exposed filters, but it doesn't work for the Partner name. This is because I cannot include the Partner name in the list of fields and still get the aggregation behavior I want (including the Content: Type with the relationship gives me a list of funding, not the totals). Of course, when I remove the Partner name I no longer have to field to point the autocomplete exposed filter to.

# Answer
> 0 votes
So the way to address this is actually easy, so sorry for having posted it.

In case anyone else is having this issue...in the panel, instead of using the exposed filters for the view with aggregation, I used the exposed filters for the view that just provided a list of Funding instances.

Then, in the settings for the view with aggregation there is no need to use autocomplete (just use Contains) - because I'm not displaying this exposed filter anymore.

---
Tags: views, panels, ajax
---


title: Why is items list lagging?

text:
# Question
Title: Why is items list lagging?
I'm exploring Drupal 8 Twig system. After I altered menu.html.twig I tried to print out menu items list, but when I load the page after appending `{{ dump( items ) }}` it all stucks, page is not loading, Apache process is at 15% CPU. Why is this happening? Can I somehow print out all item's content?

# Answer
I'm afraid twig's dump() is a resource killer. You can follow this issue on drupal.org for more information and alternatives: Twig dump crashes site/server with out of memory.

My advice would be to use Devel's kint() function, and you might want to track Symfony's Ladybug which is under development for inclusing in Drupal 8.3.
> 3 votes

---
Tags: theming, 8
---


title: When is cache_menu flushed?

text:
# Question
Title: When is cache_menu flushed?
I was caching some goodies related to the menu, and putting it in the 'cache\_menu' bin, assuming they would get cleared whenever someones edits the menu.

```
cache_set($cachekey, $mymenu, 'cache_menu', CACHE_TEMPORARY);

```

When I edit the menu, it isn't cleared. When is it cleared, then?

In what sense is it different from the *cache* bin?

# Answer
Looking at `menu_link_save()`, you will see that it calls `menu_cache_clear()` to clear only the cache of the menu the menu item belongs to. Other entries in the menu cache are not cleared.

The entire menu cache is only cleared when `menu_cache_clear_all()` is called directly (eg. by `menu_enable()`, which runs whenever a module is enabled) or indirectly (often through `menu_rebuild()` or `drupal_flush_all_caches()`).

If I were you, I would store my own data in the default 'cache' bin. I consider the menu cache to be private to the menu system; I don't want to touch it and accidentally mess something up. To clear my cache data at the right moment, I would implement `hook_meu_link_insert()` and/or `hook_meu_link_update()` and clear/rebuild my cache data from there.
> 5 votes

---
Tags: 7, caching, navigation
---


title: Render Array Customise Theming

text:
# Question
Title: Render Array Customise Theming
I have what is probably a common question ... How do render arrays get parsed into the the twig template - If we have a controller class which outputs a render array, such as:

```
$output['element1']=array ("#type"=>"markup","#markup"=>"Hello World!");
$output['element2']=array ("#type"=>"markup","#markup"=>"Today is a nice day!");

```

Now, lets say that we're using the bootstrap framework, hence using row and columns for layout, if we want the array elements to be output in the following manner:

```
<div class="row">
    <div class="col-md-12">
    Hello World!
    </div>
</div>
<div class="row">
    <div class="col-md-12">
    Today is a nice day!
    </div>
</div>

```

How can this be done? It is clear that Drupal will initially use the page.html.twig template, which will call the region.html.twig template, which in turn will call the block.html.twig template in order to display the render array. But, the block.html.twig will output the render array as:

```
 Hello World! Today is a nice day!

```

Namely,it will not output the div tags - mostly because the block.html.twig doesn't know about them. And looking at the block.html.twig it appears that the output is only available as 'content':

```
 {{ content}}

```

And there is no way of templating the content in the following way:

```
 <div class="row">
     <div class="col-md-12">
        {{ content['element1'] }}
     </div>
 </div>
 <div class="row">
     <div class="col-md-12">
        {{ content['element2'] }}
     </div>
 </div>

```

**Secondary related query:**

What would also be useful, is being able to ascertain which class called the page.html.twig so that one could use the {% if calling\_page="page name" %} in the block.html.twig template

Hopefully, you get what I am outining here. Thanks in advance and please operate upon the premise I'm totally new to Drupal when outlining solutions.

# Answer
> 3 votes
I can answer the first part of your question...

Drupal uses render arrays for the different outputs. Since you only specify two single dimension arrays with `#markup` they are rendered as 2 strings.

There are multiple ways to achieve what you want, I will highlight 2;

* Use `#prefix` and `#suffix`:

```
$output['element1']=array (
  "#type"=>"markup",
  "#markup"=>"Hello World!"
  "#prefix"=>'<div class="row"><div class="col-md-12">',
  "#suffix"=>'</div></div>',
);

```
* Use nested elements:

```
$output['element1']=array (
  'row' => array(
    '#prefix' => '<div class="row">',
    '#suffix' => '</div>',
    'cols' => array( // This has no #, so is the next level of elements
      '#markup' => t('Hello World!'),
      '#prefix' => '<div class="col-md-12">',
      '#suffix' => '</div>',
    ),
  ),
);

```

See this related issue: How to nest elements in a render array.

However, there might be cases where it is not possible to alter the output of modules. Instead you want to do this in the theme. Your suggestion was not that bad. It is just that in twig arrays are noted with a dot symbol. `{{ content['element1'] }}` should be `{{ content.element1 }}`

```
<div class="row">
     <div class="col-md-12">
        {{ content.element1 }}
     </div>
 </div>
 <div class="row">
     <div class="col-md-12">
        {{ content.element2 }}
     </div>
 </div>

```

# Answer
> 1 votes
> there is no way of templating the content in the following way

Sure there is.

You can create a **block--block-type.html.twig** template that corresponds to this particular block type.

```
<div class="row">
   <div class="col-md-12">
     {{ content.field_one }}
   </div>
</div>
<div class="row">
  <div class="col-md-12">
     {{ content.field_two }}
  </div>
</div>

```

Where `field_one` etc is the name of a field attached to the block type. Another common thing I have seen with this (Bootstrap) is that some people add fields to the block type denoting the column width. IE a select field with Small, Medium, Large, who's keys are col-sm-12, col, md-12, col-lg-12 and what have you.

```
<div class="row">
   <div class="{{ content.field_col_one_size }}">
     {{ content.field_one }}
   </div>
</div>
<div class="row">
  <div class="{{ content.field_col_two_size }}">
     {{ content.field_two }}
  </div>
</div>

```

This would mean you need to display the field with its key value, and override its template:

### field--field-col-one-size.html.twig

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

I don't know what you mean by 'calling page' though, or why that is necessary.

I haven't seen the rest of the code, but you can also render using your own theme function and twig template too in a custom controller.

To be honest, a lot of this is upfront strategy and planning when architecting content types, block types, paragraph types or other content entities. It helps you roadmap templates and how to handle how and what will render their output.

---
Tags: theming, 8
---


# Question
Title: Drupal custom page with wildcards in url not working
I have created a custom page at admin/structure/pages and have set the path to be

```
course-details/%id/%name

```

My intention is that there will be a custom block appearing on this page and the id and the name, in the URI, will pass data to the custom block. I have the block working fine and it is pulling data from a test page URI as expected. I now need to embed this block onto the course-details page, which contains content that must appear for any hit on this page regardless of the id and name.

In the settings =\> arguments for this page I have set the two arguments to be strings

In settings =\> access I have set "all criteria must pass"

When I hit the page with no id or name I see the course-details page, at this stage I do not have the custom block enabled, and I am seeing the content that must appear on all course-details pages.

However when I add the id and name, an example is as follows

```
course-details/ACM20110-01V03/certificate-ii-in-animal-studies

```

I am getting a 404 error. It seems the id and name are causing me trouble.

I have spent hours hunting on Google for trying to get my head around why this is not working. I am probably doing something silly.

Could anyone please help with this issue.

# Answer
> 0 votes
By using the named wildcards %id and %name as wildcards, Drupal will look for functions named id\_load() and name\_load(). It will pass the values of these wildcards to those functions, and use the return values as the arguments passed to the page callback. If the \_load functions are not found, or if a FALSE value is returned, or no value is returned, you will get the error you are seeing.

I'm suspecting you want your path to be:

```
course-details/%/%

```

# Answer
> 0 votes
Here is an expansion on Jaypans answer and why your item isn't working:

hook\_menu wildcard auto-loader for webform submission?

Each argument in this case will be just `%` \- and it will be up to your page callback function to convert those arguments into objects. Though, as strings, that seems a bit tricky and perhaps unreliable but I don't know enough about your application.

I am guessing you are also using something like Page Manager since you did not include a `hook_menu` definition..

---
Tags: 7, views, blocks, path-aliases
---


# Question
Title: How to add discount for final subtotal in ubercart?
I am using Ubercart in Drupal 7. I need to add discount offer based on price.

For example:

* if total purchase price $100 then 25% discount.
* If total purchase price $200 then 45%.
* and so on.

I used the uc\_discount module but it's not working according me.

# Answer
> 0 votes
Try Ubercart Simple Discount

This module works with rules, so you can add a condition in rules. You may not get an 'easy plug and play' module for doing this, but the result you want may be possible with some Rules

---
Tags: 7, ubercart
---


# Question
Title: Log Message - Page Not Found: includes/database/sqlite/log/login
When I check "**Recent Log Messages**", I keep finding a large number of "**Page Not Found**" errors with the message "**includes/database/sqlite/log/login**". I've checked the site and the directory does not exist.

My questions:

1. Should this directory exist? If so, how do I create it?
2. How do I determine what is calling for this directory?

# Answer
This is most likely somebody trying an automated script to gain malicious access to your site. There's no action required.
> 0 votes

---
Tags: 7, debugging
---


# Question
Title: What's the correct way to redirect the user when a Batch API job finishes?
I've got a form that starts a batch job. What's the right way to redirect them after it finishes? Calling drupal\_goto() in my finish function?

# Answer
```
drupal_goto('your/hookmenu/link', array('query' => array('destination', $_GET['destination'])));

```
> 3 votes

# Answer
You can set 'redirect' in hook\_batch\_alter(). For example:

```
$batch['form_state']['redirect']['path'] = 'cart';

```
> 6 votes

# Answer
If you know the redirect path in the moment you start the batch, you can

```
batch_process('my/destination/path');

```

See https://api.drupal.org/api/drupal/includes!form.inc/function/batch\_process/7
> 2 votes

# Answer
i'm create link to form (created by form api) that runs the batch with get-parameter "?destination=myRedirectPath".

batch lanch on function form\_submit() and take info about redirect after batch from url.

without "goto".
> 0 votes

---
Tags: 7, batch-operations
---


title: How to install the Memcache module?

text:
# Question
Title: How to install the Memcache module?
I'm running Drupal 6 website with AWS.

I have downloaded the Memcache API and Integration module (from the official site).

Do I need to just FTP the files into the memcache module directory and load the admin page and configure it?

What are the exact steps to install the module in Drupal via the module directory?

# Answer
Your developer most likely has more complex release methods in place, so what you can do is probably a temporary solution that he has to improve. You should definitely test the module on another environment before putting it on a production server. However, in its simplest form it will be enough to put the module folder and its contents in the sites/all/modules/contrib folder (or without contrib if that isn't present). Then go to the admin interface and enable the module in the modules page.
> 0 votes

---
Tags: 6, caching
---


title: How to integrate a booking form?

text:
# Question
Title: How to integrate a booking form?
... preferably with PHP. I am new to Drupal.

My goal is to integrate a page into an already existing project which enables to give to users the possibility to book a Hotelroom or a flight ticket while the Administrator (me) then collects the submitted information and validates the choice in the backend.

I have done this countless of times from scratch in PHP with POST. But on Drupal, when I try to integrate HTML and PHP code into a new webform or new article page, it doesnt really render it.

# Answer
After reading your question I would do the following:

Create a custom module with a custom block that holds the booking form. This way you can add the booking form on whatever page you like with the Context module for example.

The Drupal 7 example module can show and teach you how to create a block in a custom module.
> 1 votes

# Answer
By altering the Webform you can achieve. I know this is not the exact solution but you can achieve by doing some customization.

Alter webform and add php/Html code.
Implement the "`hook_form_FORM_ID_alter`".

```
function YOUR_MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    //check how you can use #submit/#validate to call custom function
    //Write your code in custom function.
}

```
> 1 votes

---
Tags: 7, webforms
---


title: Why does Drush require sudo?

text:
# Question
Title: Why does Drush require sudo?
I’m running Ubuntu 14.04.5 with Drush v 8.1.8 and I can’t seem to execute Drush without using sudo. For example if I try to execute ‘drush cc all’ without sudo, I get:

`‘Directory /home/myuser/.drush/cache/default exists, but is not writable. Please check directory permissions. ‘
‘Directory /home/myuser/.drush/cache/complete exists, but is not writable. Please check directory permissions. ’`

If I then manually modify the permissions on .drush and everything under it to 777, the next Drush command will work but the one after that will fail with the same error. I also tried ‘chown -R myuser:myuser ~/.drush’. Same result.

I thought perhaps I installed Drush incorrectly, so I tried removing and then re-installing it three different ways:

1. Using this approach: https://www.drupal.org/node/1248790 (sudu apt-get install drush).
2. This way: http://docs.drush.org/en/master/install/ (executing php to load Drush from a remote file)
3. Finally by installing Drush using method (2) and then moving Drush into my home/bin folder and chown -R to me.

All of them have the same result — drush doesn’t work without sudo. There’s no reason I can think of why this should be. What’s even weirder is if I chown of .drush (and everything under it) to me, then execute drush without sudo, it will change ownership of directories under .drush/cache to root. I don’t even know how that’s possible since I’m not root!

Please let me know how I can get Drush to work without root privileges. Thanks.

# Answer
> 2 votes
I'd suggest you follow the official install instructions here after removing your current install - http://docs.drush.org/en/master/install/

When you have it installed then navigate to your home folder:

```
cd ~/
ls -lash

```

At this point your .drush folder should have your user as owner (not root)

If it doesn't then run

```
sudo chown myusergoeshere:myusergoeshere .drush -R

```

You can run `ls -lash` again and confirm the right user and group.

You should now be able to run drush without using sudo.

---

The reason you get that error is because when you installed it the system created the folder using the root user in your home directory so as your user you don't have permission to modify the folder.

---
Tags: drush
---


title: Show field twice in node page

text:
# Question
Title: Show field twice in node page
I created a custom bundle (content type) and I've created fields

One of those field is a file type field, is a video file, stored in the private storage. I installed the videojs module to allow to watch the video.

I need to show this field twice in the node page. One in the generic file formatter that allows the user to download the file, and I also need to play the video. I decided to set up as generic file formatter and customize the twig template to show again with the video player.

I achieve to show twice with the settings formatter (generic file) with this code in the node--mybundle--full.html.twig template

```
{{ content.field_sd_video }}

```

I thought it would be something easy like field+formatter:

```
{{ content.field_sd_video|videojs_formatter }}

```

But I can't find a simple way to achieve this.

# Answer
> 1 votes
I finally found the solution, I put this code in preprocess node function. It has to be easy, but not easy to know how ;)

```
function mytheme_preprocess_node(&$variables) {

     $variables['video_caption'] = $variables['node']->get('field_video')
         ->view(array(
            'label' => 'hidden',
            'type' => 'videojs_player_list'
        ));
}

```

and I only has to add this line in twig file:

```
{{ video_caption }}

```

in my case node--mybundle--full.html.twig template

Thanks @4k4 your answer was usefull

For those arrive here looking for something similar I was inspired by Twig Recipes on page 41
It was usefull for me Twig debugging. Playing with kint and node variable and the classes used to wrap the information. Then I found that the field comes with FileFieldItemList and then I found the view method that uses EntityViewBuilderInterface

# Answer
> 5 votes
You can do this in UI, UI and code mixed, code only and in html:

**Display Suite**

Install the module Display Suite and configure this in UI.

**Extra Field**

Use the hook hook\_entity\_extra\_field() to get an extra field in *Manage Display*. You need hook\_ENTITY\_TYPE\_view() to copy the data (in this case the file) into the new field.

**Clone field in code**

See How to display a field twice in a view mode?

The last has the least overhead, but is not customizable and you have to define the field settings yourself. If you configure the second field temporarily in UI and export the view mode to yaml this helps to find the settings you need in code.

**Place link html in template**

Or if you want a quick solution in the template and you only need a simple formatted file link you can get the file url from the node and put it in html markup:

```
<a href="{{ file_url(node.field_video.entity.uri.value) }}">Example Video</a>

```

---
Tags: theming, 8, entities
---


# Question
Title: How to get hal_json format as Drupal output?
I installed Drupal 8 and these modules on my host:

* HAL
* HTTP Basic Authentication
* RESTful Web Services
* REST UI
* Serialization

These are all core modules except REST UI.

According to Drupal tutorials (https://www.youtube.com/watch?v=4xCndQQVJsg and https://www.youtube.com/watch?v=DnZo5lMICKc) when I enter this URL, Drupal would show JSON format of node 1:

```
www.example.com/node/1?format=hal_json

```

But it shows the normal (HTML) view of node 1.

What should I do to get JSON or hal+json format as output?

# Answer
Send a GET to http://theurl.com/node/1?\_format=hal+json

This should work! Make sure you enabled the Resources to read out nodes.
> 4 votes

---
Tags: 8
---


# Question
Title: Where are the database username and password stored?
I'd like to send my Drupal installation to a colleague, but I don't want him to see the username and the password of my database. Where are these informations stored?

I've seen that the username and the password are written in sitename/sites/default/settings.php, but is it the only file with these informations? Is it sufficient if I change the username and the password in this file and then send my colleague all my Drupal files and my database?

# Answer
IMO both previous answers (posted with 10 secs difference ...) are incomplete ...

The `/sites/default/settings.php` file indeed does contain that userid and password, and if you "*don't want him to see the username and the password of my database*" (as in your question), then you at a minimum remove that userid and password (which you want to keep secret) in that file.

However, your question also contains this:

> Is it sufficient if I change the username and the password in this file?

To keep your userid and password secret you are done with only this change. But if you want your colleague to be able to actually ***use*** the Drupal installation you want to send, then IMO the answer to that question is NO. Because Drupal requires that the `/sites/default/settings.php` file that your colleague will be using contains the userid and password that matches with the database after it is restored by your colleague.

**Note** (credits: sanzante): you should also send your colleague a database dump. And your colleague only has to import the database and edit the `settings.php` and add the user and password for the imported database. That config (user and password) is not dumped in the database so the colleague must have his/her own.
> 2 votes

# Answer
The settings are stored in `sites/default/settings.php`. That is indeed the only file with that information and it is sufficient that you change the username and the password in that file.
> 3 votes

# Answer
In a single word "YES". Is sufficient if I change the username and the password in `sitename/sites/default/settings.php`.
> 3 votes

---
Tags: 8, database
---


# Question
Title: Commerce Recurring Framework - Get active subscriptions?
For the Drupal Commerce Recurring Framework module I have a quesiton

Is there a way to get a user's active subscriptions programatically?

Bonus: Is there a way to delete a user's active subscriptions programmatically?

Thanks if anyone answers!

# Answer
> 0 votes
For Drupal 7:
Yes, you can find the data at the `{commerce_recurring}` database. With each recurring entity the user id has saved (uid column).

Here's an example how to get all subscription (recurring entities) from a user.

```
$uid = 1; // the user id
$result = db_query('SELECT * FROM {commerce_recurring} WHERE uid = :uid', array(':uid' => $user_from_order->uid));

```

Now you can loop over the subscriptions / recurring entities.

---
Tags: commerce
---


title: Enable a button block programmatically?

text:
# Question
Title: Enable a button block programmatically?
How do I enable a button block programmatically?

I've tried:

```
function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'visibility' => 1,
      'region' => 'content',
      'pages' => 'user',
  );
  return $blocks;
}

```

# Answer
Setting a block region doesn't work unless you set `status` to `1`, and clearing your cache of course.
> 1 votes

---
Tags: 7
---


# Question
Title: Webforms - Is it safe to allow users to upload attachments?
Is it safe to include a 'File' type field into a webform that allows users (anonymous or authenticated) to upload their files? After reading few articles on the web , it seems it makes a website vulnerable to hacking and malware.

I would like to know better about this so that I can make a decision on this and provide an answer for and against using it.

# Answer
Here is a security advisory from drupal.org that explains some of the dangers of letting anonymous users upload files: https://www.drupal.org/psa-2016-003

tl;dr

* Configure upload fields that non-trusted visitors, including anonymous visitors, can upload files with, to utilize **use the private file system**.
* Consider forcing users to **create accounts** before submitting content.
* **Audit** your public file space to make sure that files that are uploaded there are valid.
> 2 votes

---
Tags: webforms, files
---


# Question
Title: How to alter commerce order view access?
When viewing an order, I want to do checks per order, whether the user may view that order or not.

```
function my_commerce_entity_info_alter(&$entity_info) {
  $entity_info['commerce_order']['access callback'] = '_my_commerce_commerce_order_access';
}

function _my_commerce_commerce_order_access($op, $entity = NULL, $account = NULL) {
  return $entity->id == 99; // just for example
}

```

The above did not work.

I didnt find anything like `entity_access_alter` or similar.

What do I do wrong?

# Answer
You should be using `hook_commerce_entity_access_condition_ENTITY_TYPE_alter()` for commerce orders.

You receive the following parameters:

* `$conditions`: The OR conditions group used for the view access query.
* `$context`: An array of contextual information including:

+ `account`: the account whose access to view the entity is being checked
    + `entity_type`: the type of entity in the query
    + `base_table`: the name of the table for the entity type

So it becomes:

```
hook_commerce_entity_access_condition_commerce_order_alter(&$conditions, $context) {
  // If we are not allowed to view the order, leave.
  if (!user_access('some_permission', $context['account'])) {
    return;
  }

  $orders = array(99);

  // add a condition
  $conditions->condition(db_and()
    ->condition($context['base_table'] . '.order_id', $orders, 'IN')
  );
}

```
> 0 votes

---
Tags: 7, commerce, users
---


# Question
Title: Event Response not firing anonymous user
I have a module in drupal8 which only job is on an event response is to redirect a URL. It works fine for everyone except anonymous users. How do I give the module privileges to fire on every user no matter if the are logged in or not.

This is the geographic\_me\_redirect.services.yml

```
services:
  me_redirect.process_me_request:
    class: Drupal\me_redirect\EventSubscriber\ResponseSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

```

This is the response

```
class ResponseSubscriber implements EventSubscriberInterface
{

    /**
     * Constructor.
     */
    public function __construct()
    {

    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {

        ///$events[KernelEvents::REQUEST][] = ['onRouteMatch', 27];
        //-- fires the event in the kernal early oo page load 20
        $events[KernelEvents::RESPONSE] = ['process_language_request',0];
        //-- For redirecting to another domain

        return $events;
    }

    public function process_language_request(FilterResponseEvent $event)
    {

    return my logic

    }
}

```

# Answer
You can't do this when the redirect is already stored in the internal page cache. Because anonymous traffic is served from this cache before any event is fired.

You have to use this kill switch:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

If you put this in your event subscriber and clear the cache, then you prevent, that the response is cached in the internal page cache.
> 3 votes

# Answer
If you just want redirect to URL you can use class like this:

```
<?php

namespace Drupal\my_event\EventSubscriber;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class MyEventSubscriber.
 *
 * @package Drupal\my_event
 */
class MyEventSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['processEvent', 0];
    return $events;
  }

  /**
   * Redirect and cache with anonymous user
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   * @param \Drupal\Core\Url $url
   */
  protected function setResponse(GetResponseEvent $event, Url $url) {
    $response = new TrustedRedirectResponse($url->toString(), 301);
    $response->addCacheableDependency(CacheableMetadata::createFromRenderArray([])
      ->addCacheTags(['rendered']));
    $event->setResponse($response);
  }

  /**
   * Process with difference condition
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   */
  public function processEvent(GetResponseEvent $event) {
    $logic = $this->checkLogic();
    if ($logic) {
      $this->setResponse($event, Url::fromUri("https://www.example.com"));
    }
  }

  /**
   * Check logic redirect
   * @return boolean logic
   */
  protected function checkLogic() {
    return $logic;
  }
}

```

Magic here is method **setResponse**. I use event **KernelEvents::REQUEST** and set cache in method **setResponse**. It's working with anonymous user.
> 0 votes

---
Tags: 8, caching, event-subscribers
---


# Question
Title: How to change status and update account?
How can i change status to 0 and update an existing user account?

Here is the code i tried:

```
$account = \Drupal::currentUser();
$account->status = 0;
$account->save();

```

It gives me error : Call to undefined method Drupal\Core\Session\AccountProxy::save().

# Answer
> 6 votes
The account proxy class doesn't have a method called `save`. Refer to the API docs.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Session%21AccountProxy.php/class/AccountProxy/8.2.x

What you want is the block() method:

```
$account->block();

```

As `$account` should be an instance of UserInterface, returned front getAccount of AccountProxy. But without seeing the rest of the code its hard to see if this is the right approach for what you are trying to do.

If you could get the user account another way, then you could do:

```
$account = \Drupal\user\Entity\User::load('uid arg');
$account->block();
$account->save();

```

---
Tags: 8, users
---


title: Display the Last saved date on articles

text:
# Question
Title: Display the Last saved date on articles
I want to know how can i display the Last saved date and time of the article to the users. How can i do that ? since it doesn't appear on the Manage display fields ?

# Answer
You can simply edit the view mode you're using, `Default`, `Full` or `Teaser` for example:

1. Download Display Suite and enable the "Display Suite" and "Display Suite UI" modules.
2. Go to `admin/structure/types/manage/article/display/teaser` where "article" is your content type and "teaser" is the view mode.
3. In the "Layout for article in teaser" fieldset, select the "One column" layout and click Save.

4. You will now see a lot more fields, provided by the Display Suite module. One of those fields is called `Last modified`.

5. Drag that field to the top, and you're done! No custom theming or coding required.

As a side-note: in views, the field you're looking for is called "`Changed`":
> 3 votes

# Answer
Try `{{ node.getChangedTime|format_date('date_format_machine_name') }}` in your twig template.

You may also be interested in Display Suite to open up fields like this.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Is it safe to use $vars['name_raw'] instead of $vars['name']?
I ran into an issue with usernames being trimmed in articles. I found a thread here with a fix suggesting to use $vars\['name\_raw'\]: https://www.drupal.org/node/854762#comment-7614255. It works.

But I'm wondering if $vars\['name\_raw'\] should be sanitized with check\_plain or not before being displayed to the screen. I'm not sure what the difference is between $vars\['name'\] and $vars\['name\_raw'\] ? I searched and found no clear answer.

# Answer
For this particular instance you should be fine because usernames already are filtered to a limited set of characters.

Like you assumed \*_raw is unfiltered input. So in almost any other circumstance, it should be sanitized in some way before use.
> 0 votes

---
Tags: 7, users, security
---


# Question
Title: Is there an OOP alternative to hook_entity_operations_alter() in Drupal 8
In my custom module, I want to add a new action to the operations menu for each row of the user list that is displayed when going to `/admin/people`. I would like to stay in OOP-land and therefore I'm wondering if there is an alternative to implementing `hook_entity_operations_alter()` in my module? E.g. something that would allow me to create a PHP class for adding my action, or alternatively some way to add the action through the admin interface.

currently I have this code in somemodule.module:

```
/**
 * Implements hook_entity_operation_alter()
 */
function somemodule_entity_operation_alter(array &$operations, EntityInterface $entity) {
  if($entity instanceof UserInterface){
    $operations['translate']['title'] = t('Hello @entity_type', array(
      '@entity_type' => $entity->getEntityTypeId(),
    ));
    $operations['translate']['weight'] = 99;
  }
}

```

This works, but as said I would like an alternative that would skip the .module file completely.

# Answer
> 2 votes
The operations originally come from UserListBuilder. You can extend this class and alter User entity info to point list builder property to your class. The problem is that you need to implement *hook\_entity\_type\_alter* wich is not in OOP land :-).

I suggest you keep this hook until Drupal become a true OOP application.

This article contains a quck comarision of hooks vs OOP events.

# Answer
> 2 votes
No, there is not.

Extending the list builder class is something that you should only do for your own entity type, it is *not* a replacement for the hook as there can only be one active list builder class per entity type, so you could easily get into conflicts with other modules.

Plus, to do that, you'd need another hook (hook\_entity\_type\_alter()).

Hooks still exist und unless they are explicitly deprecated in favor of an OOP approach like an event (I'm not aware of a single example for that in Drupal core), it's still the right approach.

---
Tags: 8, hooks
---


# Question
Title: Drupal 8: Node preview when using Page Manager
I am using the Page Manager module in D8 to show the full node view pages. Drupal also provides a button to preview the content when creating/editing it. Is there a possibility to actually preview the page using the page manager layout?

Thanks for the answers!

Vasi.

# Answer
Not ouf the box because page\_manager is about *routes*, and node preview is a completely different route than viewing a node.

Something like Display suite and probably also Panelizer (never really used it myself) whould probably work there though.

That said, it should be possible to build something too with Page Manager too by creating a second page (with a duplicated page variant(s) that you need to keep in sync somehow) that overides the preview route, but you also need to somehow write a context provider that loads the node based on the passed tempstore argument and also a write a block that replicates the UI elements for selecting the view mode and going back to edit
> 1 votes

---
Tags: 8
---


# Question
Title: Using triggers to add new user to a mailing list
I would like the Mailman Integration module to add any new user to a mailing list. I enabled Triggers and created an action in PHP. I then assigned the action to execute when a new user is created. I can not figure out how to get the $user object for this new user though. I can get the object of myself, the logged in user using global $user, but how do I get the new user?

```
$user = [newly added user];
$mail = $user->mail;
$name = $user->name;
$uid = $user->uid;
$list_name = 'list';
mailman_integration_subscribe($list_name, $mail);
mailman_integration_set_user_option($list_name, $mail, 'fullname', $name);
mailman_integration_insert_users($list_name, $mail, 0, $uid);

```

# Answer
> 0 votes
Instead of using Actions and Triggers, I just made a custom module:

```
function mailman_user_subscribe_user_insert(&$edit, $account, $category){
  $uid = $edit['uid'];
  $name = $edit['name'];
  $mail = $edit['mail'];
  $list_name = 'list';
  mailman_integration_subscribe($list_name, $mail);
  mailman_integration_set_user_option($list_name, $mail, 'fullname', $name);
  mailman_integration_insert_users($list_name, $mail, 0, $uid);
}

```

It's possible that a custom "After adding user" PHP action does nothing more than place the code within a hook\_user\_insert function. If so, I could have replaced all my object calls to $user with array calls to $edit.

# Answer
> 1 votes
I am not sure about how you've configured your environment but have you looked into this module? It appears to extend the rules a little bit.

https://www.drupal.org/project/user\_mailman\_register

---
Tags: 7, actions
---


# Question
Title: How may I allow users to embed a view within a CKEditor text field?
I'm working on a site that includes a number of service pages (think practice areas in a law firm site) and each service has a number of identical content components (call to actions, legal disclaimers, etc) that are not always in the same order.

It would be *awesome* if there was a way for my content editors to add these components within the body field in any order they see fit. I believe the CKeditor Blocks module could accomplish this for static content, but for dynamic content I don't see a solution.

Sometimes the body looks like this;

```
{{ Paragraph }}
{{ Related Services }}
{{ Paragraph }}
{{ Call to Action }}
{{ Legal Disclaimer }}

```

and other times it's formatted like this;

```
{{ Paragraph }}
{{ Paragraph }}
{{ Call to Action }}
{{ Related Services }}
{{ Legal Disclaimer }}
{{ Paragraph }}

```

Specifically, the service content type has a 'related services' entity reference field and users need to include links to these nodes within the body of the page. Typically, if I knew these links were always presented at the end of the body, I'd just create a contextual view and present the results on the page (panels).

What are my options here? I've given some thought to using Paragraphs, but that introduces more work than I'm interested in investing at the moment.

# Answer
> 2 votes
As far as embedding a view into CKEditor, you can use a formula with Token Embed Views and or Token Insert:

---
Tags: 7, views, blocks, wysiwyg
---


title: Page redirect based on referrer

text:
# Question
Title: Page redirect based on referrer
I am looking for an option to redirect user referred from a specific url (say abc.com) to domain.com/abc in Drupal 7
if http\_referrer='abc.com' redirect to xyz.com/abc
I looked at Redirect, http response headers modules but need something for http\_referrer.

Preferably without code modification.

# Answer
> 1 votes
You could add a redirect in the .htaccess file if you're using Apache. Something like this:

```
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_REFERER} .*abc.com  [NC]
  RewriteRule .* http://example.com/abc  [R]
</IfModule>

```

---
Tags: rules, http-request
---


# Question
Title: error Refused to execute script, because its MIME type ('text/html') is not executable
When migrated my site from localhost to webserver. I see an error in chromeconsole. I used git clone to transfer my site.

> Refused to execute script from http://mydomain because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Mysite is unformatted. Theme bartik, core drupal-8.2.5

It's running smooth on localhost.

I contacted serversupport, they say it's a debug problem and not a server problem.

there is an refer in the stylesheet to ojqe8x, but is empty, how to solve this?

```
<title>mysite | mysite</title>
<link rel="stylesheet" href="/joehoe/mysite/?ojqe8x" media="all" />

```

Edit:

on this domain http://pcwebber.nl/alex/lkch/

I get this error Refused to execute script from 'http://pcwebber.nl/alex/lkch/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

# Answer
You are asking the wrong question....

When you look at your page's source code, you'll see this:

```
<link rel="stylesheet" href="/alex/lkch/?ojqox6" media="all" />
<link rel="stylesheet" href="/alex/lkch/?ojqox6" media="all" />
<link rel="stylesheet" href="/alex/lkch/sites/default/files/css/css_Z5jMg7P_bjcW9iUzujI7oaechMyxQTUqZhHJ_aYSq04.css?ojqox6" media="print" />

```

The last one is a real CSS file. The first two are not (those link to your front page). So your browser attempts to load a stylesheet, but is receiving your front page instead. That is what is triggering the error; The browser expects CSS and is instead served HTML.

The real question is, where do these 2 lines come from... And that is hard to tell, since everything in Drupal can do that.

Things you can try;

* Disable CSS aggregation in Administration \> Configuration \> Development (you want to enable this once you go live)
* Disable all non core modules (if any)
* Try a different theme

It could be something coming from a custom template as well.
> 6 votes

---
Tags: 8, migrations
---


# Question
Title: Set default "Quantity" dropdown select in product. Commerce Kickstart
Using the Commerce Kickstart distribution I have a shop site listing products. The product page shows a Quantity widget to allow the buyer to choose the product quantity to be added to the cart. (look my capture)

I need to change this widget to the standar select list html element. (look the capture)

**Update:** I found the library which generate this "spinner", is located at: **profiles/commerce\_kickstart/libraries/jquery\_ui\_spinner** I don't see any module related to this. Maybe in theme?

# Answer
I know its already a year ago, but if someone bump in this question here's one of the solution, I don't know if there's a module that already existing changing the widget type of quantity in add to cart form but you can achieve this using `hook_form_commerce_cart_add_to_cart_form_alter` like this

Example:

```
function example_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Change widget type of quantity to select list
  $form['quantity'] = array(
    '#title' => t('Quantity'),
    '#type' => 'select',
    '#datatype' => 'integer', // <-- I added this one to fix Notice: Undefined index: #datatype in commerce_cart_add_to_cart_form_validate() when you click add to cart button
    '#options' => array(
      1 => '1',
      2 => '2',
      3 => '3',
      4 => '4',
      5 => '5'
    )
  );
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to set readonly or locked a select webform field?
I want to lock a prefilled select webform field but no option is provided by the UI.So I think to do that programmatically.

Actually I do in a hook\_form\_alter:

```
$form['submitted']['discipline_du_poste']['#attributes'] = array('readonly' => 'readonly');

```

and this doesn't effect...what's wrong ?

# Answer
Not sure how much this is a helpful answer, but was looking for a recipe to do this and found this example using a simple little hook\_form\_alter (which happens to be for civicrm components in a webform but think the principle is what counts)

```
$form['submitted']['civicrm_2_contact_1_fieldset_fieldset']['civicrm_2_contact_1_relationship_relationship_type_id']['#disabled'] = TRUE;

```
> 1 votes

---
Tags: 6, webforms
---


# Question
Title: Load custom library when form contains special field type
I'm writing a custom field in Drupal 8. I added a custom library that contains js and css to my module. They will be loaded on forms. Now I need a way to load the library only when some special field is placed in the form.

How can I check if a form contains a field with field type X?

```
function rate_field_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if(/*Check if form contains field with type X*/)
   {
      $form['#attached']['library'][] = 'rate_field/admin-star-field';
   }
}

```

# Answer
I addedsome values in the render array of the formElement method in my customWidget class.

```
'#attached' => array(
    'library' => array(
      'core/jquery',
      'rate_field/admin-star-field',
    ),

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Drupal views filter with latest month with content
I am working to show a page that will display a current issue section, by which all the articles from the latest month whatever articles were posted are only shown.

Suppose the last posted set of article are December 2015 and after that nothing is posted, that view must show all articles posted on December, 2015. If the last posted set of articles were on January 2016, it must show list of articles posted on the month of January 2016 like that.

How it can be adjusted in views ?

# Answer
Try to create a date filter using the create date and set the granularity to month. The setting for the relative date field should be set to be equal to now.
> 0 votes

---
Tags: views
---


# Question
Title: The module does not dissapear after disable, uninstall, clear cache and cron job
I want to completely remove the `File entity`module from my Drupal site.

I've disabled the module via `Modules` in admin panal. Then I also uninstalled it though the panel. After that, I've deleted the files from ftp located under `/sites/all/modules/file_entity`.

I've cleared the cache. I've run the cron. I even tried `/update.php` but it says there's nothing to update `Review updates` step.

When I log into administration panel, I still see that ghost:

I don't have any module that is dependent on `File entity`.

How to remove that module? I want to do so I can install the new fresh version of it which I need.

# Answer
This module might live in a profile or in a directory that is not sites/all/modules. It is possible to have the same module in multiple places in Drupal at the same time.

You should open up the database, go to the `system` table and look for the entry for `file_entity` and see what the path is. That will tell you. You could also grep your codebase for "File entity" or "file\_entity" which should also produce results.

If not, perhaps you are on a dev/stage environment? Did your FTP program actually delete the files? Check that there wasn't a permission issue regarding deleting that.

**edit: if this is an older release of the media module, it used to ship with file\_entity under media/modules/file\_entity if I recall. Also check there. If that is the case, what you should do is completely upgrade the media module to the latest version, which looks like rc2 right now.**
> 3 votes

---
Tags: 7, installation
---


# Question
Title: Add a custom carousel block with HTML, CSS, and JavaScript
I'm new to drupal and not a coder but trying to add owl-carousel in the custom block following some online guides.

I found 2 links which had good owl carousel demos and both of them had 3 sections (HTML,CSS,JS) that need to integrate to make it work.

Links:

owl carousel

Flickity carousel

I was trying the owl carousel and the method I tried was to create a custom block with Full HTML support and used the following HTML code.

```
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<link href="/en/libraries/OwlCarousel2-2.2.0/dist/assets/owl.carousel.min.css" rel="stylesheet" />
<link href="/en/libraries/OwlCarousel2-2.2.0/dist/assets/owl.theme.default.min.css" rel="stylesheet" />
<style type="text/css">article {
  margin: 20px auto;
  width: 100%;
  padding: 1em;
  font-family: sans-serif;
  font-weight: normal;
  font-size: 1em;
  color:#FFC345;
}

.quote {
  background: #3E3831;
  padding: 15px 20px 5px 15px;
  border-radius: 5px;
  margin-bottom: 30px;
}

.quote:after {
  content: '';
  width: 0px;
  height: 0px;
  border-style: solid;
  border-width: 20px 18px 0 18px;
  border-color: #3E3831 transparent transparent transparent;
  position: relative;
  top: 37px;
  left: 20px;
}

.student {
  margin-left: 25px;
  margin-bottom: 80px;
}

.student .photo {
  background-color: #ccc;
  border-radius: 100px;
  width: 60px;
  height: 60px;
  float: left;
  margin-right: 10px;
}

.student p {
  position: relative;
  top: 5px;
  text-transform: uppercase;
}

.student p:nth-child(2) {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 0;
}

.student p:nth-child(3) {
  font-size: 14px;
  color: #777;
}
</style>
<article>
<div id="owl">
<div class="column row">
<div class="large-12 columns testimonial">
<div class="quote">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ultrices, elit sed faucibus pharetra, diam mauris bibendum orci, sit amet ullamcorper purus dui sit amet augue. Donec aliquet diam ut neque mattis, eu tristique sem rutrum.</p>
</div>

<div class="student">
<div class="photo round-image"> </div>

<p>Don Know</p>

<p>Important person, some Company</p>
</div>
</div>
</div>

<div class="row">
<div class="large-12 columns testimonial">
<div class="quote">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ultrices, elit sed faucibus pharetra, diam mauris bibendum orci, sit amet ullamcorper purus dui sit amet augue. Donec aliquet diam ut neque mattis, eu tristique sem rutrum.</p>
</div>

<div class="student">
<div class="photo"> </div>

<p>Pablo Napp</p>

<p>Important person, some Company</p>
</div>
</div>
</div>
</div>
</article>
<script src="/en/libraries/jquery-1.11.3.min.js"></script><script src="/en/libraries/OwlCarousel2-2.2.0/dist/owl.carousel.min.js"></script><script>
    $(document).ready(function () {
            $("#owl").owlCarousel({
                navigation: false,
                slideSpeed: 100,
                paginationSpeed: 800,
                singleItem: true,
                autoPlay: true
            });
        });
    </script>

```

Sorry, the code was taken from some other sources and I've only limited knowledge on it.

Could anyone please guide me how to implement such carousel.

Thanks

# Answer
> 1 votes
I would not bother with copy pasting HTML/CSS/JS into a block (this is bad practice regardless).

Instead, you might want to try the Owl Carousel or Flickity module for Drupal. You didn't mention your version, Owl Carousel exists for Drupal 7, while Flickity only exists for Drupal 8.

---
Tags: views, 8, javascript
---


# Question
Title: How could I check that the field's value has indeed been modified?
Is there a hook which could be used to execute code when a specific field of a custom content type is updated? Is there a specific hook, or should I use `hook_node_presave()`? In that case, how could I check that the field's value has indeed been modified?

# Answer
> 11 votes
Using `hook_entity_presave()`:

> You can get the original entity object from $entity-\>original when it is an update of the entity.

So something like this ought to work:

```
function foo_node_presave(\Drupal\node\NodeInterface $node) {
  if (!$node->isNew() && $node->get('field_bar')->getValue() != $node->original->get('field_bar')->getValue()) {
    // ...
  }
}

```

---
Tags: 8, entities, hooks
---


# Question
Title: Custom RESTful api GET request only works if user is already logged in, although _access has been set to 'TRUE'
Controller outputs a json response. On local machine it works fine weather user is logged in or not. But on the server if the use is not logged in to drupal the single page application that fetches unpublished nodes using ajax call gets `503 (Service Unavailable)` error. I have done what this link says and set \_access: 'TRUE' in the routing.yml file and tried couple of other things but no luck. Any idea what could be the cause?

# Answer
> 1 votes
The problem of no json output was, it turned out, because the site was under maintenance mode! And like Berdir said 503 is not access denied error!

---
Tags: 8
---


# Question
Title: How to render HTML page with attachments only from the render array?
I would like to render a full html page(with html and body tags) with content provided by a render array.

What do I need to do in order to NOT render attachments(CSS, JS, drupalSettings) from active theme or modules but solely from attachments defined in the provided render array?

---

So far this is quite close but I still see attachments from base theme:

```
\Drupal::service('bare_html_page_renderer')
      ->renderBarePage(
        $my_render_array,
        'Page label',
        'page',
        []
      );

```

Using my own, empty, theme hasn't helped.

---

Ok, I had to duplicate what bare\_html\_page\_renderer did since it attached "default" libraries form the system module. So now with my own theme all looks good but the structure is not right. Seems like the placeholders are not working properly.

My html.html.twig source code looks like:

```
<!DOCTYPE html>
<html{{ html_attributes }}>
<head>
  <head-placeholder token="{{ placeholder_token }}">
  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token }}">
  <js-placeholder token="{{ placeholder_token }}">
</head>
<body{{ attributes }}>
{{ page }}
<js-bottom-placeholder token="{{ placeholder_token }}">
</body>
</html>

```

but the rendered HTML will looks like:

```
<html dir="ltr" lang="en">
<head> </head>
<body>
<head-placeholder token="...">
<title>Page title</title>
<link rel="stylesheet" href="..." media="all">
<div>the rendered content</div>
<script src="...">
</head-placeholder>
</body>
</html>

```

---

So the issue was the there has to be at least one attribute in the header, otherwise the 'head' placeholder won't be replaced. So adding a favicon or generator or any metatag will do the trick.

Unfortunately this works only for route response with theme negotiator but not if I just want to print the pure html code since the active theme will be applied.

# Answer
So this is a working solution. The response has getContent() method so it can be used in code and not only as route response.

```
function renderHtml($some_content) {
    $html = [
      '#type' => 'html',
      'page' => [
        '#type' => 'page',
        '#title' => 'Some page',
        'content' => $some_content,
        '#attached' => [
          // At least one of these have to have value,
          // otherwise the head placeholder won't get replaced.
          'html_head_link' => [],
          'html_head' => []
        ]
      ]
    ];

    $html['page']['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'Sometag',
        'content' => 'somevalue',
      ),
    ], 'someid'];

    $active_theme = \Drupal::theme()->getActiveTheme();
    $render_theme_extension = \Drupal::service('theme_handler')->getTheme('rendering_theme');
    $new_active_theme = \Drupal::service('theme.initialization')->getActiveTheme($render_theme_extension);
    \Drupal::theme()->setActiveTheme($new_active_theme);

    \Drupal::service('renderer')->renderRoot($html);
    $response = new HtmlResponse();
    $response->setContent($html);
    $response->setMaxAge(0);
    $response = \Drupal::service('html_response.attachments_processor')->processAttachments($response);

    \Drupal::theme()->setActiveTheme($active_theme);

    return $response;
}

```

*Note: when you are using this via ajax callback, you have to unset the **ajax\_page\_state** from the post request, otherwise you'll be most likely be missing some libraries.*
> 1 votes

---
Tags: theming, 8
---


title: Use responsive images inline

text:
# Question
Title: Use responsive images inline
I can see that using styles on inline images have been left out for some reason. But when I need to make the site behave a little more responsive.

I have been looking after CKeditor plugins that could select a style for the image being include. But I haven't found any.

I have been looking after at comment on the Drupal 7 Picture module that should be what is the base for the implementation of Responsive Images in Drupal 8. But there is nothing about inline images to find - just old Drupal 7 demos on how it should work.

Any idea how to get responsive images or just a basic image style for images include in inline editor on Drupal 8?

# Answer
> 1 votes
The module Entity Embed will be able to do that. There is now a dev version available, but you better wait for the first alpha/beta-release.

Even longer it will take, until this is in core:

Allow image style/responsive image mapping to be selected in Text Editor's image dialog

This is postponed to drupal 8.1

Until then you can use jquery to move the image from an image field to an empty container in the body. To avoid flicker effects, add a style display:none in the twig template of that specific image field and show it after moving it into the body in jquery.

# Answer
> 0 votes
Add the css code into "/themes/bootstrap/css/3.3.x/overrides.min.css"

```
 img {
    display: Block;
    max-width: 100%;
    height: auto;
 }

```

# Answer
> -1 votes
You can add the class="img-responsive" in the image tag it will responsive automatically. Hope its will work for you.

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


# Question
Title: Inserting previously uploaded images into WYSIWYG editors
I'm having a photo sharing feature on the site where users upload photos which are saved as nodes.

I want to be able to have them insert any of their previously uploaded photos into articles nodes and comments.

I haven't decided on TinyMCE vs. CKEditor plugins yet.

I want to do the same for videos they have uploaded. I haven't tried IMCE yet but don't like the "windows explorer" like UI. Same with CKFinder

Our old community site has such a feature for the TinyMCE editor but I'm not sure how they did that.

# Answer
If you're using the Media module, any image uploaded should be available in the WYSIWYG insert media library tab.
> 0 votes

# Answer
IMCE works for me. Yes, it has a Windows Explorer like interface but that said it works for files in your public directory.

I use the D8 Juicebox module and the separate PC Juicebox application. Create galleries with pre-made images and thumbnails on the PC. FTP the completed Gallery up to the public files area on D8. If I want to re-use any image in another content type (say article) I just find it through IMCE and insert it.
> 0 votes

---
Tags: 7, wysiwyg
---


title: Execute code before cache is cleared

text:
# Question
Title: Execute code before cache is cleared
I want to execute code before cache is cleared, for example for the menu cache:

```
// Clear menu cache
$cache = \Drupal::cache('menu');
$cache->deleteAll();

```

I want to intervene when the cache clear is called, right before it is deleted. I've read the documentation on Drupal::cache and the Cache API but didn't find a solution. Do note that I want to do this using core code only, no contributed modules.

# Answer
> 1 votes
It isn't clean but I'm able to do this with hook\_cache\_flush. It's called when a cache clear has been called, before the cache has been cleared.

---
Tags: 8, caching
---


# Question
Title: How to update a menu link created with MenuLinkContent::create()?
I know how to search for menu items created with `*.links.menu.yml`:

```
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute('user.page');
foreach ($menu_links as $menu_link) {
  // Do something
}

```

However I'm looking for a way to search for and update a menu item created with `MenuLinkContent::create()`:

```
$home_new = MenuLinkContent::create(array(
  'title' => t('Home'),
  'link' => array('uri' => 'internal:/'),
  'menu_name' => 'main',
));
$home_new->save();

```

After creating this menu item, how do I look it back up again to modify it?

# Answer
If you remember the id after saving the menu link

```
$id = $home_new->id();

```

You can load it directly:

```
$link = MenuLinkContent::load($id);

```

If you don't know the id, you can load the menu link by a property:

```
$links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['title' => 'Home']);

if ($link = reset($links)) {
  // found a link with title "Home"
}

```
> 4 votes

---
Tags: 8, navigation
---


title: How do I create a custom plugin?

text:
# Question
Title: How do I create a custom plugin?
Basically, I want to port a custom ctools plugin created for content type from Drupal 7 to Drupal 8. This is the code I want to port.

```
function my_module_ctools_plugin_directory($module, $plugin) {
  if (($module == 'ctools') && ($plugin == 'content_types')) {
    return 'plugins/content_types';
  }
}

```

In my\_module/plugins/content\_types/my\_module.inc file i have following code:

```
/**
 * Plugin array() of ctools plugin.
 */
$plugin = array(
  'title' => t('My Module'),
  'single' => TRUE,
  'content_types' => array('my_module_custom_content_type'),
  'render callback' => 'my_module_render',
  'required context' => new ctools_context_required(t('Node'), 'node'),
  'edit form' => 'my_module_settings_form',
  'edit form validation' => 'my_module_settings_form_submit',
  'category' => 'Widgets',
);

/**
 * Render callback function.
 */
function my_module_render($subtype, $conf, $args, $context) {
  $node = $context->data;
  if (empty($node)) {
    return;
  }
  $data = \Drupal::formBuilder()->getForm('my_module_form', $context, $conf);
  $block = new stdClass();
  $block->content = $data;
  $block->title = '';
  $block->id = 'my_module_form';
  return $block;
}

```

How do I port the plugin to Drupal 8?

# Answer
> 5 votes
There are no ctools plugins anymore in Drupal 8. There's just the Drupal 8 plugin API.

Page Manager, Panels and so on use standard block plugins now in 8.x, so you basically have to port this to a block an then it should work fine.

Also, the "code" you posted only defines that you have such a plugin in your module, nothing else. If you need more specific support, you will need to post your actual code, and ask specific questions (which are probably better as a follow-up question).

---
Tags: 8, chaos-tool-suite, plugins
---


title: CSS edit rules page does not open

text:
# Question
Title: CSS edit rules page does not open
I logged in as admin. I opened the css configuration page. I clicked edit rules page. After that, css edit rules page should open but my site is stuck at screen 2(home page). After I click edit rules many times, sometimes, I get the edit rules page. I feel that this is a site wide issue not css injector issue.

Example: If I click Save on views page, it does save but my page gets stuck at the home page. I have to hit the back button to come back to view and I see that views is already saved.

If I click clear cache in performance page, I have similar issue. It does clear the cache but the site is stuck at home page. I hit back button to come back to performance page again.

I simply do not know where to start troubleshooting. I am not getting any error messages. If you could point me to right direction to solve this issue, it would be very helpful.

enter image description here

Screen2:

# Answer
Turned off overlay module. Problem has fixed.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Can't see the "help" hook on the Modules admin panel
I'm reading Drupal 7 Module Development and trying to learn module development. I've created their example module '**first**' and I'm not seeing the '**help**' link.

Here is what I have so far...

**`/sites/all/modules/first/first.info`**

```
name = First
description = A first module.
package = Drupal 7 Development
core = 7.x

```

**`/sites/all/modules/first/first.module`**

```
<?php

/**
 * @file
 * A module exemplifying Drupal coding practices and APIs.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */

function first_help($path, $arg) {
  if ($path == 'admin/help#first.') {
    return t('A demonstration module.');
  }
}

```

Now then... according to this book, when I install/activate the **`first`** module, I should see a **() Help** link to the right of my module name in the Modules admin panel.

I don't. What could be stopping this link from populating this screen. I get **`() Help`** links for all of the other modules. But not mine.

I created a subdomain on my server and installed Drupal to test with a fresh Drupal install. The help link shows up and works on the new install. So now I'm trying to wrap my head around what could be killing it on my other Drupal site? Could Devel? Coder? This is very weird.

# Answer
You have a period at the end of your path condition.

Try this:

```
function first_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('A demonstration module.');
  }
}

```
> 3 votes

# Answer
A note about modules with more than one-word name: *the path must match your module name*, if the module was called "first\_module" the path "first-module" would not work (underscore vs dash). It should look like this:

```
function first_help($path, $arg) {
  if ($path == 'admin/help#first_module') {
    return t('A demonstration module.');
  }
}

```
> 1 votes

# Answer
Hope this will help you!!

* First of all disable the module and enable it again. Also go to Administer \> Performance and hit the "Clear cached" button.
Hope this will resolve your issue.

If the issues is still there then,
* If you are using Drupal 7, this link will help you. You can see different examples.
* After enabling the module clear cache.
> 0 votes

# Answer
For anybody else who's having this problem, make sure that the Help module is enabled. That fixed it for me.
> 0 votes

# Answer
Enable the **Help Module** from *admin/modules*, then refresh page again.
> 0 votes

---
Tags: hooks
---


# Question
Title: How do I create a module that uses composer to manage a 3rd party library?
I maintain a module on Drupal.org, the jQuery Colorpicker module, which has a requirement on a 3rd party library. I created a composer.json file in the module root. When I originally installed it, I navigated to the module root and ran `composer update`, which created vendor folder in my module directory, and loaded the library to this vendor directory. I then released a beta version of the module.

One user who downloaded the library ran `composer drupal-update` from core, which installed the library to the DRUPAL\_ROOT/vendor folder. I'm thinking this is the correct way to go.

So I deleted the vendor folder from my module folder, as well as the composer.lock folder from my module folder.

However, when I run `composer drupal-update` in my drupal root, it does not install the library to my vendor folder.

I'm not really sure where to go with this - do I need to add something to my module, or is there a required command that needs to be run somewhere for Drupal to install the library when running `composer drupal-update`? I haven't worked a lot with composer, so I'm trying to find the proper way to do this so my users can use the module in the standard Drupal way.

# Answer
In order to have composer download a 3rd party library, you need (as you have already done) a composer.json file within your module. This file should contain the required 3rd party libraries. There are however quite strict guidelines for creating a proper composer.json file for Drupal in which you should at least define the following:

```
{
    "name": "drupal/example",
    "description": "This is an example composer.json for example module.",
    "type": "drupal-module",
    "license": "GPL-2.0+"
}

```

Running composer from the module root is indeed not recommended as this might become quite time consuming when installing many modules, not to mention updating all of them once in a while.

Luckily the Drupal guys have done some work, allowing composer to manage all Drupal dependencies, which is out of beta since a few weeks.

This allows you to use composer from the Drupal root to require modules as well. During the downloading of the module all dependenies of it will be resolved as well.

On a small sidenote; Reading through that blog post again leads me to assume the following should also be included in your module's composer.json file (as of writing the first link also shows an outdated message):

```
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    }

```

As for your situation, it seems you should commit a file similar to this to Drupal.org:

```
{
    "name": "drupal/jquery_colorpicker",
    "description": "jquery_colorpicker module.",
    "type": "drupal-module",
    "license": "GPL-2.0+",
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        ...
    }
}

```

And then run `composer require drupal/jquery_colorpicker` from your Drupal root.

UPDATE: After reading that blog post for the fourth time, I came to conclude that the `repositories` part is with high probability only required for the root composer file and thus not required for individual modules.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: How to get price to update when changing attrubutes within a View
I have a view and have a relationship so I can display the product price. When I change an attribute option, the price field doesnt dynamically change.

I think I will have to do something with the style settings and change to DIV, check create a CSS class and add a tokenized CSS class so it will change when the product id changes? but i cant get it to work.

What I've done so far:

1. Add relationship Content: Referenced products
2. I have 3 fields: 1. content nid (excluded from display) 2. product add to cart form. 3. commerce product price field.

**At this point i can display the price but it doesnt update when i select various attribute options**

3. Style Settings, Customize field HTML --\> DIV --\> Create a CSS class

I think under the create a CSS class i need to print a CSS class with a product id token or something like that, but cant find the correct token or CSS valule.

# Answer
> 0 votes
Found it:

1. you must add a content: NID field and exclude from display to get the token of \[nid\] available
2. Then under style settings of the price field, select 'customize field HTML'
3. HTML element = DIV
4. Select Create a CSS class
5. the CSS class for Price is: node-\[nid\]-product-commerce-price

The NID token will update when a certain attribute changes. This can also be applied to other fields as well finding the CSS with firebug and then adding in the \[nid\] token

---
Tags: views, commerce
---


# Question
Title: How can a form remember the selected tab after submit?
I'm using vertical tabs in a form, and I keep all the values with `$form_state->setRebuild(true);`. In this way, the user can change some of the submitted values.

I would like to keep the selected tab active as well. How can I achieve this?

If there aren't other solutions, I will use JavaScript to manually select the tab after the form is reloaded.

# Answer
You should be able to see which vertical tab was selected at the time your form was submitted. If not, you can certainly use js and a hidden field to keep track of it. Once you have it submitted your form then you can easily set the #default\_tab of your vertical tabs based on the value in your the recently selected tab. Something like this:

```
$form['information'] = array(
  '#type' => 'vertical_tabs',
  '#default_tab' => isset($form_state['values']['selected_tab'][...) ? $form_state['values']['selected_tab'][... : "some_tab",
);

```

Another option would be to use a pure js solution. By storing the currently selected tab in local storage and then selecting that tab when the form loads should work as well. In this case you may see your form "flash" as the selected tab is selected but that may or may not be a problem depending on your form and desired UX
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How do I add custom contextual links in a block?
I want to add more contextual links (e.g. "Edit Block") to my block apart from the existing "Configure Block".

How can I achieve this?

# Answer
> 2 votes
I know that this blog post is 100 years old, but it still applies:

http://bleen.net/blog/easier-way-add-contextual-links-drupal-7

The basic idea is to make use of `hook_contextual_links_view_alter`

For example:

```
function MYMODULE_contextual_links_view_alter(&$element, &$items) {
  // This hook is called for EVERY set of contextual links
  // on a page.  We first want to check the $element to make
  // sure we are adding a link to the correct list of contextual
  // links. In this case we only want to add a link to blocks
  // created by the "search" module. We just add links using the
  // same array structure as is used by theme_links.
  if (isset($element['#element']['#block']) && $element['#element']['#block']->delta == "site_tweets-site_tweets_block") {
    $element['#links']['social-networks'] = array(
      'title' => 'Edit social network links',
      'href' => url('/admin/config/system/site-information', array('absolute' => TRUE)),
    );
  }
}

```

---
Tags: 8
---


# Question
Title: Is there a live backend demo of drupal commerce?
Is there a live Drupal Commerce backend demo site? I would like to take a look before trying to download and install it.

# Answer
1. Go to https://simplytest.me
2. Fill in "commerce kickstart"
3. Select the latest version: 7.x-2.41
4. Click "Launch sandbox"
5. Follow the step-by-step on-screen instructions, including the database configuration screen. You will notice that all fields are already filled in so you can just press "Next".
> 2 votes

---
Tags: commerce
---


# Question
Title: How to transfer a block from one site to another?
I've built a block on my local site and now want to transfer it to a remote site.

I thought this was done via Features, so downloaded the feature files and placed them on my remote server. On the remote site I accessed Features, checked the box of the updated Feature I placed up there and hit save.

I've cleared the cache and theme registry but the new block does not appear on the remote site.

Would anyone know what I've done wrong here?

# Answer
> 4 votes
Have a look at the Bean module. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

> **This module has been included with Drupal 8 core**. Refer to this issue for more information.

# Answer
> 4 votes
You can try Block Export Import module, It will help you to import block to remote site.

> This module allows users to export all system specific blocks (are those blocks which are created using Drupal interface add block functionality) and then import it into another Drupal installation, or on the same site.
>
> No additional configuration is required to export/Import block(s). Also this module does not create any table in the database. Therefore it will not effect the application performance.

---
Tags: 7, blocks, features
---


# Question
Title: Commerce kickstart 2 creating custom front page
I subthemed the original kickstart 2 commerce site and everything works fine. I also understand the CSS structure and how to regulate that.

What I'm trying to understand is how the frontpage works and how to change the structure. It looks like the frontpage is created of blocks so I can change what shows or doesn't show on frontpage via Site settings -\> Blocks.

However, how could I add lets say a custom div with h1 heading and few paragraphs to it?

This can be easily created with adding a new basic page, where you can use full html in body and style the page to your liking. How does this work with a front page?

If I create a basic page with the paragraph "Welcome to the website" that I want to use on the front page, and then display it in a main content block, what bothers me is that it renders Read more button. Which I don't want.

Where can I do that for frontapge then?

# Answer
I suppose you could create a custom block at admin/structure/block/add. It comes with body field and after creating the block you can assign it to "content" region and set it to show up only on .

You have the possibility to create new regions in theme.info file and render them only in page--front.tpl.php.

I think these are the clean ways to do it, and don't require much coding.
> 0 votes

---
Tags: commerce
---


# Question
Title: Us js file in a theme already use by a module
I need to use in my theme a js file used originally by a other module: View slideshow.

View Slideshow take the jquery plugin Cycle from the libraries folder, on the root of the App, something like

```
libraries/js/cycle/jquery.cycle.js.

```

Now i need to use the jquery plugin Cycle in my theme, but drupal put it after my main theme js file

```
<script src=mytheme.js>
<script src=....cycle.js>

```

So it can't use it, because cycle must be before.

I add the file in my libraries.yml file like this:

```
mytheme
  js :
    - ...cycle.js: {}
    - mytheme.js: {}

```

but cycle steel remain after. How could i move Cycle on top ?

# Answer
Okay this was easy... I realise that the js file is in the library views\_slideshow\_cycle/jquery\_cycle, created by the module.

So i just have to add it has a dependencies to my theme

```
mytheme
   dependencies :
     views_slideshow_cycle/jquery_cycle.

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How do I get posts of a content type on node writing
I have three content types: endorse, deals, and recommends. Recommends has three nodes.

How do I show those three nodes from the recommend content type on the deals content type using a field on the deals content type writing panel?

# Answer
You can use the References Module, that can be used as a node reference of any other content type. After installing the module, go to deals content type manage fields, select the node reference to field to recommends content type and while configuring field make it as unlimited, and now go to deals content type writing panel, here you can see the multiple field and can access the node id or name of the references content type nodes. You can list the selected nodes of references under deals node in views using relationship.
> 0 votes

---
Tags: nodes, 8, entities
---


# Question
Title: What is the purpose of the "token" custom display setting?
On the `manage display` page of a given content type, you can choose between various display settings. The most commons are "teaser" and "default" or "full content".

However, there's also a "token" display mode (disabled by default). I assume it's added by the token contrib module, but I have no idea what its purpose is and how we're supposed to take advantage of it?

Also: is it typically used somewhere that I'm not aware of? Can it be safely deleted if it's not activated?

# Answer
As Neograph734 commented, it allows you to change the output of field tokens without actually changing the default display of the field. You can find more information here: https://www.drupal.org/node/1299662

Actually, a similar question already has been answered: Effective use of tokens view mode?
> 3 votes

---
Tags: 8, tokens
---


title: Do Simpletests require t()?

text:
# Question
Title: Do Simpletests require t()?
All Simpletest documentation and examples use the t() function for `clickLink()` or `assertText()` for example. However when I read the core issue about testing not working when locale of host session is not English and the patch that got committed (tl;dr it forces English to be the default language) I'm curious if it's really necessary.

MegaChriz has an interesting take on this, as he doesn't t() his string in Feeds tests. Extract from his comment as to why:

> In most cases, the "final" text is checked, thus the text for which the translation placeholders have already been replaced. So there is no original translation string to check for. If I remember well, there were also occasions where only a portion of the text was checked. Since tests are always run in English (at least, by my knowledge), this should have no harm.

If the default language is English, can't we simply remove the t() function from testing? Please note that I'm not looking for opinions but for facts.

# Answer
> 2 votes
I know for a fact (though it is probably not the only reason) that `t()` allows for replacement arguments:

```
echo t('my %string', ('%string' => 'Foo'));

```

Which renders as: 'my *Foo*' (emphasized text).

If you were to use such placeholders on your site, they will not work unless you wrap them through `t()` or `format_string()` (where `t()` is much much shorter).

Here comes the opinion part; if you only were to use plain text strings it probably wouldn't matter. But if you use `t()` on the front end with formatting and you would compare that value in the backend with a plain text string, it wouldn't match. And writing all tests to use `format_string()` instead would be very confusing.

In the end it all depends on your situation and your tests.

---
Tags: 7, testing
---


# Question
Title: How to import multiple images with Feeds importer from CSV?
I am using feeds importer for importing images. I have mapped the column "Image" in my CSV to the "Image: URI (field\_image:uri)" field in my importer configuration. It workds for now when I put only one image URL in the CSV file, but how to import multiple images?

# Answer
> 4 votes
You can accomplish this with choosing a character to separate your image urls with in the CSV file and using the Feeds Tamper plugin "Explode".

1. Separate the image URLs in your CSV file with a certain character, for example a pipe character: "|". Your CSV file could then look something like this:

title,image Lorem Ipsum,http://www.example.com/image1.png|http://www.example.com/image2.png
2. Install the module Feeds Tamper. Also enable the Feeds Tamper Admin UI module (included with Feeds Tamper).
3. Go the Tamper page of your feeds importer (/admin/structure/feeds/\[importer\_id\]/tamper).
4. Click "Add plugin" for the "Image: URI" mapper.
5. For the plugin to add, select "Explode". As string separator, choose the character that you used to separate your image URLs. If you followed the example, then this would be the pipe character: "|". See also the image:

The explode tamper plugin cares that your input data (for example "http://www.example.com/image1.png|http://www.example.com/image2.png") is handled as multiple values.

---
Tags: feeds, importing-exporting
---


# Question
Title: Can not aggregate a global field: Mathematical expression
I installed "Physical Fields" and I created a view (block) to display the total weight of the order in the shopping cart. In my view I added the "price" and "quantity" fields, then I add a "Global: Mathematical Expression" field with "\[field\_weight\] * \[quantity\]". I activated the aggregation on the view and I configure the parameters of the group for Global field: Mathematical expression sue "sum".

The view does not work and does not display sums. I have seen that the field of mathematical expression can not be aggregated.

How do I get the sum of this field ?

Can I do this in the "template.php" file of my theme? If yes, how ?

Here is the export of my view :

Thank you.

```
$view = new view();
$view->name = 'commerce_order_weight';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'commerce_order';
$view->human_name = 'Poids de la commande';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Poids panier';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  7 => '7',
  3 => '3',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relation: Commande Drupal Commerce : Referenced line items */
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['required'] = TRUE;
/* Relation: Commerce Line item : Referenced products */
$handler->display->display_options['relationships']['commerce_product_product_id']['id'] = 'commerce_product_product_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['table'] = 'field_data_commerce_product';
$handler->display->display_options['relationships']['commerce_product_product_id']['field'] = 'commerce_product_product_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['relationship'] = 'commerce_line_items_line_item_id';
/* Relation: Commerce Product : Referencing Nœud */
$handler->display->display_options['relationships']['field_produit']['id'] = 'field_produit';
$handler->display->display_options['relationships']['field_produit']['table'] = 'commerce_product';
$handler->display->display_options['relationships']['field_produit']['field'] = 'field_produit';
$handler->display->display_options['relationships']['field_produit']['relationship'] = 'commerce_product_product_id';
/* Champ: Commande Drupal Commerce : Identifiant (ID) de la commande */
$handler->display->display_options['fields']['order_id']['id'] = 'order_id';
$handler->display->display_options['fields']['order_id']['table'] = 'commerce_order';
$handler->display->display_options['fields']['order_id']['field'] = 'order_id';
$handler->display->display_options['fields']['order_id']['label'] = '';
$handler->display->display_options['fields']['order_id']['exclude'] = TRUE;
$handler->display->display_options['fields']['order_id']['element_label_colon'] = FALSE;
/* Champ: Commerce Product : Poids */
$handler->display->display_options['fields']['field_weight']['id'] = 'field_weight';
$handler->display->display_options['fields']['field_weight']['table'] = 'field_data_field_weight';
$handler->display->display_options['fields']['field_weight']['field'] = 'field_weight';
$handler->display->display_options['fields']['field_weight']['relationship'] = 'commerce_product_product_id';
$handler->display->display_options['fields']['field_weight']['label'] = '';
$handler->display->display_options['fields']['field_weight']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_weight']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_weight']['click_sort_column'] = 'weight';
$handler->display->display_options['fields']['field_weight']['group_column'] = 'entity_id';
/* Champ: Commerce Line Item : Quantité */
$handler->display->display_options['fields']['quantity']['id'] = 'quantity';
$handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
$handler->display->display_options['fields']['quantity']['field'] = 'quantity';
$handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['fields']['quantity']['label'] = '';
$handler->display->display_options['fields']['quantity']['exclude'] = TRUE;
$handler->display->display_options['fields']['quantity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['quantity']['precision'] = '0';
$handler->display->display_options['fields']['quantity']['separator'] = '';
/* Champ: SUM(Global : Expression mathématique) */
$handler->display->display_options['fields']['expression']['id'] = 'expression';
$handler->display->display_options['fields']['expression']['table'] = 'views';
$handler->display->display_options['fields']['expression']['field'] = 'expression';
$handler->display->display_options['fields']['expression']['group_type'] = 'sum';
$handler->display->display_options['fields']['expression']['label'] = 'Poids de la commande';
$handler->display->display_options['fields']['expression']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['expression']['precision'] = '0';
$handler->display->display_options['fields']['expression']['separator'] = '';
$handler->display->display_options['fields']['expression']['expression'] = '[field_weight]*[quantity]';
/* Filtre contextuel: Commande Drupal Commerce : Identifiant (ID) de la commande */
$handler->display->display_options['arguments']['order_id']['id'] = 'order_id';
$handler->display->display_options['arguments']['order_id']['table'] = 'commerce_order';
$handler->display->display_options['arguments']['order_id']['field'] = 'order_id';
$handler->display->display_options['arguments']['order_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['order_id']['exception']['title'] = 'Tout';
$handler->display->display_options['arguments']['order_id']['default_argument_type'] = 'commerce_cart_current_cart_order_id';
$handler->display->display_options['arguments']['order_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['order_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['order_id']['summary_options']['items_per_page'] = '25';
/* Critère de filtrage: Commande Drupal Commerce : Type de commande */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'commerce_order';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'commerce_order' => 'commerce_order',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$translatables['commerce_order_weight'] = array(
  t('Master'),
  t('Poids panier'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Line items referenced by commerce_line_items'),
  t('Products referenced by commerce_product'),
  t('Nœud referencing products from field_produit'),
  t('.'),
  t('Poids de la commande'),
  t('Tout'),
  t('Block'),
);

```

# Answer
> 0 votes
Views relies on the database to perform aggregation. Since the math field's value does not live in the database it doesn't work.

You can however use Views Aggregator plus that uses the calculated values instead.

> this module:
>
> * enumerates group members
> * produces tallies, i.e. textual histograms
> * aggregates on Views PHP code-snippet evalutations
> * can filter out result rows on regexp patterns
> * gives you sorting on Views' Math expressions
> * can process Webform submissions
> * lets you add your own custom aggregation functions

---
Tags: 7, views
---


# Question
Title: Run feeds importer from outside the site
I have a Feeds importer that's running periodically (with cron) using "Feeds Fetcher Directory" fetcher. Now I need to run the importer **on demand** from other app outside the site. Is there a way **to just run** the importer (not cron) in a similar way as cron does? (going to some url)

I'm using Drupal 7.53.

Thanks!

# Answer
Since version 7.x-2.0-beta3, Feeds has Drush support. You could use the following command to trigger an import (where 'my\_importer' is the machine name of your importer):

```
drush feeds-import my_importer

```

If the importer is attached to a content type, specify also the feed node with the option '--nid':

```
drush feeds-import my_importer --nid=2

```

Note that a source for the importer in question must exist\*. So you need to have gone through the import form at least once.

You could write a shell script that executes the drush command and that is triggered when the url is requested.

---

\*The drush command 'feeds-import' has more options, allowing you to perform an import even when no source was created yet. But I don't think that applies in your situation. See https://drushcommands.com/drush-7x/feeds/feeds-import for more information.
> 1 votes

---
Tags: feeds, importing-exporting
---