# Question
Title: getting a notice in reports for Commerce Paypal EC. IPN for Order ignored:
I am using Commerce PayPal and specifically the submodule for Express Checkout.

When checking the reports, I see many different IPN connections happening. the last two, the user is marked as "anonymous" instead of user name. The first is "IPN Validated..." and the second is **"IPN for Order 138 ignored: this operation was accommodated in the direct API response."**

Is this normal? Is there something in my settings that needs to be changed so it isn't "ignored"?

# Answer
OK, so in your case, it sounds like the IPN notification is being skipped because the order is already in the "complete" status.

To keep the IPN processing, you may need to keep the default "pending" status for such orders. That way, the IPN notification can mark the order as complete.
> 0 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: How to login into Drupal 8 using Ajax (REST API)
I want to login in my Site Drupal 8.2.3 from another application using Ajax, but is returning error all the time.

```
$.ajax({
    url : "http://localhost/Drupal-tuto-test/user/login",
    type : 'POST',
    data: {
        'username' : 'admin',
        'password' : 'admin'
    },
    dataType : 'json',
    error : function(data) {
        console.log('Error ',data);
    },
    success : function(data) {
        console.log('Success ',data);
    }
});

```

# Answer
Your POST data isn't correct, you should be using "user" and "pass". For a a more complete response, see my answer here.
> 3 votes

# Answer
If you're making an API request from a different origin in JS/AJAX, you will need to configure cross-origin-resource-sharing (CORS)

This page has more details on D8 CORS opt-in:

> This is particularly helpful for fully decoupled Drupal sites which have JS that needs to talk to a Drupal 8 site's REST API. In such cases, that Drupal 8 instance often runs on a separate domain. Due to the same origin policy those requests will be blocked by the browser.

https://www.drupal.org/node/2715637

Note: Make sure your allowed-origin is specific to the domain you want to permit access from. Using "\*" will leave it wide-open to the entire internet. Better to be specific.
> 1 votes

---
Tags: users, ajax, 8
---


# Question
Title: count entityreference multivalue field conicidences (make an attendance form)
This question is similar to this one How to make an attendance form, but i solved by entity refrence view widget module, saving date in a node, and having a field entityreference user relation with unlimited values. Now i have a views table of nodes like:

and now i can not sum how many times a user entityreference appears, ofcourse at the bottom i need to have: John=3, Mary=2, Pete=2 I tryed views aggregartor plus with no luck, please make some suggestions how to achive this.

# Answer
> 1 votes
Solved. This is what I did. In order to not make heavy loads i enebleded Entity Construction Kit (eck) module, then by rules i added an entity (instead of a node) for every user entity reference value, within two columns, one for user name, and one for date in attendance. Now I can have a view (of entities) with two exposed filter on dates (beginning and ending dates) Then I override my views table tpl view with the following code. It displays a 2 column table, first: username, second: number of days that user has attendance. the following code assumes that username is second field on your view ($fieldloop == 2 ). code:

```
<?php $names = array(); ?>

```

```
<?php foreach ($rows as $row_count => $row): ?>
   <?php $fieldloop = 1; ?>
    <?php foreach ($row as $field => $content): ?>
    <?php if ($fieldloop == 2 ) {$names[] = strip_tags($content);} ?>
    <?php $fieldloop = $fieldloop + 1; ?>
    <?php endforeach; ?>
<?php endforeach; ?>

  <?php $attendances = (array_count_values($names)); ?>
<body>
<table>
<tr><th>Alumno</th><th># dias</th></tr>
<?php foreach ($attendances as $attendance => $value) : {
?><tr><td>  <?php print $attendance ; ?></td>
<td> <?php print $value; ?></td></tr>
<?php } endforeach; ?>
</table>
</body>

```

---
Tags: 7, entities, views
---


# Question
Title: Filter condition like "from now to now+1 year" on a date field in Views
I have a custom entity with (among others) a field defined this way:

```
$fields['datedistribution'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Date distribution'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'weight' => 2,
  ))
  ->setDisplayOptions('form', array(
    'weight' => 2,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

The values of this field are stored in the database in YYYY-MM-DD format.
I designed a View on this custom entity displaying (among others) this 'datedistribution' field and I use it as a filter criterion. I would like to a filter condition like "from now to now+1 year". The available operators being

how can I do that?

# Answer
> 1 votes
I believe I can help, if I understand your question correctly. First you should make sure that when you set the filter up, it's in Select form.

Then you can select the operator as "is between" Then you select "Enter a relative date" in the dropdown, and you can put now and now+1 year. Not sure if your date fields have a start and end date...

# Answer
> 0 votes
`NOW()` will not work

I have used this method first fetch date from database then put date to condition

```
$time = \Drupal::database()->query( "SELECT NOW() as currtime " );
$timere = $time->fetchAll();

```

---
Tags: views, 8
---


# Question
Title: Unsubscribing from mailing list for anonymous user in simplenews
I use the Simplenews module for newsletters of my site. But I don't send out mails, rather use the module for subscribing and unsubscribing. Now for the anonymous user it gets difficult to unsubscribe since the user doesn't get any mail other than the subscribe mail. I read the comment in https://drupal.org/node/337628 #6, but I don't think I have an option here.

So I want to add an unsubscribe button to my block. How can I do that?

Drupal Version - 7.22 Simplenews Version - 7.x-1.0

# Answer
I needed the same thing, so I thought I'd share my solution.

In hook\_form\_alter():

```
  // Check that this is a simplenews form and the user is anonymous
  // If so, add an Unsubscribe button with a custom submit handler before the
  // default simplenews form submit handler is called
  if (strpos($form_id, 'simplenews_block_form') !== FALSE && $user->uid == 0) {
    $form['unsubscribe'] = array(
      '#type' => 'submit',
      '#value' => t('Unsubscribe'),
    );

    $form['unsubscribe']['#submit'] = $form['#submit'];
    array_unshift($form['unsubscribe']['#submit'], 'custom_simplenews_form_unsubscribe');
  }

```

Then the custom submit handler will be something like this:

```
function custom_simplenews_form_unsubscribe(&$form, &$form_state) {
  // Change action to unsubscribe and exit so the simplenews handler will take over
  if ($form_state['clicked_button']['#value'] == 'Unsubscribe') {
    $form_state['values']['action'] = 'unsubscribe';
    $form_state['values']['submit'] = 'Unsubscribe';
  }
}

```

So, when control is passed to simplenews\_block\_form\_submit() in simplenews.subscription.inc the user will be unsubscribed using the module's workflow.
> 1 votes

# Answer
Create a block that augments the standard subscription block with a link to the unsubscribe user. The content of the block is just

```
<p><a href="/newsletter/subscriptions">Unsubscribe</a></p>

```

The block is filtered on unauthenticated users.
> 1 votes

# Answer
Here is the compete code with the modifications mentioned above, that works well for me. Just change the "mythemename" in the first line and put the code in the template.php (in your theme directory).

```
function mythemename_form_alter(&$form, &$form_state, $form_id) {
 global $user;
 if (strpos($form_id, 'simplenews_block_form') !== FALSE && $user->uid == 0) {
  $form['unsubscribe'] = array(
   '#type' => 'submit',
   '#value' => t('Unsubscribe'),
  );

  $form['unsubscribe']['#submit'] = $form['#submit'];
  array_unshift($form['unsubscribe']['#submit'], 'custom_simplenews_form_unsubscribe');
 }

}

function custom_simplenews_form_unsubscribe(&$form, &$form_state) {
    if ($form_state['clicked_button']['#value'] == $form['unsubscribe']['#value']) {
     $form_state['values']['action'] = 'unsubscribe';
     $form_state['values']['submit'] = 'Unsubscribe';
    }
}

```
> 0 votes

---
Tags: 7, emails, notifications
---


# Question
Title: Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs?
I am trying to pass URL parameters and access them in a preprocess function. I have done a fair amount of research but did not find an answer. It works if I do the following /example?id=1, but that's quite ugly and non-SEO friendly. Clean URLs is much better.

Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs?

# Answer
Yes, the arg() function can do this.

https://api.drupal.org/api/drupal/includes%21path.inc/function/arg/6.x

At the end of Drupal's .htaccess file, you can see how Drupal makes those URLs work by rewriting them to ?q= if they are not real files or directories. Without this, they would cause a 404 too.

In http://api.drupal.org/api/function/arg/6 you can see how it handles them.
> -1 votes

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


# Question
Title: How to create parent child menu programatically?
I have an array like this :

```
Array(
  [0] => Array(
    [link_title] => Level == bod
    [link_path] => link1
    [menu_name] => parrent-child-menu
    [weight] => 1
    [expanded] => 1
  )
)
Array(
  [0] => Array(
    [link_title] => Level == About// us///
    [link_path] => link1
    [menu_name] => parrent-child-menu
    [weight] => 3
    [expanded] => 1
  )
)
Array(
  [0] => Array(
    [link_title] => Level == name12
    [link_path] => link1
    [menu_name] => parrent-child-menu
    [weight] => 5
    [expanded] => 1
  )
)
Array(
  [0] => Array(
    [link_title] => Level == name13
    [link_path] => link1
    [menu_name] => parrent-child-menu
    [weight] => 5
    [expanded] => 1
  )
)
Array(
  [0] => Array(
    [link_title] => Level == name14
    [link_path] => link1
    [menu_name] => parrent-child-menu
    [weight] => 5
    [expanded] => 1
  )
)

I want it in the following format:

Array
(
    [0] => Array
        (
            [link_title] => Level == bod
            [link_path] => link1
            [menu_name] => parrent-child-menu
            [weight] => 1
            [expanded] => 1
            [children] =>
                    Array
                        (
                            [0] => Array
                                (
                                    [link_title] => Level == About// us///
                                    [link_path] => link1
                                    [menu_name] => parrent-child-menu
                                    [weight] => 3
                                    [expanded] => 1
                                    [children] =>
                                            Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [link_title] => Level == name12
                                                            [link_path] => link1
                                                            [menu_name] => parrent-child-menu
                                                            [weight] => 5
                                                            [expanded] => 1
                                                        )

                                            )
                                            Array
                                            (
                                                [0] => Array
                                                    (
                                                        [link_title] => Level == name13
                                                        [link_path] => link1
                                                        [menu_name] => parrent-child-menu
                                                        [weight] => 5
                                                        [expanded] => 1
                                                    )

                                            )
                                            Array
                                            (
                                                [0] => Array
                                                    (
                                                        [link_title] => Level == name14
                                                        [link_path] => link1
                                                        [menu_name] => parrent-child-menu
                                                        [weight] => 5
                                                        [expanded] => 1
                                                    )

                                            )
                            )

                    )
    )

```

)

# Answer
> 0 votes
You need to set the value of `plid` to the `mlid` of the parent link. For example, you need to have this kind of menu structure.

```
About
  Vision
  Mission
  History

```

To create that programmatically you need first to create the `About` then get the `mlid`. After that you are good to create the `Vision`, `Mission`, and `History` as you have the `About` `mlid` already. Please see menu\_link\_save. Check this related thread as well.

# Answer
> 0 votes
See below example, hope you will get the solution to create parent-child menu programmatically.

```

$items['hotels'] = array(
'title' => 'Hotel Process',
'page callback' => 'hotels_page',
'access arguments' => array('access content'),
'weight' => 1,
);
$items['hotels/hotels2'] = array(
'title' => 'Hotel Statistics',
'page callback' => 'hotels_page',
'access arguments' => array('access content'),
'weight' => 1,
);

```

This also works:

```

$items['hotels'] = array(
'children' => array('hotels2'),
'title' => 'Hotel Process',
'page callback' => 'hotels_page',
'access arguments' => array('access content'),
'weight' => 1,
);
$items['hotels/hotels2'] = array(
'parent' => array('hotels'),
'title' => 'Hotel Statistics',
'page callback' => 'hotels_page',
'access arguments' => array('access content'),
'weight' => 1,
);

```

---
Tags: routes, taxonomy-terms
---


title: D8 to D8 migrate source plugin?

text:
# Question
Title: D8 to D8 migrate source plugin?
Migrate Source

> The migration configuration entity always contains a source key. The value is an associative array containing the name of the plugin and the configuration of it. Only the plugin key-value pair is mandatory, some plugins might not have any configurations.
>
> ```
> source:
>   plugin: d6_node
>
> ```

Googling I see examples outhere that use `d6_node` and `d7_node` but what does one use to migrate nodes from d8 to d8?

Looking at the `core/modules/node/src/Plugin/migrate/source` folder there is no such thing as `d8_node`

# Answer
> 3 votes
The Drupal 8 migration module has been moved into core as explained in this issue. If you're using at least Drupal 8.6.x, you don't need to apply the patch.

---

Old answer:

I'm going out on a limb and say that currently there isn't one and it can only be done by creating a custom plugin.

Just found this Drupal 8 migration (source), thanks Berdir & Primsi.

---
Tags: 8, migrations
---


# Question
Title: How to add a slideshow inside a node with Slick?
I created a Content Type with an Image Field that could take multiples images. I would like to display a slideshow of these images. So for each node of this Content Type, I would have a different slideshow, directly inside the node. On Drupal 7, there is the Field Slideshow module that seems to do that, but I'm on Drupal 8.

So I installed Slick Carousel and Slick Extras so I can use the formatter called Slick Image for my multiple images field. But there are many options and I can't find the correct ones to have the slideshow working.

Here are the options :

Can anyone give me the right options ?

# Answer
> 0 votes
The problem comes from an incompatibility from the theme I use, Zircon, with Slick carousel. The full explanation and the solution can be found here : https://www.drupal.org/node/2875173#comment-12075392

In brief, the solution is to comment the following lines in zircon.libraries.yml with the `#` sign :

```
# assets/includes/slick/slick/slick.js: {}
assets/includes/bootstrap/js/bootstrap.js: {}
assets/includes/flexslider/jquery.flexslider.js: {}
assets/includes/flexslider/jquery.flexslider-min.js: {}
assets/js/slideshow.js: {}
# assets/js/carousel.js: {}

```

This file is in /themes/zircon/ folder

---
Tags: 8
---


title: Can Features package its dependencies?

text:
# Question
Title: Can Features package its dependencies?
I have just created a Feature that has about 10 module dependencies. I installed the feature on the target Drupal instance, and discovered that the dependencies were not included in the feature tarball. Is there a way to tell features to package dependency modules into the feature so that they will get installed along with the feature? Or am I misunderstanding what the features module is supposed to do?

# Answer
> 4 votes
I think the latter is true, and you're misunderstanding what Features does.

Features takes any database-stored configuration (Views for example), and exports it to code. The generated module is essentially just a package that then contains the code version of your configuration.

For example, if you create a Feature containing a Blog content type, and a View that show all Blog articles in a list - the generated Feature is simply a module with that configuration stored in code, and exposed to Drupal.

If you want all of the modules packaged, you are looking more towards a distribution - which is a completely different kettle of fish.

To cut a long answer short, Features is a module builder - so as with any other module, dependencies must be retrieved seperately.

# Answer
> 0 votes
This may be a bit late, but if you are using drush (the command line Drupal tool), the dependent modules will be downloaded when you enable the feature.

So if you have a feature called "MyFeat" which is dependent on modules A, B and C, you can copy the MyFeat folder to the target site (at sites/all/modules). Then from the websites/myDrupalSite directory, run the command "drush en MyFeat". Drush will detect the dependencies and ask if you want to download A, B and C.

May be not as elegant as Distros or Apps, but works for me and hope this helps you as well.

Alan

---
Tags: 7, features
---


# Question
Title: Hook_enable vs hook_install [granting permissions to user role]
In Drupal 7, I'm trying to grant a permission to a user role using hook\_install and it doesn't work. But it works with hook\_enable. Do you know how to make it work with hook\_install as well?

```
function porta_batch_editor_install() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

```

It works with the following approach:

```
function porta_batch_editor_enable() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

```

# Answer
> 0 votes
It should work on install. Are you actually uninstalling the module? Disabling and uninstalling is not the same thing in Drupal 7. Uninstall at `admin/modules/uninstall`, once the module is disabled. You can use `drush pm-disable/pm-uninstall module_name`.

* test.module

```
function test_permission() {
  return array(
    'test permission' => array(
      'title' => t('Test permission title'),
    ),
  );
}

```
* test.install

```
function test_install() {
  $test_perm = array('test permission');

  $perms = module_invoke_all('permission');
  // We can find the 'test permission' in $perms.

  $role = user_role_load_by_name('administrator');
  user_role_grant_permissions($role->rid, $test_perm);
}

```

The above gives administrators the test permission on module install.

---
Tags: 7, hooks
---


# Question
Title: Why do I get the "could not find the controller" error?
I'm trying to setup DrupalGap with Commerce following this tutorial, but I get this error:

> 404 not found: could not find the controller.

I've manually confirmed Services are set up properly with Advanced REST client (Chrome), with this instructions. All seems OK; the endpoint/resource is operating and I receive a *200 OK* response, but when I try to test the application from admin/config/services/drupalgap, I always get this error.

I use Services frequently and I can confirm It's working good on this site. I also verified DrupalGap is working too.

What could it be?

# Answer
> 1 votes
A `301` is a redirect, so it sounds like you have the Global Redirect module enabled. See this issue for details: https://www.drupal.org/node/1927336

The patch allows you to declare paths that should be ignored by the Global Redirect module so it doesn't hijack Service calls to your Drupal site. You'll input something like this into the configuration text area once the patch has been applied:

`drupalgap/*`

---
Tags: services, javascript
---


title: How can I filter nodes by author name?

text:
# Question
Title: How can I filter nodes by author name?
I'm trying to make page with nodes filtered by author name. My context filter is comming from url.

My path looks like domain.xx/drupal/authors/johny

If i set validation by user ID, and send user ID in path, all works properly.

You can see contextual filter setup in attachment.

---

# Answer
On editing view, click the advanced settings then click relationships area, click Add.

There are many tables you can join to the content listing. In this case, search for "author" options, and select Content: Content author. Click Apply. Now add field 'user' in view also set filter criteria as needed.
> 1 votes

# Answer
Depending on your configuration (if `domain.xx/drupal/authors/johny` is the path alias of a user account), you can also select `user id from url` as the default value, instead of raw value from URL.

Drupal will recognize the unaliased path `user/x` and extract the user id.

For this to work, your contextual filter must filter by auther id.
> 0 votes

---
Tags: 8, views
---


title: How do I create a path alias?

text:
# Question
Title: How do I create a path alias?
I'm trying to create a path alias for a node type, where the first part of the alias is the url path of the organic group. I tried this

```
[node:og-group-ref:1:url]/[node:content-type]/[node:title]

```

but it didn't work. When I tried this

```
[node:og-group-ref]/[node:content-type]/[node:title]

```

it did create an alias, but \[node:og-group-ref\] refered to the node title, not the path alias of the node.

From here - https://www.drupal.org/node/2302879 \- saw that there are tokens for \[node:og-group-ref:url:relative\], but thats not a valid token on my site. I am using Organic groups 7.x-2.7.

Is this a possible alias?

# Answer
I'm not sure what the real answer is to this issue, but I found a workaround: I created my own token which provided me this alias

```
/**
 * Implements hook_token_info().
 */
function example_tokens_token_info() {
  $types['og_path_alias'] = array(
    'name' => t('The OG Path Alias'),
    'description' => t('Tokens for the OG path alias'),
  );
  $og_path_alias['path_alias'] = array(
    'name' => t('The OG Path Alias'),
     'description' => t('The OG path alias'),
  );
  return array(
    'types' => $types,
    'tokens' => array(
      'og_path_alias' => $og_path_alias,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function example_tokens_tokens($type, $tokens, array $data = array(), array $options =     array()) {
  $replacements = array();

  if($type === 'og_path_alias') {
    $node = $data['node'];
    foreach($tokens as $name=>$original) {
      switch($name) {
      case 'path_alias':
      $node_wrapper = entity_metadata_wrapper('node', $node);
      if($node_wrapper->__isset('og_group_ref')) {
        $chapters = $node_wrapper->og_group_ref->value();
        foreach($chapters as $chapter) {
          $new_alias = drupal_get_path_alias('node/' . $chapter->nid);
        }
      }
      $replacements[$original] = $new_alias;
      break;
  }
}
}

return $replacements;
}

```
> 0 votes

# Answer
The Entity token module, part of Entity API module, can do this for you. it provides token replacements for all properties that have no tokens and are known to the entity API, such as fields within a group tied to a node. e.g \[node:og-group-ref:0:field\_name\_here\]
> 0 votes

---
Tags: organic-groups, path-aliases
---


# Question
Title: Adding a custom js file to a core theme like Seven
I've copied over the Seven theme to my /theme folder on Drupal 8 and I'm trying to customize it by adding in my own js file called custom.js. I added it to the seven.libraries.yml file as shown below, but I don't see it loading up on any of the pages. I even did clear the cache. Nothing shows up. I did add a custom.css file and that is showing. What could be wrong or that I'm missing?

```
global-styling:
  version: VERSION
  js:
    custom.js: {}
  css:
    base:
      css/base/elements.css: {}
      css/base/typography.css: {}
      css/base/print.css: {}
    component:
      css/components/admin-list.css: {}
      css/components/content-header.css: {}
      css/components/breadcrumb.css: {}
      css/components/buttons.css: {}

```

# Answer
Asset injector has been made specifically to carry out the functionality that you stated. Simply install the module & flush cache.

Within configuration you'll see the link Asset injector and there you can select the theme to add your custom CSS/JS.

Hope that helps!
> 1 votes

# Answer
Actually it was indeed working after I read up on the following about how to declare these assets: https://www.appnovation.com/blog/how-add-js-and-css-assets-drupal-8-theme

```
In one of my previous posts I wrote about creating a Drupal 8 theme and declaring assets (JS and CSS) associated with it. Recently there were a few changes in Drupal 8's core and the way these assets are served to a theme or a module. Drupal 8 introduces a concept of asset libraries for JS and CSS in themes and modules. One of the recent core updates was about changing the way these assets are attached to the theme .In this post I wanted to go over a few practical examples of how these assets can be added and customized. Here are some scenarios:

Through a global library
Deleting or overriding existing styles served by core
Declaring various dependencies that are provided by Drupal 8's core
Specifying assets scope or sending JS to the footer
Specifying media type
Adding external CSS or JS library, e.g: Google Fonts
Adding conditional CSS or JS for older IE browsers
Adding custom libraries to specific pages, e.g: front page
Global styles and scriptsIn the example below global-styling is a name of a library (a file or collection of files) that is used for global styles. It is declared in a theme_name.libraries.yml and then also added to the theme_name.info.yml file. This specific library will now be available across the whole site.Here is how it will look in the theme_name.libraries.yml file.
global-styling:
version: VERSION
css:
theme:
css/style.css: {}

Then it's declared in the theme_name.info.yml file.
name: Example
type: theme
core: 8.x
libraries:
- theme_name/global-styling

Declaring scripts would be very similar. In the theme_name.libraries.yml
global-scripts:
version: VERSION
js:
js/script.js: {}

Then in the theme_name.info.yml file, we add these libraries.
name: Example
type: theme
core: 8.x
libraries:
- theme_name/global-styling
- theme_name/global-scripts

Now these two libraries or collections of JS and CSS files are available across the whole site. These two separate sets of CSS and JS can also be combined into one library.
global-styles-and-scripts:
version: VERSION
css:
theme:
css/style.css: {}
js:
js/script.js: {}

Deleting or overriding existing styles served by coreIn the theme_name.info.yml file:
stylesheets-remove:
- normalize.css

or to override the core's stylesheet:
stylesheets-override:
- normalize.css

Declaring dependenciesBy default Drupal 8 doesn't load any additional scripts. For example jQuery is not loaded, but it can be declared as a dependency. For all core assets look into /core/assets/vendor. You will find modernizr, jQuery and other useful things in there.Example of declaring a dependency.
global-scripts:
version: VERSION
js:
js/script.js: {}
dependencies:
- core/jquery
- core/jquery.once
- core/modernizr

Specifying scope of a JS file or sending it to the footerThere are many cases when it would be best to have a JS asset at the footer of the page. By default they will be included in the header but you can easily send them to the footer by specifying the scope in the theme_name.libraries.yml file.
js/script.js: { scope: footer }

```
> -1 votes

---
Tags: theming, 8
---


# Question
Title: "Image Upload Button" section remove after click on upload
I am trying to edit users's profile page in Drupal 7. I have an image upload button there, but it remove (hide) after click on upload button .

But If i login with admin its working fine, means image upload section is not hiding on upload click.

Any suggestions ?

Thanks

# Answer
> 0 votes
Put the following code in a custom module, this module will act on all users but admin (user 1), this will work after user saves/updates his account. inside function there are two sentences begining with $form, first will hide user picture field, second will disable it. use only one. code:

```
// implementes hook_form_alter
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
global $user;
$uuid = $user->uid;
/*  check that user is NOT admin (No1) */
if ($uuid !='1') {
if ($form_id == 'user_profile_form') {
//dsm($form);
if (!empty($user->user_picture) {
    // Prevent editing a field
    // hiding the field entirely on the edit form.
    $form['field_user_picture']['#access'] = FALSE;

    // disable update field on the edit form.
    $form['field_user_picture']['#disabled'] = TRUE;
    }
 }
}
}

```

---
Tags: views, entities, media
---


# Question
Title: Get menu link item from MenuLinkTreeElement
Hey I am loading a drupal 8 menu in the following way:

```
if ($menu != NULL) {
    $tree = \Drupal::menuTree()
    ->load("my_menu", new MenuTreeParameters());

```

This returns MenuLinkTreeElement objects. It does not seem possible to fetch the fields attached to the menu item.

How can I do that? Should I load the menu through another function?

# Answer
You can get the menu link content entity by accessing the uuid with the method `getDerivativeId()` of the plugin:

```
if ($link instanceof \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent) {
  $uuid = $link->getDerivativeId();
  $entity = \Drupal::service('entity.repository')
    ->loadEntityByUuid('menu_link_content', $uuid);
  $field_value = $entity->field_example->value;
}

```
> 12 votes

---
Tags: 8, navigation
---


# Question
Title: Print {{ node.body.value }} in node--content-type.twig missing figure and figcaption tag of image
My code in node--content-type.html.twig is the following.

```
{% autoescape false %}
  {{ node.body.value }}
{% endautoescape %}

```

In my node there are images, centered and with a caption, but when I view the node detail, the images are not centered because of missing figure and figcaption tags.

How can fix it?

# Answer
This is my code to corrected it:

```
<p>{{ content|without('body') }}</p> <!--Other fields in Full content mode-->
{{ content.body }} <!--This is body field. Don't forget config show it in Full content mode-->

```

If someone has a better solution please help me! Sorry my English not good.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to properly add inline Javascript code to a webform with javascript injector module
I have recently started leaning Drupal 7. I have built my first Webform and I'd like to add a field that calculates automatically number of days between two dates as shown in below  I tried to follow this tutorial but I didn't understand it so I tried to use the module js injector to solve the problem!

This is the JS injection rule that I used

```
jQuery(document).ready(function($) {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});
});
});

```

But it doesn't work. Can you help me finding the error? It seems I didn't write it well on Drupal as js rule.

This is the javascript code that I want to write:

```
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet"             href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
});
});
</script>

```

# Answer
> 2 votes
You need to use proper Drupal jQuery Syntax.

Screw the js injector module, you can do the same like this:

Create a block, for Text format select Full HTML and put this code

```
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>

(function ($) {
$( document ).ready(function() {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});

});
})(jQuery);

</script>

```

Place the block in some region.

For **Visibility Settings**

Pages, select `only listed pages` and type the url for your webform.

# Answer
> -1 votes
There are two basic ways to do it in Drupal: Drupal - Community Documentation - Adding JavaScript to a Webform

---
Tags: 7, javascript, rules, webforms
---


# Question
Title: autocomplete taxonomy field depend on another taxonomy field
There is a content type Animal in which two taxonomy field are used say Animal Type and Breeds . Breeds taxonomy is autocomplete taxonomy field . so What i want Breeds taxonomy field depend on Animal type taxonomy field. i.e, when cats are select from animal type field then breeds taxonomy show only cats type breeds .How can this acheive ?

# Answer
> 0 votes
I hope this is a drupal site on development state.

If it is possible to you, I recommend you to create just one taxonomy vocabulary, where Animal type are parent terms of Breeds terms as a tree:

Cat

* Curl
* Bengal

Dog

* Afghan
* Akita

Then you can use Simple Hierarchical Select or Hierarchical Select, where you can allow users to select a parent term first and then childs.

Hope this help, if you need help with views filters or things like that I can help you :)

---
Tags: taxonomy-terms
---


# Question
Title: Why and what wrapper should I use for my module's JavaScript file?
I am defining a d3.js script for my module like this:

```
test:
  js:
    js/test.js: {}
  dependencies:
    - mymodule/d3
    - core/drupalSettings
d3:
  remote: https://d3js.org
  version: "4.x"
  license:
    name: BSD
    url: https://opensource.org/licenses/BSD-3-Clause
    gpl-compatible: true
  js:
    https://d3js.org/d3.v4.min.js: { type: external, minified: true }

```

In my controller, I am sending my data (in `$data`) to the script, like this:

```
$page[] = array(
  '#markup' => 'foo',
  '#attached' => array(
    'library' =>  array(
      'mymodule/test',
    ),
    'drupalSettings' => array(
      'mymodule' => array(
        'test' => array(
          'data' => $data,
        ),
      ),
    ),
  )
);

```

It's working fine, but I've noticed that most js files in core have a wrapper - there is some information here.

Should I be using a wrapper for my script? and if so, what should the wrapper be? and why?

There is no jQuery in my script:

```
(function (Drupal, drupalSettings, d3) {
  Drupal.behaviors.mymoduleTest = {
    attach: function (context, settings) {

      const data = JSON.parse(drupalSettings.mymodule.test.data);

      ...

      console.log(data);

    }
  };
})(Drupal, drupalSettings, d3);

```

I'm wrapping my code, with these three lines top an bottom, but I don't understand if I need any of it?

# Answer
> 4 votes
There are a couple of different things at play here.

This:

```
(function (Drupal, drupalSettings, d3) {

})(Drupal, drupalSettings, d3));

```

is an Immediately Invoked Function Expression (IIFE). Quoting gion\_13 from the canonical SO post on the subject:

> This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

That's why you'll see it so often in Drupal's (and pretty much any other framework or library's) JS code; it's generally considered good practice.

Ben Alman's blog post is a must read if you're not familiar with this pattern. Yes, it's a good idea to use it in your own code.

This:

```
Drupal.behaviors.mymoduleTest = {
    attach: function() {

    }
};

```

is a Drupal "behavior". Quoting the docs:

> Any object defined as a property of Drupal.behaviors will get its attach() method called when the DOM has loaded both initially and after any AJAX calls.

This allows your code to re-run on elements that may have been replaced as a result of an AJAX or other JS event, so you don't need to keep track of that.

Say you had a d3 chart bound to an element in the content area, and an AJAX operation on the page replaces the content area with new HTML; the d3 bindings will be lost, and the chart will no longer show. Assuming the AJAX op was invoked by Drupal's API in some way, your `attach` method will be invoked automatically, and the chart will be re-bound to the new element in the content area.

It's a good idea to conform to this pattern when writing JS code for a Drupal site, it has the potential to save time and headaches later on.

As always it'll pay to use common sense with stuff like this; if you find yourself using these patterns, then immediately trying to get around them for a couple of specific requirements, those situations may be exceptions where it's best not to use them.

---
Tags: 8, javascript
---


# Question
Title: Different Feeds Tamper per destination in mapping
I have a csv feeds importer I'm trying to build where I would like the last 2 digits of a code to be mapped to the task code field, but the full 4 or 5 digit number be mapped to the GUID.

From the interface I can only see a way to run the tamper on the source field for all destinations. Is there some way I can tamp in different ways for different destination fields? (or tamp for one destination, and use the raw value for another)

# Answer
First thing this morning, I realized what Map to multiple fields using 'Blank source' in the documentation means. I was able to have Task Code as my source for GUID, then Blank Source 1 as my source for Task Code.

In the tamper for Blank Source 1 I use Copy Source Value before doing my other transform:

---
> 2 votes

# Answer
Aram Boyajyan wrote a nice article on how to create a custom tamper plugin.

```
function YOUR_MODULE_tamper_language_callback($result, $item_key, $element_key, &$field, $settings, $source) {

```

*perhaps* one of these callback params holds the destination? something for you investigate.

If yes, then you would just do an if statement.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "FROM"
I've some db\_query that I change to drupal 7 API use db\_select but Iam received error like this

> PDOException: SQLSTATE\[42601\]: Syntax error: 7 ERROR: syntax error at or near "FROM" LINE 2: FROM ^: SELECT FROM {jurnal\_kas} jurnal\_kas WHERE (id = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 42387 )

db\_query();

```
$jkas = db_query("SELECT * FROM {jurnal_kas} WHERE id=$id")->fetchAssoc();

```

db\_select();

```
$jkas = db_select('jurnal_kas')   ->condition('id', $id)
->execute()->fetchAssoc();

```

Can anyone help that will be great thanks

# Answer
You aren't selecting any field, (See Dynamic queries: fields.)

For example, you could select all fields with code similar to the following.

```
$jkas = db_select('jurnal_kas')
  ->fields('jurnal_kas')
  ->condition('id', $id)
  ->execute()
  ->fetchAssoc();

```
> 2 votes

---
Tags: 7
---


# Question
Title: How to use Value Objects in Content Entities
I have a content entity that contains value objects. How would I go about storing the value objects? What is the best way to do this?

As I see it I have the following options.

1. Creating a custom TypeData (as described here) to serialize the value objects before persisting.
2. store the value object properties as map and add computed fields for the getting the hydrated value objects.

# Answer
I think I understood the motivation behind the entity api.

The entity api is not an orm. It is a dbal. The entity definitions do several things:

1. define the database schema
2. define the hydration to a concrete object.
3. define form handling
4. routing

What does this do with handling Value Objects?

# Storing Value Objects

Let's assume we have the following interface, we want to create an entity for:

```
<?php
interface Product
{
   public function getId(): int;
   public function setId( int $id );

   public function getTitle(): string;
   public function setTitle( string $title );

   public function getPrice(): Price;
   public function setPrice( Price $price );

}

```

Which means we got one value object Price, which has a value and a currency.

## Store the value objects values as fields

When thinking about storing a value object in a table, you would normally define a table as follows:

```
+------------------------+-----------+---------------+
|id|title                |priceValue | priceCurrency |
+------------------------+-----------+---------------+
|1 |Hitchhiker           |4200       |USD            |
+------------------------+-----------+---------------+

```

In drupal you define the schema in the static baseFieldDefinitions method and in the annotation, though that mainly just says which table to use. Please note drupal requires an id and uuid field.

```
<?php
/**
 * @ContentEntityType(
 *   id = "product",
 *   label = @Translation("Product"),
 *   base_table = "product",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */
class Product extends ContentEntityBase implements ContentEntityInterface
{
    ...

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
           ->setLabel(t('ID'))
           ->setDescription(t('The ID of the Product entity.'))
           ->setReadOnly(true);

        // Standard field, unique outside of the scope of the current project.
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
           ->setLabel(t('UUID'))
           ->setDescription(t('The UUID of the Product entity.'))
           ->setReadOnly(true);

        $fields['title'] = BaseFieldDefinition::create('string')
           ->setLabel(t('Title'))
           ->setDescription(t('The title of the Product entity'))
           ->setSettings([
                'default_value' => '',
                'max_length' => 256,
                'text_processing' => 0
            ]);

        // define the necessary fields for our Price object

        $fields['price_value'] = BaseFieldDefinition::create('integer')
           ->setLabel(t('Price Value'))
           ->setDescription(t('How much does the product cost in the currencies smalles unit (e.g.cents)? '));

        $fields['price_currency'] = BaseFieldDefinition::create('string')
           ->setLabel(t('Price Currency'))
           ->setDescription(t('The currency the Price is given in'))
           ->setSettings([
              'default_value'   => 'USD',
              'max_length'      => 3,
              'text_processing' => 0,
           ]);

    }
}

```

Now that we have defined what the database should look like, let's take care of hydration

```
<?php
/**
 * @ContentEntityType(
 *   id = "product",
 *   label = @Translation("Product"),
 *   base_table = "product",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */
class Product extends ContentEntityBase implements ContentEntityInterface
{

    public function getId()
    {
       return $this->get('id')->get(0)->get('value')->getValue() ;
    }

    public function setId( $id )
    {
       $this->get('id')->setValue($id);
    }

    public function getTitle()
    {
       return $this->get('title')->get(0)->get('value')->getValue() ;
    }

    public function setTitle( $title )
    {
       $this->get('title')->setValue($title);
    }

    public function getPrice()
    {
       return new Price(
            $this->get('price_value')->get(0)->get('value')->getValue(),
            $this->get('price_currency')->get(0)->get('value')->getValue()
        );
    }

    public function setPrice( Price $price )
    {
       $this->get('price_value')->setValue($price->getValue());
       $this->get('price_currency')->setValue($price->getCurrency());
    }

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {
        ...
    }
}

```

## Storing a list of value objects

Let's say our product comes in different formats (I know no one would actually design it that way, I just can't come up with a better example)

```
<?php
interface Product
{
   public function getId(): int;
   public function setId( int $id );

   public function getTitle(): string;
   public function setTitle( string $title );

   public function getPrice(): Price;
   public function setPrice( Price $price );

   public function getFormats(): array;
   public function setFormats( Format ..$formatset);

}

```

For the sake of brevity I will pretend a Format only has one property.

### as fields of the product table

If there is a known upper bound to the number of formats I could pretty much design my database as before

```
+--+---------------------+-----------+---------------+-------------+-------------+
|id|title                |price_value|price_currency |format_title1|format_title2|
+--+---------------------+-----------+---------------+-------------+-------------+
|1 |Hitchhiker           |4200       |USD            |hardcover    |balloon      |
+--+---------------------+-----------+---------------+-------------+-------------+

```

### as a referenced table

It would be nicer to design it as two tables, that way it can easily grow without changing my database

```
+--+---------------------+-----------+---------------+
|id|title                |price_value|price_currency |
+--+---------------------+-----------+---------------+
|1 |Hitchhiker           |4200       |USD            |
+--+---------------------+-----------+---------------+

+----------+------------+
|product_id|format_title|
+----------+------------+
|1         |hardcover   |
+----------+------------+
|1         |balloon     |
+----------+------------+

```

And that somehow seems possible, but I didn't dig into that, yet.

### serializing

The least nicest, but easiest solution in Drupal is serializing the list of formats

```
+--+---------------------+-----------+---------------+-----------------------------------+
|id|title                |price_value|price_currency |format_set_serialized              |
+--+---------------------+-----------+---------------+-----------------------------------+
|1 |Hitchhiker           |4200       |USD            | #!gobblediegook%&                 |
+--+---------------------+-----------+---------------+-----------------------------------+

```

The hydration would then look like the following

```
<?php
class Product extends ContentEntityBase implements ContentEntityInterface
{

    ...

    public function getFormats()
    {
        return unserialize(
            $this->get('format_set_serialized')->get(0)->get('value')->getValue()
        );
    }

    public function setFormats( format ...$formatSet )
    {
       $this->get('format_set_serialized')->setValue(serialize($formatSet));
    }

    ...
}

```

# What about computed fields, custom type data and custom storage handlers?

These exist to put field specific hydration logic in the dbal part of your entity.

The question is "Will someone access the data through the entity api (dbal layer) instead of your fully hydrated domain class?"

If the anyswer is yes, then consider writing a repository service, that is available everywhere. I imagine most use cases revolve around getting domain specific data into drupal's database. So circumventing the domain logic seems like a very bad idea.

If the answer is still yes, then go for it.

I tried following the process described here. It worked but I had to add functions, that were not mentioned and were not part of the interface (specifically postSave and preSave). Also I encountered some very unhelpful errors on the way. After I had a working solution I scraped it for the simpler process outlined above. Your mileage may vary.
> 0 votes

---
Tags: 8, entities
---


title: flexslider cant adjust height

text:
# Question
Title: flexslider cant adjust height
I have installed Flexslider on my site (just locally on PC at the moment), it adjusts the width of the slide fine when I reduce the size of the screen width using the browser, but the height of the slide always stays the same and the image appears crushed when the browser is at minimum width. Can anyone help please? I have tried going through all the youtube videos etc.. but cant see what I'm doing wrong. I am using the Omega 3 theme if thats relevant.

# Answer
> 2 votes
I run into this when using Omega 4. What I do is set my base img tag to have an auto height:

```
img {
  height: auto;
}

```

# Answer
> 0 votes
@media screen and (max-width:320px) { .comp{ font-size: small; width: 184%; } .img-responsive{ height:auto; } .slider{ height:auto; }

}

add class="comp" to each image and try

---
Tags: javascript
---


title: Pass nid as argument to embedded view

text:
# Question
Title: Pass nid as argument to embedded view
I am using twig tweak to embed a view in node.tpl.twig

{{ drupal\_view('testview', 'block\_1', '12') }}

how can I pass current nid {{ node.id() }} as argument instead of static '12' in this case?

# Answer
> 1 votes
Oh - it is quite simple :)

```
{{ drupal_view('testview', 'block_1', node.id() ) }}

```
* sorry still learning basics :D

---
Tags: views, theming
---


# Question
Title: How to remove user role using hook_user_update
I am having trouble trying to remove a role after user account submit.

I have used the following code:

```
function vdb_form_alter(&$form, $form_state,  $form_id) {
  global $user;

}
  if(($form_id === 'user_profile_form')and (isset($form['account']['pass'])) and (in_array('Hybridauth', array_values($user->roles))) ) {
      $form['#submit'][] = 'my_module_hook_user_update';

}
function my_module_hook_user_update($edit, $account, $category) {
  $role_position = array_search('Hybridauth', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);
  }
}

```

Resulting in the following errors:

Warning: Missing argument 3 for vdb\_hook\_user\_update(), called in \includes\form.inc on line 1471 and defined in vdb\_hook\_user\_update() (line 46 Notice: Trying to get property of non-object in vdb\_hook\_user\_update() (line 47 Warning: array\_search() expects parameter 2 to be array, null given in vdb\_hook\_user\_update() (line 47 Warning: Attempt to modify property of non-object in vdb\_hook\_user\_update() line 50

I have tried using hook\_user\_presave however using this hook hybridauth module gets stuck.

# Answer
> 1 votes
The errors in your code are two:

* `vdb_hook_user_update()` is not the correct name for an implementation of `hook_user_update()`
* `vdb_hook_user_update()` is being used as form submission handler

As consequence of the second point is that you are declaring the function with the wrong arguments, since a form submission handler gets two arguments: `$form` and `&$form_state`.

As Clive pointed out, you should use `hook_user_presave()`, which is invoked before the user account is saved in the database. Remove the code adding the form submission handler, and implement `hook_user_presave()` using code similar to the following one.

```
function vd_user_presave(&$edit, $account, $category) {
  if (!empty($account->uid) && ($key = array_search('Hybridauth', $account->roles)) !== FALSE) {
    unset($account->roles[$key]);
  }
}

```

# Answer
> 0 votes
It is not need to set a submit handler, by default when you user update hook documentation `Modules may use this hook to update their user data in a custom storage after a user account has been updated.`, so you don't need set a submit handler in `form_alter` ,as Clive mentioned in comment you can also try hook user presave,

and So

```
function mymodule_user_presave($edit, $account, $category) {
  $role_position = array_search('Hybridauth', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);
  }
}

```

# Answer
> 0 votes
Have you tried unsetting the edit parameter which should also have roles in it and your function my\_module\_hook\_user\_update($edit, $account, $category) should have &$edit.

---
Tags: users, hooks
---


title: field_create_field enable chosen

text:
# Question
Title: field_create_field enable chosen
I am using field\_create\_field and field\_create\_instance to create a taxonomy\_autocomplete field in a rules action.

Can anyone help me enable chosen by default for these fields?

```
$vocab = '[vocabulary:machine-name]';

$field = array(
  'field_name' => 'field_termref_' . $vocab,
  'type' => 'taxonomy_term_reference',
  'settings' => array(
    'allowed_values' => array(
      array(
        'vocabulary' => $vocab,
        'parent' => 0
      ),
    ),
  ),
);
field_create_field($field);

$instance = array(
    'field_name' => 'field_termref_' . $vocab,
    'entity_type' => 'node',
    'label' => '[vocabulary:name]',
    'bundle' => 'product',
    'required' => false,
    'widget' => array(
        'type' => 'taxonomy_autocomplete'
    ),
    'display' => array(
        'default' => array('type' => 'hidden'),
        'teaser' => array('type' => 'hidden')
    )
);

field_create_instance($instance);

```

# Answer
> 0 votes
Using devels dpm function i managed to find the correct name of the setting, so the following now works...

```
$vocab = '[vocabulary:machine-name]';

$field = array(
  'field_name' => 'field_termref_' . $vocab,
  'type' => 'taxonomy_term_reference',
  'cardinality' => -1,
  'settings' => array(
    'allowed_values' => array(
      array(
        'vocabulary' => $vocab,
        'parent' => 0
      ),
    ),
  ),
);
field_create_field($field);

$instance = array(
    'field_name' => 'field_termref_' . $vocab,
    'entity_type' => 'node',
    'label' => '[vocabulary:name]',
    'bundle' => 'product',
    'required' => false,
    'widget' => array(
        'type' => 'options_select',
        'settings' => array(
           'apply_chosen' => 1
        )
    ),
    'display' => array(
        'default' => array('type' => 'hidden'),
        'teaser' => array('type' => 'hidden')
    )
);

```

---
Tags: 7, entities
---


# Question
Title: How to change Title field label and description for Custom Content Entity
I've created a custom content entity (generated via drupal console), I can add custom fields just fine via the cms.

What I'm try to do now is change the default label from 'Name' to 'Artwork Title'.

I've tried the following, but I'm not seeing the changes.

```
class EntryEntityForm extends ContentEntityForm {

      /**
       * {@inheritdoc}
       */
      public function buildForm(array $form, FormStateInterface $form_state) {
        $form = parent::buildForm($form, $form_state);

        $form['name']['widget']['#title'] = $this->t('Artwork Title');
        $form['name']['widget'][0]['#title'] = $this->t('Artwork Title');

        $entity = $this->entity;

        return $form;
      }
...
}

```

Can someone please point me in the right direction?

# Answer
> 8 votes
I managed to change the label using the following:

```
$form['name']['widget'][0]['value']['#title'] = $this->t('Artwork Title');

```

Hope this helps someone else.

---
Tags: 8, forms, entities
---


# Question
Title: Attach a particular profile2 form to user registration form
I have about 3 profile types each with their own registration path. But there's one without a path. I want to attach this to the main registration form. So that it shows when adding user on the main user add page but not other pages.

i got it to show with the code below but error when saving the user.

Recoverable fatal error: Argument 1 passed to profile2\_save() must be an instance of Profile, instance of ProfileType given,, called in C://....

```
function short_fixes_form_user_register_form_alter(&$form, &$form_state) {
  global $user;
  $current_user_role = in_array('family',$user->roles);
  $form['account']['status']['#access'] = FALSE ;
  if($_GET['q'] == 'admin/people/create' && $current_user_role){
      $form_state['profiles'] = array(
        'family' => profile2_get_types('family')
      );
      profile2_attach_form($form, $form_state);
    }
}

```

# Answer
try this,

```
$user_register_form = drupal_get_form('user_register_form');
$form_state['profiles'] = array(
'CUSTOM_PROFILE_TYPE_NAME' => profile2_get_types('CUSTOM_PROFILE_TYPE_NAME')
);
profile2_attach_form($user_register_form, $form_state);
print(drupal_render($user_register_form));

```
> 1 votes

---
Tags: 7, users
---


title: db_update not working as expected

text:
# Question
Title: db_update not working as expected
I am trying to develop a custom module; so far it works as it should. The only problem is I can't seem to get the MAC address to remain unchanged on update. It keeps getting the device ID number instead of the MAC field. How do I avoid the MAC address is changed?

```
function device_delete_request($uid = null, $macaddress, $device_id = null) {
  db_update('argon_user_stuff')
    ->fields(array(
      'id' => $device_id,
      'uid' => $uid,
      'macaddress' => $macaddress,
      'deletedmacaddress' => $macaddress,
      'updated' => REQUEST_TIME,
      'deleted' => REQUEST_TIME,
      'active' => 0
    ))
    ->condition('uid', $uid, '=')
    ->condition('id', $device_id, '=')
    ->execute();

    // Set the message and return to the user's profile page
    drupal_set_message('Device deleted');
    return drupal_goto("user/{$uid}/devices");

}

```

# Answer
Is that mac address is a required field? It may be possible mac address passing to this function not getting change, you may need to debug mac address before the function call.
> 0 votes

---
Tags: database
---


# Question
Title: What is the value of "Drupal user" in Drush status for?
What is the value of "Drupal user" in Drush status for? Suddenly, one of my websites lists the Drupal user as "anonymous" instead of blank, like the other environments. I noticed the change after pulling in code from the repo and the data from production, but it may have always been like that.

# Answer
> 1 votes
The value "Drupal user" is the user the Drush command is run as. You can supply a (valid) user name to any Drush command using `-u` \- for example `drush status -u admin`. Your implicit question, why did the status command suddenly report "anonymous" as the user, I can not answer. You would have examine the code you pulled - maybe something in the settings?

---
Tags: users, drush, staging
---


# Question
Title: How do I add multiple links in each table row form table?
I am new to drupal 8. I have created a form listing in admin.Now i want to add three or more links for operation(Edit/Delete/Suspend) in single TD columns. Can anyone let me know how to do this? I tried by concatenation two links but did not work. I am creating links as below.

```
$query = \Drupal::database()->select('vacations', 'v');
    $query->fields('v');
    $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
    $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
    //$results = $query->execute()->fetchAll();
    $results = $pager->execute();
    // Initialize an empty array
    $output = array();
// Next, loop through the $results array
    foreach ($results as $key => $result) {
      $approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
      $reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
      $newLink = $approve_link; // this works
      //$newLink = $approve_link . "|" . $reject_link; //this does not work it shows plain html in table columns
      $output[$result->id] = [
        //'id' => $result->id,
        'employee_name' => $result->employee_name,
        'employee_email' => $result->employee_email,
        'vacation_start_date' => $result->vacation_start_date,
        'vacation_end_date' => $result->vacation_end_date,
        'leave_days' => $result->leave_days,
        'status' => $result->status,
        'operations' => $newLink,
      ];
    }
    $form['table'] = [
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $output,
      '#empty' => t('No users found'),
    ];

```

I am using Drupal 8.

# Answer
After a long research i was able to acheive this as follows:

```
$approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
$reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
$mainLink = t('@linkApprove | @linkReject', array('@linkApprove' => $approve_link, '@linkReject' => $reject_link));

```

and then use $mainLink in foreach loop. Thanks for all your help.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: Updates for custom module not showing in update.php list
I've created a custom module for my Drupal 7 website, under `sites/all/modules/custom/tm_general` which has the following updates in the `tm_general.install` (please see image attached).

The site is being installed from scratch, meaning the DB is empty when installing. After installation, I have enabled the custom module through the UI.

The problem I'm encountering is that when visiting `mysite.local/update.php` the updates won't show up. It says `No pending updates.`

What am I missing?

Thanks a lot in advanced!

# Answer
> -1 votes
If you are freshly enabling the module, all updates will be applied by default. If you are upgrading that module from previous module to new one..then you will see those upgrade messages on /update.php

# Answer
> -1 votes
The 'system' table in your db contains the current "version" of modules, so I would check there first.

Also, if these modules are dependencies, you can just include them in your module.info (writing module .info files in Drupal 7) by simply adding

```
dependencies[] = devel
dependencies[] = views

```

and so on.

---
Tags: updating
---


# Question
Title: adding css classes into a specific image field
is there a way to add css classes **only** to specific image field?

with the image field name **field\_news\_images**:

```
<img class="thumbnail" src="../images/something.png"/>

```

There are no options to add the classes in the manage display

# Answer
> 3 votes
Add this code to your theme's template.php function:

```
function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_news_images') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['#item']['attributes']['class'][] = 'thumbnail';
    }
  }
}

```

Clear the cache.

# Answer
> 7 votes
As of Drupal 8.2

```
function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_news_images') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'thumbnail';
    }
  }
}

```

# Answer
> 0 votes
Field formatter module provides this functionality

1. This module allows site administrators to add classes to the outer HTML wrapper for any field display.
2. Classes can be specified at the Manage display settings for content types, users and other entities

---
Tags: media, theming
---


# Question
Title: How to display certain links in a menu only if a precondition is met?
I've added a checkbox to menu creation so that certain items in the menu will be displayed only if that checkbox is ticked (`For test user`).

That's the theory anyway.

How can I determine if that checkbox is ticked when displaying the menu on a page? I assume some hook is involved here, but I can't quite figure out which one.

Any nudging in the right direction is more than welcome.

# Answer
First of all you need to store value of 'For Test User' checkbox as variable OR as separate column in menu\_links table.

like variable\_set(url, checkbox\_value);

By using hook\_menu\_alter you can check the variable is set for that url. and if its not set you can set $items\['url'\]\['access callback'\] = FALSE, By setting this menu will not be visible.

Let me know if anything different required.
> 0 votes

---
Tags: 8
---


# Question
Title: Paragraphs Collection (Behavior plugins) vs. Field Group
I'm trying to build a site (or define site a building configuration), which allows editors to create their own layouts using the Paragraphs module. Powerful options for editors, reuseability across different projects and full control over the generated HTML are important.

There will be grid paragraphs to create the layout/structure containing content paragraphs for image, text, sliders, videos, accordions, etc. Most paragraphs will have "non-content" data like column width, background color, slider autoplay on/off, etc. So far I've found two ways the to handle the non-content part, but I'm unsure which is the better way to do it:

A) Use normal fields for non-content settings and Field Group to create finetune the editor interface. Use template preprocessing and/or Twig logic to create the desired frontend output. (Do frontend coding in a base theme to allow reuseability across different projects.)

B) Use the Plugin-system from Paragraphs Collection to create "behavior" plugins (code and YAML configuration) for non-content settings. Get the frontend stuff done with preprocessing in the module's code.

The collection plugin was created by the maintainers of the paragraphs plugin themselves, so B) is obviously *the way it should be done*. It also more clearly separates content from design/other stuff. However, I'm usually doing frontend coding, and while I'm used to PHP, I'm fairly new to Drupal, so A) would be the path I'm used to. Also the paragraphs behavior plugin is explicitly labelled as experimental and not ready for production use.

I'm looking for some hints from experienced Drupalers on which route to take, also concerning long term maintenance for many small sites (at least 4-5 years) and reuseability across different client projects.

# Answer
> 1 votes
As you stated, the Paragraphs Collection module should be considered Experimental, and not used in Production environments:

> THIS PROJECT IS EXPERIMENTAL. DO NOT USE IT IN PRODUCTION PROJECTS. THERE IS NO UPGRADE PATH UNTIL A BETA RELEASE.

This is especially true if your plan is to use this on multiple sites, with the life expectancy of 5 years.

The common method in Drupal 7, and currently in Drupal 8 is your first point, to use fields for settings and use preprocesses and/or twig templates to turn those fields into classes/markup you want.

For re-usability, you will either want to use the Features module and a base theme, or create your own module that will handle the config, templates and styling. I took that route with the Bootstrap Paragraphs module.

---
Tags: 8, entities, paragraphs
---


# Question
Title: 7 - Add classes to individual fields of paragraph bundle
Hi in paragraphs module for drupal 7, how can we assign classes/html tags to individual field items of paragraph bundle?

There is Classy Paragraph module that lets us to add classes to the paragraph wrapper/section. How to achieve the same for individual fields of paragraphs?

# Answer
Most people add another field, such as a select list with predefined options, and turn that into a class using a preprocess, or merge in the paragraph twig template. If don't have a predefined list, and you allow user input, you will need to sanitize the input.

How I do it in the twig template is like this:

```
{# Renders Width field. #}
{# Sets class name from values in database. #}
{% if content.bp_width|render %}
  {% set layout_width = content.bp_width['#items'].getString() %}
  {% set layout_width_classes = [
'paragraph--width--tiny' == layout_width ? 'paragraph--width--tiny',
'paragraph--width--narrow' == layout_width ? 'paragraph--width--narrow',
'paragraph--width--medium' == layout_width ? 'paragraph--width--medium',
'paragraph--width--wide' == layout_width ? 'paragraph--width--wide',
'paragraph--width--full' == layout_width ? 'paragraph--width--full',
  ]
  %}
{% endif %}

{# The template default set classes. #}
{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}

{# Merges Width field with classes. #}
{% set width_field = content.bp_width|render %}
{% if width_field %}
  {% set classes = classes|merge(layout_width_classes) %}
{% endif %}

{# Prints div with classes, and content without Width field. #}
<div{{ attributes.addClass(classes) }}>
  <div class="paragraph__column">
    {{ content|without('bp_width') }}
  </div>
</div>

```

How do the Bootstrap styles get added? Here is an excerpt from the LESS file:

```
.paragraph {
  .make-row();
  margin-left: 0;
  margin-right: 0;
}

.paragraph > .paragraph__column {
  .make-sm-column(12);
  .make-md-column(12);
  .make-lg-column(12);
  padding-bottom: @jumbotron-padding;
}

```

Which compiles into the following CSS:

```
.paragraph {
  margin-left: -15px;
  margin-right: -15px;
  margin-left: 0;
  margin-right: 0;
}
.paragraph > .paragraph__column {
  position: relative;
  min-height: 1px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 30px;
}

```

You can overwrite that in your theme if needed.
> 1 votes

---
Tags: 7, theming, entities, paragraphs
---


# Question
Title: What does "attach to content type" option in Feeds importer do?
I am struggling to find a clear explanation of what the "attach to content type" field in the basic settings of a Feeds importer actually does. The closest explanation I can find is from here:

> "Feeds importers" can be used attached to a content type or on standalone forms. If attached to a content type, an import (or aggregation) is created by creating a node. This is e. g. useful when you would like your users to contribute feeds or when you need to track many feeds of data of the same kind.Alternatively, a Feeds importer can be used on a standalone form. This is useful for one-off imports like importing nodes.

I don't understand what this explanation means. Would be grateful if someone could explain what setting this "attach to content type" option actually does.

# Answer
> 0 votes
Yeah - I found this confusing as well.

Personally, I always select "standalone" which means that when I'm ready to import nodes with an importer I've created, I go to the path /import (e.g., http://example.com/import)

On this screen, I can select my importer and then launch the actual import (the one I created under /structure/feeds).

If you decide to attach to a content type instead, it just means that you go to /content/add/\[content type\] to launch the import process rather than /import. This way just never made sense to me conceptually, but there are probably good reasons to use this approach. Probably depends on who (which roles) you want to be able to use feeds imports.

Anne

# Answer
> 0 votes
Basically it comes down to this:

* If you have one source to import: use the standalone import form. For example: a single CSV file.
* If you have multiple sources to import (all in the same data structure): attach to a content type. For example: several RSS feeds.

When attaching an importer to a content type it means that you need to create node of that type in order to import content. Since you can create multiple nodes of that type, you can import multiple sources this way.

Attaching an importer to a content type can also be useful if you want to allow your end users to import content. You could for example make use of node access to determine who may import what.

---
Tags: 7, feeds
---


title: Invalidate single block cache in D7

text:
# Question
Title: Invalidate single block cache in D7
I have a custom site-wide block that shows on all pages, which I would like to be heavily cached for anon users but able to be invalidated when I modify its settings, or en/disable it (both drupal variables set in an admin page).

I've managed to achieve this pretty nicely in D8 with `Cache::invalidateTags()`, as well as some custom Acquia stuff to invalidate the varnish cache. However in trying to port this same functionality to a D7 site I've not managed to find any good method of doing it.

Any help much appreciated, thanks in advance!

# Answer
You may have a look at Block Refresh, and implement your custom logic on top of it whenever you want to send a `Cache-Control: max-age=0` :

```
//Override external cache max age if set
  if (isset($settings[$block_id]['bypass_external_cache']) && $settings[$block_id]['bypass_external_cache'] != '') {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . intval($settings[$block_id]['bypass_external_cache']));
  }

```
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How to show results in entityreference autocomplete only after the user enters 5 characters
I want to know if it's possible to show result of an entityreference autocomplete only when the user enters 5 or 6 characters.

# Answer
> 1 votes
One way to do it is create your own custom autocomplete (a good example is here) in your custom module. Then within your custom autocomplete function check if the submitted autocomplete string is 5-6 chars long then execute the search, like so (using the example from the tutorial above):

```
function demo_autocomplete($text) {
  if (strlen($text) > 5) {
  // execute your code here:
    $results = array();
    ... etc
    drupal_json_output($results);
  }
}

```

---
Tags: 7
---


title: Using Services, request new password

text:
# Question
Title: Using Services, request new password
Tell me, how do I enter, via the module Services has, if I have "pass\_reset\_token" and then change the user password? How to password recovery. Tell me please! I'm desperate =(

# Answer
Services user update function internally calls Drupal's user\_account\_form function (via user\_profile\_form). In user\_account\_form, it's specifically looking for pass-reset-token as a $\_GET parameter, so to update password via Service, unfortunately you have to pass it as a GET parameter on a PUT call.

Example:

PUT https://drupal/:api-endpoint:/user/:uid:?pass-reset-token=:pass\_reset\_token: and the body is {"pass":":new-password"}.

If you wanted to be able to pass "pass\_reset\_token" as a parameter in the body, you could override \_user\_resource\_update so that it checks if the pass\_reset\_token parameter is present and puts it into $\_GET\['pass-reset-token'\] prior to calling user\_profile\_form.
> 2 votes

---
Tags: 7, services
---


# Question
Title: Best way to log clicks on a link of a custom content type
I have a custom content type (bundle, drupal 7) which has a link (rules link module) and I want to log the number of clicks on this link. At the moment I've an integer field in the bundle and I use rules to increment it and save the node every time the link is clicked. I think this method is not efficient and has also security implications so I ask you suggestions on how to do it better. I considered writing a small custom rule (module) which increment the value directly in the field table which probably would have less overhead but I think it would still not be very secure as I don't know how to handle a large number of clicks in a short time. Thanks for any help.

# Answer
> 1 votes
A possible alternative to "record the clicking of such link" is to use the Message module to create a message like so:

* Date = date the link was clicked.
* User target = the user who clicked the link.
* Message type = something like "Link of custom content type clicked".
* Message text = whatever you want and possibly using "Replacement tokens" to have any of the tokens that you have available in your rule also included in your message text (should you have any such need).

Since messages are entities, you could add any additional fields you may need to complete such custom logging.

With this approach, you've reduced your question to (eg) creating an appropriate view (and/or chart?) of all such messages that got created.

---
Tags: security, nodes
---


title: Adding ajax to a date field

text:
# Question
Title: Adding ajax to a date field
Anything I could find related to this question was for Drupal 7.

I am building a form that needs to perform a certain ajax function when a date is selected. I have built my form to work similarly to the "Form API Examples - Ajax Form Example" part of the Examples module.

To test, I set it up so that, like in the example, when this Select element is changed it triggers the function "dateCallback":

```
$form['dropdown'] = [
    '#title' => $this->t('Test'),
    '#type' => 'select',
    '#options' => ['option1' => '1', 'option2' => '2'],
    '#ajax' => [
        'callback' => '::dateCallback',
        'wrapper' => 'log-wrapper',
    ],
];

```

This executes perfectly.

However, when I try to set up a Date element to do the same function, nothing happens. No Ajax spinner, just nothing happens at all.

```
$form['date'] = array(
    '#type' => 'date',
    '#title' => t('Date'),
    '#ajax' => [
        'callback' => '::dateCallback',
        'wrapper' => 'log-wrapper',
    ],
);

```

It does not work even if I include `'event' => 'onchange'` in the `#ajax` array.

Is it possible to make ajax functions trigger on a changed date field?

# Answer
After some more searching I found a patch for this issue here: https://www.drupal.org/node/2781103

Seems to be working for me in Drupal 8.2.6. I did have to restart apache before it started to work, maybe a cache clear was all I needed for it though.

Not sure if I should accept this answer since it may become quickly outdated.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Having a field output custom markup when empty
So due to very rare use-case client issues, we've had to use a somewhat hacky solution to solve one of our goals. I am looking for a solution (hacky is fine) to solve one of the problems created by this solution. This is in Drupal 8 for reference.

I'll give the breakdown of where we are, and what sort of solution we're trying to achieve:

We needed to essentially duplicate the functionality of the menu system based on dynamic values on a given page, based on relevant field values. Occasionally, this would have to be done several times over.

To do this, we used a module that allowed us to place HTML elements inside the node display to wrapper several fields that would all be displayed inside this "menu", so that they'd have the proper menu markup.

We also created a custom display suite template to display each row properly (i.e. it contains the menu markup for each row) and we're using that as the field widget for each given field.

So it looks like this in the Manage Display page:

```
div
    ul
         FIELD (with the custom DS template widget)

```

**Here's the problem:**

We also need to have a couple of static links, based on the URL with some arbitrary additional pathing afterwards, which we're currently doing in the custom template (unfortunately with logic in the template).

Looks like this:

```
{% if element['#field_name'] == 'field_name_1' or element['#field_name'] == 'field_name_2' %}
    <li class="menu-item {{ element['#field_name'] }}" data-responsive-menu="accordion large-dropdown"><a href="{{ url('<current>') }}/url1" >Link1</a></li>
    <li class="menu-item {{ element['#field_name'] }}" data-responsive-menu="accordion large-dropdown"><a href="{{ url('<current>') }}/url2" >Link2</a></li>
    {%endif %}

```

The only problem is that since this requires a given field to have a value in it, and the links always need to be rendered, we want to know if there's a way to insert a value so that a specific field is never truly empty.

We were thinking of putting in `` for markup. How would we go about checking if a field is empty, and if so, inserting custom markup into it so that the template always renders the field?

We tried `HOOK_node_view_alter()`, but that gives us a render array that isn't particularly easy to traverse or modify (though maybe this is the solution, I'm not sure). We've tried putting in a

```
$build['#post_render'][] = 'MY_MODULE_node_post_render';

```

hook, but that seems to give us the HTML in a way that isn't easily changeable.

**So the question is - how do we put custom markup in an empty field to be displayed in a given entity view mode, but display the normal results of the field if there are results?**

# Answer
> 0 votes
This is what I eventually did to get it to work.

```
function MY_MODULE_entity_display_build_alter(&$build, $context) {
  $view_mode = $context['view_mode'];
  $object = $context['entity'];
  if (empty($build['field_machine_name']['#field_type'])) {
    $field = 'field_machine_name';
    $build['field_machine_name'] = global_events_faux_element($build, $field, $view_mode, $object);
  }
}

function MY_MODULE_faux_element($build, $field, $view_mode, $object) {
  $element = array(
    '#theme' => "field",
    '#title' => "Field Name Here",
    '#label_display' => "hidden",
    '#view_mode' => $view_mode,
    '#language' => "en",
    '#field_name' => $field,
    '#field_type' => "text_long",
    '#field_translatable' => FALSE,
    '#entity_type' => "node",
    '#bundle' => "bundle_name",
    '#formatter' => "smart_trim",
    '#is_multiple' => FALSE,
    '#object' => $object,
    '0' => array(
      '#markup' => "",
    ),
    '#weight' => 2,
  );
  return $element;
}

```

---
Tags: theming, 8, hooks
---


# Question
Title: Background Images Paths are Changed when CSS Aggregation is On
I have a Drupal 7 site with and Adaptives Themes subtheme enabled and set as default. I was recreating the Drupal 6 site in Drupal 7 on a subdomain and have recently transferred it over. My site has worked any problems until I turned on the aggregator for the CSS and JS files.

When my CSS files are compressed, the background images paths are not only absolute, `background-image: url(images/relative_to_CSS_file.png)` =\> `background-image: url(/subdomain/sites/all/themes/theme_name/css/images/relative_to_CSS_file.png)`, it adds the subdomain in the path. Instead, I would like to just remove the subdomain.

I have flushed the caches a few times, but this problem persists. How do I update these files?

# Answer
Thank you @jessehs from Drupal.org.

His solution, which worked for me, is the following:

> Long story short, the problem was that Adaptive Theme appears to be doing a "pre-caching caching" of the compiled CSS files in the sites/default/files/adaptivetheme/ directory.
>
> The way to get the aggregated files to actually build is to clear all caches and immediately save the theme's settings form at /admin/appearance/settings/\[themename\], then do another cache clear, just for good measure.

Also included at the source is a helper module that will flush these files when you flush the cache.

Source: https://www.drupal.org/node/1995938
> 1 votes

---
Tags: css-js-aggregation, theming
---


# Question
Title: How do I vary PathAuto paths based on a field?
I have a field type called "Venue". If the Venue is in the US, I want the path to be:

```
/CITY/my-venue

```

But if it's in any other country, the path must be:

```
/AU/CITY/my-venue

```

In other words, non-US venues must get their country code appended to the front.

Is this even possible with the current PathAuto module? Or how can one do this?

# Answer
> 2 votes
The easiest approach is to define a custom token using hook\_token\_info() and hook\_tokens(). Based on the venue, you either return the country code or nothing. If the token has no value, pathauto will automatically clean it up and drop that part.

Pathauto tokens for taxonomy terms except root for example has some hints on how to implement custom tokens.

# Answer
> -1 votes
> Follow these steps (first enable token module):
>
> 1. go to Configuration \> Search and metadata \> URL aliases \> Patterns
> 2. select "Pattern type" as "content"
> 3. Add "Path pattern" (Click on "Browse available tokens" and select fields from token list.)
> 4. You can choose " Content type"
> 5. Add label. 6 Save.

---
Tags: 8, path-aliases
---


title: Aggregation CSS loads old files

text:
# Question
Title: Aggregation CSS loads old files
I'm a little exhausted and don't know where to look anymore.

After checking "aggregate and compress CSS-Files" it seems that Drupal is loading old files.

So far I tried:

* Clearing Cache (of course)
* Deleting the aggregated files from "sites/default/files/css"
* Reloading page to re-aggregate the css files

Unfortunately Drupal is still loading the old files.

Where is Drupal getting these old files from and how to delete or refresh them?

# Answer
> 1 votes
These aggregated CSS and JS files are generated by `drupal_build_css_cache()` and `drupal_build_js_cache()` functions when the hash of the content changes (based on the *sha256*).

If clearing cache didn't help, to force removal of cached files, you can remove the following variables: `drupal_css_cache_files`, `drupal_js_cache_files`.

Using drush, it's:

```
drush -y vdel drupal_css_cache_files && drush -y vdel drupal_js_cache_files

```

See also: Aggregated CSS/JS file names, when regenerated?

---

Other thing to check is `drupal_stale_file_threshold` variable which may prevent removing the old files via drupal\_delete\_file\_if\_stale(), if it's set to high.

Read more at `drupal_build_css_cache()` API docs page:

> The cache file name is retrieved on a page load via a lookup variable that contains an associative array. The array key is the hash of the file names in `$css` while the value is the cache file name. The cache file is generated in two cases. First, **if there is no file name value for the key, which will happen if a new file name has been added to `$css` or after the lookup variable is emptied** to force a rebuild of the cache. Second, **the cache file is generated if it is missing on disk**. **Old cache files are not deleted immediately** when the lookup variable is emptied, but are **deleted after a set period** by `drupal_delete_file_if_stale()`. This ensures that files referenced by a cached page will still be available.

# Answer
> 1 votes
Try flushing the cache, saving your theme settings, and flush them again.

Some themes, such as Adaptive Themes, still keeps some files that aren't flushed until the themes settings are saved.

I discovered it here.

You could also try AdvAggr. Thank you @mikeytown2!

---
Tags: 7, theming, css-js-aggregation
---


# Question
Title: Headless Drupal 8 - cookie authentication
I am successfully using a headless Drupal 8 setup that I am querying through Drupal 8 core REST API with basic auth from jQuery AJAX. Now I need to get closer to production conditions, so I started trying to use cookie-based authentication. Problem is that the exact same query that successfully POSTed content using basic auth now returns an HTTP 403.

Is there any working example of a POST request to create an article with cookie authentication? Am I missing something?

I have a fresh Drupal 8.3.1 install with REST UI, Serialization and HAL modules enabled. The REST endpoints are configured through REST UI. The */node/{node}* endpoint is set up to allow all requests in all formats with cookie auth. Taxonomy and user endpoints are configured likewise. The queries (POST & GET) to REST API are made from AJAX calls from jQuery. These queries work fine with basic auth. This is a query example.

```
$.ajax({
      url: 'my_drupal/entity/node?_format=hal_json&foo=bar,
      method: 'POST',
      headers: {
        'Content-Type': 'application/hal+json',
        'X-CSRF-Token': csrfToken, // I got that token by first GETting my_drupal/rest/session/token
        'Authorization': 'Basic ' + btoa(this.credentials)
      },
      data: JSON.stringify(node),
      success: function (node) {
         // success logic here
      }
    });

```

Please note that I already tried removing the *Authorization* header with no luck.

Monitoring HTTP requests, I do see the Drupal authentication cookie being sent along with my POST request.

# Answer
> 4 votes
It looks like maybe you are not successfully retrieving the CSRF token. The CSRF token can be retrieved from `/rest/session/token`.

See https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities for examples on POSTing to core entity endpoints.

# Answer
> 4 votes
> the 403 error comes with a message saying "Authentication method not allowed on this route"

OK, so it appears that route may not support the cookie authentication method, by default.

For example, https://api.drupal.org/api/drupal/core%21modules%21rest%21config%21optional%21rest.resource.entity.node.yml/8.2.x \> View source

```
langcode: en
status: true
dependencies:
  module:
    - basic_auth
    - hal
    - node
id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
  methods:
    - GET
    - POST
    - PATCH
    - DELETE
  formats:
    - hal_json
  authentication:
    - basic_auth

```

You will need to extend or alter the node resource POST config in *rest.resource.entity.node.yml* to ensure the "cookie" method is enabled in `supported_auth`

e.g: Configure in admin UI

More info: https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview \> "Drupal 8.2 & Later"

---
Tags: 8, cookies
---