# Question
Title: What services must I leave switched on in Elysia cron
I have installed Elysia Cron to import some Feeds data periodically. However, I have switched off all the other cron tabs that I have in order not to interfere. However, my database size grows to ten times the size as when the cron was switched on without Elysia cron.

Must I switched them on and with what periodicity?

# Answer
Elysia cron is just an improved durpal cron service. You must have enabled the services you have enabled by deafualt in the standard Drupal cron. Some of them, for example, remove temporal data from the database (probably the reason your database is growing).

So, yes, you must have the services enabled, and those are the services enabled byu default by Drupal. Obviously the exact services that must be turned on depends on each installation.
> 1 votes

---
Tags: 7, database, cron
---


# Question
Title: How can I add a custom attribute to a link field?
For analytics/tracking purposes, I would like to add a custom attribute to a link field. Is there a way to add an additional text field to the link, similar to the title attribute field?

# Answer
On Drupal 7 there are several ways to go about this depending on your setup.

If you are using Display Suite you can add custom attributes to the link field (and all the various wrappers) by setting the field template to Expert:

You could also use `template_preprocess_field()` in a module or your theme to add additional attributes to the link before it is rendered.

Display Suite is more limiting but often easier (particullarly if it is already in use). Since the preprocess function is in PHP it will give you more flexibility that may or may not be useful.
> 3 votes

---
Tags: 7, nodes, entities, navigation
---


# Question
Title: How do I add attributes to an entity reference field?
Let's say we have a RECIPE content type that has a multi-value entity reference field to a FOOD content type, so as to represent the ingredients.

Each ingredient on a recipe needs to hold a quantity (eg: '1 cup') in addition to the reference itself. How can we add that attribute?

We'd like to avoid having an additional entity to hold the relationship for performance reasons. Also, sticking to core's entity reference field seems a good idea so the rest of the ecosystem can recognize the relationship.

# Answer
The best and standard way to do this is with paragraphs.

Enable the paragraphs module, then add a paragraph type called ingredient with the two fields, an entity reference field and a field for the quantity.

if you want an ingredient to be reusable, keep in mind that paragraphs are not reusable. If you want to reuse an ingredient, say "1 cup flour", then you could use an entity reference field to another reusable entity type, such as media or taxonomy, or another node type.
> 5 votes

---
Tags: 8, entities
---


title: Should I create a role for every user?

text:
# Question
Title: Should I create a role for every user?
On Drupal 7 I have tested many modules, because I simply want in the user view some fields which are public and others can only see friends (user relationship or flag friend, ...). would be nice if I had a fieldgroup 'open' and 'friends' with the correct permission.

Because it is not running yet, I want by register a new user creating and assign a role named role\_userID. These I want do with a rule but I can't do it... After this I can give every friend of this person his role, that they can see the fields.

Or is not a good idea? How can I do that? Thanks Thomy

# Answer
> 3 votes
I seem to understand that for every user with "uid" = "userID", you want to create 1 role like "role\_userId" ... That means if you have dozens of users (only), you have dozens of roles. Not to mention that you have hundreds (or thousands?) of users if you'd have hundreds (or thousands?) of roles ... IMO that ***is not a good idea***. I'm not sure what exactly you're up to with that "*user view some fields which are public and others can only see friends (user relationship or flag friend, ...)*", as in your question, but it does seem to be related to access permission somehow.

Have a look at the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

In your case you could have 1 Group "**Type**" (eg: "User Groups"?), and create 1 group for each user. Think of a ***Group Type*** as equivalent to a Content Type, and a ***Group*** (of a specific Group type) as equivalent to a node of a specific Content Type). You'd probably come close to having something with a 1-to-1 relationship between a specific user and Group permissions related to that user (whereas Group permissions is not the same as standard Drupal permissions ...).

Also, since Group is fully entity based, it integrates perfectly with Rules also. With that in mind, you could use Rules to capture Rules Events about ***user relationship*** or ***flag friend*** (as in your question), and then trigger Rules Actions to manage various access levels to the Group designated to that user. Important to realize: you wouldn't need like dozens (or hundreds/thousands?) of "roles".

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources

---
Tags: 7, entities, users
---


# Question
Title: Drupal node "ranking" based on views sorting
I am creating a site where there are nodes (which are "causes") that users can donate to (i.e. buying a donation product using Drupal Commerce, which is sort of irrelevant, but just for the record).

I would like to display a "ranking" on each node based on how much money has been donated to that cause. It will be output something like "Rank: 50 out of 210".

My question is: *What is the best way to do this?*

I know how I could create a view and sort it by the criteria that I'm wanting, but then how to display on a node the index from the view... ? I don't know how to do that.

I've thought about figuring out a way to use Rules to assign a value to a field in the node whenever a donation is made... ? That might be a decent bet.

If anyone has any direction for me on this, I'd really appreciate it.

# Answer
No need to make things that difficult; Views supports a field that display the sort index. It's labeled ***Global: View result counter***.

It won't get you total results, but you can put that information in the header/footer with the ***Global: Result summary*** field.
> 0 votes

# Answer
Ranking gave me some headaches too (user ranking). What I ended up doing was:

1) creating a Views VBO list (shows the ranking in the order I need), 2) sent it to Rules and load the list (load a list of entity ids from VBO action) 3) and loop through it. Within the loop I added an INT counter variable. This variable sets the value of the ranking field on the user profile. The counter is increased by 1 at the end of the loop.

The rule is executed on cron (so the changes in the ranking are only then visible). I just could not figure out a better way but it works for me.
> 0 votes

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


# Question
Title: How to check if search_index's solr is running?
To prevent fatal errors, I need to check if solr is running.

Given:

```
$solrIndex = \Drupal::entityTypeManager()
  ->getStorage('search_api_index')
  ->load('global');

```

How do I check if the solr server that $solrIndex is pointing to is online?

There is an -\>isAvailable() method on the server object when you call the $index's -\>getServerInstance() method, but it returns a false positive when the solr server is stopped:

I'm surprised I can't check it from the server object, but this returns a false positive when solr is stopped:

```
$false_positive = $solrIndex->getServerInstance()->isAvailable();

```

# Answer
> 3 votes
The SolrConnector plugin provides a `pingServer()` function that will determine it the endpoint can be accessed, so to really test it you likely need to be able to call that.

I'd first check to see if there is an abled server by calling `$solrIndex->isServerEnabled()`.

Then I'd get the server, its backend, the connector, and run the ping:

```
$server = $solrIndex->getServerInstance();
$backend = $server->getBackend();
$connector = $backend->getSolrConnector();
$response = $connector->pingServer();

```

or just

```
if( $solrIndex->getServerInstance()->getBackend()->getSolrConnector()->pingServer() ){
  // Yup
}
else {
 // nope
}

```

The return value from `pingServer()` is:

> The latency in milliseconds if the core can be accessed, otherwise FALSE.

# Answer
> 1 votes
I was able to check if the server is up this way:

```
$solrConnector = $solrIndex
  ->getServerInstance()
  ->getBackend()
  ->getSolrConnector();

$solr_status = ($solrConnector->pingServer() !== FALSE);

if (!$solr_status) {
  // handle Solr being unavailable
}

```

---
Tags: 8, search
---


# Question
Title: where does $data come from in hook_tokens?
In a custom module i have hook\_tokens() implemented in order to create some custom tokens. What i realized is that some data is being declared as null but i don't know where this is happening. These values are coming from user input in a submitted web form. input from traditional web form fields do appear but input added through payment method fields are the ones appearing as null.

this is a small snip of what var\_dump($data) shows:

```
$data['webform-submission']->payments[34]->contextObj->submission->data[47][0]"August"
$data['webform-submission']->payments[34]->contextObj->submission->data[46]array[1]
$data['webform-submission']->payments[34]->contextObj->submission->data[46][0]"1"
$data['webform-submission']->payments[34]->contextObj->submission->data[16]array[1]
$data['webform-submission']->payments[34]->contextObj->submission->data[16][0]null
$data['webform-submission']->payments[34]->contextObj->submission->data[35]array[1]

```

EDIT:

Thanks for the clarification on where $data comes from. I also realized that the hook i created (hook\_token\_info) is not being utilized. When i create a token i do not see it listed under Browse available tokens when i edit emails templates under the web form tab. Oddly hook\_tokens is being called when i pass token\_alter('\[submission:custom:card\_type\]', array('submission'=\>$card\_type)) however the token is empty.

# Answer
> 1 votes
The `$data` is whatever is originally passed to the `token_replace` function by the process that's doing the token replacement.

The var itself is:

> An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.

It's essentially just an array that's used to pass extra context to the token replacement, and it can contain anything at all.

For example if you were writing a module that introduced a custom entity type, you could use this feature to pass an instance of that type in to be used in your own tokens.

In your specific case, it's presumably the Webform module that prepares that data array, so that would be where to look if something's missing. Or it could be a submodule if that's what you've used to provide the payment fields themselves.

---
Tags: 7, webforms, tokens, payment-gateways
---


# Question
Title: How to find Image URI in Kint via .entity in the node tree
I am working on Drupal 8 finally and using the replacement for Krumo which is Kint. It packs a lot more information in than Krumo did, and came with a bit of confusion.

While trying to get the image uri of an image that was rendered via a content type, the uri was not listed. I did however find an answer here Get Image URL in Twig .

And I saw that my reference needed `.entity.uri.value` prepended to it. This worked, but after further inspection of my node tree in kint I could not find anything the led to .entity as a reference. So how do I found out what to appended to my node tree reference if it is not listed?

# Answer
Every image in Drupal 8 is a file entity.

You can try in `template_preprocess_node()`:

```
$image_file_id = $variables['node']->field_image[0]->target_id;
$image_file = \Drupal\file\Entity\File::load($image_file_id);
$uri = $image_file->uri->value;

```
> 1 votes

---
Tags: theming, media, uri
---


# Question
Title: How do I make block only visible if the 'field_date_value' is in the past?
What code do I use on a D7 website if I want a block only to be visible if the `field_date_value` of a date node is in the past?

On a D6 site, I had this working for all date nodes:

```
$match = FALSE;
$types = array('date' => 1);
if (arg(0) == 'node' && is_numeric(arg(1) )) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type])) {
    $match = TRUE;
  }
}
return $match;

```

But this code does not work on a D7 site. Besides, all that I want is it to only show a date node when the date in the past. (For a past event.)

# Answer
Pretend you need a block to be visible on a node depending on the value of a date field on the node.

A good example is a website that lists classes as nodes. You want a block visible only on class nodes. You also only want that block visible if the date of the class is in the future.

The classes are created by making nodes of a custom content type called "class". Each class node contains an date field called "class\_date" that contains the date of the first day of the class. The date field is a regular ISO date field type. This PHP snippet returns TRUE if the node is a "class" and the "class\_date" field is in the future and the block is then visible.

```
<?php
$node = menu_get_object();
if ( !empty($node)  && $node->type == 'class' ) {
  if ( !empty($node->field_class_date) && !empty($node->field_class_date['und']) && !empty($node->field_class_date['und'][0]) ) {
     $parts = explode('T', $node->field_class_date['und'][0]['value']);
     $date_parts =  explode('-', $parts[0]);
     $class_date = $date_parts[1] . '/' . $date_parts[2] . '/' . $date_parts[0] . ' ' .  $parts[1];
     $on = strtotime($class_date);
     $now = time();
     if ( $on >= $now ) {
        return TRUE;
     }
  }
}
return FALSE;
?>

```
> 0 votes

# Answer
You could try to use the Rules block visibility module instead. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "perform validations similar to the logic included in the code shown in your question".

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
> 0 votes

---
Tags: 7, entities, datetime
---


# Question
Title: How to get content language abbreviation ("en" instead of "English") in a View?
Im trying to get the content language abbreviation in a view, when I select "content: Language" field then it shows me "English" but I need to get its abbreviation "en", I though there was an option in the view field but there isn't.

# Answer
Assuming this is the language of a node. It should actually be stored in the database as `en`, `es`, etc and then being rendered.

To get the content from the database without it being rendered here are the steps.

* Go to your view. Here's a sample one I'm using:
* Check the `Information` link on the bottom right hand side.

* When you click it, you should see a screen like so:

* Here my two fields are listed as well as two other parts of the view where different things are occurring.
The names on the right hand side are different overrides you can implement to intercept the process of generating the display. Depending on the name is the precedence. The further a name, the more specific it is.
* Now, you need to decide how specific you want your change to be. I think using something like `views-view-field--testlang--language.tpl.php` is good. In my example, *testlang* is the name of the view and *language* the name of the field.
* Click on the link next to the name of the field you want to override. It might be something like `Field Content: Language (ID: language):`. Once you have this, copy the content it's showing you.

Now that you have the name and the content of the field, go to your theme and create a file with the name you selected. If you have a `templates` folder on your theme, put it there.

Paste the code that your website generated for you,

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

```

And now you modify it.

At the top you can see that you have the following variables available: `$view`, `$field`, `$row`, `$output`. The `$row` variable is the SQL result.
This is why I asked where you how it's stored on the database. I'm assuming up to now, we are using a node's language.

Well, if you take that `<?php print $output; ?>` and change it for `<?php var_dump($row); ?>`, it will give you the result from the database. If now you go to where you view is shown, or to the preview, you should see a line with something similar to:

`object(stdClass)[94]
 public 'node_title' => string 'Consequat Nostrud Occuro Quadrum' (length=32)
 public 'nid' => string '26' (length=2)
 public 'node_language' => string 'es' (length=2)
 public 'node_created' => string '1479304373' (length=10)`.

Now, if you change your line to: `<?php print $row->node_language; ?>`, it should print the value as it's stored in the database in 2 letter country codes.

Good luck! Hope this helps.
> 2 votes

---
Tags: 7, views, i18n-l10n
---


title: Send base URL for my custom block

text:
# Question
Title: Send base URL for my custom block
In my Drupal 8 site, I am developing a custom block in my module custom, with some text and some images. I created a template, and everything works fine. Now I need to add some images for my custom block, and I don't know how to pass the base URL to call those images.

In Drupal 7 I used the following code.

```
function bloques_block_view($delta = '') {
    $block = array();

    $ruta = $GLOBALS['base_url'] . '/' . drupal_get_path("module", "mymodule");
    $link = $GLOBALS['base_url'] ;

  switch ($delta) {

//footer
    case 'footer':
      $block['subject'] = '';
      $block['content'] = leer_template('footer.tpl', array('%ruta%' => $ruta, '%link%' => $link));
      break;
  }
  return $block;
}

```

Everything works well, but in Drupal 8 it is a little different. The problem comes with `build()`.

```
    public function build() {
    $ruta = 'holamundo',
    return array(
        '#theme' => 'mymodule',
        '#title' => 'my title ',
        '#ruta' => '<p>' . $ruta . '</p>'
    );

```

}

Just the title works in the template file; `$ruta` is not working.

```
  <h2>My Custom Block {{ title }}-{{ ruta }}</h2>

```

I don't know if this is the correct way to declare the base URL (just like I did in Drupal 7).

```
  $ruta = $GLOBALS['base_url'] . '/' . drupal_get_path("module", "bloques");

```

# Answer
You can try template\_preprocess\_block(&$variables). There is a global $base\_url variable. Create variable for block template:

```
function your_module_preprocess_block(&$variables){
  global $base_url;
  $variables['base_url'] = $base_url;

}

```

Now you can use {{base\_url}} in twig template of your block.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Let anonymous view dpm() when using Omega subtheme
I need to debug a D7 site from the anonymous user. What settings need to be changed to allow anonymous to view dsm(), dpm(), krumo(), etc. commands?

Note: I have already enabled `Access developer information` under the Devel module for all roles.

# Answer
> 0 votes
The Omega custom child theme was blocking messages from being printed.

Excerpt from zone--content.tpl.php:

```
<!-- zone--content.tpl.php -->
<?php if ($wrapper): ?><div<?php print $attributes; ?>><?php endif; ?>
  <div<?php print $content_attributes; ?>>
    <?php if ($breadcrumb && 0): // DISABLED! ?>
      <div id="breadcrumb" class="grid-<?php print $columns; ?>"><?php print $breadcrumb; ?></div>
    <?php endif; ?>
    <?php if ($messages && $is_admin): ?>
      <div id="messages" class="grid-<?php print $columns; ?>"><?php print $messages; ?></div>
    <?php endif; ?>
    <?php print $content; ?>
  </div>
<?php if ($wrapper): ?></div><?php endif; ?>

```

Note the `if ($messages && $is_admin)` statement.

This is the correct answer for this particular case despite the lack of information provided in the initial question. Though the other answers provided are relevant and highly informative, this answer is selected to help future users troubleshoot.

Thanks everyone for your help!

# Answer
> 13 votes
Give them `Access developer information` permission at `admin/people/permissions`.

Note that this opens a huge security risk so make sure you revoke it when you are done with debugging.

# Answer
> 2 votes
To use `drupal_set_message()` for anonymous user, you need to have a `uid= 0` in `users` table. Check in your users table with uid=0 record exists. If not create a user with `uid = 0;` Also, check here

# Answer
> 0 votes
If you have given the Access developer information permission to anon. user, make sure that the page you are accessing does not have any missing resources: images or anything that would result in status 404 being returned by the server.

While generating 404 response, the server calls `drupal_get_messages()` which effectively clears the Drupal message queue, resulting in `$messages` variable being empty when rendered in page.tpl.php .

# Answer
> 0 votes
Probably someone needs to debug a variable right away and want to have something like DPM for ONE particular anonymous user without giving the "Access developer information" to ALL anonymous users (which is a dangerous thing in production environment), then you can do this:

```
  if ($some_condition_is_true) {
      has_krumo();
      drupal_set_message(krumo_ob($my_var));
  }

```

Hope that helps!

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


# Question
Title: Can I redirect the user to some other page if the result of a view is empty?
How do I redirect the user to some other page, when the view returns empty result?

# Answer
> 10 votes
In your views **No results behavior** Choose ' Global: Text area ' choose php filter and add the following code.

```
<?php
 drupal_goto('node/1'); //path to redirect
?>

```

# Answer
> 3 votes
Better yet do it in your views-view.tpl.php and avoid using PHP in UI like.

```
  <?php if ($rows): ?>
    <div class="view-content">
      <?php print $rows; ?>
    </div>
  <?php elseif ($empty): ?>
    <div class="view-empty">
      <?php drupal_goto('some_page'); ?>
    </div>
  <?php endif; ?>

```

if you want to pass query to new url use this for goto

```
drupal_goto('your_url', array('query'=>array(
'variable_name1'=>'variable_value1',
'variable_name2'=>'variable_value2',
'variable_name3'=>'variable_value3',
...... ...
)));

```

or if you want to goto an anchor on page use this

```
drupal_goto("node", array('fragment' => $node->nid));

```

---
Tags: 7, views, redirection
---


# Question
Title: Creating a view that shows multipule blocks containing content with filtered by differnt taxonomy terms
Im looking to create some pages that contain blocks of content based on a separate taxonomy term for each block.

Right now i created a separate block view for each taxonomy term, and added each view into its own block on the block administration page. (http://cs.scottrlarson.com/services) It works, but I want to have more control over the container of the set of blocks as a whole so I can style the blocks in a flexbox. I wondered if there was a way to create a view that had different blocks filtered by taxonomy terms for each block that way I could set a style name for the container of the blocks allowing me to use flexbox styles.

If anyone has a better way to do this please let me know. Thanks.

# Answer
You could make a parent `block` view that has all of the subsequent views as `attachment` display type. Or add the other views in the footer of your first view...
> 0 votes

---
Tags: views, theming
---


# Question
Title: "Drush sqlc < myfile.sql" doesn't return the site to previously working state. Are there files to be deleted?
I've backed up my drupal 8 database via the CLI using `drush sql-dump > myfile.sql`.

I make some changes to the site and break it, then I try to restore it via `drush sqlc < myfile.sql`.

It works for a bit, until I click something and it messes up again as if there was something written to the files causing it and it is not just the database alone that is the culprit. I get this error:

> The website encountered an unexpected error. Please try again later.

A totally vague error as I'm not sure what is causing it.

Are there any files that are written to the Drupal directory that has to be deleted as well when doing a `drush sqlc < myfile.sql` restore?

# Answer
> 3 votes
> The website encountered an unexpected error. Please try again later.

There was an error on PHP that Drupal couldn't handle.

---

If you have your install set to log errors, check the report.

Another option, on your `settings.php` add:

```
$config['system.logging']['error_level'] = 'verbose';

```

To show the errors.

# Answer
> 3 votes
All `drush sqlc` does is apply the `mysqldump` to your database. If the target has tables that are not known of by the source those tables will not be dropped by the dump file before being replaced.

You should **take a backup**, then run `drush sql-drop` first, clearing the way for your replacement database.

For example,

```
drush sql-dump > /location/to/backup-file
drush sql-drop
drush sql-cli < /location/of/myfile.sql

```

---
Tags: 8, database, configuration, backups
---


# Question
Title: Showing the description for the term identified by the argument in the Taxonomy Term view
I have a view that is a clone of the Taxonomy Terms default view, it has the depth modifier turned on. I would like to provide the description field for the taxonomy that has been loaded in the header if it exists. I'm using this with pathauto, so while the actual url may be something like /pub/by/geo-area/ethiopia, views gets the tid (lets say 3046) as the argument.

How can I then put the description field from that taxonomy term into the header of the view? I tried creating a relationship for the taxonomy term content, but since I don't know at the time of creating the view what vocabulary the term will be from, and because it is possible that there will be multiple terms for that vocabulary attached to some of the nodes, that doesn't seem to be workable.

I considered an attachment, but I'm not sure how I could pull that off either. Can I do this without an extra module?

# Answer
> 2 votes
> I want the description for the term coming in via the contextual filter argument

Ok then,

1) Create a new view

* **Show:** Taxonomy Terms.
* ☑ Create a Block
    + **Display format:** Unformated list **of** Fields

2) Save and Continue.

* Add the Contextual Filter.
* Add the description field.

3) Go back to your other view and attach view to header.

---
Tags: 7, views
---


# Question
Title: Load Javascript code within iframe of Article edit
I am trying to enhance a module CKEditor Responsive Plugin. I am basically looking to make the adjacent divs of equal heights by running a javascript code, this is the code:

```
/* From: https://codepen.io/micahgodbolt/pen/FgqLc */
/* Thanks to CSS Tricks for pointing out this bit of jQuery
http://css-tricks.com/equal-height-blocks-in-rows/
It's been modified into a function called at page load and then each time the page is resized. One large modification was to remove the set height before each new calculation. */

(function ($) {
 equalheight = function(container){

 var currentTallest = 0,
 currentRowStart = 0,
 rowDivs = new Array(),
 $el,
 topPosition = 0;
 $(container).each(function() {

                   $el = $(this);
                   $($el).height('auto')
                   topPostion = $el.position().top;

                   if (currentRowStart != topPostion) {
                   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
                   rowDivs[currentDiv].height(currentTallest);
                   }
                   rowDivs.length = 0; // empty the array
                   currentRowStart = topPostion;
                   currentTallest = $el.height();
                   rowDivs.push($el);
                   } else {
                   rowDivs.push($el);
                   currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
                   }
                   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
                   rowDivs[currentDiv].height(currentTallest);
                   }
                   });
 }

 $(document).load(function() {
                  equalheight('.equal_heights');
                  });

 $(window).resize(function(){
                  equalheight('.equal_heights');
                  });
})(jQuery);

```

I am loading this into the module using the following line:

```
// Raj:
  drupal_add_js(drupal_get_path('module', 'ckeditor_responsive_plugin') . '/js/equal_heights.js');

```

in the `.module` file `ckeditor_responsive_plugin.module`:

```
<?php
/**
 * @file
 * Hooks implementations.
 */

/**
 * Add the basepath to the Drupal.settings js object.
 * Implements hook_page_build().
 *
 * @param array $page
 *    Page array.
 */
function ckeditor_responsive_plugin_page_build(array &$page) {

  $module_base_path = url( drupal_get_path('module', 'ckeditor_responsive_plugin'),
    array(
      'absolute'=>true,
    )
  );

  $my_settings = array(
    'basePath' => $module_base_path,
  );
  drupal_add_js(array('ckeditor_responsive_plugin' => $my_settings), 'setting');

// Raj:
  drupal_add_js(drupal_get_path('module', 'ckeditor_responsive_plugin') . '/js/equal_heights.js');
}

/**
 * Define the CKEditor plugin.
 * Implements hook_ckeditor_plugin().
 *
 * @return array
 *   CKEditor settings.
 */
function ckeditor_responsive_plugin_ckeditor_plugin() {
  return array(
    'responsivness' => array(
      'name' => 'responsivness',
      'desc' => t('CKEditor Responsive Plugin : Allow to insert responsive areas'),
      'path' => drupal_get_path('module', 'ckeditor_responsive_plugin') . '/responsivness/',
      'buttons' => array(
        'responsivness' => array(
          'icon' => 'images/responsivness.png',
          'label' => t('Add responsive area'),
        ),
      ),
    ),
  );
}

```

Everything is working in the article view, however, when I "edit" the article, the article contents are loaded into iframe and that is where things start breaking.

Live article view:  `equal_heights` is the class on which the height is explicitly set by javascript.

Now, when user tries to edit it, the whole article related HTML is loaded as an iframe and as a result, I think, the javascript is not able to get the elements within the iframe. This is what is happening:

I have set a red background for the `equal_heights` divs to show the difference in both mode.

I suspect that there has to be a hook like:

```
function ckeditor_responsive_plugin_page_build(array &$page)

```

which will help me load the javascript for edit mode, but I am not able to figure it out.

Looking forward for some help and advices.

# Answer
> 1 votes
Your JS code needs to access the CKEDITOR iframe. How?

```
// some code to grab the element with the CKEditor iframe
// [0] is use to get the element, not the jQuery wrapper...
var CKEDITORiframeDOM = jQuery('.cke_contents iframe')[0].contentDocument

```

With CKEDITORiframeDOM you can access all the elements on the iframe... and use jQuery too.

```
var $CKEDITORiframe = jQuery(CKEDITORiframeDOM);

```

Now to find an element in your iframe is simple...

```
console.log($CKEDITORiframe.find('p').text());

```

Finally you need to write a bit of JS code in order to make your script work also with the elements inside the iframe.

Hope that helps!

PD: In some browsers you will need to use document instead of contentDocument.

PD2: Want more info about iframe access with JS? See https://stackoverflow.com/questions/1451208/access-iframe-elements-in-javascript

---
Tags: 7, wysiwyg, theming, javascript
---


title: How to use image URL in custom Views?

text:
# Question
Title: How to use image URL in custom Views?
I use the Image URL Formatter module for my custom Views. The Views settings look like so:

### Setting field:

### Setting custom text:

This is the result I get:

### Inspect html

```
<div class="views-field views-field-nothing"><span class="field-content">
<div>
http://example.com/sites/default/files/color-placeholder/team-1.jpg
)">
  <ul class="social-team"><li><a class="fa fa-facebook" href="#"></a></li>
    <li><a class="fa fa-instagram" href="#"></a></li>
    <li><a class="fa fa-twitter" href="#"></a></li>
    <li><a class="fa fa-github" href="#"></a></li>
    </ul>
  <a href="/md8/features/kate-benke" hreflang="en">Kate Benke</a>
  Back-End Developer
</div>
</span></div>

```

How should I correct my config to use mage URL?

Note: I don't want override template.

# Answer
Views field strips out `<div style="..">` tag. To add background image you need to follow below steps:

1. Add global custom field into view header and put below code.

> ```
> <style type="text/css">
>     .background-img {
>       background: url('{{ field_photo_team }}');
>     }
> </style>
>
> ```

2. Now assign ***background-img*** class to **Global :Custom text** field like

.

```
<div class="background-img">
{{ field_social }}
{{ title}}
{{ field_profession_team }}
</div>

```

> Note: Use Global Text Area in view header and select an input filter where html tags aren't limited i.e. full html text format
> 2 votes

---
Tags: views, 8
---


title: Create node with multiple image fields

text:
# Question
Title: Create node with multiple image fields
I have a requirement to create a node with a REST API. I am using the services module from which I am able to create node of any content type successfully. But here I have added new three image fields which contains upload field type.

With this services api, I want to create node with title body and upload 3 images as well from a HTML form.

How can I achieve this with API.

# Answer
> 0 votes
1. Patch the Services module to allow for multiple items on a field
2. Use Services to create the file and get the file id
3. Use Services to save/update the node and place the file ids onto the image field

For steps 2 and 3, see this blog post.

---
Tags: services, media
---


title: Redirect after login to specific page

text:
# Question
Title: Redirect after login to specific page
We have a link on our site which will redirect users to the edit profile page when they are logged in.

We have same link for the anonymous users which will redirect the user to login page when it clicked.

We would like to redirect users to the edit profile page after login but if users use normal login link, after login, they are redirected to the homepage.

I would like to know how we can redirect users to edit profile page after login only if they clicked on the edit profile link.

# Answer
> 1 votes
In Edit Profile link append destination parameter like:

```
if(user_is_anonymous()){
  $editlink = l(t('Edit Profile'), 'user/login', array('query' => array('destination' => 'user/UID/edit')));
}

```

Then after login, it will redirect to profile edit page.

# Answer
> 0 votes
There are different ways to do this, refer this https://www.drupal.org/node/683696

---
Tags: 7, users, redirection
---


# Question
Title: How to add a button that jumps to an external link in the content type?
I would like to add a purchase button in the content type, the button is an internal link, for example:www.example.com/go/nodeid. And then add an external purchase link to the text field, for example:https://item.jd.com/2385876.html. Click the buy button (internal link) JS jump to the external links, because I do not want to search engine crawling the external link address. For example,  open the page（http://www.chong4.com.cn/read.php?18818）, showing the link（http://www.chong4.com.cn/cydb/go.php?18818\_127334\_22s）, click will jump to（https://detail.tmall.com/item.htm?id=536478627694&ali\_trackid=2:mm\_13376157\_4604749\_42838263,22s18818:1479362916\_3k2\_69258376

# Answer
> 2 votes
> **nofollow**: Links to an unendorsed document, like a paid link. ("nofollow" is used by Google, to specify that the Google search spider should not follow that link)
>
> source: HTML rel Attribute

All you have to do is write your link like this:

`<a rel="nofollow" href="http://www.example.com/something">Buy Now</a>`

# Answer
> 1 votes
Implement the *internal link jump to external link* logic as per requirement. Now to avoid indexing of external links, you can install and configure Noindex External Links module.

> Module let's you take full control of external links indexing. Pages could also pass HTML-validation.

# Answer
> 0 votes
Alternatively, you can use the Redirect module

Which allows you to redirec to external urls.

# Answer
> -1 votes
For add links in content type you can use link module. That provide you link field.Add link field in your content type.

---
Tags: 7, theming
---


# Question
Title: How to use a variable in script tag of template file?
I want to use `$node->title` in the script tag so that I can get data dynamically for particular titles. So I am not getting how can I achieve this. I tried like below, but not worked.

```
 <script type="text/javascript">
     var job_title = $node->title;
     var container_id = "#footer";
     Springest.getTrainings(job_title, container_id);
  </script>

```

Thanks for any suggestions.

# Answer
You can simply embed php in javascript, however the way you are adding your js is not recommended, please look around drupal way of adding js and sending values from php to javascript.

Having said that, the following code might help you-

```
<script type="text/javascript">
     var job_title = <?php echo $node->title; ?>;
     var container_id = "#footer";
     Springest.getTrainings(job_title, container_id);
  </script>

```
> 0 votes

---
Tags: 7, theming, javascript
---


# Question
Title: What are best practices for reusing blocks between sites?
What's the best way of reusing blocks between sites in Drupal 7? I want to re-use not only the block, but also the block's position in my theme.

Apparently, Features extra is designed for this. However, on the project page, it says that UUID Features Integration is the future of the module.

UUID Features Integration, however, doesn't seem to work (although a patch is available to fix things). Also it has been dropped in favor of Deploy.

Deploy, however,doesn't seem to work with blocks and is designed more for exporting nodes. So, I'm not really sure how it is a replacement for UUID Features.

What is the best practice for what I want to achieve?

PS. this is a new version of the question "Latest Best Practise: Reusing content/functionality between Drupal 7 sites", as I was told to post it as a separate question.

# Answer
> 2 votes
Page Manager, Panels and Features.

The plugin architechture in Ctools, which is the project in which Page manager belongs, is the best way to re-use blocks, among other things.

All my block placements are done with Panels, and then exported to code with features.

# Answer
> 1 votes
Another best practise about this topic is to use he Bean module. Here is a quote about its project page:

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

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

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

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

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

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


# Question
Title: Commerce ogone running on ogone page but not in drupal side
I installed the commerce\_ogone module on Drupal 7 with Drupal commerce modules in local environment.

**First shop, first case :**

1. I set my payment method to my test account (PSID, sha in, sha out). When I chose Ogone in the cart I was redirected to ogone page. I set test credit card number and I validated.
2. At this moment, Ogone told me that "Your payment is authorized". Next I was redirected to the review page of the Drupal cart. On this page I have the message "Payment failed at the payment server. Please review your information and try again." but there is nothing in Drupal log.
3. I also received an email from ingenico test with my order but I can see that sentence : "This transaction must be confirmed manually in the administration module to generate a payment."

But I don't know how and why I need to confirm manually ?

**Second shop, second case :**

1. Same as above.
2. Same as above but there is the following message in error log : "SHA signature doesn't match feedback".
3. Ogone told me by email that there is a problem with the http request. The error is "Error in HTTP response - http result = -1" but there is nothing about this error inside the list of all error code of Ogone.

Any idea ?

# Answer
The problem was in the list of parameters that are used in sha1 in the function `commerce_ogone_sha1_out_parameters`. I found a patch in this issue https://www.drupal.org/node/2736531 and it solved the problem.

```
diff --git a/commerce_ogone.sha1.inc b/commerce_ogone.sha1.inc
index dbf7096..9ee45f1 100644
--- a/commerce_ogone.sha1.inc
+++ b/commerce_ogone.sha1.inc
@@ -31,13 +31,16 @@ function commerce_ogone_feedback_valid_sha1($feedback, $sha1out) {
  *   SHA1-OUT security hash.
  */
 function commerce_ogone_sha1_out_parameters() {
-  return array('AAVADDRESS', 'AAVCHECK', 'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT',
-    'BIN', 'BRAND', 'CARDNO', 'CCCTY', 'CN', 'COMPLUS', 'CREATION_STATUS', 'CURRENCY',
-    'CVC', 'CVCCHECK', 'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY',
-    'DCC_EXCHRATE', 'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR',
-    'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOURS', 'DIGESTCARDNO', 'ECI', 'ED',
-    'ENCCARDNO', 'IP', 'IPCTY', 'NBREMAILUSAGE', 'NBRIPUSAGE',
-    'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR', 'NCERRORCARDNO', 'NCERRORCN',
-    'NCERRORCVC', 'NCERRORED', 'ORDERID', 'PAYID', 'PM', 'SCO_CATEGORY',
-    'SCORING', 'STATUS', 'SUBBRAND', 'SUBSCRIPTION_ID', 'TRXDATE', 'VC');
+  return array('AAVADDRESS', 'AAVCHECK', 'AAVMAIL', 'AAVNAME', 'AAVPHONE',
+    'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT', 'BIC', 'BIN', 'BRAND', 'CARDNO',
+    'CCCTY', 'CN', 'COLLECTOR_BIC', 'COLLECTOR_IBAN', 'COMPLUS',
+    'CREATION_STATUS', 'CREDITDEBIT', 'CURRENCY', 'CVCCHECK',
+    'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY', 'DCC_EXCHRATE',
+    'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR',
+    'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOURS', 'DEVICEID', 'DIGESTCARDNO', 'ECI',
+    'ED', 'EMAIL', 'ENCCARDNO', 'FXAMOUNT', 'FXCURRENCY', 'IP', 'IPCTY',
+    'MANDATEID', 'MOBILEMODE', 'NBREMAILUSAGE', 'NBRIPUSAGE',
+    'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR', 'ORDERID', 'PAYID', 'PAYIDSUB',
+    'PAYMENT_REFERENCE', 'PM', 'SCO_CATEGORY', 'SCORING', 'SEQUENCETYPE',
+    'SIGNDATE', 'STATUS', 'SUBBRAND', 'SUBSCRIPTION_ID', 'TRXDATE', 'VC');
 }

```
> 0 votes

---
Tags: commerce
---


title: Theming link fields, getting URL value

text:
# Question
Title: Theming link fields, getting URL value
From a field template level, how can I get the link field URL value so I can theme this thing? Here is my overridden field template for this field:

```
{% for item in items %}
    {%
      set classes = [
        'btn',
        (loop.index0 == 0) ? 'btn--primary' : 'btn--inverted'
      ]
    %}

    <a href="{{ item.content['#uri'] }}" class="{{ classes|join(' ') }}">{{ item.content['#title'] }}</a>
{% endfor %}

```

It only holds two possible values.

I have tried every possible way to access the field value, but nothing seems to work.

# Answer
If you want to do the theming of the link field from a field twig level, it might be a better approach to keep the existing link render element, which is in `item.content` and add the bootstrap classes to it:

**field--link.html.twig**

```
{#
/**
 * @file
 * Theme override for a field.
 *
 * Add bootstrap button style to a link field
 */
#}
{% for item in items %}
  {%
    set link_classes = [
      'btn',
      (loop.index0 == 0) ? 'btn--primary' : 'btn--inverted'
    ]
  %}
  {% set content = item.content %}
  {% set content = content|merge({ '#attributes': { class: link_classes } }) %}
  {{ content }}
{% endfor %}

```

You have to get `item.content` on the top level of the array, so that you can merge `#attibutes`. That is why you need `{% set content = item.content %}`.
> 2 votes

# Answer
Ok... found my answer.

There are two ways you could do this. One way, is in the themename.theme file:

```
function mytheme_preprocess_field(&$variables) {
  if ($variables['element']['#bundle'] == 'motivation_card' && $variables['element']['#field_name'] == 'field_link') {
    foreach ($variables['items'] as $index => $item) {
      $variables['items'][$index]['content']['url'] = $item['content']['#url']->toString();
    }
  }
}

```

Another (preferable) way that I used is to use the render\_var twig function.

```
{{ render_var(item.content['#url']) }}

```
> 5 votes

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


# Question
Title: How to add Facebook share/like icon in Blog Entry header?
I want to add a header to my "blog entry" content type that will have a couple icons for sharing with Facebook, Twitter, email, and Google +1.

How can I do this?

I currently have the icons in a block in the sidebar.

# Answer
The AddToAny module lets you do this. You choose to have the button show in the content, and then use a negative weight to float the button to the top of your content (aka the header section).
> 1 votes

# Answer
Below are some alternatives to pick from (quotes are from their project pages).

# Modules with a stable D7 release:

* ShareThis:

> Integration with the ShareThis social bookmarking utility on selected node types.
>
> The code for this project was based on the original share project for Drupal 5.x. The code for this project has been trimmed down to only work with the ShareThis system, and not require any additional modules to work properly.
* Service Links:

> Service Links facilitates the adding of social networks links or javascript buttons within the content with a special focus on developers and themers interested to extend their number or customize their displaying. Built on Drupal for Drupal doesn't include commercial advertising or spying hidden code and doesn't require third part libraries.
>
> The services included are various: del.icio.us, Digg, Facebook/Facebook Share/Facebook Like, Furl, Google Bookmark/Google Plus One, IceRocket, LinkedIn/Linkedin button counter, MySpace, Newsvine, Reddit, StumbleUpon, Technorati, Twitter/Twitter widget, Yahoo Bookmark, and many more, they are split for language in different packages: basque, dutch, farsi, german, hungarian, italian, polish, russian, spanish, swedish.
>
> Other services are availables to be included within an extra module which can be built easily through a web interface.
* ShareBar:

> The Drupal Sharebar module lets you easily add a "floating" social media submission bar on your website (like that found on Mashable) that includes share buttons for the most popular social media websites online such as Facebook, Twitter, and Google +1 Buttons.
* Share Buttons by AddToAny:

> Share buttons for Drupal including AddToAny's universal sharing button, Facebook, Twitter, Google+, Pinterest, WhatsApp and many more.
>
> Large vector share buttons use AddToAny SVG sharing icons. AddToAny vector icons load efficiently, are mathematically precise, scalable to any size, and stunning on High-PPI screens such as Retina and Retina HD displays.
* Easy Social:

> Centered in a single place, you don't need to worry in including external javascript libraries, and enabling several social modules.
>
> Despite a bunch of other social modules, this module fits exactly if you want simple share buttons without worrying about messy configurations.
>
> Easy Social is available both as blocks, attached to nodes, comments and also as a Views field.

# Modules with an unstable D7 release:

* Follow:

> Follow adds sitewide and per user links that link to various social networking sites. The links reside in two blocks. The Follow Site block lists all the links for the site itself, and by default is visible on all pages. The Follow User block lists all the follow links for the user and is visible only on user profile pages.
* AddThis:

> Provides an AddThis.com button or toolbox to let your users share your content to social network sites.
* Social media:

> The Social media module helps integrate your website with social media sites such as Twitter, Facebook and Google+. It provides an centralized way of managing social media profile information and plug-in widgets such as follow and share buttons.

# Recommended resources

For additional details, refer to these articles:
> 0 votes

# Answer
If you mean you want it at the top of each single blog entry...

In **Administration \>\> Structure \>\> Contentypes**,

1. select the content type where you want to place the share buttons. (In your case it maight be News content type)
2. Go to manage display and select the display mode where you need the buttons.
3. You should be able to see AddToAny in the Disabled section.
4. Move AddToAny at the top of the enabled fields section and click on save.

If you want to be at top of the page then you will need to

1. Go to /admin/structure/block, Select the region where you want the buttons
2. Click on "Place block"
3. Locate AddToAny buttons
4. Click on Place block
5. In the pop up window under Visibility, you will need to configure how to relate buttons with Drupal nodes. If you wan it only under News, and guessing your path to news is /news, you could select "Pages" here and add the following two lines: /news /news/\* having ticked "Show for the listed pages"

I recommend you to make some tests with visibility options to understand how it works.

1. Click on "Save block" in the pop-up
2. Click on Save Blocks

Hope this helps!
> 0 votes

---
Tags: nodes, social-network
---


title: Check if a view is enabled or disabled

text:
# Question
Title: Check if a view is enabled or disabled
How can I check from a custom module if a specific view is enabled or disabled?

# Answer
> 1 votes
Having a view object, checking if the view is disabled just requires to check the value of `$view->disabled`; if it is `TRUE`, the view is disabled.

```
if (!$view->disabled) {
  // The view is enabled.
}

```

This method works independently from the view type, and it doesn't give false negatives when a module alters the output returned from a hook implemented by another module, which is what could happen with `hook_block_view()`, whose output could be altered by `hook_block_view_alter()`.

To get a view object, you can use `views_get_view($name)`, which is the function used also from `views_block_view()`.

```
if ($view = views_get_view($name)) {
  if ($view->access($display_id)) {
    $view->set_display($display_id);
    if (isset($view->display_handler)) {
      $output = $view->display_handler->view_special_blocks($type);
      // Before returning the block output, convert it to a renderable
      // array with contextual links.
      views_add_block_contextual_links($output, $view, $display_id, 'special_block_' . $type);
      $view->destroy();
      return $output;
    }
  }
  $view->destroy();
}

```

If you also need to know if the currently logged-in user has access to the view (i.e. the user can see the view output), you need also to call `$view->access($display_id)`, where `$display_id` can be easily get from the delta of the block with `list($nothing, $type, $name, $display_id) = explode('-', $delta);`.

The code you need to use, in the case of just checking if the view is enabled is similar to the following.

```
$view = views_get_view($name);
// Always check the value returned from views_get_view(), since it can return NULL.
if (!empty($view) && $view->disabled) {
  // The view exists and it is enabled.
}

```

In the case you need to check the currently logged-in user has access to the view, the code should be similar to the following one.

```
$view = views_get_view($name);
// Always check the value returned from views_get_view(), since it can return NULL.
if (!empty($view) && $view->access($display_id)) {
  // The view exists and the user has access to it.
}

```

# Answer
> 1 votes
I did it with `module_invoke()`.

```
$block = module_invoke('views','block_view','-exp-machinenameoftheview-page');
if (!empty($block)) {
  // The view is enabled.
}
else{
  // The view is disabled.
}

```

# Answer
> 1 votes
You can use the views\_get\_view function to do this.

```
$view = views_get_view('view_name');
if ($view->disabled) {
  // Do something
}

```

---
Tags: 7, views
---


# Question
Title: Call a function in one of the modules from a custom PHP file on my Drupal site
I need to run a function in one of my module. This function is perfectly visible throughout my drupal site.

For one of my option, I have to run this function when colorbox loads. I have no idea which PHP file is called when the colorbox opens. I do know where the JS code is when colorbox opens, so what I did was this:-

```
...
...
inline:function(){
        $.get("sites/all/themes/my_theme/set_session2.php");
        return $.urlParam('inline', $(this).attr('href'));
      },
...
...

```

In this way, I can run a php file where I placed that function. Problem is that function is not visible in this PHP file.

Is there any way, I can get through this problem?

Best.

# Answer
All php files inside drupal cannot be directly accessed by incoming request. You should create a endpoint for `$.get` which can be done by `hook_menu`

```
function mymodule_menu() {
  $items['mymodule/endpoint'] = array(
    'page callback' => 'mymodule_page_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

function mymodule_page_callback() {
  module_load_includes('php', 'mymodule', 'set_session2');
  // call function here.
}

```

`module_load_includes` can include the php file you want from the module. So please place the php file inside the module folder.

In javascript, just update the url to the one you just defined.

```
...
...
inline:function(){
    $.get("/mymodule/endpoint");
    return $.urlParam('inline', $(this).attr('href'));
},
...
...

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to compare two fields for filter criteria in view
I want to compare this field value with another field value

How can I do that?

Thank you very much!

# Answer
> 4 votes
With latest views in 7 you have under global filters, "field comparison" filter that you can select any 2 fields which you added into fields of that view (they can be hidden fields) and that is it. Image below shows how this looks:

---
Tags: views
---


# Question
Title: Is it Possible to Change "Edit Permissions" Based on a Field Value on that Node?
I have users that need to be able to edit a piece of content they created until the status field on the piece content is updated to a particular value.

I've done some research and it looks like there are questions that are similar to mine but different enough that their solutions don't seem applicable.

I realize this question might be vague but I don't know how else to phrase it.

Are there any solutions to my problem?

Edit: I am using Drupal 7.

# Answer
I think you can achieve this by implementing `hook_node_access()` with a check on the particular field.

https://forumone.com/ideas/programmatically-restricting-access-to-drupal-content has a very similar use case (except the field there is an entityreference field to users, but you get the gist)
> 1 votes

---
Tags: 7, users
---


# Question
Title: Choose node item from list and add to form
I have content type 'Machinery' and I need to create the form for users where they can enter their name, email, phone number and to select some node from a list and attach it to form.

The user can select unlimited items and when click on 'Add' to add to form.

In this way, the user has the option to attach some machines to the form and send a request for renting those machines. Email that will be sent from this form needs to contain all fields along with the list of added machines.

Since I need this content type because I'm using it for another page to show the list of available machines, I need to create the form in this way so when I add new machine (node) it's automatically available on this list in the form.

Any idea how I can do this? Is there some way to create form through Views so I can add this list field?

I'm working on Drupal 8.

# Answer
> 1 votes
I'm not sure what kind of form your question is about. You say, you want to e-mail the result, so this is probably a *Contact form*.

Here you can add a reference field for content and then configure this field for the content type "Machinery". You can set this to unlimited values, so that you can add multiple machines. The default is an autocomplete field. You can change this to a select list in "Manage form display".

# Answer
> 1 votes
You can create a contact form easily with the yamlform module. There is an "Entity select" form element that allows the user to select from a list of nodes (or taxonomy terms, or whatever entity you like).

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


# Question
Title: How do I get the filename for a file uploaded via form?
I created a module to upload files from a form. I am able to save the files in the proper folder, but I want to get the name of the uploaded files to save them in the database.

```
class MyForm extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['resume'] = array(
        '#type' => 'managed_file',
        '#title' => t('File'),
        '#required' => TRUE,
        '#upload_validators'  => array(
            'file_validate_extensions' => array('pdf doc docx'),
            'file_validate_size' => array(25600000),
        ),
        '#upload_location' => 'public://myfile/',
    );

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('name'))));
   }
}

```

# Answer
The 'managed\_file' FormElement plugin specifically stores the uploaded file as a managed file entity. This plugin stores the file entity id inside form state value as part of its validation.

```
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('name'))));
    // Use the fid to load the file entity. Unfortunately ManagedFile loads the file entity, but does not store it in form state.
    $fid = $form_state->getValue('resume');
    $file = \Drupal\file\Entity\File::load($fid);
    // Do something other than "echo" $file->getFilename() here.
  }

```
> 5 votes

# Answer
Piggybacking off of mrradcliffe's method.

```
$fid = $form_state->getValue('resume');

```

Then do a DB query

```
$db = \Drupal::database();
$data = $db->select('file_managed', 'fe')
  ->fields('fe')
  ->orderBy('fe.fid', 'DESC')
  ->range(0, 1)
  ->condition('fe.fid', $fid, '=')
  ->execute();
$value = $data->fetchAssoc();
$filename = $value['filename'];

```

This should give you the filename, but per your request, it's actually already stored in the database.
> 1 votes

---
Tags: 8, forms, files
---


# Question
Title: How to show a notification at a speicific page based on visitor's country?
I need to notify (only notify) users ordering through my Drupal Commerce based website that we don't serve their country, if they are not from a specific country. How can I achieve this on the checkout page only?

I know smart IP module can help me determine the country per IP, how can I implement the notification at the checkout page, before user proceed with his order.

# Answer
> 0 votes
If you can sort out the Smart IP bid and you get the user's country then you can use Context and Context GeoIP.

Create a new Context where you can choose the countries you don't deliver as a condition and show block as a reaction. Your block might be a modal box informing your users.

---
Tags: commerce
---


# Question
Title: How do I use dpm() or kint() to debug a block plugin I created?
I created a custom module which implements a block plugin. The code was generated with Drupal Console. When I try to debug the code within the build function, I get a *function not found* error.

Why doesn't my code print the value of `$build`?

```
namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("test block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $build['default_block']['#markup'] = '1:Implement DefaultBlock.';
    dpm($build);
    //kint($build);
    return $build;
  }

}

```

# Answer
`dpm()` definitely works within a custom block; I just tested. Since it calls a service, you may need to clear your cache before it shows up, for example with the command line with `drupal cache:rebuild all` or `drush cr`.

To test if the service is available, you could use this code.

```
dump( \Drupal::service('devel.dumper')); die();

```

Another thing to consider is that blocks are cached in Drupal 8 by default. Make sure your `build()` is actually executing. You may want to turn off the rendering cache while developing, in settings.php or settings.local.php.

```
$settings['cache']['bins']['render'] = 'cache.backend.null';

```
> 3 votes

---
Tags: 8, debugging
---


# Question
Title: Why is doing KernelTests Code Coverage so slow?
In my D8 project I have Unit and Kernel tests. Running them (via CLI) without "--coverage-html" is fine. Unit tests in general are ~300ms, Kernels are around 3s (of course based on the size of dependencies and the amount of the test cases).

But when I also want to have code coverage Unit tests are fast as usual but Kernel tests are incredible slow (10-20 minutes).

I started to use filters and whitelisting in the phpunit config file, but that affects only the result (the generated coverage files) but not the speed, which makes the impression that PHPUnit also loops through the Kernel Dependencies (such as core files).

Has anyone met this problem before? What can cause it?

Here is my filtering options:

```
<filter>
    <whitelist>
        <directory suffix=".php">./web/modules/custom/test_module</directory>
    </whitelist>
</filter>

```

# Answer
> 3 votes
A kernel tests actually installs Drupal (in-memory only, but still), that means it runs thounsands and thousands of lines of code.

You can't really do anything to change that, xdebug (I guess you use that) would actually have to support a native whitelist to keep the overhead minimal, but that would in turn also result in overhead.

---
Tags: 8, testing
---


# Question
Title: Drupal private messages database table design
I am trying to get the raw message data from a Drupal instance running the Privatemsg module.

I have tracked the message data down to the `pm_message` and `pm_index` tables but I am struggling to understand the database structure / design.

I am trying to get the author and recipient users for a message, however in the majority of cases the `pm_message.author` and `pm_index.recipient` are exactly the same user. How do I get the author and recipient of a message from the database?

I think this maybe due to me not understanding threads in database design (can't see how `thread_id` is created or relevant), sample query I am running to get the data:

```
SELECT
author, recipient, body, timestamp
FROM pm_message, pm_index
WHERE pm_message.mid = pm_index.mid

```

# Answer
In general with Drupal you want to avoid directly querying the database if you didn't create the tables yourself. Instead try to use functions provided by core or the module to get the data for you. The table structures are often complicated and may change without notice, but the functions for accessing those tables generally adapt to the changes (this is more true of core than contrib modules, but is frequently true of both).

In the case of Privatemsg the Drupal 7 version (and probably 6) provide several useful functions to pull the message data (see the main module file). For example you can load an entire thread with `privatemsg_thread_load`:

```
/**
 * Load a thread with all the messages and participants.
 *
 * This function is called by the menu system through the %privatemsg_thread
 * wildcard.
 *
 * @param $thread_id
 *   Thread id, pmi.thread_id or pm.mid of the first message in that thread.
 * @param $account
 *   User object for which the thread should be loaded, defaults to
 *   the current user.
 * @param $start
 *   Message offset from the start of the thread.
 * @param $useAccessDenied
 *   Set to TRUE if the function should forward to the access denied page
 *   instead of not found. This is used by the menu system because that does
 *   load arguments before access checks are made. Defaults to FALSE.
 *
 * @return
 *   $thread object, with keys messages, participants, title and user. messages
 *   contains an array of messages, participants an array of user, subject the
 *   subject of the thread and user the user viewing the thread.
 *
 *   If no messages are found, or the thread_id is invalid, the function returns
 *   FALSE.

 * @ingroup api
 */
function privatemsg_thread_load($thread_id, $account = NULL, $start = NULL, $useAccessDenied = FALSE) {

```

There are also several functions that generate the query objects for pulling the module's data like `privatemsg_sql_list`:

```
/**
 * Query definition to load a list of threads.
 *
 * @param $account
 *  User object for which the messages are being loaded.
 * @param $argument
 *  string argument which can be used in the query builder to modify the thread listing.
 *
 * @see hook_query_privatemsg_list_alter()
 */
function privatemsg_sql_list($account, $argument = 'list') {

```
> 3 votes

---
Tags: 7, privatemsg
---


# Question
Title: Programatically remove field content from all nodes where content equals 'string'?
I am doing a migration from D7 to D8. Due to various issues in the initial site, I am doing content migration through CSV import rather than the direct drupal to drupal migration that's built in.

My content type has a Video Embed Field in it, which was throwing errors on migration unless it was filled. As such, I had to throw in a placeholder video URL for all nodes that didn't have the node filled.

Is there a way to (within drupal, or via a SQL query) programatically remove the field content from all nodes where the url is "youtube.com/myPlaceholderVideo"? All the content is in, but now I'm stuck with ~450 nodes with this placeholder URL.

# Answer
The video\_embed\_field module adds a simple field based on whatever you named it. So if your field is named "field\_youtube\_embed\_test", you'd get a field on your content type that is a standard drupal field, with a table "node\__field\_youtube\_embed\_test" and a revision table "node\_revision\__field\_youtube\_embed\_test". You can run a query to delete all entries based on bundle as that is one of the columns on both tables. So you can run a query for each.

```
DELETE from node__field_youtube_embed_test where field_youtube_embed_test_value = 'youtube.com/myPlaceholderVideo' and bundle = 'article';

DELETE from node_revision__field_video_embed where field_youtube_embed_test_value = 'youtube.com/myPlaceholderVideo' and bundle = 'article';

```

Or if you want to delete everything from those tables, you just use the truncate command:

```
TRUNCATE node__field_youtube_embed_test;

TRUNCATE node_revision__field_video_embed;

```

Using a query works for simple fields such as textfields, booleans, etc, but it doesn't work for more complex structures such as field collections or paragraphs. For those, you would probably want to iterate through them programmatically and unset the value and then save the node.
> 1 votes

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


title: Deprecated version of DFP (v201508)

text:
# Question
Title: Deprecated version of DFP (v201508)
We are getting emails from google about the latest version of Double-click for Publishers' (dpf) API.

Currently our site appears to still be using a deprecated version (v201508) and need to update to v201608 by November 30. https://developers.google.com/doubleclick-publishers/docs/deprecation

Is this dfp api change is going to affect the dfp module?

# Answer
> 0 votes
As far as I can tell the DFP module doesn't load API version specific files and so unless you are using additional custom JS or loading the DFP JS files directly from your site (instead of pulling them from Google), there is no reason the API change should effect the module itself.

---
Tags: 7, advertising
---


# Question
Title: Programmatically rendering a Views pane with arguments from context
I'm trying to programmatically render a Views pane (ie. a Pane display of a view) with a taxonomy term as argument (passed in the pane context)

The following code illustrate how the pane is rendered

```
$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
ctools_content_render($selected_type, $selected_subtype, array(), array(), array(), $context);

```

It mostly works and the view is rendered. However, the taxonomy term in the context is not used as argument for the view.

In the pane views display's settings, the "Argument input" for the one views' argument is configured as "Term ID" "From context":

I looked at the code for the view display handler. Arguments handling is done in `views_content_plugin_display_panel_pane::pane_process_conf()`. I checked there and the issues seems to be that `$conf['context']` is not set. So `$context_keys` ends up being an empty array. Later in the switch statement, `$key = array_shift($context_keys)` sets `$key` to `NULL`, the `isset($contexts[$key])` test fails and the `$argument` is ignored.

I have no idea if this is a bug with Views pane, or if something is missing in the pane rendering code.

Note: I'm actually using a Pane Field field in a Paragraphs bundle.

# Answer
I got it to work with

```
$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
$config = array(
  'context' => array('context_taxonomy_term_1');
);
ctools_content_render($selected_type, $selected_subtype, $config, array(), array(), $context);

```

So, in order to render a Views Pane display with contextual filters coming from the pane's context you to populate `$context` and inform the display handler on which entries of `$context` to use for each contextual filter with `$config['context']`.
> 1 votes

---
Tags: views, panels, chaos-tool-suite
---


title: Invalid Signature in Services Oauth

text:
# Question
Title: Invalid Signature in Services Oauth
When using the Services API with a PUT request, it returns an error saying that the signature is invalid. When working with POST I was getting access denied because the bundle was specified but this seems to be completely different.

```
401 Unauthorized : Invalid signature 21
["Invalid signature"]

```

For testing purposes, "Cache pages for anonymous users" and "Cache blocks" are both unchecked. I cleared the cache once to make sure it wasn't that.

It appears to be that the server generated signature does not match, but I saw the answer below, and the two signatures are completely different, not just missing a plus sign. I was able to log the signatures that the server sees to the devel debug log.

Service request with OAuth (Invalid signature error)

One thing I noticed which I wasn't sure about is that the base string that got logged for the request on the server started with GET, but this is a PUT request. Is that normal or could that be a bug in the implementation? My Oauth client is using PUT as the method.

---

**Update:** In looking into it, that does indeed seem to be the problem or at least part of it.

```
if($_SERVER['REQUEST_URI'] == '/api/rest/resource/18.json'){
    die('hi put' . $_SERVER['REQUEST_METHOD']);
}

```

The above code inserted at the beginning of index.php gives me `hi putGET`. However POST works perfectly fine.

My access log has this line

```
"PUT /api/rest/resource/21.json HTTP/1.1" 401 21 "empty referrer" "My User Agent String"

```

# Answer
> 0 votes
Once I figured out that the access log was different than the `$_SERVER` variable, I called my hosting provider and discovered that their servers are only configured to allow GET and POST (haven't checked HEAD).

So I invented this hack to use the header, since it seems that Apache just transparently changes unrecognized methods to GET.

```
if( isset($_SERVER['HTTP_X_REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
    $_SERVER['REQUEST_METHOD'] = $_SERVER['HTTP_X_REQUEST_METHOD'];
}

```

---
Tags: 7, services, authentication-authorization
---


# Question
Title: Why are we using utf8mb4_general_ci and not utf8mb4_unicode_ci?
Drupal is moving to support utf8mb4, however, it is using utf8mb4\_general\_ci. Why take the time to move over to support it, and then not fully support it? Is there a specific reason, or just continuing utf8\_general\_ci from previous?

Would there be any problems with ignoring this and using Unicode anyway?

Drupal Ticket: MySQL driver does not support full UTF-8 (emojis, asian symbols, mathematical symbols)

Here is a question on stack exchange which says really there is no reason not to use Unicode now days and finally, on this question, it says "utf8\_general\_ci is a legacy collation that does not support expansions, contractions, or ignorable characters."

I note that WordPress uses utf8mb4\_unicode\_ci.

# Answer
> 10 votes
It seems to me that the recommendation is outdated and that `utf8mb4_unicode_ci` will work without problems. It has been used by a lot of people for a long time.

---

There is a difference between changing the character set from `utf8` to `utf8mb4` (to support more codepoints) and changing the collation from `general_ci` to `unicode_ci` (to get more accurate sorting). Both changes can cause their own problems, so doing both independently makes sense.

`utf8mb4` is used by default since 8.0.0-beta12. The main issue seemed to be a change of key lengths limitations for InnoDB but as I understand it, `utf8mb4` should have worked with the default MyISAM engine even before that change.

Switching to `unicode_ci` shouldn't cause problems, but may unexpectedly changes the order of sorting for some sites.

The default collation setting is just a *default* and modules can choose their own collations anyway if they need to. I also haven't found any documentation that says modules should expect a certain collation. The database install guide just lacks a clear statement about which collations are supported and is inconsistent:

* In the section about phpMyAdmin it says that you have to

> Make sure you select COLLATION utf8\_general\_ci
* Later in the section about installation from command line, `general_ci` doesn't seem to be required and any UTF-8 collation will do:

> Note: The database should be created with UTF-8 (Unicode) encoding, for example utf8\_general\_ci.

Furthermore, PostgreSQL is supported and it seems its default UTF-8 collation is equivalent to `utf8mb4_unicode_ci`, so using that with MySQL should be fine too.

# Answer
> 2 votes
Below link explains that utf8mb4\_unicode\_ci is better than utf8mb4general\_ci (which is a little bit faster) because the second one have problems in sorting order in some languages: https://stackoverflow.com/a/766996/860099

---
Tags: database
---


# Question
Title: NL and other languages visible, but English site not visible and showing error after translating news item
I get below error when try to reach my site (see screenshot):

The *editor* of the site made a news item and translated it to English. Now the English (default) site can't be reached. But the other languages are still working. For example the dutch version.

> Notice: Undefined offset: 5 in tb\_megamenu\_insert\_tb\_item() (line 347 of /var/www/clients/client7/web17/web/sites/all/modules/tb\_megamenu/tb\_megamenu.functions.inc). Notice: Undefined index: href in include() (line 2 of /var/www/clients/client7/web17/web/sites/all/modules/tb\_megamenu/templates/tb-megamenu-item.tpl.php). Notice: Undefined index: href in include() (line 2 of /var/www/clients/client7/web17/web/sites/all/modules/tb\_megamenu/templates/tb-megamenu-item.tpl.php). Notice: Undefined index: options in include() (line 2 of /var/www/clients/client7/web17/web/sites/all/modules/tb\_megamenu/templates/tb-megamenu-item.tpl.php). Recoverable fatal error: Argument 2 passed to url() must be of the type array, null given, called in /var/www/clients/client7/web17/web/sites/all/modules/tb\_megamenu/templates/tb-megamenu-item.tpl.php on line 2 and defined in url() (line 2220 of /var/www/clients/client7/web17/web/includes/common.inc).

# Answer
> 0 votes
From the error msgs shown, it seems that you're using the TB Mega Menu module. So think of a way to get that module disabled (eg using the Dutch admin screens to disable a module, or using Drush if you have it available). That might possibly help to get rid of those errors again.

If you then also unpublish (or delete?) that news item where your problems started from, you may have a stable situation again. And from there continue your investigation to find the real cause (root) of your issue.

Doei!

---
Tags: 7, i18n-l10n, navigation
---


# Question
Title: Why does the Login Destination module not redirect to page?
I installed and enabled the Login Destination module, and added a login destination rule.

In Internal page or external URL I added `myhomepage` which is a basic page URL that I want to show after a user performs a login. If authenticated user login then it would not redirect to default page.

My default dashboard page is `/cms` and dashboard page after user login is `cms/96/dashboard` (`96` in it is the `uid` of the user).

I have a three types of users:

* authenticated user
* administrator
* employee entry form

And I want authenticated user and employee entry form user to be redirect to cms/{uid}/dashboard (but not administrator users).

Some more details about my configuration:

* **Redirect upon triggers** : I have only select the first one and that is Login, registration, one-time login link
* **Only the listed pages:**

+ `cms`
    + `cms/register`
    + `cms/*/edit`
* and under setting tab I have checked both checkboxes.

But when I try to login then user gets redirected to default page.

Any suggestions?

# Answer
You can use Rules module.

**Events:** User has logged in.
**Condition:** User has role.
**Actions:** Page redirect.

Other Way through coding:

You can use hook\_user\_login

```
function hook_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('cms');
 else
  drupal_goto('cms/{$account->uid}/dashboard');
}

```

Updated rule:

```
{ "rules_after_login_rule" : {
    "LABEL" : "After Login Rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "cms\/[account:uid]\/myhomepage" } } ]
  }
}

```

Look at these post as well.

How to rediret to specific page depends upon user roles

I want to redirect the user to profile page after they log in

Redirect user based on role and node content
> 2 votes

# Answer
It's not clear to me what exactly you want to achieve with the Login destination module. But if all you want to do is to redirect a user after logging in, to a page that somehow corresponds to which roles the user has, then you can simply do that using the Rules module. And optionally also use the Conditional Rules module if you have more sophisticated redirect logic you need to implement.

Read on for more details about all this using some rules examples to get you going. These Rules are in Rules export format, which you can import in your own site if you have the Rules UI enabled, and after you enabled this rule

### Example that should match your case

```
{ "rules_redirect_selected_roles_to_selected_pages" : {
    "LABEL" : "Redirect selected roles to selected pages",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } },
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "cms\/[account:uid]\/myhomepage" } } ]
  }
}

```

Here is what this rule does, after a users completed a login:

* Check if for the logged in user both of these Rules Conditions are `true`:

+ the user ***does not have*** role "administrator" (which is the role with role id = "3").
    + the user ***does have*** the role with role id = "4".
* If both (!!!) Rules Conditions are satisfied, then the Rules Action will perform a redirect to `cms/[account:uid]/myhomepage`, whereas the `[account:uid]` in this redirect path will be replaced by the uid of the user who logged in.

Notes:

* In this rule there is no check about "authenticated role", because as per the Rules Event (="User has logged in"), you can be sure the user is authenticated.
* If needed, adapt the role id (="4") in the above rules example to fit the role id of your role that corresponds to role "employee entry form". If you have other custom roles (not mentioned in your question), then it could well be that the role id for "employee entry form" is another value.

### More sophisticated redirect example

After you also enable the Conditional Rules module, you can implement (way) more sophisticated redirect logic, as in this Rules example:

```
{ "rules_redirect_selected_roles_to_selected_pages" : {
    "LABEL" : "Redirect selected roles to selected pages",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } },
            "DO" : [ { "redirect" : { "url" : "node\/32" } } ]
          },
          { "ELSE" : [
              { "CONDITIONAL" : [
                  {
                    "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
                    "DO" : [ { "redirect" : { "url" : "node\/14" } } ]
                  },
                  { "ELSE" : [ { "redirect" : { "url" : "node\/22" } } ] }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
}

```

Here is what this rule does, after a users completed a login:

> **if** the user has access to role with role id = 3 (= admin), **then** a redirect is done to `node/32`. **else** **if** the user has access to role with role id = 4 (= some custom role), **then** a redirect is done to `node/14.` **else** redirect to `node/22.`

Adapt the node ids (= 32, 14, 23) and role ids (=3, 4, ...) to whatever fits your case, and extend the if/then/else constructs as much as you want (or use a "switch"-alternative if you prefer).

Note: as an alternative to using the Conditional Rules module to implement the above Rules logic, you can also split such rules in multiple rules, and combine that with replacing the Rules Actions which invoke appropriate Rules Components. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

### Conclusion

With only 1 custom rule you can implement whatever redirect logic so that for each role you implement an appropriate page to redirect to after logging in. That's really it, and it works like a charm.
> 1 votes

---
Tags: 7, redirection
---


title: Edit CKEditor's config programmatically

text:
# Question
Title: Edit CKEditor's config programmatically
I've created a Drupal 8 module that adds a custom plugin to the core's CKEditor. This plugin allows users to add tabbed content to their pages.

The problem is that the plugin adds a class to the element it creates and CKEditor by default removes classes from most elements once you save the node.

I can change CKEditor config for Basic HTML editor (admin/config/content/formats/manage/basic\_html) to allow classes in elements by changing to in "Allowed HTML tags" input.

Now I would love to be able to do this programmatically somehow. How can I change the configuration for CKEditor in a Drupal module? Especially the "extraAllowedContent" config value.

The project for reference purposes can be found at https://github.com/j-vee/ckeditor\_tabber

# Answer
I had a similar case, i had to add a few attributes to the basic\_html format in the Allowed HTML tags so it could work with the module editor\_advance\_link which allows the users to add title, class, id and target attributes to the a tag when using the core's CKEditor.

So this is what i did with some code i found here ( https://www.drupal.org/files/issues/allow\_image\_style\_to\_be-2061377-224.patch)

```
if ($filter = FilterFormat::load('basic_html')) {
    if (($filter_html = $filter->filters('filter_html')) && $filter_html->status) {
      $config = $filter_html->getConfiguration();
      $allowed_html = !empty($config['settings']['allowed_html']) ? $config['settings']['allowed_html'] : NULL;
      $matches = [];
      if ($allowed_html && preg_match('/<a ([^>]*)>/', $allowed_html, $matches)) {
        $new_attributes = array_filter(explode(' ', $matches[1]));
        $new_attributes[] = 'target';
        $new_attributes[] = 'title';
        $new_attributes[] = 'class';
        $config['settings']['allowed_html'] = preg_replace('/<a ([^>]*)>/', '<a ' . implode(' ', array_unique($new_attributes)) . '>', $allowed_html);
        $filter->setFilterConfig('filter_html', $config);
        $filter->save();
      }
    }
  }

```

Don't forget to include: `use Drupal\filter\Entity\FilterFormat;`

This code is needed to be run only once, so i had to include it in a .install file in a custom module.
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to stop drush displaying a Drupal error message?
This question is a follow-on from this one about creating managed files. If you look at the question in the link, you'll see that I am writing a drush command to detect all the inline-images in a just-migrated Drupal 8 system, and add them into Drupal as managed images attached to the relevant nodes. To cut a long story short, this bit of code takes the existing file name and creates an entry in Drupal:

```
$file = entity_create('file');
$file->setFilename($file_name);
$file->setFileUri('public://images/'.$file_name);
$file->save();

```

This works fine, except that it very irritatingly displays this error message with every file: `Object(Drupal\Core\Entity\Plugin\DataType\EntityAdapter).uri: The file <em class="placeholder">public://images/rint135_graph4_0.articleimage.PNG</em> already exists. Enter a unique file URI.`

Of course the file exists! That is precisely the point! Despite the error message everything seems to work ok, but I would really like to get rid of those error messages. I guess that they are being set by drupal\_set\_message(), since they include HTML which of course is pointless in drush - but I can't find any way to switch them off.

# Answer
> 0 votes
Two options:

1. Hide the messages with `ob_start()` and `ob_end()`.
2. Avoid the messages by moving the target file out of the way, and moving it back again after saving the entity.

---
Tags: drush, status-messages
---


# Question
Title: What is required to get a custom module to appear in uninstall list?
**Solution**: Ayesh K provides the correct answer below.

---

What is required to get a custom module to appear in uninstall list? I thought all you had to do was specify a database schema in `hook_schema()`, but I've done so and my module does not appear in the uninstall list. Currently my module consists of the following code in the `.install` file:

```
<?php

/**
 * Table schema definition for the Events Sponsors module.
 */
function event_sponsors_schema() {
    $schema['event_sponsors_sponsors'] = array(
        'description' => 'A collection of event sponsors.',
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => "Unique ID for the sponsor.",
            ),
            'name' => array(
                'type' => 'varchar',
                'length' => '255',
                'not null' => TRUE,
                'description' => 'The name of the sponsor.',
            ),
        ),
        'primary key' => array('id'),
        'unique keys' => array(
            'id' => array('id'),
        ),
    );

    $schema['event_sponsors_sponsor_relations'] = array(
        'description' => 'Maintains sponsor and node relations.',
        'fields' => array(
            'sid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The sponsor ID, as can be found in the sponsors table.',
            ),
            'nid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The node ID as can be found in the node table.',
            ),
            'ordinal' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The order this sponsor appears alongside the node.',
            ),
        ),
        'primary keys' => array('sid','nid'),
        'unique keys' => array(
            'sid' => array('sid'),
            'nid' => array('nid'),
        ),
    );

    return $schema;
}

```

Any insight is appreciated.

# Answer
> 5 votes
For Drupal 6, you needed to install/uninstall schema using `hook_install` and `hook_uninstall`.

This is not necessary for Drupal 7.

Module will appear in uninstall list if both of these conditions are met:

* module implements `hook_schema` OR `hook_uninstall` in its `.install` file.
* module was enabled once and now is in disabled status.

If the only purpose of `hook_uninstall` is to uninstall the schema, you do not need a `hook_uninstall` function. For `variable_del()`, etc: you need. If you have any of these and module has data in the site already, you will see the uninstall check box.

# Answer
> 1 votes
Use `hook_uninstall()` like this way.
variables must not undefined.

```
function mymodule_uninstall() {
  variable_del('mymodule_var');
  variable_del('mymodule_var2');
}

```

# Answer
> -1 votes
A very simple solution for newbies like me in drupal 7.

You can't uninstall a module when it's running or active. So try, to disable your module first and it should appear to uninstall list afterwards.

---
Tags: 7
---


title: How do I make view section scrollable?

text:
# Question
Title: How do I make view section scrollable?
I created a most read section with 4 articles in views.

The height is over. How do I make this section scrollable?

Is there any scrollbar settings in views?

# Answer
> 0 votes
```
#(block-id-here){
  height:200px;
  overflow-y:scroll;
}

```

Thanks, Smalution.

I had found out the solution for this.

---
Tags: views
---


# Question
Title: Migrated D8 site breaks when cache_discovery is truncated
I was developing a site for a migration on Acquia's free tier, but it turned out there wasn't enough space for all of the files. Since I can no longer use local development/acquia for development, I decided to migrate it all over to another host that I use.

Did my normal process of installing a clean site on the new server, and then copying the modules, themes, and file folders from the old dev site to the new dev site, and then importing the full database dump from the old database into the new database.

Boom, site is up and running. I go to clear the caches on the new dev site to finalize the migration and am met with the angry error "The mysite.com page isn’t working. mysite.com is currently unable to handle this request. HTTP ERROR 500".

After re-importing a few times and clearing the cache tables one at a time, I've learned that the `cache_discovery` table in particular is the culprit. Clearing all of the other cache tables works fine, but when I clear this one the site throws that error.

Anybody know what might be happening here? I never encountered anything like this in D7 and this is my first D8 build, so I'm not sure how to proceed.

# Answer
> 2 votes
> Did my normal process of installing a clean site on the new server, and then copying the modules, themes, and file folders from the old dev site to the new dev site,

In D8 all information from annotations and yaml files are newly discovered on a cache rebuild. And your mix from the clean site install and the copied files did not fit together. This could be one file, which is left over from an older core or module version and you get this problem. So the solution is, to copy complete site archives or when updating remove the old code completely before replacing it.

# Answer
> 1 votes
Not sure what was wrong with the config above, but instead of going that route I just transferred over the entire site archive and it's now working. If you have this issue, just transfer a site archive instead.

---
Tags: 8, caching
---


# Question
Title: How to manage programmatically the access of a content node type?
From a custom module, I created a new type of content type via the drupal api (using the hook node\_info). Thanks that, I can create node of this content type.

I would like allow access to nodes of this content type only for his author. And I want the author have only access to the view page of the node (edit page denied). How can I do that?

In Short: In my custom module, how allow only access to the view node page only the author of the node? The author can only access to the view page of a node created by the author. And, edits pages aren't be accessible for all non-admin users.

# Answer
We need to set permission for doing this. Permission can be done specific to a Role not to a User. Please use below codes. Please update your role name instead of 'New Role' and machine name of your content\_type instead of 'your\_content\_type'.

```
$role_name = "New Role";
$role_permissions = array(
  'create your_content_type content',
  );

$role = user_role_load_by_name($role_name);
user_role_grant_permissions($role->rid, $role_permissions);

```
> 1 votes

---
Tags: 7, nodes, users
---