# Question
Title: views_embed_view fails with contextual filters?
I have a view with 2 contextual filters, each is set to display all results if not present. This is tested on the Views edit screen using the Preview Contextual Filters. Both contextual filters filter taxonomy term Ids.

With none set it gives loads of results; with '152' it returns three results; with '152/366' it returns one result. These are the expected results.

However in my Drupal 7 code I have tried the following, but none of the ones with filters work:

```
print views_embed_view('my_view','default'); // ✔ all shown

print views_embed_view('my_view','default',152); // ✘ nothing
print views_embed_view('my_view','default','152'); // ✘ nothing
print views_embed_view('my_view','default',array(152)); // ✘ nothing
print views_embed_view('my_view','default',array('152')); // ✘ nothing
print views_embed_view('my_view','default',152,366); // ✘ nothing
print views_embed_view('my_view','default','152','366'); // ✘ nothing
print views_embed_view('my_view','default',array(152,366)); // ✘ nothing
print views_embed_view('my_view','default',array('152','366')); // ✘ nothing
print views_embed_view('my_view','default','152/366'); // ✘ nothing

```

Also, all the ones that use `array` for the contextual filter argument generate an error: "html\_entity\_decode() expects parameter 1 to be string, array given"

I feel like I'm missing something obvious here...

# Answer
> 5 votes
If you have devel installed , try checking with this syntax , if you do not see any result then try passing the arguments as 4/1(w.r.t given example) in the preview of views to cross check you have results with those combination of exposed filters. Debugging at devel/php will save lots of your time.

```
dpm(views_embed_view("view_name", "view_display_type", 4, 1));

```

# Answer
> 0 votes
This is fixed for you, however there is another detail which may break the display of the view. If the arguments are optional then when not selected they will have the option `-Any-` with the value **All**.

In my case when `-Any-` was selected the view would break. Selecting specific value would work OK. The solution is in the Contextual filters options of the view. The Exception value under Exceptions must be **All** and it is case sensitive. Then the filter is ignored.

# Answer
> 0 votes
If your View has some Organic Group Relationships on it, be careful if you add a relationship like the one in **#2** below. For me, adding that Relationship results in non-administrative users not being able to see any results from the `views_embed_view`.

Here's the Contextual Filter and Relationships *that causes no results for me*:

## Contextual filters

* Taxonomy term: Term ID

## Relationships

1. OG membership: OG membership from Content
2. (OG membership from node) OG membership: Group Content from OG membership

At first I thought it may be a user permissions problem (from a comment on the accepted answer here), so I got desperate and I disabled and uninstalled the `og_access` module and rebuilt the user permissions, which didn't fix it either.

At this point, I recalled that these same Relationships work just fine on a different View, and so by this I figure that the combination of these Organic Group Relationships and the Taxonomy Term ID Contextual Filter are somehow together causing some weird access bug.

So the fix for me is to remove the 2nd OG Relationship from the View since it isn't a 100% requirement for my View, and to leave the Contextual Filter because it is required. It sure would be nice to bring in the Organic Group that owns the content here though.

It's sad that this happens, I bet I've been burned by this in the past multiple times and never really noticed this much about it until now. In the past I know I've given up on Views many times and just built a custom `db_select` to get the data I need. Le sigh, I hope this helps someone and my future self that gets burned by this again.

---
Tags: 7, views
---


title: Home Page rel="canonical"

text:
# Question
Title: Home Page rel="canonical"
We created a home page as node/1850 which is specified in /admin/config/system/site-information. When I look at the generated code, I see:

```
<link rel="canonical" href="/node/1850" />

```

This results in Google listing the url of the home page as https://dom.ain/node/1850 which is not what we want.

What is the best way to correct this? I believe the following is correct.

```
<link rel="canonical" href="/" />

```

# Answer
You can use metatag module to adjust metatags like these.

After installing you can visit the settings page `/admin/config/search/metatag` and there is a specific set of metatags to adjust for front page. Edit those settings and adjust canonical but I believe by default it sets this to `[site:url]` which should be OK.

**Alternatively** or if you don't want to install a module just for this you can do it using `hook_preprocess_html` in your `THEMENAME.theme`

```
function THEMENAME_preprocess_html(&$variables) {
  //if not front page do nothing
  if(! \Drupal::service('path.matcher')->isFrontPage())
    return ;

  //unset if set
  foreach ($variables['page']['#attached']['html_head'] as $key => &$value) {
    if ($value[0]['#tag'] == 'link' && $value[0]['#attributes']['rel'] == 'canonical') {
      unset($variables['page']['#attached']['html_head'][$key]);
      break;
    }
  }

  //add canonical
  $canonical = [
    '#type' => 'html_tag',
    '#tag' => 'link',
    '#attributes' => [
      'rel' => 'canonical',
      'href' => '/',
    ],
  ];
  $variables['page']['#attached']['html_head'][] = [$canonical, 'canonical'];
}

```
> 0 votes

---
Tags: 8, uri
---


# Question
Title: Table form valueCallback strange behaviour
I am creating a table form using the table element. I do not push sub elements into #rows. I work as with children elements. But valueCallback does not map values right. I am looking inside. It looks very strange. Especially:

```
return is_array($input) ? array_combine($input, $input) : [];

```

$input always is array. So combining result is weird with "array" key https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Table.php/function/Table%3A%3AvalueCallback/8.5.x

```
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

  // If #multiple is FALSE, the regular default value of radio buttons is used.
  if (!empty($element['#tableselect']) && !empty($element['#multiple'])) {

    // Contrary to #type 'checkboxes', the default value of checkboxes in a
    // table is built from the array keys (instead of array values) of the
    // #default_value property.
    // @todo D8: Remove this inconsistency.
    if ($input === FALSE) {
      $element += [
        '#default_value' => [],
      ];
      $value = array_keys(array_filter($element['#default_value']));
      return array_combine($value, $value);
    }
    else {
      return is_array($input) ? array_combine($input, $input) : [];
    }
  }
}

```

For me $input already is ready to move into #value. It does not need altering here. I hope it works well and I do something wrong. But not it seems weird for. Clarify it, please.

# Answer
My solution is below. It is a weird solution because It requires small changes.

Define a table value callback.

```
    $form['links'] = [
      '#type' => 'table',
      ...
      '#value_callback' => array($this, 'valueCallback'),
    ];

```

Implement the callback.

```
 /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    return $input;
  }

```

The data has structure as it has been sent. So the standard data processing works badly for my case.
> 0 votes

---
Tags: 8, forms
---


title: Missing commands in drush 9.3

text:
# Question
Title: Missing commands in drush 9.3
I have installed drush 9 as dependency of my drupal 8 project as explained in: http://docs.drush.org/en/master/install/

```
cd ${D8_PROJECT}
composer require drush/drush

```

Then, I have installed `drush launcher` as explained in: https://github.com/drush-ops/drush-launcher (ubuntu)

```
wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.6.0/drush.phar
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

```

Everything is working fine except that some command are missing. Here is the list of command I have:

```
Drush Commandline Tool 9.3.0

Run `drush help [command]` to view command-specific help.  Run `drush topic` to read even more documentation.

 Available commands:
 _global:
   help                                 Display usage details for a command.
   list                                 List available commands.
   browse                               Display a link to a given path or open link in a browser.
   runserver (rs, serve)                Runs PHP's built-in http server for development.
   updatedb (updb)                      Apply any database updates required (as with running update.php).
   version                              Show Drush version.
   generate (gen)                       Generate boilerplate code for modules/plugins/services etc.
   drupal:directory (dd)                Return the filesystem path for modules/themes and other key folders.
   user:login (uli)                     Display a one time login link for user ID 1, or another user.
   entity:updates (entup)               Apply pending entity schema updates.
   updatedb:status (updbst)             List any pending database updates.
   config:pull (cpull)                  Export and transfer config from one environment to another.
   pm:security (sec)                    Check Drupal Composer packages for pending security updates.
 cache:
   cache:get (cg)                       Fetch a cached object and display it.
   cache:clear (cc)                     Clear a specific cache, or all Drupal caches.
   cache:set (cs)                       Cache an object expressed in JSON or var_export() format.
   cache:rebuild (cr, rebuild)          Rebuild a Drupal 8 site.
 core:
   core:status (status, st)             An overview of the environment - Drush and Drupal.
   core:init (init)                     Enrich the bash startup file with bash aliases and a smart command prompt.
   core:rsync (rsync)                   Rsync Drupal code or files to/from another server using ssh.
   core:execute (exec, execute)         Execute a shell command. Usually used with a site alias.
   core:edit (conf, config)             Edit drushrc, site alias, and Drupal settings.php files.
   core:topic (topic)                   Read detailed documentation on a given topic.
 php:
   php:eval (eval, ev)                  Evaluate arbitrary php code after bootstrapping Drupal (if available).
   php:script (scr)                     Run php a script after a full Drupal bootstrap.
 site:
   site:ssh (ssh)                       Connect to a Drupal site's server via SSH.
   site:set (use)                       Set a site alias that will persist for the current session.
   site:alias (sa)                      Show site alias details, or a list of available site aliases.
   site:alias-convert (sa-convert, sac) Convert legacy site alias files to the new yml format.
   site:install (si, sin)               Install Drupal along with modules/themes/configuration/profile.
 sql:
   sql:connect                          A string for connecting to the DB.
   sql:create                           Create a database.
   sql:drop                             Drop all tables in a given database.
   sql:cli (sqlc)                       Open a SQL command-line interface using Drupal's credentials.
   sql:query (sqlq)                     Execute a query against a database.
   sql:dump                             Exports the Drupal DB as SQL using mysqldump or equivalent.
   sql:sync                             Copy DB data from a source site to a target site. Transfers data via rsync.

```

Where are the `user-create`, `role-create` and other commands?

... and what is really weird, is the fact that yesterday I did use the `drush locale-update` command... and today this command is also gone.

# Answer
I finally understood my problem.

Looking at the @M.Schmitt comment, I could find that both syntax are working: `user:create` and `user-create`. A lot of commands are not available when there is no connection to the database. When I ran `drush` on a multisite installation without default site, I get the small list of commands; when I ran `drush @alias`, I get all the commands.
> 2 votes

---
Tags: drush, composer
---


# Question
Title: User may edit their webform submissions, but only while in draft
I don't want users to be able to edit their webform submissions after they have been submitted (in this case it's an application form that needs to be reviewed).

The trouble is, they also need to be able to partially complete and return to it. If they've saved a draft, to continue, they have to access:

```
/webform/{webform}/submissions/{webform_submission}/edit

```

and with 'Update own webform submissions' disallowed (which you can do per webform, remember) that route is blocked.

I can't see anything obvious in the options for drafts *(Settings \> Submissions)* yet I can't be the first person to have needed this…

**Solution I've come up with so far:**

* enabling edit/update access for all users
* adding a RouteSubscriber for `entity.webform.user.submission.edit`
* loading the submission there, using `->isDraft()` to check its status
* denying access for `false`, depending on role/ownership

Any better ideas?

(NB: this doesn't involve anonymous users - they have to be registered and logged in.)

# Answer
> 3 votes
You don't need a custom route, you can hook into the entity access check for the existing entity routes:

*mymodule.module:*

```
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Implements hook_ENTITY_TYPE_access().
 */
function mymodule_webform_submission_access(WebformSubmissionInterface $webform_submission, $op, AccountInterface $account) {
  if ($op == 'edit' && !$webform_submission->isDraft() && in_array('role', $account->getRoles())) {
    return AccessResult::forbidden()->cachePerPermissions();
  }
  return AccessResult::neutral()->cachePerPermissions();
}

```

---
Tags: 8, webforms
---


# Question
Title: How to adjust the login pages with bootstrap?
Components used:

* Bootstrap 3.7.1.
* Drupal 8

I would like to adjust the size of the login screen (and related screens) to a size of 6 grids. So I think adding the following bootstrap class

```
col-md-6 offset-md-3

```

to

```
.block-user-login-block

```

will do the trick. I can add this to the block css.

But bootstrap needs to have .row class just before this. How can I easily solve this?

# Answer
Solved by changing the bootstrap class to

col-md-6 col-md-offset-3
> 0 votes

---
Tags: theming
---


# Question
Title: What versions from the Symfony components are used from core?
Which Symfony version does Drupal use for the Symfony components? Is it a goal to support the latest versions of the components or is this simply not possible?

# Answer
> 12 votes
It is more accurate to say that Drupal 8 uses Symfony components, rather than all of Symfony. If you look at 'core/composer.json' you will see all of the individual components that Drupal uses listed out. The precise versions that get installed are listed in the 'composer.lock' file.

Drupal 8.2.x uses the 2.8 versions of these components.

For Drupal 8.3.x, there are issues open for updating to 3.1 and 3.2, but these are still works in progress. (I think there may be a 3.3 issue, but I can't find it).

The goal is to start tracking the 3.x versions, but the conversion has not been straightforward.

# Answer
> 5 votes
To check this yourself whatever version of Drupal you are using, you can just ask composer:

```
composer info | grep -E '^symfony'

```

Or for an individual package:

```
composer info symfony/yaml

```

# Answer
> 3 votes
As of Drupal 8.4.3 here are the versions of Symfony libraries and other closely related libraries specified in core/composer.json:

```
"php": ">=5.5.9",
"symfony/class-loader": "~3.2.8",
"symfony/console": "~3.2.8",
"symfony/dependency-injection": "~3.2.8",
"symfony/event-dispatcher": "~3.2.8",
"symfony/http-foundation": "~3.2.8",
"symfony/http-kernel": "~3.2.8",
"symfony/routing": "~3.2.8",
"symfony/serializer": "~3.2.8",
"symfony/translation": "~3.2.8",
"symfony/validator": "~3.2.8",
"symfony/process": "~3.2.8",
"symfony/polyfill-iconv": "^1.0",
"symfony/yaml": "~3.2.8",
"twig/twig": "^1.23.1",
"doctrine/common": "^2.5",
"doctrine/annotations": "^1.2",
"symfony-cmf/routing": "^1.4",
"symfony/psr-http-message-bridge": "^1.0",

```

These can generally be updated using `composer update` (full composer info). Symfony 4 came out a few weeks ago and there are also 3.3 versions of libraries that exist. So it seems like Drupal 8 minor releases will lag behind Symfony releases, but not stop moving.

---
Tags: 8
---


title: Rest API pagination

text:
# Question
Title: Rest API pagination
I am using drupal 8.5 and have tried everything people say to get pagination working, but it does not over rest api. I have 2 news articles, and I set the page value to 1 per page. I have tried passing in page as a get parameter but still always returns the first news article.

# Answer
> 2 votes
Ensure that you have the Full Pager enabled on the View. This will enable paging. Right now you’re only telling the view to show one thing.

---
Tags: paging
---


# Question
Title: Multiple shopping cart view in cart page
I want to show `shopping cart view` in different style on mobile view . how can I clone `shopping cart view` to show it on another format like `unformatted list` or what is your approach to show this views on mobile on none table format ?

Thank You

# Answer
Try https://www.drupal.org/project/commerce\_responsive\_ui as a starting point. This module uses different displays (no tables) for the cart and checkout views.
> 0 votes

---
Tags: 7, views, commerce
---


# Question
Title: Add restriction to content on the basis of various User
I am new in drupal, So I want to know how can I restrict my content in content listing according to various users. e.g. I have four contents named A,B,C,D. Now I want Customer1 to see and edit only content A and B. While Customer2 can do the same with C and D only. I've done my research and read about "form\_node\_admin\_content\_alter" but not sure how it works. So kindly provide me an efficient solution for this.

Thank you

# Answer
Creat role and assign role to the different user. Based on role set permissions of view content under people permission page.

If A role user can see A type of content so you can allow permission to view that content type page.
> 0 votes

---
Tags: hooks
---


# Question
Title: Call to undefined function variable_get()
I have an ansible script that transfers a production database to my devel server, then runs a few Drush commands to prepare it (e.g. updating the filesystem settings, clearing the cache).

A more complex task is updating a nested configuration value like the following one.

```
mail_system:
  default-system: SmtpMailSystem
  maillog: MaillogMailSystem

```

Supposedly I ought to be able to do this with `drush ev` (aka php-eval) and `variable_get()` and `variable_set()` as with `drush7 ev '$v = variable_get("file_public_path")'`, but I get this error message.

> Error: Call to undefined function variable\_get() in /usr/local/bin/drush7.4.0/commands/core/core.drush.inc(1122): eval()'d code, line 1

It **does** work correctly when I use the interactive shell.

```
drush7 core-cli
self> variable_get('mail_system');
array:2 [
  "default-system" => "SmtpMailSystem"
  "maillog" => "MaillogMailSystem"
]

```

I can work-around it by reading the content of `$conf` easily enough.

```
drush7 ev 'global $conf; echo $conf["mail_system"]["default-system"];'

```

Writing involves a database query and clearly `variable_set()` is in core.

Why cannot I use `variable_get()` and `variable_set()`?

I am using Drush 7.4.0 and Drupal 7.59.

(I also have Drush 8.1.16 available, but that's much use for this, *Drush 8*'s cget and cset require *Drupal 8*, and *Drush 8* doesn't have *Drush 7*'s vget and vset.)

# Answer
> 1 votes
It seems you are confusing Drush 8 and 9 - Drush 8 has `vget` and `vset`.

Using Drush 8, the following two commands worked:

```
drush vget "mail_system"

drush ev 'print_r(variable_get("mail_system"));'

```

PS! Drush 7 isn't supported and you should use Drush 8 (currently 8.1.17) for Drupal 7.

---
Tags: 7, drush
---


title: Creating a Display Suite Custom Layout

text:
# Question
Title: Creating a Display Suite Custom Layout
I'm using Display Suite for my website and I want to add a couple layouts to Display Suite, to apply to some pages. I have checked out how to add custom layout to Drupal Suite with google, Stack Overflow and Drupal Answers. What I did:

* created a folder "ds\_layouts" in my custom theme folder;
* created a folder for my custom layout "ds-2col-stacked-custom" in "ds\_layouts" folder;
* created two files "ds-2col-stacked-custom.css" :

\>

```
.ds-2col-stacked > .group-fhl {
  float: left; /* LTR */
      width: 70%;
}

.ds-2col-stacked > .group-fhr {
  float: right; /* LTR */
  width: 30%;
}

 .ds-2col-stacked > .group-left {
  float: left; /* LTR */
  width: 50%;
}

[dir="rtl"] .ds-2col-stacked > .group-left {
  float: right;
}

.ds-2col-stacked > .group-right {
  float: right; /* LTR */
  width: 50%;
}

[dir="rtl"] .ds-2col-stacked > .group-right {
  float: left;
}

.ds-2col-stacked > .group-footer {
  clear: both;
}

```

and "ds-2col-stacked-custom.html.twig" :

```
    <{{ outer_wrapper }}{{ attributes.addClass('ds-2col-stacked', 'clearfix') }}>

  {{ title_suffix.contextual_links }}

    <{{ fhl_wrapper }}{{ fhl_attributes.addClass('group-fhl') }}>
    {{ fhl }}
  </{{ fhl_wrapper }}>

  <{{ fhr_wrapper }}{{ fhr_attributes.addClass('group-fhr') }}>
    {{ fhr }}
  </{{ fhr_wrapper }}>

  <{{ header_wrapper }}{{ header_attributes.addClass('group-header') }}>
    {{ header }}
  </{{ header_wrapper }}>

  <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
    {{ left }}
  </{{ left_wrapper }}>

  <{{ right_wrapper }}{{ right_attributes.addClass('group-right') }}>
    {{ right }}
  </{{ right_wrapper }}>

  <{{ footer_wrapper }}{{ footer_attributes.addClass('group-footer') }}>
    {{ footer }}
  </{{ footer_wrapper }}>

</{{ outer_wrapper }}>

```
* in file "Mytheme.layout.yml", I added:

>

```
ds_2col_stacked_custom:
  label: Two column stacked layout custom
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: ds_layouts/ds-2col-stacked-custom/ds-2col-stacked-custom
  library: ds_2col_stacked_custom
  regions:
    fhl:
      label: fhl
    fhr:
      label: fhr
    header:
      label: Header
    left:
      label: Left
    right:
      label: Right
    footer:
          label: Footer

```
* in file "Mytheme.libraries.yml", I added:

>

```
# DS.
ds_2col_stacked_custom:
  version: VERSION
  css:
    theme:
      ds_layouts/ds-2col-stacked-custom/ds-2col-stacked-custom.css: {}

```

In Manage Display for page I see the option for my custom layout, and when I apply it, it's working (html tags and css classes are added to the page), but it does not apply any of my css for my layout. I think there is something wrong with the way I added css file to my custom layout.

# Answer
> 4 votes
You’re calling a library with dashes but it was defined with underscores. Update it to match the name.

You should be calling it via 'mytheme/library-name', so:

`library: mytheme/ds_2col_stacked_custom`

---
Tags: 8, theming, display-suite
---


# Question
Title: js in default/files causes extreme slowdown of website
for the past week my website is plagued with over 4000ms hanging upon entering, more so at sometimes. After using firefox's performance monitor, I pinpointed it to several lines of code in a js file under /sites/default/files/js. Here is a snippet of the js:

```
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e)....

```

It continues on like that for dozens of more lines, and it is impossible for me to fit it all here. I know this is an autogenerated code issue, but do not know where I should start looking.

Can anyone pinpoint me to the correct area to look at? Thanks.
Aaron

# Answer
Drupal aggregates all of the javascript files added by any modules and themes. So that's why its all 1 big file.

You could turn off the JS aggregation by going to "Configuration \> development \> performance" and unticking the JS option.

That will allow you to narrow down the actual script that might be slowing you down. It's almost certainly not something from Drupal core itself and more likely to be something custom youve done in a theme or a module you've enabled
> 1 votes

---
Tags: 7, theming, database, javascript, caching
---


# Question
Title: How to add a block to a region in html.tpl?
I'm using Drupal 7.

I have a custom template html--custom.tpl.php.

I have a custom block that contains the main menu. This block is enabled in the header region of block admin.

Up to this point, everything but the menu block prints.

How can I print the custom block in the header region of the html.tpl file?

# Answer
> 0 votes
You should make a new theme region similarly to how the header section works and add your block through the block admin into your new region. Rather than trying to get a block to come out in any other way

See this for more: https://www.drupal.org/docs/7/theming/assigning-content-to-regions

---
Tags: 7, theming, blocks, navigation
---


# Question
Title: Unable to update header value using hook_views_pre_render?
I have create the header value using Global: Unfiltered text (Global: Unfiltered text) .

BY us hook\_views\_pre\_render i want to update the header value . How can I update the header value .

How to update header text in hook\_views\_pre\_render provide the solution for the header value to update but its not working for me

```
    function mytheme_views_pre_render(ViewExecutable $view) {

      if ($view->id() == 'works') {
//    enter code here
             $my_value='No result found';
             $view->display['page']->handler->handlers['header']
             ['area_1']->options['content'] = $my_values;

        }

      }
    }

```

# Answer
> 1 votes
```
 $view->display['page']->handler->handlers['header']
             ['area_1']->options['content'] = $my_values;

```

please change the value of the area\_1 if anyone want change the header value programmatically .

Just hover the **Global: Unfiltered text (Global: Unfiltered text)** header value and you will get the area\_1 value .

---
Tags: views, 8, hooks
---


# Question
Title: How to disable/enable cache of all views programmatically?
Case: I have over 50 views in my site and for performance improvement all were enabled to cache data during their implementation.

Now I want to disable cache for all views at once for some reason (make it more realtime).

Please help.

# Answer
> 1 votes
You could switch them all off with features and a bit of hacking. Also, as this involves changing lots of things in mass, make sure you back up your work before doing it and make sure you test it out on a dev server first.

With features, you can create a feature containing just your views. You can then download this feature, which will give you something that looks a lot like a module file.

One of the files in this module will be a file called your\_feature.views\_default.inc, which will contain a bunch of code that will look ALOT like a view export script (because that's exactly what it is.)

If you look at the lines of code, they each represent a configuration in your views, you should be have a bunch of lines that looks like:

```
  $handler->display->display_options['cache']['type'] = 'time';
  $handler->display->display_options['cache']['results_lifespan'] = '3600';
  $handler->display->display_options['cache']['results_lifespan_custom'] = '0';
  $handler->display->display_options['cache']['output_lifespan'] = '3600';
  $handler->display->display_options['cache']['output_lifespan_custom'] = '0';

```

depending how you set your caching. Regardless, if you want to shut off caching on all your views, all of those lines need to become:

```
$handler->display->display_options['cache']['type'] = 'none';

```

One your edits are done, save the file and upload the feature module back up to your site in your sites/all/modules folder.

Once it's uploaded, head back to your site, and head to the features admin at admin/structure/features, you should see your feature hanging out there, and it's state should be "Overridden." Click on "Overridden," and you see the overview of your feature, along with a handy-dandy button on the lower right hand of the screen that says "revert components." Click the checkbox next to the views list (to tell features what you want reverted), and then click on the revert components to revert the views to what is stored in code.

Now, there is a down side to using this method. The way features works is it actually takes your view and stores it in code, not the DB. So removing your feature would actually remove you views as well. This will be true until you edit your view, in which case it would go back in the database (just that one view though, not all of them).

# Answer
> 1 votes
If you are looking for a permanent solution. I would suggest doing it in an update hook. Create an array of the views or views/displays you want to affect, and then do something like the following

```
<?php
$views = array(
  'view1' => array(),
  'view1' => array('master', 'display_1'),
);

foreach ($views as $view_name => $displays) {
  $view = views_get_view($view_name);
  foreach($view->display as &$display) {
    if (empty($displays) || isset($view->display[$display]) {
      $display->display_options['cache']['type'] = 'none';
    }
  }
  $view->save();
}

```

If you are looking for a temporary solution (as in for development/testing purposes), consider setting `$conf['views_skip_cache'] = TRUE;` in your settings.php or local.settings.php file. This will turn off caching completely for Views. See views\_cache\_get().

# Answer
> 0 votes
I don't think it's possible as Views are saved in the database as a PHP array.

However, there are 2 cache tables `cache_views` and `cache_views_data` which contain the various cached items, if you emptied the contents of these tables it would have the same effect as turning off caching apart from you'd need to empty these tables on every request.

# Answer
> 0 votes
Think you're looking for this module https://www.drupal.org/project/views\_cache\_bully

It's listed in the speaker notes of slide 26 from the DIY Drupal 7 performance presentation

Looking at how the module works you'd want to implement hook\_views\_pre\_view(). Here's where the magic happens in the module

```
/**
 * Implements hook_views_pre_view().
 */
function views_cache_bully_views_pre_build(&$view) {
  // Run if this view does not have a cache.
  if ($view->display_handler->get_plugin('cache')->plugin_name == 'none') {
    // Make views_cache_bully_view_is_exempt() available.
    module_load_include('inc', 'views_cache_bully');
    if (!views_cache_bully_view_is_exempt($view)) {
      // Enable the view cache.
      $view->display_handler->override_option('cache', array(
        'type' => 'time',
        'results_lifespan' => variable_get('views_cache_bully_results_lifespan', 3600),
        'output_lifespan' => variable_get('views_cache_bully_output_lifespan', 3600),
      ));
    }
  }
}

```

So in your case I would change it to this

```
/**
 * Implements hook_views_pre_view().
 */
function mymodule_views_pre_build(&$view) {
  // Run if this variable is enabled.
  if (variable_get('mymodule_no_views_cache', TRUE)) {
    // Disable the view cache.
    $view->display_handler->override_option('cache', array(
      'type' => 'none',
    ));
  }
}

```

---
Tags: 7, views, caching, performance
---


title: Meta description to views

text:
# Question
Title: Meta description to views
Is there a way to add meta description to views in Drupal 8?

# Answer
> 0 votes
Use the "Metatag Views" sub module that comes with Metatag module. Link https://www.drupal.org/project/metatag

---
Tags: views, 8, meta-tags
---


# Question
Title: Views filter handler for user authored from Custom Form
How can I make a custom views filter handler to filter a list of users which the current user created?

For example: The user adds members to the site a view will show only the members that the user added.

In views, there is a relationship for sorting content based on the current user "Content authored" which is similar.

# Answer
> 0 votes
As pointed out by 4k4 there is no user authored data in the tables, so I thought I would add what I did to output a view of users the author created.

For me, I needed to do some of this in my custom module you might be able to do this in the configuration if your use case is easier.

```
 1. Create user reference field in /admin/config/people/accounts/fields
 2. Install https://www.drupal.org/project/cer/
 3. Add a corresponding reference in /admin/config/content/cer for your field and the user entity.
 4. Create a relationship for your view from the user field.
 5. Output your view as a block list on your user account page.

```

Now when a user creates a reference the view will shorten to a list of your users.

I took this a step further and created a custom form module to register a user and in code populate the user entity reference field with a form submit for the current user's id. This bit took me a while to work out so hope this helps someone else. :)

```
$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$user->set("field_your_field_name",$uid);

```

---
Tags: views, 8, users, forms
---


title: Custom migration: image fields to media

text:
# Question
Title: Custom migration: image fields to media
When migrating existing Drupal 7 fields, most things work.

I need to convert images (using image upload) in Drupal 7 site to reusable media.

Any help?

# Answer
> 1 votes
For the D7 image files to D8 Media core entities custom update I recommend you examine this blog post for ideas: https://chromatichq.com/blog/migrating-drupal-file-fields-media-entities-without-migrate-module

### Example Code Snippets from the blogpost:

```
/**
 * Create media entities from existing file fields.
 */
function example_update_8401() {
  // Load all of the article and page nodes.
  $nodes = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(['type' => ['article', 'page']]);
  foreach ($nodes as $node) {
    // Verify that the file field has a value.
    if (!empty($node->field_file_image->entity)) {
      // Create the new media entity and assign it to the new field.
      $node->field_media_image->entity = example_create_media_image_entity(
        $node->field_file_image->entity,
        $node->field_file_image->alt
      );
      $node->save();
      \Drupal::logger('chromatic_image')->notice(
        sprintf('Updated image for node "%s".', $node->getTitle())
      );
    }
  }
}

use Drupal\media_entity\Entity\Media;

/**
 * Creates a media image entity from a file entity.
 *
 * @param \Drupal\file\FileInterface $file
 *   The existing file object.
 * @param string $alt
 *   The image alt text.
 *
 * @return \Drupal\media_entity\Entity\Media
 *   The media entity.
 */
function example_create_media_image_entity(FileInterface $file, $alt = NULL) {
  $media_entity = Media::create([
    'bundle' => 'image',
    'uid' => '1',
    'name' => $file->alt,
    'status' => Media::PUBLISHED,
    'field_media_image' => [
      'target_id' => $file->id(),
      'alt' => $alt,
    ],
  ]);
  $media_entity->save();
  return $media_entity;
}

```

Your mileage may vary on the above approach.

---
Tags: 8, migrations, media
---


# Question
Title: Unnecessary showing admin content in main theme
In one of my sites I have the bug: when I submit some admin forms, for example after editing a view, or create a taxonomy vocabulary the result page appears in the main site theme instead of admin theme. If I simply visit these admin pages, for example /admin/structure/taxonomy they appears in admin theme as designed. Also these admin pages is showing in admin theme if i refresh them after form submitting.

So the front-end theme appears only after form submitting on only some cases. For example taxonomy vocabulary creation has this bug, but taxonomy term creation does not have it.

No themekey or some similar modules installed.

What can be a cause?

# Answer
> 1 votes
Finally I found that Backup and Migrate module caused this bug https://www.drupal.org/project/backup\_migrate/issues/1379152

# Answer
> 1 votes
If you use customError module, make sure you your theme dropdown setting is set to "Default theme" in yoursite.com/admin/config/system/customerror.

---
Tags: 7, views, theming, taxonomy-terms
---


# Question
Title: AJAX Views arguments: how to specify quantity of results and what are other options that can be used?
From this great answer I have a working jQuery implementation of a simple call to an existing view using AJAX. Which is brilliant, but I want to specify the number of results differently to as is setup in the existing view, and I want to know what other options I can use under `view_args`.

I can't find documentation/a full example of what's available and how to use it. Is there any?

```
$.ajax({
    url: url,
    type: 'post',
    data: {
        view_display_id: v_display,
        view_name: v_name,
        //   view_args: {}, // your views arguments
        view_args: v_args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
            return response[1].data; // do something with the view
        }
    }
});

```

I inspected the HTML of the Views admin page and saw the pager was encapsulated from the other arguments, and tried this but it carried on supplying 6 items (which is odd because the view is saved to display 10):

```
var data = {
    'view_name':'ajax_test',
    'view_display_id':'block',
    'pager_options': {
        'items_per_page':'1',
    }
};
$.ajax({
  url: '/views/ajax',
  type: 'post',
  data: data,
  //pager_options: {items_per_page:1},
  dataType: 'json',
  success: function (response) {
    if (response[1] !== undefined) {
      document.write(response[1].data); // do something with the view
    }
  }
});

```

# Answer
Previous experience tells me with Drupal 7 that if I don't find an answer after a day of research then people probably haven't approached it like this and I'm unlikely to find much assistance, so I'm doing the custom menu item approach instead, as people have suggested in the discussions I've read.

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items['ajax/%'] = array(
        'page callback' => 'get_view_with_args_get_ajax',
        'page arguments' => array(1),
        'type' => MENU_CALLBACK,
        'delivery callback' => 'ajax_deliver',
        'access arguments' => array('access content'),
    );

    [....etc....]

function get_view_with_args_get_ajax($args) {
    views_get_view($name);
    return 'Args: ' . $args;
}

```
> 0 votes

---
Tags: 7, views, ajax
---


# Question
Title: How to delete field programmitically using hook_update?
We have a situation where in different environments we have to manually delete fields. Rather than manually doing that, we want to programmatically deploy the changes. The idea that is being is discussed is to use a custom module which calls the hook\_field\_delete\_instance() hook.

The issue we are having is how to best pass in the content type machine name and the machine name for a single content type. We are understanding that when we reused the field on a separate content type, we are essentially creating an alias on the current content type that points to the original content type holding the field name.

Using the situation below, what is the best way to delete the two fields on the on the basic page only using the hook\_field\_delete\_instance() on a custom module?

Situation:

We have two content types: article and basic page. We created several fields on the article content type that we ended up reusing on the basic page.

Article:

1. field\_art\_original\_publish\_date
2. field\_art\_country\_tag
3. field\_art\_image

Basic Page:

1. field\_art\_image (reused from article content type)
2. field\_art\_country\_tag (reused from article content type)

---

Update:

So now that i am thinking further on this, i would like 1 hook update for 1 field deletion so that if a hook update fails then i know which fields need attention.

Here is what i have come up with using what @Clive has suggested.

```
function mymodule_update_7001(&$sandox) {
     mymodule_delete_field('field_art_image', 'page' );
}

function mymodule_update_7002(&$sandox) {
    mymodule_delete_field('field_art_country_tag', 'page');
}

function mymodule_delete_field($field_mn, $ct_mn) {
    $entity_type = "node";

    $field_instance = field_info_instances($entity_type, $field_mn, $ct_mn);
    field_delete_instance($field_instance);

    //setting the batch size to a large number resolves my prior issues
    $batch_size = 20000;
    field_purge_batch($batch_size);
}

```

# Answer
> We are understanding that when we reused the field on a separate content type, we are essentially creating an alias on the current content type that points to the original content type holding the field name.

Not quite - each instance exists in its own right, unaffected by any other instance of the same field on another entity type/bundle. Removing it from one bundle (content type) won't touch it on another bundle, regardless of which one it was originally attached to.

You won't need `hook_field_delete_instance()` for this, just a combination of `field_info_instance()` and `field_delete_instance()` in an update hook. Something like this:

```
/**
 * Remove old fields from the Basic Page content type.
 */
function MYMODULE_update_7100() {
  $field_art_image = field_info_instance('node', 'field_art_image', 'page');
  field_delete_instance($field_art_image);

  $field_art_country_tag = field_info_instance('node', 'field_art_country_tag', 'page');
  field_delete_instance($field_art_country_tag);

  return 'Fields deleted, data will be cleared up on cron.';
}

```
> 4 votes

# Answer
I found this code for drupal 8 that worked very good for me here https://gist.github.com/jacerider/78b926acbb201666a0fc3a1f8102cb44

**This empty the field, them remove field from bundle**

I just added in a hook\_update\_N() \[https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook\_update\_N/8.2.x\]\[1\]

```
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

$bundles = ['user'];

$fields['user_picture'] = [
  'entity_type' => 'user',
];

foreach ($bundles as $bundle) {
  foreach ($fields as $field_name => $config) {
    $field = FieldConfig::loadByName($config['entity_type'], $bundle, $field_name);
    if (!empty($field)) {
      $field->delete();
    }
  }
}

foreach ($fields as $field_name => $config) {
  $field_storage = FieldStorageConfig::loadByName($config['entity_type'], $field_name);
  if (!empty($field_storage)) {
    $field_storage->delete();
  }
}

```

\[1\]: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook\_update\_N/8.2.x "hook\_update\_N"**strong text**
> 0 votes

---
Tags: nodes, entities, hooks
---


# Question
Title: FAPI text_format field value not being passed to submit handler
I created a form that I wanted to be reusable. So I created to form below to imported into a add form and a edit form. Please be aware I do have the validateForm, and submitForm function in my code.

```
class PaneConfigurationForm extends ConfigFormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'admin_pane_settings';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, $element = null) {

       $form['description'] = array(
          '#type' => 'text_format',
          '#title' => 'description',
          '#default_value' => '<p>The quick brown fox jumped over the lazy dog.</p>',
          '#value' => '<p>The quick brown fox jumped over the lazy dog.</p>',
          '#format' => 'full_html',
       );

       return parent::buildForm($form, $form_state);
    }
}

```

So in my AddPane form I use the \Drupal::formBuilder()-\>getForm() function to get the form and apply it to my parent form. For some reason when I submit the form the value is not passed to the submit handler, only to form format.

```
class AddPaneForm extends Formbase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'add_admin_pane';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state, $element = null) {

          $form = \Drupal::formBuilder()->getForm('Drupal\_module_\Form\PaneConfigurationForm');

          $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
          );
    }

    public function submitForm(array &$form, FormStateInterface $form_state)
    {
          $form_state->getValue('description')
    }
}

```

What can I do to allow the format and value to be passed to the submit handler, not just the text\_format field's format.

# Answer
> 0 votes
Just remove the `#value`:

```
$form['description'] = array(
  '#type' => 'text_format',
  '#title' => 'description',
  '#default_value' => '<p>The quick brown fox jumped over the lazy dog.</p>',
  '#format' => 'full_html',
);

```

`#value` permeates all the way through a form build/validation/submission, and doesn't get replaced with user input.

`#default_value` will cover the initial value when the form loads.

---
Tags: 8, forms
---


# Question
Title: Can filter by file upload description but not sort by it?
I have a simple page/content type where a user can upload files and give them a description.

I then hide that field on the page and display the files using a view in a block.

I can get it to show the files no problem and display them with a custom output, however I just can't seem to be able to sort by the text description, rather than the filename - the field just isn't there to sort by.

The description field does however show up in Filter Criteria where I've exposed it to allow users to search for files using the file description rather than the file name.

I'm not really sure how/where to look as I've tried all sorts of combos of the fields I have and none of them seem to be what I need.

Any help appreciated!

# Answer
> 0 votes
to sort by a field you should have that field in the result of view, in your example you can sort by the field "Resource Upload" because it figure in FIELDS section.. so to sort by "Description" field you have to add it first to FIELDS section and you can hide it later.

---
Tags: views
---


# Question
Title: How to create a view that outputs an HTML list?
I want to create a menu like this so I create a new view and I make some change in format (html list) and fields but I can not do it like the original one !

# Answer
It looks like you need to group the rows by your "File Usage: Entity Label (Assurance particuliers)" field.

To do that go to the "HTML List" settings and select that field in the dropdown of the "Grouping field Nr.1" setting.

You will then want to hide the field from display, and you do that in the field's own settings, "Exclude from display".

You can also add "File Usage: Entity Label (Assurance entreprises)" and "File Usage: Entity Label (Assurance de personnes)" fields and set them as Grouping fields Nr.2 and Nr.3 in the HTML List settings to give you the second and third columns in your list. Don't forget to hide these also!

I hope this helps.
> 0 votes

---
Tags: views, 8, theming
---


# Question
Title: RULES : How to redirect user to a page after login unless they're using the one-time-login-url?
I created a rule to redirect users to the front page after they login. It works fine

The problem is when a user uses the link received on his email to choose a new password, or after clicking on the link to validate their signup, they're also forced redirected to the front page instead of heading to their user page to choose a password (in the case of a forgotten password) or finish their profile setup (after clicking on the link to validate their registration)

Any ideas on how to fix this ?

# Answer
> 0 votes
**1st method:**

I believe there is a module called **Login toboggan** which will allow you to do exactly what you want.

**From the module page:**

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> Allow users to login using either their username OR their e-mail address.
>
> Allow users to login immediately.
>
> Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
>
> The other brings the user to a separate page, but returns the user to their original page upon login.
>
> Optionally redirect the user to a specific page when using the 'immediate login' feature.
>
> Optionally redirect the user to a specific page upon validation of their e-mail address.
>
> Optionally display a user message indicating a successful login. ...

**2nd method:** I believe when someone **request a password**, the format of the link will be similar to this one:

https://www.drupal.org/user/reset/...

If so, you can create a rule to redirect the user upon login to a specific page. However, add **one condition** which will be:

**Data comparison**: the link should not contain the word **reset**

Hope it helps,

---
Tags: 7, rules
---


# Question
Title: How do I Send a single mail with Rules and VBO?
I have a view of nodes that I edit with VBO. I filter this nodes by author. When I edit this nodes I send a mail to author with a rule but I have a problem when I edit more than one nodes with VBO. In fact Rule sends as many email as they are the nodes.

How I can do to send only a single email to the author that I have filtered in the views?

I use Drupal 7.

UPDATE: I've added the rule that I'm using but not works

```
{ "rules_send_mail_to_owner" : {
"LABEL" : "Send Mail to Owner",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_i18n" ],
"ON" : { "node_update--prenotazione" : { "bundle" : "prenotazione" } },
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "list\u003Cuser\u003E" },
      "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
    }
  },
  { "list_add" : {
      "list" : [ "variable-added" ],
      "item" : [ "node:field-proprietario" ],
      "unique" : "1"
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "variable-added" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "giupenni78@gmail.com",
            "subject" : "Prova notifica LCS",
            "message" : "Questa \u00e8 una prova\r\n[node:field-proprietario]\t",
            "from" : "info@lowcostsicilia.it",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]
}
}

```

# Answer
Here is a blueprint to do what you're asking about:

* Create a new variable, which you define as a "list of users" (so that you can use this list later on to "*loop through this list*").
* Replace the "send an eMail" (within your existing Rule) by an action to "**Add an item to a list**" (using the list you created via that new variable). When doing so, you make sure to set "ENFORCE UNIQUENESS" to `true`, so that you "*only add the item to the list if it is not yet contained*" (see where I'm going?).
* In the end, the value of the new variable will contain a list of *unique* users. So just add another Rules loop (at the end?), to iterate over each of the users in that list. And guess what you can then do in this additional Rules loop ... indeed: send an email to each of those users. And since each user is only contained 1 time in that list, they will only receive 1 eMail.

***Easy, no***?
> 2 votes

---
Tags: 7, rules, views
---


# Question
Title: Charts Module not working for one site - No messages in the log
Using Drupal 8.5.4 and I am referencing the url as https://www.ostraining.com/blog/drupal/create-charts-with-views/

as a guide. I have built charts with an empty scratch sites without issues. However, when I try to integrate it into an existing site I get nothing. I have checked the sites messages with but nothing is there. I am not really sure where to look to troubleshoot the issue.

I just want a basic chart, nothing fancy out of the gate.

# Answer
As the Charts maintainer, I am happy to help. My first recommendation is to update to the latest version of Charts (beta1). This has improved handling of fields within Views and a new default in place for Charts Attachments that prevents some issues that users have faced previously. The next thing, and what I think is most likely, is that the libraries did not install properly. Please try disaggregating your JS (from the Admin \> Config \> Development \> Performance page) and then on the page where the chart should be displaying, try inspecting the code and looking for the library's .js file (e.g. highcharts.js). If you're using Chrome, the console tab may tell you something about what is happening.

This also seems silly to say, but be sure your View has results, that it has a field for a title and a field for data, and that those are set in the format settings. This should help for most issues you would experience, but if you are still having trouble please add more information to this post so that your issue can be better diagnosed. Good luck!
> 1 votes

---
Tags: 8
---


# Question
Title: Entity queue JSONAPI pagination & How to add JSON API in views?
I'm using below modules

https://www.drupal.org/project/entityqueue & JSON API

Through entity queue. I have added 5 Articles.

Now I would like to apply pagination on that.

We are accessing via

`http://domain.com/jsonapi/my-5-articles?include=items`

I tried to add `include=items&items[paging]=1`. but seems not working

I need to add `limit` & `offset`

If we do same in

`http://domain.com/jsonapi/node/article?page[limit]=1`

then we are getting

```
"links": {
"self": "http://domain.com/jsonapi/node/article?page%5Blimit%5D=1",
"next": "http://domain.com/jsonapi/node/article?page%5Boffset%5D=1&page%5Blimit%5D=1",
"last": "http://domain.com/jsonapi/node/article?page%5Boffset%5D=31&page%5Blimit%5D=1"
},

```

We are not able to get same in `entityqueue`.

How to add JSON API in views?

# Answer
Is sounds like you're assuming functionality that may-or-may-not be there.

Assuming `/jsonapi/my-5-articles` is an alias for `/jsonapi/entity_subqueue/$MY_QUEUE_MACHINE_NAME?include=items`, `items[paging]` isn't a query param for pagination, only `page` is (with `[]` options for specifying page size & offsets).

It sounds like what you want, in terms of the JSON API spec, is a paginated **compound document** (i.e. the `included` property that has all your queue nodes for the `items` relationship). Per the JSON API spec:

> A server MAY choose to limit the number of resources returned in a response to a subset (“page”) of the whole set available.
>
> A server MAY provide links to traverse a paginated data set (“pagination links”).
>
> Pagination links MUST appear in the links object that corresponds to a collection. To paginate the primary data, supply pagination links in the top-level links object. To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

It's optional for the JSON API module to supply pagination links. If it does supply them, it will be in the `links` document property for the resource you're requesting.

Since you're wanting pagination for included resources, the spec says:

> To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

I'm assuming "corresponding links object" is different from "top-level links" and they're referring to `links` property for objects within the `included` array.

From a quick look over the JSON API docs/code it doesn't appear to support this functionality. That may or may not be the case, you'll need to see if it does. You should check the project's issue queue.

The specs' flexibility on this scenario means the authors may not have put the functionality in there. If that's the case, you'll need to figure out a workaround or implement your own solution here.
> 1 votes

---
Tags: 8, entities
---


title: How do I alter prices?

text:
# Question
Title: How do I alter prices?
This is a follow up to Ubercart alter product price when product added to cart.

I have an attribute called "Billing Term". It has options: 6 months, 12 months and 24 months. If 6 months is selected, 0% discount must be applied. 6 months, 5% discount must be applied. and 24 months, 10% discount must be applied.

I set up the attributes to make no change to the price, because I can't find a way to make attributes adjust a price by percentage.

The best solution to my problem would be to find a way to specify attribute discounts in %. But I couldn't find a way to do that. If you know of a way, please do tell, as that is for sure better than my other options below.

So, with all attribute adjustments to be 0, I figured I could something similar to what was done here (but this post is for Drupal 7). So I tried this:

```
function comply_advantage_uc_cart_alter(&$items)
{
  print '<pre>'; print_r($items); die(); <--- this makes apache run out of memory
  print '<pre>'; print_r(arrray_key($items)); die(); <--- this prints out "2", and then "3" and then "5" etc.
  $items[45]->price = 29393; <--- this doesnt adjust the price

```

}

I was hoping to do something like this:

```
$items[5]->price = $items[5]->price * 0.95; // to apply 5% discount

```

How can I accomplish this?

I found out that `$items[5]` type is *CartItem*.

# Answer
> 0 votes
Figured it out:

```
function comply_advantage_uc_cart_alter(&$items)
{
    $item->price->setValue($item->price->value * 0.95);
}

```

Hope it helps someone!

\** IMPORTANT \**

It looks like if you use

```
$item->price->setValue($item->price->value * 0.95);

```

Yo might end up altering the price several times. So I had to actual recalculate the price completely, without using $item-\>price-\>value, or it would deduct 5% multiple times.

---
Tags: 8, ubercart
---


# Question
Title: How can I get the Contact Form "Manage Display" Settings programmatically?
I am trying to use `hook_mail_alter` to create a custom contact mail.

I want to get the display setting of the contact form.

(example path: http://mysite/admin/structure/contact/manage/my\_contact\_form/display/mail)

The things I want to know are:

* Field Label
* If its disabled or not
* Field order
* Field ID

How can I get this information in the PHP script?

EDIT:

I was able to get most of the information I wanted. but I couldn't get the field weight to display in the right order. I have a display mode called 'mail' and I want to get the weight of each field in this mode.

for now the code looks like this:

```
/**
 * Implements hook_mail_alter().
 */
function contact_plus_mail_alter(&$message) {
    if (isset($message['id']) && $message['id'] == 'contact_page_mail') {

        $siteName = \Drupal::config('system.site')->get('name');
        $siteMail = \Drupal::config('system.site')->get('mail');
        /** @var \Drupal\contact\Entity\Message $contactMessage */
        $contactMessage = $message['params']['contact_message'];
        $entityType = $contactMessage->getEntityType()->id();
        $bundle = $contactMessage->bundle();

        $contactForm = $contactMessage->getContactForm();
        $form_title = $contactForm->label();
        $recipients = implode(',', $contactForm->getRecipients());
        /** @var \Drupal\Core\Field\FieldItemListInterface[] $fields */
        $fields = $contactMessage->getFields();
        $data = [
            'title' => $form_title,
            'fields' => [],
        ];
        foreach ($fields as $key => $field) {
            $fieldDefinition = $field->getFieldDefinition();
            $data['fields'][] = [
                'label' => $fieldDefinition->getLabel(),
                'info' => $field->getValue(),
                'display_options' => $fieldDefinition->getDisplayOptions(),
                'weight' => '', // I want to get the field weight for the 'mail' display mode.
            ];
        }
        // TODO: order the data by weight

        // ... send the email
    }
}

```

# Answer
I was able to retrieve the order of the 'mail' display. The secret was in the `->getComponets()` function in this part:

```
$display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entityType . '.' . $bundle . '.' . $displayMode);
$displayFields = $display->getComponents();

```

the final code looks like this:

```
/**
 * Implements hook_mail_alter().
 */
function contact_plus_mail_alter(&$message) {
    if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
        $message['send'] = false;

        $siteName = \Drupal::config('system.site')->get('name');
        $siteMail = \Drupal::config('system.site')->get('mail');

        /** @var \Drupal\contact\Entity\Message $contactMessage */
        $contactMessage = $message['params']['contact_message'];
        $entityType = $contactMessage->getEntityType()->id();
        $bundle = $contactMessage->bundle();
        $contactForm = $contactMessage->getContactForm();
        $form_title = $contactForm->label();
        $recipients = implode(',', $contactForm->getRecipients());
        // Data for the email
        $data = [
            'title' => $form_title,
            'today' => (new \DateTime('now', new \DateTimeZone('UTC')))->format('m/d/Y'),
            'fields' => [],
        ];
        // get the 'mail' display mode if defined
        $viewModes = \Drupal::service('entity_display.repository')
            ->getViewModeOptionsByBundle(
                $entityType, $bundle
            );
        $displayMode = array_key_exists('mail', $viewModes) ? 'mail' : 'default';

        // get display field settings (weight, id, etc...)
        /** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $display */
        $display = \Drupal::entityTypeManager()
            ->getStorage('entity_view_display')
            ->load($entityType . '.' . $bundle . '.' . $displayMode);
        $displayFields = $display->getComponents();

        // put the fields info in the email data
        foreach ($displayFields as $key => $fieldConfig) {
            $field = $contactMessage->get($key);
            $fieldDefinition = $field->getFieldDefinition();
            $data['fields'][$key] = [
                'label' => $fieldDefinition->getLabel(),
                'info' => $field->getValue(),
                'display_options' => $fieldDefinition->getDisplayOptions(),
                'weight' => $fieldConfig['weight'],
            ];
        }

        // order by weight
        function compare_weight($a, $b) {
            return strnatcmp($a['weight'], $b['weight']);
        }
        uasort($data['fields'], 'compare_weight');

        // send the email for the responsible
        $emailSender = new EmailSender($siteName . '<' . $siteMail . '>', $recipients, $form_title, 'my_theme', $data);
        $emailSender->createAndSendEmail();

        // send a copy to the person who filed the form
        if (isset($data['fields']['field_email'])) {
            $email = $data['fields']['field_email']['info'][0]['value'];
            $emailSender->to = $email;
        }
        $emailSender->createAndSendEmail();
    }
}

```

Hope it helps someone.
> 0 votes

---
Tags: 8, forms, emails
---


# Question
Title: How do I update the unit price of an order item on Add to Cart in Commerce 2.x?
I added an event subscriber for add to cart event. There I defined a function to react on add to cart event. Everything works fine as my eventsubscriber is being called. I want to update the unit price of product which is being added to cart. Below is the code I used but it is not working. Price of the product is not updating to the price I am setting.

```
public function updateProductPrice(CartEntityAddEvent $event) {
    $unit_price = new Price('15.00', 'EUR');
    $event->getOrderItem()->setUnitPrice($unit_price,TRUE);
  }

```

I have tried with both overide TRUE and FALSE but nothing works.

# Answer
I managed to update the price by updating the order item of order rather than the order item in event.

```
$items = $event->getOrder()->getItems();
foreach ($items as $key => $item) {
    $currencyCode = $item->getUnitPrice()->getCurrencyCode();
    $unit_price = new Price('20.00', $currencyCode);
    $item->setUnitPrice($unit_price,TRUE);
    $item->save();
}

```
> 1 votes

# Answer
The problem with this approach is the price will be recalculated on the next order item refresh. You can't just depend on altering this item at the Add to Cart. You'll need a price resolver or else some other tie into the order refresh process.
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: How can I hide the authoring information?
Normally I would just click manage display and disable authoring information from showing, but with layout builder enabled, I don't have this option. I only have the Manage Layout option, which doesn't contain any way to disable the authoring information.

# Answer
> 1 votes
Try to disable this information in content type settings.

---
Tags: 8, layout-builder
---


title: adding jquery at the very bottom

text:
# Question
Title: adding jquery at the very bottom
I know how to add or attache a jquery/javascript file on the specific page.

My problem is that I'm trying to add jQuery file (included in theme) at the end of every thing in the body tag so any other file or module would not override it but can't figure out yet.

Is there any way to do that?

**Example:**

# Answer
You need to set a dependancy on your library definition. e.g. if you want your custom.js after geofield then in the library you define custom.js you need to set a dependancy e.g.:

```
mylibrary:
version: VERSION
js:
  js/custom.js: {weight: 0}
dependencies:
  - geofield_gmap/geofield_gmap

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Drupal statistics does not count visits when I see the node from a custom panel
I have a web site where each node has three diferents designs (i do it through panels and arguments) and i use the statistics module, that way i can see how many visits has the node.

But the statistics module jus count the visits when they visit the main design. I can explain with a example:

* website .com/node/01 \<---when a user visit this url, a visit is counted
* website .com/node/01/mobile \<----- here is not counted the visit
* website .com/node/01/lightbox \<----here is not counted the visit

This was built for panels and arguments... so, is there anyway to put a php code in two panels that visitors don't have to start to count?

Best,

# Answer
It's because panels doesn't invoke node\_view(). Please try following code:

```
function MODULE_ctools_render_alter(&$info, &$page, &$context) {
  if ($context['handler']->task == 'node_view') {
    $key = $context['handler']->conf['context'];
    $node = $context['contexts'][$key]->data;
    statistics_node_view($node, 'full')
  }
}

```
> 4 votes

# Answer
You can do it by using theme template preprocess function ie:

```
function template_preprocess_page(&$vars) {

 $statistics = '(function ($) {
  $(document).ready(function() {
    $.ajax({
      type: "POST",
      cache: false,
      url: "'.url(drupal_get_path('module', 'statistics') . '/statistics.php').'",
      data: "nid='.arg(1).'"
    });
  });
})(jQuery);';
   drupal_add_js($statistics, array('type' => 'inline', 'scope' => 'footer'));

}

```
> 2 votes

# Answer
I took the db\_merge() code from https://api.drupal.org/api/drupal/modules%21statistics%21statistics.module/function/statistics\_exit/7.x

That is

```
db_merge('node_counter')->key(array('nid' => arg(1)))->fields(array(
        'daycount'   => 1,
        'totalcount' => 1,
        'timestamp'  => REQUEST_TIME,
      ))->expression('daycount', 'daycount + 1')->expression('totalcount',     'totalcount + 1')->execute();

```

... inside my own \_ctools\_render\_alter() hook function. Hence, incrementing it manually.
> 0 votes

# Answer
Solution for Drupal 8.

```
function MODULE_panels_build_alter(array &$build, $panels_display) {
        if ($nid = \Drupal::routeMatch()->getRawParameter('node')) {
                $build['#attached']['library'][] = 'statistics/drupal.statistics';
                $settings = ['data' => ['nid' => $nid], 'url' => \Drupal::request()->getBasePath() . '/' . drupal_get_path('module', 'statistics') . '/statistics.php'];
                $build['#attached']['drupalSettings']['statistics'] = $settings;
        }
}

```
> 0 votes

---
Tags: panels, nodes
---


title: Underscore is added to links in view

text:
# Question
Title: Underscore is added to links in view
I'm writing a workaround to fix the breaking changes introduced to our XML feed when we updated from Drupal 8.4 to 8.5. Since PATH is no longer available but has been replaced with LINK, I've had to craft the `Rewrite Results` to be `/news/{{ view_node }}`, which displays a properly formatted URL in the preview:

```
<link>http://sitename.com/news/article-title</link>

```

However, in the actual XML feed, it comes out like this:

```
<link>http://sitename.com/news/article-title_</link>

```

arbitrarily adding an underscore and breaking the URL. Is there a way to make this not happen?

# Answer
After much work I came up with a workaround. My first thought was to add a Twig filter to `views-view-row-rss.html.twig` like so `<link>{{ link | replace('_', '') }}</link>` but the underscore was still being displayed, which told me that either 1. the Twig filter wasn't working or 2. the underscore was being applied later in the render process.

The Twig template's documenation made reference to a `template_preprocess_views_view_row_rss()` hook I found implemented in `/core/modules/views/views.theme.inc` so I added the following hook to my `custom.theme` PHP file:

```
function ncei_preprocess_views_view_row_rss(&$variables) {
  $item = $variables['row'];
   $variables['title'] = $item->title;

   //$variables['link'] = $item->link;
   $variables['link'] = str_replace("_", "", $item->link);

   if (isset($item->description) && is_array($item->description)) {
     $variables['description'] = (string) \Drupal::service('renderer')-
       >render($item->description);
   }

 $variables['item_elements'] = [];
 foreach ($item->elements as $element) {
   if (isset($element['attributes']) && is_array($element['attributes'])) {
     $element['attributes'] = new Attribute($element['attributes']);
   }
   $variables['item_elements'][] = $element;
 }
}

```

I commented out the original line above for reference, but I'm setting the `link` variable to the item's link, stripped of all undertscores. This isn't the best solution, and will break if the link actually contains underscores, but it worked as a temporary workaround in the meantime.
> 1 votes

---
Tags: views, feeds
---


# Question
Title: alterations in tpl file work, but not dpm();, dsm(); or drupal_set_message();
This question here at DA has a popular suggestion to check `page.tpl.php` to see if it says `print $messages;`. I verified this and this is the case.

I cleared caches many times, btw after which there actually is a drupal message saying the caches are cleared.

I made sure the `dpm()`, `dsm()` or `drupal_set_message()` functions are nicely outside any conditional statement or php logic whatsoever. I also put all these functions on different places in the `tpl` file. Still no result.

The same theme also has another tpl file that I used before and had some commented dpm(); functions that I uncommented but these didn't work anymore either.

Devel module is **enabled** and I am logged in as **admin** the whole time.

# Answer
> 1 votes
You have access to the entire Drupal bootstrap within template files. Template files are loading at the very end of a page request post bootstrap. If dpm() or dpr() is not working it is most likely because you are viewing the site as an anonymous user. The devel module by default does not allow access to it's functionality for anonymous users. Try logging in as admin and you should see the output of your devel module function calls.

As an F.Y.I. template files are not the typical place for a dpm() as you either need to know the variable you are after or put a get\_defined\_vars() calls inside it which can be quite heavy depending on where you are in stack. It is more common to use dpm()'s in template hooks such as:

Then you can see all the variables that are available to your template files.

# Answer
> 0 votes
Not a fix for your issue but a work around could be to use Devel Debug Log instead. You can use ddl($var) and will save to a log in which you can see the output on the log page. Much better than trying to spit out dpm messages in $messages variable.

---
Tags: 7, theming, debugging
---


# Question
Title: can you put views field values into a global token?
Suppose I want to use a paragraph field value of an entity for metatag title (by using metatag views module)

I can successfully get the value of the paragraph entity and display it on the view

Now, is there a way i can save those field to a token so i can use it here?

Regards,

# Answer
I do not believe this is possible if paragraphs module does not provide this token itself. The way to do it would be to create your own token. Even with this it may be tricky to figure out that information.

To create your own token you will need to look into the hook\_token\_\* items such as hook\_token\_info.

It sounds like to me your best bet would be attempting to hook into the views pre processing and change the value that way.
> 1 votes

---
Tags: 8, tokens, meta-tags
---


# Question
Title: How to access the existing field value in a custom field?
I have a content type which shows video in iframe from youtube. There is a field which I can enter the youtube link and it will render the iframe using the link.

I have created a custom field which will take the youtube link as input and get the youtube statistics using youtube api. The field will display a div in the page with view count and number of likes of the video.

I wanted to access the already existing field value (youtube link which shows iframe), to show my stats information, as both are same. In my custom field module, I am taking an input field which is the youtube url.

For a user, it will be repetitive, if he types the url twice. Also I already have so many contents added to my content types, so it will be a burden to the content creators to go and add values to my newly created field.

Is there any way, I can access the existing fields value of my same content type ?

Here is my code :

YoutubeStat.php

```
<?php

namespace Drupal\youtube_stat\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface as StorageDefinition;

/**
 * Plugin implementation of the 'player_info' field type.
 *
 * @FieldType(
 *   id = "Youtube_stat",
 *   label = @Translation("Youtube statistics"),
 *   description = @Translation("To Display Youtube statistics"),
 *   category = @Translation("Custom"),
 *   default_widget = "Youtube_statDefaultWidget",
 *   default_formatter = "Youtube_statDefaultFormatter"
 * )
 */
class Youtube_stat extends FieldItemBase {

  /**
   * Field type properties definition.
   *
   * Inside this method we defines all the fields (properties) that our
   * custom field type will have.
   *
   * Here there is a list of allowed property types: https://goo.gl/sIBBgO
   */
  public static function propertyDefinitions(StorageDefinition $storage) {

    $properties = [];

    $properties['videoId'] = DataDefinition::create('string')
      ->setLabel(t('Video Id'));

    return $properties;
  }

  /**
   * Field type schema definition.
   *
   * Inside this method we defines the database schema used to store data for
   * our field type.
   *
   * Here there is a list of allowed column types: https://goo.gl/YY3G7s
   */
  public static function schema(StorageDefinition $storage) {

    $columns = [];

    $columns['videoId'] = [
      'type' => 'char',
      'length' => 255,
    ];

    return [
      'columns' => $columns,
      'indexes' => [],
    ];
  }

  /**
   * Define when the field type is empty.
   *
   * This method is important and used internally by Drupal. Take a moment
   * to define when the field fype must be considered empty.
   */
  public function isEmpty() {

    $isEmpty =
      empty($this->get('videoId')->getValue());

    return $isEmpty;
  }

}

```

YoutubeStatDefaultFormatter.php

```
    <?php

namespace Drupal\youtube_stat\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal;

/**
 * Plugin implementation of the 'Youtube_statDefaultFormatter' formatter.
 *
 * @FieldFormatter(
 *   id = "Youtube_statDefaultFormatter",
 *   label = @Translation("Youtube statisctics"),
 *   field_types = {
 *     "Youtube_stat"
 *   }
 * )
 */
class Youtube_statDefaultFormatter extends FormatterBase {

  /**
   * Define how the field type is showed.
   *
   * Inside this method we can customize how the field is displayed inside
   * pages.
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {

    \Drupal::service('page_cache_kill_switch')->trigger();
    //$memory = (string)ini_get("memory_limit");
      //ini_set('memory_limit', '-1');
    $elements = [];
    foreach ($items as $delta => $item) {

      $JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=*_API_KEY_*&part=statistics&id={$item->videoId}");
      $JSON_Data = json_decode($JSON);
      $viewCount = $JSON_Data->items[0]->statistics->viewCount;
      $likeCount = $JSON_Data->items[0]->statistics->likeCount;
      //$dump_data = '<pre>'.json_encode($item).'<pre>';
      $stat_div = "<div><span>Views : ".$viewCount."</span> <span>Likes : ".$likeCount."</span></div>";
      //$result = $query->fetchAll();
      $elements[$delta] = [
        '#type' => 'markup',
        '#markup' => $stat_div,
        '#cache' => ['max-age' => 0]
      ];
    }
    //ini_set('memory_limit', $memory);
    return $elements;
  }

}

```

Is there any way to achieve this ?

# Answer
I don't think this warrants a custom field but could be handled many other ways. A couple options here

1.) You can preprocess the node and provide your value as a variable to use in the node.tpl.php template.

2.) Create a new Drupal field and use hook\_form\_alter and on your submit take the value from the youtube field and place it into your new field. Then hide the field from the end user when they edit the node. Then run a one time function to loop through existing content types and update it with the youtube value.
> 0 votes

---
Tags: views, 8, entities
---


# Question
Title: OutboundPathProcessor is not appending $options array?
I have a simple `OutboundPathProcessor` that should append a query string and a URL fragment, but nothing is happening.

### mymodule.services.yml

```
services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MyModulePathProcessor
    tags:
      - { name: path_processor_outbound }

```

### MyModulePathProcessor.php

```
namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

class MyModulePathProcessor implements OutboundPathProcessorInterface {

  function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

    $options['query']['foo'] = 'bar';
    $options['fragment'] = 'baz';

    return $path;
  }

}

```

It seems the `$options` array is passed by reference, and in fact LanguageNegotiationUrl::processOutbound is placing multiple values in the `$options` array.

Why doesn't my code work?

I just figured out that it does work if I add a URL prefix using `$options['prefix'] = 'prefix/';`, so some options are getting applied.
Why aren't fragment and query used?

# Answer
It seems there is a bug report for that. I found a reference to that issue in a inline comment inside `LanguageNegotiationContentEntity::processOutbound()`.

At the moment, after applying the patch from that issue, query parameters get added to the URL as you would expect and without any need to instantiate 'prefix', but fragment doesn't. More work/comments should go into that issue to assist with resolving it.

As an alternative and in order to get fragments to work, you could try extending the Drupal\Core\Routing\UrlGenerator and replace the url\_generator.non\_bubbling service. (See https://www.drupal.org/node/2026959.)

---
> 2 votes

# Answer
This issue is fixed now for `$options['query']` on Drupal v8.5.5, but not yet for `$options['fragment']`. If someone needs to alter fragments in an OutboundPathProcessor, there is a core patch for fragments in this issue on d.o

https://www.drupal.org/project/drupal/issues/2881077#comment-12100638
> 0 votes

---
Tags: 8, uri
---


title: Two different front pages?

text:
# Question
Title: Two different front pages?
I have a website at mydomain.com. I am creating a clone of it on mydomain2.com. The only difference is that I want the landing pages to be different. Both domains are running the same codebase.

How do I make the landing page differ, depending on what domain you are on?

(Note: Without using i18n)

# Answer
You can do this by using the Domain Access module which is meant for creating a site (with one code base and one database) where certain content is accessible by DomainA and other content is accessible by DomainB. In your case you can set all content to be accessible to both domains and just change the site settings for the front page based on current domain. In D8 there is the Domain Site Settings module which makes this easier, but in D7 you should use Domain Variable to change site\_front based on the current domain.

This method will allow you (for example) to create two view pages or nodes or whatever (one for each domain) and display completely different content (or content in a different order) depending upon the domain.
> 2 votes

# Answer
I would suggest creating a custom Route (or hook\_menu for D7) that acts as a routing mechanism to send you to the right page. The custom logic would look at the $\_SERVER variable and then do a drupal\_goto to the appropriate page of choice.

example.com/landing would route to example.com/other-landing
> 0 votes

# Answer
you can use hook\_theme in your template.php file to introduce two different theme to drupal, then in page.tpl.php file check if user is visiting current page (use $is\_front variable for that) or you can use page--front.tpl.php, the you can check $front\_page value which has the address of front page, based on different address you can print one of your themes

example : in template.php :

```
function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'first_front' => array(
      'render element' => 'page',
      'template' => first-front-page,
    ),
    'second_front' => array(
      'render element' => 'page',
      'template' => second-front-page,
    ),
  );
}

```

then in page--front.tpl.php, use this code:

```
<?php if($front_page == "first_url") : ?>
  <?php print render(theme('first_page', array('page' => $page))); ?>
<?php endif; ?>
<?php if($front_page == "second_url") : ?>
  <?php print render(theme('second_page', array('page' => $page))); ?>
<?php endif; ?>

```
> -1 votes

---
Tags: 7, redirection
---