title: 1 Views Filter (exposed) for 2 fields

text:
# Question
Title: 1 Views Filter (exposed) for 2 fields
I am interested in having one view filter for two separate fields.

Example: In a staff directory I am working on, users have both a "First Name" and "Nickname" field.

The output results show both, but in order to keep it user-friendly, I would like to have a "First Name" filter that sorts by both "First Name" and "Nickname" based on the input.

I found this question on here and it seems like it gives the proper direction of what I am looking for but I am not quite sure how to execute this solution.

3 separate fields,one views exposed filter

The suggestion based on the question above would be to expose both the "First Name" and "Nickname" filters but to hide the "Nickname" filter with CSS.

Following that, if a user typed a name such as "John" into the "First Name" filter and then clicked "Submit", before the query is executed, the input value "John" would also be automatically input into the CSS-hidden "Nickname" filter.

The concept makes sense to me but I am confused as to how to execute it.

Are there any detailed guides that could explain how I could make that happen? With the PHP code given in the question linked above, would I have to modify a core file? Would it be in a template file? Would it have to be in a module file?

Or is there an even simpler solution to this that I am not thinking about?

Any help is appreciated. Thank you!

# Answer
> 1 votes
Have you tried with an exposed **Global Combine fields filter** ? I'm not sure which Views version implemented that filter.

Alternatively, you may use the Views filters populate module :

1. Add the fields you want to search in a OR combination of filters, not exposed.
2. Add the **Global : Populate filters** provided by the module (exposed), checking the filters you added in the Or group.

---
Tags: views
---


# Question
Title: .bash_profile has to be resourced every time
I installed Drush 8.0.0 for Drupal 8 on Linux Mint 17.1 via Composer.

I added Composer's directory to .bash\_profile.

```
export PATH="$HOME/.composer/vendor/bin:$PATH"

```

The problem is that every time I want to run Drush now, I have to re-source .bash\_profile with `source ~/.bash_profile`.

Otherwise, I get an error saying it is not installed.

> The program 'drush' is currently not installed. You can install it by typing: sudo apt-get install drush

How can I keep it sourced?

# Answer
You need to put these commands in your ~/.bashrc file, which is sourced every time a new shell is started.

You might also want to try the new `drush init` command, which should do this setup for you. Be sure that you are using Drush 8.0.1 or later.
> 2 votes

---
Tags: drush, 8
---


title: Rules flag on flagging flag

text:
# Question
Title: Rules flag on flagging flag
I got a "flag A". this flag can be flagged with "flag B".

I would like to send an email via the Rules module to the flagging-user of flag A, when flag A has been flagged with flag B.

My problem is I can't find a replacement token for flagging-user of flag A.

I get a lot of tokens for flag a except a token to address the flagging user of flag a.

Available Tokens for Flagged-Flag:

```
[flagged-flagging:date]
Flagging date   The date an item was flagged.

[flagged-flagging:flag-freundschaftsspiel-bestaetigen-count]
Freundschaftsspiel bestätigen flag count    Gesamtzahl der Kennzeichnungen für die Kennzeichnung Freundschaftsspiel bestätigen

[flagged-flagging:flag-freundschaftsspiel-bestaetigen-link]
Freundschaftsspiel bestätigen flag link Flag/unflag link for Freundschaftsspiel bestätigen

[flagged-flagging:original]
Original flagging   The original flagging data if the flagging is being updated or saved.

[flagged-flagging:field-fs-mannschaft]
Mannschaft  Feld "field_fs_mannschaft".

[flagged-flagging:field-flag-fs-trikotfarbe]
Trikotfarbe Feld "field_flag_fs_trikotfarbe".

[flagged-flagging:og-membership]
OG memberships  A list of all OG memberships of the flagging entity.

[flagged-flagging:og-membership--1]
Aktiv OG membership A list of all OG memberships of the flagging entity with Aktiv state.

[flagged-flagging:og-membership--2]
Ausstehend OG membership    A list of all OG memberships of the flagging entity with Ausstehend state.

[flagged-flagging:og-membership--3]
Gesperrt OG membership  A list of all OG memberships of the flagging entity with Gesperrt state.

[flagged-flagging:field-fs-mannschaft--og-membership]
OG membership from field Mannschaft A list of all OG memberships registered in field Mannschaft.

[flagged-flagging:field-fs-mannschaft--og-membership--1]
Aktiv OG memberships from field Mannschaft  A list of all OG memberships with Aktiv registered in field Mannschaft.

[flagged-flagging:field-fs-mannschaft--og-membership--2]
Ausstehend OG memberships from field Mannschaft A list of all OG memberships with Ausstehend registered in field Mannschaft.

[flagged-flagging:field-fs-mannschaft--og-membership--3]
Gesperrt OG memberships from field Mannschaft   A list of all OG memberships with Gesperrt registered in field Mannschaft.

[flagged-flagging:flag-freundschaftsspiel-bestaetigen]
Whether the entity is flagged with flag freundschaftsspiel_bestaetigen  Whether the entity is flagged with flag freundschaftsspiel_bestaetigen.

[flagged-flagging:field_fs_mannschaft]
Mannschaft  Field Entity Reference.

[flagged-flagging:field_flag_fs_trikotfarbe]
Trikotfarbe Field Referenz auf Taxonomy-Begriffe.

```

This is the export of the rule:

```
{ "rules_freundschaftsspiel_best_tigen" : {
    "LABEL" : "Freundschaftsspiel best\u00e4tigen",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_i18n", "flag" ],
    "ON" : { "flag_flagged_freundschaftsspiel_bestaetigen" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "flagged-flagging" ], "field" : "field_fs_mannschaft" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[flagged-flagging-user:mail]",
          "subject" : "test",
          "message" : "test \r\n[flagging-user:name]",
          "from" : "[site:mail]",
          "language" : [ "flagging-user:language" ]
        }
      }
    ]
  }
}

```

The token used in the mail action "to" is just an exmaple. There is just no token for the mail of the user of the flagged flag.

The only mail token available is the one of the flagging-user:mail. That would be the flagging-user of flag B.

I guess I would need something like flagged-flagging:flagging-user:mail.

Is there a way I could send an email to the user of flag A that has been flagged by flag B?

The Rule should do as follows:

When a flag ("A" or the same as "Freundschaftsspiel") is flagged by flag "Freundschaftsspiel bestaetigen" then send an email to the user (flagging-user) whos flag has been flagged by "Freundschaftsspiel bestaetigen".

The only condition right now is the one you asked me to add in your first comment. Add a field that is contained in the original flag (Flag A or Freundschaftsspiel).

Freundschaftsspiel is a "friendly game".

The flagged-flagging-user is just a construction of me. It is not found in the replacement patterns.

But some kind like this would be the token a need. As shown above all other data of flag "A" is available, ecept the "author" or flagging-user.

To explain the whole thought behind all this.

A user creates an entity "Freundschaftsspiel" with Date and Team data. All other others that are interested in competing against this team in a friendly match can flag this entity with flag A or "Freundschaftsspiel" flag.

The author of the entity "Freundschaftsspiel" gets a list of interests in a view.

He then flags one of these interests with flag B or "Freundschaftsspiel bestaetigen".

That is when the rule should be fired.

# Answer
It's tough to tell what is needed to address your question. But make sure your rule includes a condition that is something like "entity has field", whereas that field is something related to your "flag A". That might make your "flagging user for flag A" available as the token that you're looking for.

**Edit 1**: after giving it some more thought, and now that the (updated) question also includes the rule you have so far, I think there is something wrong in what you're trying to achieve (or I don't understand it):

* You want to send an eMail to the "***flagging-user of flag A, when flag A has been flagged with flag B.***"
* "***with flag B***" is clearly something any authorized user can do (that's fine).
* "***flag A has been flagged***" seems to me like "something" (= flag A) that can be flagged (like with "flag B"). Let's assume (replace) "flag A" for a moment by an entity like a nodes or users (which typically are used for flagging): there is no such thing as "flagging-user" for a node (or user) entity, except if you're talking about flag B. In that case such flagging user indicates the user who has used flag B to flag an entity like a node (or a user).
* Because of what I explained above, I think you cannot find such "flagging user for flag A", simply because that doesn't exist. That may not be an answer you like to hear, but I'm afraid that is an answer.

Maybe you should try to better explain your usecase first, to check if there is a way to replace your "flag A"-part with some other thing (entity) for which you can then use your existing "flag B"?

**Edit 2**: Below is an additional attempt to answer your question, based on this part that you added to the end of your question:

> A user creates an entity "Freundschaftsspiel" with Date and Team data. All other others that are interested in competing against this team in a friendly match can flag this entity with flag A or "Freundschaftsspiel" flag.
>
> The author of the entity "Freundschaftsspiel" gets a list of interests in a view.
>
> He then flags one of these interests with flag B or "Freundschaftsspiel bestaetigen".
>
> That is when the rule should be fired.

The above confirms what I started to think already ... looks like you're making it too complicated. Forget what is above (in my answer). And keep the "flag A" and the "view" you already have, but get rid of your "Flag B". Just enhance you view by adding the functionality provided by the Rules Link module. Some details about it (from its project page):

> This module lets you create links which trigger arbitrary functionality with the help of Rules.
>
> ...
>
> The links are usually displayed using Views.
>
> There are three types of links:
>
> * Javascript - Links that will trigger the rules using Ajax.
> * Token - This are basic links, that will reload the page after calling them.
> * Confirmation link - Show a confirmation form before executing the rule

So instead of "flagging with flag B" (which is clicking a link also, I know ...), the solution is that the link gets clicked that is added via the Rules Link module. To the user (= author of that entity) it will (should!) probably look "similar".

With this (2nd) edit, I'd hope you can you get the rest of your "flagging the flags"-puzzle resolved. Curious to hear how it will turn out.
> 1 votes

---
Tags: 7, rules, tokens, flags
---


title: Content type slug in route, how?

text:
# Question
Title: Content type slug in route, how?
I have a content type "Company", each company will have a login page that show the logo of the company and a login form via Restful.

I have created a module that define a route:

```
company_md.login:
  path: '/{company_slug}/login'
  defaults:
    _controller: '\Drupal\company_md\Controller\DefaultController::login'
    _title: 'Company XX Login'

```

When I go to that URL it give me Not Found 404, whats wrong in my routing?

# EDIT 1

This how the path look:

```
http://companies.local/node-13-company/login4

```

# EDIT 2

My routing file:

```
testd8.name:
  path: '/node/{node1}/login'
  defaults:
    _controller: '\Drupal\testd8\Controller\DefaultController::login'
  requirements:
    _access: 'TRUE'
  options:
    parameters:
      node1:
        type: entity:node

```

# Answer
Do you have an entity type or a content type? If you create one in the UI, it's a content Type. Then it really is a node, so what you want to use is {node}. Then upcasting will work (assuming you have NodeInterface $node in your controller).

That said, access denied is, as Ivan Jaros said, the missing access definitions. The default access definition is that that access is denied. `access: 'TRUE'` will give anyone access.

What you likely want to use is `_entity_access: node:view` then the standard node access system is invoked and the user has access if he can view that node.
> 1 votes

---
Tags: 8, routes
---


# Question
Title: How to set one content type to only one language in a multilingual site?
I have a multi language website, it's for both English and Arabic, the site's default language is English, but for specific content type which is blog section of the website. I need to set it's default language to Arabic and to never translate it's content. Is it possible?

# Answer
Install the Entity Translation module then go to edit your content type and under ***Publishing options*** in ***Multilingual support*** check the option ***Enabled, with field translation***

Go to: YOUR\_SITE/admin/config/regional/entity\_translation and configure your content type like this:

Obviously I select French but in your case you must select Arabic.
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: Randomly show one item from the last x posted
I have worked out how to select a random item - add a sort criteria of type Global: Random. I can also select from, say, the last month, by adding a filter. However, if I want to select randomly from the last, say, 5 items posted, I can't find a way to do that.

# Answer
Sort your View by ***Content: Post date (desc)*** and set the Pager to ***Use pager: Display a specified number of items | 5 items***

Go to the ***Advanced Settings*** in the view and click in the ***Theme: Information***

Search the ***Style output:*** section and select a name, in my case was views-view-unformatted--temp.tpl.php

Go to the folder `YOUR_SITE/sites/all/modules/views/theme` and copy to your theme folder the file `views-view-unformatted.tpl.php` and rename it to **views-view-unformatted--temp.tpl.php**

Edit your new file `views-view-unformatted--temp.tpl.php` and put inside only this code to show only one element:

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
 //Selecting one element from your last 5 posted elements
 $element = $rows[rand(0, 4)];
 $rows = array();
 $rows[] = $element;

?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

In the View go to the bottom of the Information window and click **Rescan template files** and click **OK**, then save your View.

And go to see your result.

**Attention:** Remember to repeat these steps if you ever change theme.
> 6 votes

---
Tags: views
---


title: Node_save fails silently

text:
# Question
Title: Node_save fails silently
I am trying to programmatically update a node with a value from another entity. When I call `node_save`, the function just "stops". There is nothing in watchdog or in my php\_logs that would indicate that any issue was encountered.

```
$node = node_load($base_node->nid, FALSE, TRUE);

$node->field_product[LANGUAGE_NONE][] = array('product_id' => $entity->product_id->value());

dpm('This text prints.');

node_save($node);

dpm('This text does not print.'); //This line is never executed.

```

I have tried a variety of methods for saving the node including using entitymetadatawrappers on `$node`. So far, nothing I have tried has gotten me anywhere.

Thanks!

**Edit**:

A few more details on what I have tried/am trying to do.

This field is a product reference field that I am adding a reference to.

There is nothing at all in the php logs or the watchdog logs.

I am trying to do this as a part of custom rules action. I was originally using the `add item to list` action, but only one item was being added to the list (usually there will be 4-5). As a test, I tried to update and save the node manually (thus the code above).

I should have specified that part, but got a bit wrapped up in my own solution. Either way, it seems pretty odd to me.

**Edit** Part 2:

I have confirmed that the structure for `field_product` is correct. I am also doing checks to make sure that I am not referencing a non-existent field, etc.

I wasn't originally using `dpm`s for debugging, it just seemed like the simplest way to communicate my issue. Originally I was doing some further processing on my data that was not being done. Since that further logic isn't pertinent to the problem, I added a `dpm` as an example. There were no errors in the following logic and it wasn't dependent on the node save.

# Answer
The field structure you are using for your entity reference field is not correct. See entityreference\_field\_schema().

The correct column name is target\_id, not product\_id, so it should be like this:

```
$node = node_load($base_node->nid, FALSE, TRUE);

$node->field_product[LANGUAGE_NONE][]['target_id'] = $entity->product_id->value();

node_save($node);

```

This assumes you are using an entity wrapper to access the `$entity` object but not for accessing the `$node` object.

**\[edit\]**

Regarding your `dpm()` not firing, it is quite possible it is firing but you aren't seeing the output. This can happen depending on where you are calling it from.

A good alternative in these cases could be dd() or watchdog() since their output will be visible regardless of where you call it from.
> 0 votes

---
Tags: nodes
---


# Question
Title: Drupal Console Installation: The "phar.readonly" setting needs to be off to create Phars
I am trying to install the Drupal Console for Drupal 8 on Linux Mint 17.1. During the installation I am getting the following warning notice:

`[ ] Notice: The "phar.readonly" setting needs to be off to create Phars.`

Any idea how to solve this? Will this effect the console operation?

# Answer
> 2 votes
Add this to your php.ini:

```
phar.readonly = Off

```

It won't affect the console's operation (unless it needs to create phars at some point, in which case it now can, whereas it couldn't before).

# Answer
> 0 votes
Yes it won't affect the console operation; the message will be removed on the next release since the installer has been changed.

And you can remove the warning by doing what Clive mentioned.

---
Tags: 8
---


# Question
Title: Is possible to sort a views field that is generated by custom views handler?
I have a view field that is generated by a views handler. The logic inside the render method is as following:

```
function render($class) {

  if (class_hasnt_started($class)) return 'Registered';

  if (user_completed_entire_course($class)) return 'Completed';

  if (user_completed_some_classes($class)) return 'Attended x of y';

}

```

My question is, can such a field be sorted?

# Answer
For a Table display, use the style options to make the field sortable.
> 0 votes

---
Tags: 7, views
---


title: How do I print full path?

text:
# Question
Title: How do I print full path?
My current code works:

```
<img src="<?php print $base_url . '/' . drupal_get_path('theme', 'lapost'); ?>/images/cart-template-logo.png" />

```

But if you check in source it prints only `/sites/all/themes/lapost/images/cart-template-logo.png`

It works if you load image on-site, but it also gets sent to email and when mail arrives it gives dead image shortcut, because the path is missing the www.webaddress.com part.

# Answer
> 2 votes
You can use the url():

```
$imgurl = drupal_get_path('theme', 'YOURTHEME') . '/images/image.png';
$final_url = url($imgurl, array('absolute' => TRUE));

```

This will provide a url like http://example.com/sites/all/themes/YOURTHEME/images/image.png

# Answer
> 0 votes
Use base\_path to get full url of site

> Returns the base URL path (i.e., directory) of the Drupal installation.

The base\_url global contains the base\_path of the drupal installation, and this might be a subdirectory like 'drupal'. If you don't need this, there's another global variable named 'base\_root', which doesn't contain the base path:

```
$GLOBALS['base_url'] => http://example.com/drupal
$GLOBALS['base_root'] => http://example.com

```

By the way, perhaps one should use the global variables supplied by Drupal, so instead of using

```
$root = $GLOBALS['base_root']

```

we should better use

```
global $base_root;
$root = $base_root;

```

If you get image file path then you use this

There is catch here, for example if you want to use get url of http://example.com/files/logo.png, than use

```
$url = base_path() .'files/logo.png';

```

If you write this

```
$url = base_path() .'/files/logo.png';

```

It will return - http://files/log.png. which is incorrect.

---
Tags: 7, theming, emails
---


title: Open external links in new tab

text:
# Question
Title: Open external links in new tab
I am using the Bootstrap theme for Drupal 7. I want to open all external links in new tab. For this there are some contribute modules available. But I want to do it in programmatically. When I searched I found this but it is not working for me. Is there any other hook to do this?

This is the code I am using.

```
function mytheme_links($variables) {
  dpm($variables);
  $variables['options']['attributes']['target'] = '_blank';
}

```

# Answer
Try this *js based* code;

```
Drupal.behaviors.externalMenu = function(context, settings) {
    $('#your_menu_id').attr('target', '_blank');
};

```
> 1 votes

# Answer
Drupal doesn't pass any `$variables['options']` to that theme function. That is clear from the documentation for `theme_links()`.

Since you just want to add an attribute, and not alter the output of a theme function, you just need to implement a theme preprocess function.

```
function mytheme_preprocess_links(&$variables) {
  $links = $variables['links'];
  if (count($links) > 0) {
    foreach ($links as $key => $link) {
      if (url_is_external($link['href'])) {
        $links[$key]['attributes']['target'] = '_blank';
      }
    }
    $variables['links'] = $links;
  }
}

```
> 1 votes

# Answer
Try `url_is_external()` function to determine if link is internal or external.

Your code could be something like below:

```
function mytheme_links($variables) {
  $link = $variables['options'];
  if (url_is_external($link)) {
    $variables['options']['attributes']['target'] = '_blank';
  }
}

```
> 0 votes

# Answer
I have found another solution which works as expected. This is the code I have used

```
      $('a').not('[href*="mailto:"]').each(function () {
        var isInternalLink = new RegExp('/' + window.location.host + '/');
        if ( ! isInternalLink.test(this.href) ) {
          $(this).attr('target', '_blank');
        }
      });

```

which opens the external links in new tab. Place the code in your custom js file
> 0 votes

---
Tags: 7, theming
---


title: How do I get the global user object?

text:
# Question
Title: How do I get the global user object?
How do I get the global user object in `hook_preprocess_page()`?

# Answer
```
<?php
public function behave() {
  $account = \Drupal::currentUser();
  if ($account->id() == 1) {
    return "Hi, boss!";
  }
  else {
    return "You are not the site administrator.";
  }
}
?>

```

Note that in neither case is the value an actual User object. Rather, as of Drupal 8 it is a UserSession object, which duplicates some, but not all, of the information of a user. It may also represent the Anonymous User rather than a saved User entity. See link for more information.
> 7 votes

---
Tags: users, 8, theming
---


# Question
Title: Smart Paging Clean url redirects to Queried strings automatically
I just use Smart Paging module and it works great. Except one thing, when I click on next link, next page clean url is automatically redirected to queried string url.

Like `xyz.com/some-url.html/p/0/1 to xyz.com/some-url.html?page=0%2C1`

I'm not able to figure out the reason for this.

Can you please help?

Thanks.

# Answer
> 0 votes
Issue was with Global Redirect Module. Patch here https://www.drupal.org/node/1843500#comment-7535655 works, testing it on development site for now.

---
Tags: paging
---


# Question
Title: How to filter content in views based on user id
Is there a way to for a normal user (without admin power) to set permissions for a specific piece of content (not a content type) so that it is only visible to a specific user? I want it so that said specific user can see content that has been specifically assigned to them in a table in a view.

# Answer
> 0 votes
You can do it by using these modules:

* If you want to give permissions to node then you can use this module

Node Access

> Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

* If you want to "assign" node to some user, you can use user reference field and then in view add filter for that field and make it filter by current user.

For user reference use this field

References

> There were a couple changes in the way 'References' views are handled ("referenceable nodes/users defined by a view"), which might require double-checking those existing on your site:
>
> * The 'label' (node title or user name) is no longer automatically added if not included in the view. If some of your 'References' views currently do not include it, you might want to add it explicitly,
> else it will no longer appear in the widgets.
> * The HTML generated by the view is no longer stripped out before being handed to "checkboxes / radios" widgets, thus allowing advanced formatting. You might want to check for Reference views having fields configured to display "as links", since the (probably unwanted) tags generated by Views are not removed anymore.

# Answer
> 0 votes
have you seen **Field Permissions** module ? visit https://www.drupal.org/project/field\_permissions

by this module, you can add permissions to fields in order to visible/invisible part of content type.

---
Tags: views, entities, users
---


# Question
Title: How to add custom permission for a node?
Is there any way to add custom permissions for a node?

Here is the requirement: I have a node where I have to set 2 permission, view & subscribe. View permission I can use the default content view permission. But how can I introduce a new permission for subscribe?

# Answer
A possible alternative is to use the Rules module, and create a rule that is a variation of the rule mentioned in my answer to the question aboutr "How to make the permissions of a module more granular?".

The variation in your case will be something like so:

* Use the path specific to the node of your case.
* Adapt the "Rules Action" to fit your needs.

You may also want to add some "Rules condition(s)" related to the "role" that is required to allow actions like edit, delete, etc. If you have multiple actions like that, you either build one such rule for each action, or you use the Conditional Rules module to make it all fit in a single rule. Obviously, this approach does not "introduce" a new permission that can be assigned by an admin (which is not a requirement either in the original version of this question, right?).
> 0 votes

# Answer
Permissions are created using `hook_permission`:

```
function hook_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

```

And checked with `user_access()`:

```
if (user_access('administer my module')) {
  // Access granted
}

```
> 0 votes

---
Tags: users
---


# Question
Title: Getting the pretty url for a node if it's a term
I'm using 'pretty urls' with autopath for my nodes so example.com/node-name but I'm having trouble getting that in the context of a term page.

So on the node template itself I'm doing:

```
 if ( arg(1) == 'term') {
      //do stuff
 }

```

To get the link to the nodes page:

```
<a href="<?php echo $base_url . '/node/' . $node->nid; ?>" class="btn btn-primary" role="button">View details »</a>

```

But this takes me to the node number url so example.com/node/23 or something like that. I would like the nice url. When I var\_dump $node all I can get to build a url is the id, any ideas? Preferably something in the code, I like controlling stuff in the templates if I can.

# Answer
Figured it out, using drupal\_get\_path\_alias. So something like in the node:

```
$url = drupal_get_path_alias('node/' . $node->nid);

```
> 0 votes

---
Tags: nodes, taxonomy-terms
---


# Question
Title: EntityFieldQuery not returning Bundle data
I've defined an entity in `hook_entity_info` as follows:

```
function foo_entity_info() {
  return array(
    'Foo' => array(
      'label' => t('foo'),
      'base table' => 'foo',
      'entity keys' => array(
        'id' => 'bar',
        'label' => 'bar',
      ),
      'module' => 'foo',
      'fieldable' => TRUE,
      'bundles' => array(
        'Foo' => array(
          'label' => t('Foo'),
          'admin' => array(
              'path' => 'admin/config/foo/fields',
              'access arguments' => array('access content'),
          ),
        ),
      ),
      'views controller class' => 'EntityDefaultViewsController',
    ),
  );
}

```

When I run the following code:

`$info = entity_get_info('Foo');` it all looks OK

When I run the following code:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type','Foo');
  $result = $query->execute();

```

it all looks OK

But when I run the following code:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type','Foo')
    ->entityCondition('bundle','Foo');
  $result = $query->execute();

```

I get an empty array in `$result`. This seems wrong.

What should I expect to see in `$result` and why aren't I seeing it?

Many thanks,

MB

# Answer
> 0 votes
> What should I expect to see in $result

You should expect to see an array of data that represents the entities that match your query. This array will contain a key for each entity type it returns, and an array within each of those keyed by the individual entity IDs. The inner-most array will contain bundle key data for the entity. You will need to run the ID(s) through `entity_load()` or equivalent if you want access to general field/property data for the entities.

> why aren't I seeing it?

Not really possible to say without more information. If you know that you have existing entities that match the criteria, and they're not showing up in an EFQ, that's potentially the sign of a deeper problem with your installation (or it might not be, it depends).

If that's the case, clear your caches and try again. If that doesn't fix it, reinstall your entity module. After that, you're left with step-debugging to find out what DB query is being produced, you can run that against MySQL proper to see what's going on, and so on.

---
Tags: entities
---


title: How to render HTML from variable

text:
# Question
Title: How to render HTML from variable
I want to render as HTML not string on Twig. I have a variable that hold form HTML but after putting on Twig template it's render as string like given below:

1) Set loginpopup variable in preprocess hook.

```
function MYTHEMENAME_preprocess_page(&$variables) {
    $variables['loginpopup'] = array(
   '#plain_text' => "<div style='display:none'><div id='login-pop'>".drupal_render($form)."</div></div>"
    );
   }

```

2) Render on Twig template file as :

```
 {{ loginpopup }}

```

But it's visible as string (i.e. double-escaped).. What's the problem and how do I fix it?

# Answer
You should not render in a preprocess function.

Wrap the additional container around your $form and put this into your variable:

```
function MYTHEMENAME_preprocess_page(&$variables) {
  $variables['loginpopup'] = array(
    '#type' => 'container',
    '#prefix' => '<div class="visually-hidden"><div id="login-pop">',
    '#suffix' => '</div></div>',
    'form' => $form,
  )
}

```

The style attribute is filtered by the xss filter. You can use the class `visually-hidden`, this is in drupal predefined.
> 3 votes

# Answer
You should definitely NOT put HTML into render arrays (I'm not saying you cannot (you can with #prefix and #suffix), you just shouldn't - that's D7 thinking). You should define a theme hook/template for that so that you can use your own template. But if you have to use inline template:

```
$page['noscript'] = [
  '#type' => 'inline_template',
  '#template' => '<noscript><div>{{ message }}</div></noscript>',
  '#context' => [
    'message' => $noscript_message,
  ],
];

```
> 5 votes

---
Tags: 8, theming
---


# Question
Title: Can a module provide a default block with editable content? (editable through the standard block interface)
I have multiple blocks I'd like to include in a module/install profile; (containing markup) but need to be editable through the standard block UI? What's the best way to implement this?

# Answer
Drupal adds custom blocks in a form submit function using database queries directly, it doesn't expose an API for that particular function unfortunately, so you'll have to write/copy the code manually.

You can find all the code you need in `block_add_block_form_submit()`.

You insert the custom block into the database like so:

```
$delta = db_insert('block_custom')
  ->fields(array(
    'body' => '<p>Some markup</p>',
    'info' => 'Block description',
    'format' => 'full_html',
  ))
  ->execute();

```

Then you need to make this block available to all installed themes:

```
$query = db_insert('block')->fields(array('visibility', 'pages', 'custom', 'title', 'module', 'theme', 'status', 'weight', 'delta', 'cache'));
foreach (list_themes() as $key => $theme) {
  if ($theme->status) {
    $query->values(array(
      'visibility' => 1, // visible
      'pages' => '', // list of pages
      'custom' => 1, // This is a custom block
      'title' => 'Block title',
      'module' => 'block', // The block module handles custom modules
      'theme' => $theme->name,
      'status' => 0,
      'weight' => 0,
      'delta' => $delta,
      'cache' => DRUPAL_NO_CACHE,
    ));
  }
}
$query->execute();

```

You'll want to put that code either in `hook_install()`/`hook_enable()` if you plan to do this in a custom module, or `hook_install()` if you're doing it in an install profile.
> 2 votes

# Answer
Have a look at block\_example.module, there it goes like so:

```
/**
 * Implements hook_block_info().
 *   Hello Drupal, here is a new block.
 */
function MYMODULE_block_info() {
  $blocks = array();
  $blocks['configurable_block'] = array(
    'info' => t('My Block\'s name'),
    // Setting the following two values will enable this block on ALL themes.
    // Better place this block manually after module activation. Alternatively
    // you could db_update the theme value programmatically, of course.
    //'status' => TRUE,
    //'region' => 'content',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>',
  );
  return $blocks;
}

/**
 * Implements hook_block_configure().
 *   To create a configurable block we need to add a form to our block.
 */
function MYMODULE_block_configure($delta = '') {
  $form = array();
  if ($delta == 'configurable_block') {
    $form['MYMODULE_block_content'] = array(
      '#type' => 'textfield',
      '#title' => t('Block contents'),
      '#size' => 60,
      '#description' => t('This text will appear in the example block.'),
      '#default_value' => variable_get('MYMODULE_block_content', t('Some example content.')),
    );
  }
  return $form;
}

/**
 * Implements hook_block_save().
 *   Whenever the block content is edited, it gets stored into the DB.
 */
function MYMODULE_block_save($delta = '', $edit = array()) {
  if ($delta == 'configurable_block') {
    variable_set('MYMODULE_block_content', $edit['MYMODULE_block_content']);
  }
}

/**
 * Implements hook_block_view().
 *   Tells Drupal what it should put into the block's content.
 */
function MYMODULE_block_view($delta = '') {
  switch ($delta) {
    case 'configurable_block':
      $block['subject'] = '';
      $block['content'] = MYMODULE_block_content($delta);
      break;
  }
  return $block;
}

/**
 * A module-defined block content function.
 */
function MYMODULE_block_content($which_block) {
  switch ($which_block) {
    case 'configurable_block':
      $result = array(
        '#markup' => variable_get('MYMODULE_block_content',
          t('A default value. This block was created at %time',
            array('%time' => date('c'))
          )
        ),
      );
      return $result;
  }
}

```
> 0 votes

---
Tags: blocks
---


# Question
Title: Is there a way to add clauses like accept = 'image/*' to input items via forms API?
I'd like to add "accept" attributes to some of the input fields for my site's content types -- to end up with something like `<input type="file" id="edit-field-whatever-und-0-upload" name="files[field_whatever_und_0]" size="22" class="form-file" accept="image/*">`, so that (most) browsers will limit the selectable items to .jpg, .png, etc. I've tried doing this by adding an `#attributes` clause to a form's `hook_form_alter` handler, but haven't been able to find the right way to write the clause -- I can't get the `accept` clause to show up in the html.

In place of this, I'm currently adding it through some jQuery that runs on document.ready, but it would feel cleaner if I could do it through the forms api. Is this possible? Any hints out there? Thanks!

# Answer
You can override theme\_file to achieve above if you would like to alter file input element in template.php ..

```
function YOURTHEMENAME_file($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'file';
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-file'));

  return '<input' . drupal_attributes($element['#attributes']) . ' accept="image/*" />';
}

```

below code works for me

```
function seven_file($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'file';
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-file'));

  return '<input' . drupal_attributes($element['#attributes']) . ' accept="image/*" />';
}

```
> 2 votes

# Answer
Old question but i wanted to solve this same issue and this led me to come up with a general solution to set the accept attribute for all drupal file and image widgets.

```
/**
* Implements hook_field_widget_form_alter().
*/
function MODULENAME_field_widget_form_alter(&$element, &$form_state, $context)
{
  switch ($context['field']['type'])
  {
    case 'file':
    case 'image':
    {
      // add custom file widget process callback
      $element[$context['delta']]['#process'][] = '_MODULENAME_file_process';
      break;
    }
  }
}

/**
* Custom element process callback for file widgets
**/
function _MODULENAME_file_process($element, &$form_state, $form)
{
  // set accept attribute from allowed extensions
  $exts_string = @$element['#upload_validators']['file_validate_extensions'][0];
  if ($exts_string)
  {
    $exts = explode(' ', $exts_string);
    $element['upload']['#attributes']['accept'] = '.' . implode(', .', $exts);
  }

  return $element;
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: Change order (weight) of blocks before page load programatically
Is there a way to change order of blocks before page load (according to current node id for expample)? In hook\_preprocess\_page or something like that? I don't want to use any modules for this.

# Answer
You can use hook\_block\_list\_alter to achieve this. Be aware that the `$block->weight` attribute won't be affected at this point in the proceedings, but there are solutions in the comments to this problem.
> 1 votes

---
Tags: blocks
---


# Question
Title: How to create a page showing certain roles?
I want to create a page that shows the organisation of the group behind the website. To do this, I would like to render a list of certain Drupal roles, along with every user that has that role. However, I have no idea how to do this without writing a custom module. Is there a way?

# Answer
> 1 votes
Create a view (using Views module) of users with a grouping by role. You can add a filter for the specific roles that you want to include.

# Answer
> 1 votes
You can also display drupal user based on role. If want to add more fields for user profile, use profile 2 module.

Or if you want to create user profile as content then you need to create a content type with a taxonomy Field (add taxonomy with name role). To shows the contents use views and grouped the content based on taxonomy terms.

---
Tags: 7
---


# Question
Title: Reset/Delete the value of a field with node_save()
I have a content type with a `field_FOO` of type `text`. I have a procedure that check which nodes have this `field_FOO` without value (`$node->field_FOO == array()` ), extract 1 at random, make some operations, set a value for this field (`field_FOO[LANGUAGE_NONE][0]['value'] = 'bar'`) and save the node.

Now for 10.000+ nodes I need to delete this value but I don't want to do a `node_load`, empty `field_FOO`, `node_save` because for every `node_save` Drupal change the changed date associated with that nodes.

So, how can I "**delete**" the value of a field without use `node_save()`? If I delete the entry from `field_data_field_FOO` table I risk a site down ?

In the `field_data_field_FOO` table there is a "deleted" column. If I set it to 1, at the next `hook_cron()` that fields are deleted without a site down ?

Thanks.

# Answer
If you want to do by changing the database entry then you need to check key constraints for the field table and also you need to remove its dependency from the parent table.
> 0 votes

---
Tags: entities
---


# Question
Title: Drupal module to make html pages of all nodes automatically
I am looking for a solution / module which can create the whole site in HTML .

So every time the user does content changes, he can click on a button, it will create the html for that node only or the whole site and syncs it to an FTP or same hosting.

I do not want to use caching or any other technique to speed up the site.

is it possible with drupal ? thanks

# Answer
The Boost module is the closest thing to 'Drupal as a static generator'.

> Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic.

**EDIT**: You could also look at the Static module. However it doesn't provide a mechanism to get the files onto a server, you would need to set that up separately.
> 4 votes

---
Tags: nodes, performance
---


# Question
Title: Text format field missing for minimal installation
I installed minimal version of latest stable Drupal 8. It does not include any HTML text formats so I had to add my own custom Full HTML text format next to default Plain Text.

It also doesn't include any content types, so I had to create my own Basic page content type with Body field.

When adding/editing content under body field it doesn't show the Text format field drop-down and I cannot select neither out of two formats, it just loads up some default CKEditor.

Also with minimal installation it doesn't include Administrator role. So I did create my own custom Administrator role and gave it all permissions, including under Filter, but still no effect, even though I'm user/1.

How do I get `Text format` working/displaying on Minimal installation?

# Answer
> 1 votes
Look in the standard profile:

```
core/profiles/standard/config/install

```

In comparision the minimal is rather empty:

```
core/profiles/minimal/config/install

```

You can take this yml-file for the text format, put it in the sync-folder and import it:

```
core/profiles/standard/config/install/filter.format.full_html.yml

```

But probably you need much more configuration, did you consider to start over with the standard profile?

---
Tags: entities, users, 8, input-formats
---


# Question
Title: How to render a template in a module controller?
I want to render a custom template in a module controller but I don't know how. How do I achieve this?

# Answer
> 8 votes
You need to let Drupal know about the theme, and then you can leverage it in the controller code. The template needs to be in the folder my\_module/templates.

my\_module.module

```
function my_module_theme() {
  $theme['template_name'] = [
    'render element' => 'build',
    'template' => 'template_file_name',//This is only needed if you need a different template file name than the array key above, 'template_name'.
  ];

  //override existing template for this module
  $theme['html__my_module__template_file_name'] = [
    'template' => 'html--my_module--template_file_name',
  ];
  return $theme;
}

```

src/Controller/MyModuleController.php

```
public function index() {
  $build['#theme'] = 'template_name';
  //populate your build renderable array..
  return $build;
}

```

---
Tags: 8, page-controller
---


# Question
Title: Remove '-Any-' value from exposed filter term field
I have a view with an exposed filter field. This field always shows the `-Any-` value. The data shown is dynamic so I cannot select the values to show. I have to remove that option in some way.

I've looked at this answer but this is for a form and I'm trying to do this for a views page of type chart. Anyway, I can't even dpm the form name as is said in the example.

My view name is `x_report_plus_feature_dashboard` and the display is `page1`.

How can I do this? Thanks!

**EDIT:**

I was able to remove the '-Any-' value with the following code:

```
function HOOK_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    unset ($form['field_MYFIELD_tid_selective']["#options"]['All']);
  }
}

```

But now I have a problem. When I go to the view, the data shown is still the same that was shown when `-Any-` was selected. For me it's ok to show the data for the first entry as default but how to do it?

# Answer
> 1 votes
Setting the exposed filter to `required` will remove the `-Any-` option.

---
Tags: taxonomy-terms, views
---


# Question
Title: Why is the token in my custom module not replaced?
I want to use the token `[user:name]` in my module. This module contains a sample ControllerBase class

In my class I test this:

```
class Page_test_Controller extends ControllerBase {

    /**
     * {@inheritdoc}
     */
    public function token() {
        $build = array(
            '#type' => 'markup',
            '#markup' => t('[user:name] hello'),
        );
        return $build;
    }

}

```

When I load my page the token isn't replaced as shown here:

What am I missing or doing wrong?

# Answer
> 4 votes
Translatable strings don't use tokens, but placeholders, see for example https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/function/FormattableMarkup%3A%3AplaceholderFormat/8 for some documentation, or https://www.drupal.org/node/322729 (more 7.x, but conceptually still mostly OK).

Tokens are when you have user configurable text like the user register/confirmation mails. It doesn't make sense to have token in a text that is hardcoded since tokens are only useful if that text can be customized by the user. For documentation on how to use the token API, see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21Token.php/class/Token/8

---
Tags: 8, tokens
---


# Question
Title: How can I AND two OR statements with the #states feature of Drupal 7?
This page explains nicely how to use OR with the #states feature. However, when I try to AND two OR statements, It doesn't seem to AND them together. Is there a way to do this? This is what I tried.

```
 'visible' => array(
    array(
      array(':input[name="vehicle"]' => array('value' => 'truck')),
      array(':input[name="vehicle"]' => array('value' => 'car')),
    ),
    array(
      array(':input[name="mileage"]' => array('value' => '10')),
      array(':input[name="mileage"]' => array('value' => '20')),
    ),

  ),

```

# Answer
I found out that this can be done this way:

```
$form['non_phd_student'] = array(
    '#type' => 'item',
    // This #states rule says that the "non_phd_student" item should only
    // be shown if the "student_type" form element is set to "Undergraduate" or "graduate".
    '#states' => array(
      'visible' => array(
        array(
          array(':input[name="student_type"]' => array('value' => 'undergraduate')),
          array(':input[name="student_type"]' => array('value' => 'graduate')),
        )

      ),
    ),
);
$form['non_phd_student']['thanks'] = array(
  '#type' => 'item',
  '#description' => t('Thanks for providing your graduate status and your country');
  '#states' => array(
  //Because this has ['non_phd_student']
  //The or in $form['non_phd_student'] is ANDed into the or of this statement.
  // Action to take: Make visible.
  'visible' => array(
    array(
      array(':input[name="school_country"]' => array('value' => t('Other'))),
      array(':input[name="school_country"]' => array('value' => 'UK')),
    )
  ),
),
);

```

There is another answer that takes more work. We can do this because AND statements can be inside the OR statements. Also, because of Propositional Logic we can get the same results this way:

```
'visible' => array(
  array(
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '10'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '10'),

    ),
  ),

),

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Are there any pitfalls pointing config sync to profile's config/install?
Is this good practice? I have pointed my config sync to:

```
$config_directories['sync'] = 'profiles/PROFILENAME/config/install';

```

Experiments with `drush cex` have worked, allowing a cycle of UI changes, config export, and re-installation with the new changes.

We will not be going live with D8 for a while, so the team's plan is to use this method to gain familiarity with the config system and other parts of D8 using this simple method.

# Answer
No, I don't think that is a good idea. default configuration is something else than the config sync folder. For example exported config has a UUID and system.site has a site UUID while default config shouldn't.

They are two different use cases. default config is for installing new sites and the config export is to deploy configuration between different installations of the *same* site.

What you might want to look into is https://www.drupal.org/project/config\_installer, a simple installer that allows to install based on an config export/sync folder.
> 7 votes

---
Tags: 8, configuration
---


# Question
Title: How to download programmatically a module?
I need to programmatically download projects from drupal.org, and then eventually enable it with `modules_enable`. Anyone knows how to do it?

Here's the final solution : I'm sharing the code i used for those who'll face the same problem.

```
    /**
     *
     * Function downloading the last version of the module in MY_MODULE_MODULE_DIRECTORY
     * $modulename correspond au nom system du module
     *
     * @param string $modulename
     */
    function MY_MODULE_download_module($modulename) {
      // DEBUT CODE TELECHARGEMENT

      $base_url = 'http://updates.drupal.org/release-history/' . $modulename . '/7.x';
      // @TODO MODULE NAME

      $xml = drupal_http_request($base_url);
      if (!isset($xml->error) && isset($xml->data)) {
        $data = $xml->data;
      }
      try {
        $xml = new SimpleXMLElement($data);
      }
      catch (Exception $e) {
        // SimpleXMLElement::__construct produces an E_WARNING error message for
        // each error found in the XML data and throws an exception if errors
        // were detected. Catch any exception and return failure (NULL).
        return;
      }
      $json = json_encode($xml);
      $array = json_decode($json, TRUE);
      $download_link = $array['releases']['release'][0]['download_link'];

      $path = MY_MODULE_contrib_dowload($download_link);
      MY_MODULE_archive_extract($path, MY_MODULE_MODULE_DIRECTORY);

      // FIN CODE TELECHARGEMENT
    }

    /**
     * Fonction downloading a file
     * Inspired from update_manager_file_get($url).
     * Upload the file in the temporary folder
     *
     * @param url $url
     */
    function MY_MODULE_contrib_dowload($url) {
      $parsed_url = parse_url($url);
      $remote_schemes = array(
        'http',
        'https',
        'ftp',
        'ftps',
        'smb',
        'nfs'
      );
      if (!in_array($parsed_url['scheme'], $remote_schemes)) {
        // This is a local file, just return the path.
        return drupal_realpath($url);
      }

      $cache_directory = _update_manager_cache_directory();
      $local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
      // load the file in the right directory

      return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
    }

    /**
     * Function inspired from update_manager_archive_extract($file, $directory)
     * extracts a file to a directory
     *
     * @param path_to_file $file
     * @param path_to_directory $directory
     * @throws Exception
     * @return A path
     */
    function MY_MODULE_archive_extract($file, $directory) {
      $archiver = archiver_get_archiver($file);
      if (!$archiver) {
        throw new Exception(t('Cannot extract %file, not a valid archive.', array(
          '%file' => $file
        )));
      }

      // Remove the directory if it exists, otherwise it might contain a mixture of
      // old files mixed with the new files (e.g. in cases where files were removed
      // from a later release).
      $files = $archiver->listContents();

      // Unfortunately, we can only use the directory name to determine the project
      // name. Some archivers list the first file as the directory (i.e., MODULE/)
      // and others list an actual file (i.e., MODULE/README.TXT).
      $project = strtok($files[0], '/\\');

      $extract_location = $directory . '/' . $project;
      if (file_exists($extract_location)) {
        file_unmanaged_delete_recursive($extract_location);
      }

      $archiver->extract($directory);
      return $archiver;
    }

```

# Answer
Normally you want to use `drush`, e.g.

```
drush -y en module_name

```

which would download, install and enable your module of interest.

Check `drush.api.php` to use appropriate API hooks which could be useful.

If you don't want to use Drush, check how Update Manager does that in `update/update.manager.inc`, e.g.

To get the list of available files to download for specific project you've to fetch and parse the release history which is available at:

```
https://updates.drupal.org/release-history/project_name/7.x

```

the same as drush does that (check by `drush -vd dl foo`) and get the links from there.
> 10 votes

# Answer
With drupal 8 I fell in love with drupal console.

The output is much clearer and it provides you with suggestion (and sometimes completion) on the arguments.

To download a module using console the long command is: `drupal module:download module_name` and the short command is: `drupal m:download module_name`

Console provides you with the downloadable versions of that module and asks you which you want to download.

To install a module using console the long command is: `drupal module:install module_name`. and the short command is `drupal m:i`
> 2 votes

---
Tags: 7, files
---


# Question
Title: How to get distinct nodes for a view and its attachments?
I have a view of type "block" showing 1 node and another display attached to that block showing 3 nodes, in both displays nodes are sorted randomly, the problem is that I can't find the way to add a "distinct" for both views, so sometimes both displays show the same node because of the random sorting

Is there any way to solve it?

EDIT: I've posted an image with the real view, has you can see in this case first and the third nodes are duplicated, sometimes it happends because i need them to show randomly

# Answer
> 1 votes
Rather than using a block for the top node, and an attachment for the lower 3 (like you are using now), I would use just one block (or page) that shows only 4 nodes, chosen at random with `Global: Random` as a Sort criteria (you can specify only 4 items to be shown by changing the `Use pager:` option).

THEN I would override the the `Style output` template file for the block (in `Theme: Information` in the `Advanced` area) to style the output of the block, for example by defining two divs, one for the top node, and one that wraps the 3 nodes below. Then use CSS to tweak the presentation (for example, floating left the bottom 3 nodes)

There are many good tutorials on overriding views templates, for example here.

# Answer
> 2 votes
You can achieve you requirement by following below steps.

1. Under view **Advance** setting, click on **Query settings**.
2. Now select **Distinct** checkbox.

---
Tags: 7, views
---


# Question
Title: Multi-site with two sites sharing the same domain?
There is absolutely no problem to have multi sites, where:

* **domain1.com** points to site A
* **domain2.com** points to site B

But I want to have multi-site setup, where:

* **domain1.com** points to site A
* **domain1.com/blabla** points to site B

I was doing everything to solve it, for example using directory structure like that:

* domain1.com
* domain1.com.blabla

or using file sites.php with content:

```
$sites = array(
'domain1.com' => 'domain1.com',
'domain1.com' => 'domain1.com.blabla',
);

```

Nothing works, site 'domain1.com' takes all traffic.

FYI:

* I'm using nginx.
* I'm using Drupal 7.
* I do not want to use the module Domain as I want to have separated databases.

Please help!

# Answer
I have done this before. Given a generic `location / { ... }` entry for Nginx which serves `domain1.com` to make the subdirectory install work I did the following 2 steps. I am not aware of a solution that doesn't involve making a symlink.

**Step 1:**

In your Nginx configuration:

```
    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            index index.php;
            try_files $uri $uri/ @rewrite;
            expires max;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }

    location /blabla {
     try_files $uri $uri/ /blabla/index.php?$args;
    }
    location ~ /blabla/.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
            webuser /usr/share/nginx/html;
    }

```

**Step 2:**

Then wherever your docroot is for your site you add an alias with your subfolder name to the main docroot, allowing the path to be valid for Drupal:

```
$ pwd
/usr/share/nginx/html

user@localhost:/usr/share/nginx/html$ find . -type l -ls
41059    0 lrwxrwxrwx   1 webuser    webuser           21 Sep 25 01:58 ./blabla -> /usr/share/nginx/html

```

You will still need your `sites.php` configuration as you have listed. You will need to restart Nginx.
> 2 votes

---
Tags: 7, multi-sites
---


# Question
Title: How to make User Picture a required field?
I do not see any option to make User Picture required in Account - Manage Field settings as it is not a real field in D7. Any tips?

# Answer
You can do it by using these modules :

Register with Picture

> 1. Install and enable the module
> 2. Navigate to: **Configuration -\> Account Settings**. (admin/config/people/accounts)
> 3. Check **Enable user pictures** if it isn't checked already.
> 4. Confirm **Enable pictures on registration** is checked.
> 5. Use the **Registration Picture Field Weight** field to adjust the display order of the picture field on the registration form. It can be a negative or positive number.

user picture field

> 1, Add a image field to user, for example "field\_user\_avatar"
>
> 2,config this field,and make it show on user register form.
>
> 3,install this module, navigate to "admin/config/people/user\_picture\_field", here you can config the "Machine name of source field that used as user picture"
>
> When user register an account, he/she upload an image through image field "field\_user\_avatar", this image will be used as user's picture(avatar).
> 1 votes

---
Tags: 7, media
---


title: Ho to make a whole block clickable?

text:
# Question
Title: Ho to make a whole block clickable?
I have made the block and want it to be clickable(entire block) and we can provide the path to it?

Note: There is other question with same heading but it does not provide the answer and it is in context of views.

# Answer
> 1 votes
In the `template.php`, add an "**onclick**" attribute with **theme\_preprocess\_block**:

```
function mytheme_preprocess_block(&$variables, $hook) {
  if ($variables['block']->delta == "my-viewblock-name") {
    $variables['attributes_array']['onclick']='my_click-routine()';
  }
}

```

Then, in a `.js` file you add

```
function my_click-routine(){
  // Do whatever you want here, e.g. show the "page view" when clicking on the block view;
  document.location="page-view-url";
}

```

This makes the entire block clickable. You can also do more than just navigate to another page.

---
Tags: blocks
---


# Question
Title: Bluehost cloud hosting, varnish caching issue authenticated user
I have narrowed down my problem to varnish on my cloud server provided from bluehost.

When logged in you make an edit, but it is not reflected back until 5-10 minutes later.

Clearing all caches, browser history, etc. nothing helps expect logging into bluehost and clearing the varnish cache.

Any ideas?

# Answer
> 1 votes
Just to add that varnish **only work for anonymous user** not for authenticated.

There are various module available to purge varnish cached data on a particular event such as node insert, update, delete and many more.

Configure events properly in module configuration and that should do the needful.

Following are module :

expire

purge

---
Tags: 7, caching, proxies
---


# Question
Title: Sitemap still contains URLs of deleted pages
I've deleted some products from my commerce kickstart database by means of standard Drupal commerce kickstart tools. But it looks like something gone wrong. Because some deleted pages URLs are still in sitemap,so Google webmaster tools tell me about 404 pages.

I've rebuilt sitemap n+1 times but those URLs are still here.

What tables should I check to find tails have to be deleted manually? What tables does the sitemap module use to build sitemap file?

# Answer
if you are using the XMLSitemap module, uninstall it and run cron to delete its tables from the database, then reinstall it, it will generate the right urls
> 0 votes

---
Tags: uri, xml-sitemap
---


# Question
Title: How to create view of referenced nodes with fields?
I have `node reference` field which can take multiple values in it and I want to create a `view` of fields of these referenced nodes.

How do I achieve this?

# Answer
Adding node reference field to contextual filter and select "Provide a default argument" in it and select "Content ID from URL". This will do the needful.
> 0 votes

---
Tags: views, nodes
---


title: Profile2 not editable for new users

text:
# Question
Title: Profile2 not editable for new users
I have two different profile2 profiles, the usual stuff. I just found out that creating new profiles of *type a* makes it impossible for the user to edit his profile.

**How it should be:**

The user registers and goes to his empty profile, sees edit buttons and links.

**How it is:**

The profile is empty. you see the frame for where an image belongs, but no text at all, no buttons, no links.

I took over the project with very little documentation, already existing users have full and right functionality. I did a permission rebuild, checked them and tweaked them without any success.

The users have permission to view, edit and delete own content.

Where should I look for the problem? What could cause such behaviour?

# Answer
> 0 votes
It turned out to be a CTools problem, I simply applied the patch mentioned in this comment:

https://www.drupal.org/node/2336985#comment-9748735 (#16)

```
diff --git a/plugins/content_types/entity_context/entity_field.inc b/plugins/content_types/entity_context/entity_field.inc
index 5861d1c..070266e 100644
--- a/plugins/content_types/entity_context/entity_field.inc
+++ b/plugins/content_types/entity_context/entity_field.inc
@@ -129,8 +129,7 @@ function ctools_entity_field_content_type_render($subtype, $conf, $panel_args, $

   $all_values = field_get_items($entity_type, $entity, $field_name, $language);
   if (!is_array($all_values)) {
-    // Do not render if the field is empty.
-    return;
+    $all_values = array();
   }

   // Reverse values.

```

---
Tags: users
---


# Question
Title: Customize the output style of a view field
I have a view block, where fields are added in the table. I followed below steps to customize the output fields:

1. Navigate to the edit screen for a view (for example, admin/structure/views/view/MYVIEWNAME/edit).
2. In the Fields section, click a field. The Configure Field dialog box displays.
3. Click Style Settings.
4. Enabled the following options: Customize Field HTML
5. Specified the HTML element `<div>` to wrap around the item. and clicked on Create a CSS Class and specified a class name.
6. disabled the Add Default Classes option.
7. Clicked on Apply.

**The problem is, the specified class name in step no. 5**. got added to the corresponding `<td>` of the view table and not to the selected html element `<div>`

How to add class name for the specified HTML element `<div>` ?

# Answer
For this case, don't use Style Settings. Instead, use Rewrite results.

Click on Replacement patterns, to get the Token of your field.

Then just wrap Token inside div tag.
> 1 votes

---
Tags: views, entities, theming
---


title: wysiwyg upload image as background

text:
# Question
Title: wysiwyg upload image as background
I learn how to upload images by using IMCE Wysiwyg bridge module.

How about upload images and treat it as background picture?

# Answer
> 1 votes
the module ImageCache Actions suit your need. one of the effects that it provide is :

> Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency

---
Tags: 7, wysiwyg, files
---


# Question
Title: How to configure a Slideshow with thumbnails in modal window
I have tried to get the following scenario to work, with no success. I have 3 images. They are displayed in thumbnail form, in the bottom of a div. A main, preferred image, is displayed in a larger size above the thumbnails. I need that, when clicking on the thumbnail, the main image will change. So, in the image included, if I click on the green image, the main image will change from red to green.

Also I need that when clicking on the larger image, a modal window will appear, with a Slideshow of all the images, starting from the one clicked.

I have managed to make it work very easily with PHP-Javascript alone (10 minutes of programming) but I am not able to do it with none of the following modules: Colorbox, FlexSlider, Lightbox2.

Even when launching a View with FlexSlider content using Lightbox2, it works but it takes ages to load the content, even if I have disabled all extra HTML stuff by making a template tpl suggestion.

Sincerely, I don't think it is so complicated behaviour. Also there is the approach of FlexSlider with thumbnails, but I cannot manage to include the lightbox (modal window) effect.

# Answer
I was able to find a perfect solution to this, very easily as always. I use module Lightbox2, with the Slideshow option. Now I don't put the href with the reference to the big images in the small images - that would be standard behaviour, but I create 3 empty href with the data (the data come from an array passed to the .tpl.php):

```
<a href="<?php print $image_value["filename"] . "-960.jpg"?>" id="imagelink<?php print $conti; ?>" rel="lightshow[products]<?php echo $conti; $conti++;?>" ></a>

```

The images themselves have other code which just changes the main image:

```
function change_photo(filename, conti){
    var object = document.getElementById("product-photo");
    object.src = filename + "-480.jpg";
    contagen = conti;
} // function

```

And finally in the onClick of the main image, I launch the slideshow by simulating a click of the empty links at the begginning of the code:

```
function launchslide(){
    var object = document.getElementById("imagelink" + contagen);
    object.click();
} // function

```
> 0 votes

---
Tags: media, javascript
---


# Question
Title: Slideshow of images which are not a field of node
I have used FlexSlider module to create an image slider. It works perfectly. I create a content type, with image field, create several nodes of that type, and finally I create a View of that content type. In the Format of the View, I can choose the FlexSlider style, and I am done.

What I want is to use several large images, which are many (3.000) images, and instead of creating 3.000 nodes, I would like to have the images externally, in a folder and referenced by a table of its own, and do a Flexslider using the View that already have, with mimimum modifications. Is it possible to get the same effect but without using nodes? If I load the images into nodes using Feeds, it takes ages, and I have some problems, so decided to go with the images outside of the nodes. Maybe a SQL alter could do it?

# Answer
> 0 votes
I have solved the problem by using Lightbox2 module, which allows to render a Slideshow with no need of a View or configuring the images as fields of nodes.

You can see the solution with some code, in this other question and answer of mine. So this is a solution for someone looking for:

1. A gallery of many many images.
2. Slideshow with thumbnail.
3. Thumbnail + Medium image (detail of product, for example), with the Slideshow launched from the Medium image, no the thumbnails.

How to configure a Slideshow with thumbnails in modal window

---
Tags: views, nodes, media, javascript
---


# Question
Title: field_info_field API to get human readable name
We want get human readable name from field info API.
For e.g. in below API call
**field\_info\_field('field\_image')**

From UI for Drupal to add Article as below:

Can we get this human readable names i.e. Title, Alternate Text etc from API.

# Answer
> 0 votes
You can't, no - the labels are set statically in code (in image.field.inc), they don't come from the API:

```
// Add the additional alt and title fields.
$element['alt'] = array(
  '#title' => t('Alternate text'),
  '#type' => 'textfield',
  '#default_value' => isset($item['alt']) ? $item['alt'] : '',
  '#description' => t('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
  // @see http://www.gawds.org/show.php?contentid=28
  '#maxlength' => 512,
  '#weight' => -2,
  '#access' => (bool) $item['fid'] && $settings['alt_field'],
);
$element['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => isset($item['title']) ? $item['title'] : '',
  '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
  '#maxlength' => 1024,
  '#weight' => -1,
  '#access' => (bool) $item['fid'] && $settings['title_field'],
);

```

---
Tags: entities, media
---


title: Run Batch process every 1 hour

text:
# Question
Title: Run Batch process every 1 hour
Currently, I have a batch process that is triggered on a form submit.

With more detail, I have something like this:

```
function mymodule_form_submit($form, &$form_state) {
  // call some functions

  $number_of_sets = 5;

  $batch = array(
    'title' => t('Getting data...'),
      'operations' => array(),
      'finished' => 'mymodule_batch_finished',
      'init_message' => t('Starting ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => TRUE
    );

  foreach (range(0, $number_of_sets - 1) as $i) {
    $batch['operations'][] = array('mymodule_batch', array($cookie, $var1, $var2));
  }
  batch_set($batch);

  // call a final function
}

```

This works fine trough the GUI, i.e., manually submiting the form.

But I need to have the possibility to schedule this batch operation or, more correctly, I need to schedule all the code in that form submit.

This is what I've tried:

```
function mymodule_cronapi($op, $job = NULL) {
    $items['Import Data'] = array(
        'description' => 'Import Data',
        'rule' => '0 * * * *', // every hour
        'callback' => 'mymodule_proccessdata',
    );
    return $items;
}

function mymodule_proccessdata() {
  // call some functions

  $number_of_sets = 5;

  $batch = array(
    'title' => t('Getting data...'),
      'operations' => array(),
      'finished' => 'mymodule_batch_finished',
      'init_message' => t('Starting ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => TRUE
    );

  foreach (range(0, $number_of_sets - 1) as $i) {
    $batch['operations'][] = array('mymodule_batch', array($cookie, $var1, $var2));
  }
  batch_set($batch);

  // call a final function
}

```

So, basically, I call the same code in the form submit in the hook\_cronapi. Everything works fine except for the batch operation.

So, it is not possible to call a batch operation with cron?

I've read about using drupal `queue` but I'm really lost on how to adapt the code I have and I'm concerned that using `queue` will just schedule the operation and not do it at the precise time, like it's done with the submit.

Any toughts?

**EDIT:** I tried queue with no success. See below.

```
function mymodule_cron_queue_info() {
  $queues = array(
    'dothings' => array(
      'worker callback' => 'mymodule_proccessdata',
      'time' => 60*30,
    ),
  );
  return $queues;
}

function mymodule_cron() {
  $import_item = DrupalQueue::get('dothings');
  $import_item->createItem(array());
}

```

# Answer
Check with `drupal_is_cli()` if you are running from command line.

If yes, just fire the entire process instead, no need for batch-api as there will be no timeouts.
> 1 votes

---
Tags: cron, batch-operations
---


# Question
Title: How to build an url to access filtered view?
From a first view I need to dynamically build an URL to add a link to another filtered view named gallery\_details. I created a tpl template for my view where I build the URL like this one:

> http://www.example.org/?q=gallery-details&field\_main\_categorie\_value=Anciens&field\_categorie\_value=dessin&page=2

where `field_main_categorie` and `field_categorie` are the two used filters. When the two filters are "exposed" it works, but if I uncheck the exposed filters, this URL become invalid. I don't want to let the user to directly select the filters on gallery\_details, also a solution may be to hide the exposed filters in gallery\_details view.

I guess that there is a better solution.

# Answer
Have you tried using Contextual Filters in your view? It sounds like they do what you want.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Resetting a configuration object to "factory settings"
My module defines a configuration entity (specifically a BBCode tag macro with a template) that can be created and edited with a web form.

It can also be created by other modules using a `config/install/xbbcode.tag.*.yml` file - and of course those objects can also be edited and deleted.

Is there a way to access and recreate the original version of a config object that has been edited, without having to reinstall the whole module? I like the flexibility of customizing these templates, but users need to be able to restore the factory settings somehow.

# Answer
> 3 votes
Core does not provide such an API, not in a way that is easy to use.

There is a contrib module that provides this, but it's probably too complicated to rely on for a specific use case.

# Answer
> 1 votes
After thinking about this for a while, the solution may be to add a special "editable" flag on user-created objects, and block the update/delete operations on everything else with an entity access handler.

A custom "clone" operation could then be used to create an editable copy of the object, leaving the original unchanged.

---
Tags: entities, 8, configuration
---


title: How to use tokens in a node?

text:
# Question
Title: How to use tokens in a node?
I added a new content type. How can I use tokens when editing a node of that content type?

For example, if I put "*Hello \[user:name\]*", the page shows the following:

As shown above, the "*\[user:name\]*" token in it is not replaced with the username.

# Answer
> 5 votes
You need a text filter to replace tokens in fields. You can configure them in `admin/config/content/formats`. In drupal 7 you can install the needed text filter with:

Token Filter

But this will not be ported to drupal 8 in the same way as in drupal 7:

Issue Token Filter in Drupal 8

As this is a very simple piece of code, there is an unofficial version for drupal 8:

token\_filter-8.x

# Answer
> 4 votes
This is something one typically does with the Token Filter module. Some details from its project page:

> Token Filter is a very simple module to make token values available as an input filter.
>
> The module now supports native tokens (e.g. \[site:name\]) and all global tokens by default. It even allows some contextual tokens like node or user to be replaced, but currently does not encourage users to use them in the filter help text.

This module currently has a beta version for D8.

---
Tags: 8, nodes, tokens
---


title: Twig overriding parent variables

text:
# Question
Title: Twig overriding parent variables
I want to override the block.html.twig 'classes' variable in my block--system-branding-block.html.twig which extends block.html.twig. I tried to set the 'classes' inside block--system-branding-block.html but this didn't work.

**block.html.twig**

```
{%
 set classes = [
  'block',
  'block-' ~ configuration.provider|clean_class,
  'block-' ~ plugin_id|clean_class,
]
%}
<div{{ attributes.addClass(classes) }}>
 {{ title_prefix }}
 {% if label %}
   <h2{{ title_attributes }}>{{ label }}</h2>
 {% endif %}
 {{ title_suffix }}
 {% block content %}
   {{ content }}
 {% endblock %}
</div>

```

**block--system-branding-block.html.twig**

```
{% extends "block.html.twig" %}

{% block content %}
  {% if site_name %}
    <div class="site-name">
     <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>
   </div>
  {% endif %}
  {% if site_slogan %}
   <div class="site-slogan">{{ site_slogan }}</div>
  {% endif %}
{% endblock %}

```

I want to put another entry in the classes variable just for the block--system-branding-block.html.twig witch extends the block.html.twig

# Answer
It's not quite the approach you had in mind (modifying the classes variable) but I would recommend you do as Bartik does and work with the Attribute object instead:

```
{% extends "block.html.twig" %}

{% set attributes = attributes.addClass('new-class-goes-here') %}

{% block content %}
  {% if site_name %}
    <div class="site-name">
     <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>
   </div>
  {% endif %}
  {% if site_slogan %}
   <div class="site-slogan">{{ site_slogan }}</div>
  {% endif %}
{% endblock %}

```

I think the key thing here is that the variable you are modifying is initialized (and used) *outside* of the twig block. If the variable were initialized inside the twig block then I can see needing to override it inside the child templates's twig block as well.

More on working with Attributes in templates here: https://www.drupal.org/node/2513632
> 4 votes

# Answer
You can't "override" any variables from non-block.
In fact, what you must re-assign the `classes` array from inside a block in the child template (or in the same), like this:

```
<!-- block.html.twig -->

{% set classes = ['foo', 'bar'] %}

<!-- block--system-branding-block.html.twig  -->

{% extends 'base.html.twig' %}

{% block someblock %}
   {% set classes = classes | merge(['another-classe']) %}
{% endblock %}

```

On-line code working: http://twigfiddle.com/rav5tx
> 1 votes

# Answer
You can go like this in your .theme file:

```
function yourtheme_preprocess_block__system_branding_block(&$variables)
{
$variables['attributes']['class'][] = "yourotherclass";
}

```

That's if you use the standard block.html.twig - Code you are showing above seems to be not standard block.html.twig
> 0 votes

---
Tags: blocks, 8, theming
---


# Question
Title: In the OG API, which hooks are available when a group admin adds or removes a user from a group?
**Question:**

In the context of Organic Groups API, is there a hook that fires when an group administrator adds or removes a user from the group (or when a user self joins or self-removes their account)?

Ultimately, I was hoping for a hook that was fired around `og_group()` and `og_ungroup()` as that's how I best understand the API so far.

# Answer
You can find all OG hooks here.

You already mentioned two of them, but for the sake of a complete answer here are the hooks fired on membership add/edit/delete:

Also, as memberships actually are entities you can also use all hooks used for saving and deleting entities, like hook\_entity\_update and hook\_entity\_delete. You can find them in this list.
> 3 votes

# Answer
Well, this always seems to happen after offering a bounty. I stumbled upon these nifty hooks.

If anyone has a better idea, the bounty is still active..
> 0 votes

---
Tags: 7, organic-groups
---


# Question
Title: Is there an event before and after form is submitted via ajax?
Currently if a form is submitted via ajax is will show the throbber and "please wait" message(which can be configured on the ajaxified button that submits the form.

I would like to perform some additional actions before and after the form is submitted via ajax so I am looking for events that are being triggered and on which elements they are being triggered.

# Answer
When you look in `ajax.js` you find several prototype functions, that can be used like hooks in drupal:

core/misc/ajax.js:

```
 /**
   * Modify form values prior to form submission.
   *
   * @param {object} form_values
   * @param {HTMLElement} element
   * @param {object} options
   */
  Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
    // This function is left empty to make it simple to override for modules
    // that wish to add functionality here.
  };

```

You can override this prototype-functions in your own js-file:

```
(function($) {
   var ajaxBeforeSubmitOriginal = Drupal.Ajax.prototype.beforeSubmit;
   Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) {

      // your code

      // call original function since it can be already overridden
      ajaxBeforeSubmitOriginal.call(this, form_values, element, options);
   }
})(jQuery);

```

This is the most basic version. More info: https://www.drupal.org/node/1372840
> 7 votes

# Answer
I think the most simple way you can handle this(without worrying about Drupal at all) is by using Jquery methods described at http://api.jquery.com/category/ajax/global-ajax-event-handlers (more examples at https://stackoverflow.com/questions/5051276/how-to-know-which-element-in-body-triggered-ajax-request-in-jquery)

I'm not sure if Drupal 8 has some particular code for that, but with pure JS you'll be able, for sure.
> 1 votes

# Answer
You could use validateForm to trigger before your form is submit, you just need to get the triggered element. For the "after" part, you could check if your call/ajax code has worked (return a bool) and then do something.

I'm not to familiar with drupal 8 though but that the way I'll do it
> 0 votes

---
Tags: forms, ajax, 8
---


# Question
Title: Bash script to configure the database for a drupal site install not working
I have a bash script that I want to use to be able to configure a drupal site without having to go through the browser screens.

My setup is using XAMPP on MAC OS X with PHP

Directory for my files are `/Applications/XAMPP/xamppfiles/htdocs/zinco`

I've set up drush using composer.

The following command:

```
drush site-install standard --db-url='mysql://**phpmyadminusername**:**phpmyadminpassword**@127.0.0.1/**websitename**' --site-name=**websitename** --debug

```

Returns the errors:

```
Starting Drush preflight. [0.01 sec, 2.18 MB]                        [preflight]
Loading drushrc "/Users/chris/.drush/drushrc.php" into "home.drush"  [bootstrap]
scope. [0.01 sec, 2.18 MB]
Cache HIT cid: 7.1.0-commandfiles-0-db580a5f73406ff96a3c32b2bade2057     [debug]
[0.02 sec, 2.24 MB]
Bootstrap to phase 0. [0.09 sec, 6.16 MB]                            [bootstrap]
Bootstrap to phase 1. [0.09 sec, 6.16 MB]                            [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.09 sec, 6.52 MB]  [bootstrap]
Initialized Drupal 7.41 root directory at                               [notice]
/Applications/XAMPP/xamppfiles/htdocs/zinco/blah [0.1 sec, 6.52 MB]
Find command files for phase 1 (max=1) [0.1 sec, 4.58 MB]                [debug]
Cache HIT cid: 7.1.0-commandfiles-1-388d122ebce884666d6793a66ef4f7e2     [debug]
[0.1 sec, 4.58 MB]
Found command: site-install (commandfile=site_install) [0.1 sec, 4.58[bootstrap]
MB]
Calling hook drush_core_site_install_validate [0.14 sec, 6.55 MB]        [debug]
Returned from hook drush_core_site_install_validate [0.14 sec, 6.56      [debug]
MB]
Calling hook drush_core_pre_site_install [0.14 sec, 6.56 MB]             [debug]
Cache MISS cid: 7.1.0-alias-path--ba3c3f210d58349a27067f15d6ee74a3       [debug]
[0.15 sec, 6.67 MB]
sql-query: SELECT 1; [0.16 sec, 6.67 MB]                             [status]
Executing: mysql --defaults-extra-file=/private/tmp/drush_rUKuqF --database=blah --host=127.0.0.1 --silent  < /private/tmp/drush_BtklU5 > /dev/null
You are about to CREATE the 'blah' database. Do you want to continue? (y/n): y
Sites directory                                                         [notice]
/Applications/XAMPP/xamppfiles/htdocs/zinco/blah/sites/default
already exists - proceeding. [9.69 sec, 6.67 MB]
Drush bootstrap phase : bootstrap_drupal_site() [9.69 sec, 6.68 MB]  [bootstrap]
Initialized Drupal site default at sites/default [9.69 sec, 6.68 MB]    [notice]
Find command files for phase 2 (max=) [9.7 sec, 4.73 MB]                 [debug]
Cache MISS cid:                                                          [debug]
7.1.0-install_profile-66ecfeb9791a023150773849f1550c5d [9.7 sec, 4.73
MB]
Cache HIT cid: 7.1.0-commandfiles-2-adcbc259623838c285e92ee0febd23c7     [debug]
[9.7 sec, 4.74 MB]
sql-query: SELECT 1; [9.7 sec, 4.74 MB]                              [status]
Executing: mysql --defaults-extra-file=/private/tmp/drush_CHP0QP --database=blah --host=127.0.0.1 --silent  < /private/tmp/drush_LYzbtS > /dev/null
sql-query: DROP DATABASE IF EXISTS blah; CREATE DATABASE blah        [status]
/*!40100 DEFAULT CHARACTER SET utf8 */; [9.71 sec, 4.74 MB]
Executing: mysql --defaults-extra-file=/private/tmp/drush_iWxNeP --database=information_schema --host=127.0.0.1 --silent  < /private/tmp/drush_8im4te
  sh: mysql: command not found
Returned from hook drush_core_pre_site_install [9.72 sec, 4.73 MB]       [debug]
Calling hook drush_core_site_install [9.72 sec, 4.74 MB]                 [debug]
Starting Drupal installation. This takes a while. Consider using the [ok]
--notify global option. [9.72 sec, 5.03 MB]
Calling install_drupal(Array) [9.72 sec, 5.03 MB]                        [debug]
exception 'Exception' with message 'Resolve all issues below to      [error]
continue the installation. For help configuring your database server,
see the <a
href="http://drupal.org/getting-started/install">installation
handbook</a>, or contact your hosting provider.<p
class="error">Failed to connect to your database server. The server
reports the following message: <em>SQLSTATE[HY000] [2002] Connection
refused</em>.<ul><li>Is the database server running?</li><li>Does the
database exist, and have you entered the correct database
name?</li><li>Have you entered the correct username and
password?</li><li>Have you entered the correct database
hostname?</li></ul></p>' in
/Applications/XAMPP/xamppfiles/htdocs/zinco/blah/includes/install.core.inc:415
Stack trace:
#0
/Applications/XAMPP/xamppfiles/htdocs/zinco/blah/includes/install.core.inc(339):
install_run_task(Array, Array)
#1
/Applications/XAMPP/xamppfiles/htdocs/zinco/blah/includes/install.core.inc(77):
install_run_tasks(Array)
#2 /Users/chris/.composer/vendor/drush/drush/includes/drush.inc(719):
install_drupal(Array)
#3 /Users/chris/.composer/vendor/drush/drush/includes/drush.inc(705):
drush_call_user_func_array('install_drupal', Array)
#4
/Users/chris/.composer/vendor/drush/drush/commands/core/drupal/site_install_7.inc(80):
drush_op('install_drupal', Array)
#5
/Users/chris/.composer/vendor/drush/drush/commands/core/site_install.drush.inc(289):
drush_core_site_install_version('standard', Array)
#6 [internal function]: drush_core_site_install('standard')
#7
/Users/chris/.composer/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_core_site...', Array)
#8
/Users/chris/.composer/vendor/drush/drush/includes/command.inc(210):
_drush_invoke_hooks(Array, Array)
#9 [internal function]: drush_command('standard')
#10
/Users/chris/.composer/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#11
/Users/chris/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62):
drush_dispatch(Array)
#12 /Users/chris/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#13 /Users/chris/.composer/vendor/drush/drush/drush.php(11):
drush_main()
#14 {main} [9.93 sec, 11.64 MB]
Command dispatch complete [9.93 sec, 11.58 MB]                          [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   0.21       1      210.03

```

Can anyone advice me on how to get by this problem?

I'm not sure whether i'm putting in the right credentials to access mysql/phpmymadin, it's quite confusing. If someone could possibly walk me through them, that would be great.

Thanks in advance.

# Answer
`sh: mysql: command not found`

Either mysql is not installed at all, or the `mysql` cli tool is not on your $PATH.
> 1 votes

---
Tags: drush, database, configuration
---


# Question
Title: How to set product price with rules on checkout
I want to set the product price for a special SKU in checkout. Because i calculate the price based on the cart value this is needed.

I tried all rules but none is changing the price, how can this be done?

# Answer
You must be using the product pricing system, which requires a rule assigned to the "Calculating the sell price of a product" event. Rules on this event can make use of a variety of *Line item* related actions to manipulate the unit price of the line item, and you'd just add conditions to your rule to only apply pricing based on the product SKU.

See the FAQ on Rules data selection for information on checking the product SKU:

https://drupalcommerce.org/faq/rules-field-data-selection
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Admin (uid=1) access denied to custom module page
I'm developing a custom module and the last step is to add custom permissions. I've added the administrator role to the new permission, but I see "Access Denied" when viewing /ledger/reports/balance-sheet. I've cleared caches, reloaded the module, and rebuilt permissions. I've even dug into the users.module file in core to verify that it is entering the if uid==1 return TRUE; section of function user\_access(). Any help would be appreciated.

```
/***************************************************************
 * Drupal core hooks
 * *************************************************************/

/**
 * Implements hook_menu().
 */
function ledger_reports_menu() {
  $items = array();

$items['ledger/reports'] = array(
  'title' => 'Ledger Reports',
  'description' => 'List of available reports',
  'page callback' => 'ledger_reports_page',
  'access callback' => TRUE,
  'weight' => 10,
);

$items['ledger/reports/balance-sheet'] = array(
'title' => 'Test Balance Sheet',
'description' => 'The current balance of all asset, equity, and liability accounts',
'page callback' => 'ledger_reports_balance_sheet',
'page arguments' => array(3),
'access callback' => array('view ledger reports'),
'weight' => 10,
);

/**
 * Implements hook_permission().
 */
function ledger_reports_permission(){
  return array(
    'view ledger reports' => array(
      'title' => t('View Ledger Reports'),
      'description' => t('View the accounting reports.'),
    ),
  );
}

```

# Answer
> 2 votes
This:

```
'access callback' => array('view ledger reports'),

```

Needs to be:

```
'access arguments' => array('view ledger reports'),

```

Currently you're trying to make Drupal invoke a function by string while giving it an array - it's not going to like that very much ;)

---
Tags: 7, users
---


title: I can't upload images in CKEditor

text:
# Question
Title: I can't upload images in CKEditor
With Drupal 8 I'm having issues uploading images in a node.

I select an image in the upload dialog box and add it, yet when I go to view the page the image is not there? Directory permissions for image uploads are set to read/write.

When I inspect the source, I don't even see an image path.

My upload dialog box looks pretty crappy too.

>

What am I doing wrong?

# Answer
Resolved with update to Drupal 8.0.1
> 1 votes

---
Tags: media, 8
---


# Question
Title: strtotime() doesn't return unix timestamp in custom view when $row->field_date is an English date
I'm confused. I'm using a Global: PHP field inside a view to tweak the output of the row based on the date value of a certain field.

```
print (strtotime((string)$row->field_date));

```

Doesn't seem to return anything.

```
print $row->field_date;

```

Returns "Tuesday, December 1, 2015"

```
print strtotime('Tuesday, December 1, 2015');

```

Returns 1448956800

I've tried converting the $row object to an array just for fun with `get_object_vars($row)` but that didn't work either.

In my case I expect that `print (strtotime((string)$row->field_date));` returns the value (unix timestamp) 1448956800.

# Answer
> 1 votes
`$row->field_date` contains markup, not just the date/string value hence strtotime() won't/can't return a valid unix timestamp. To fix, try using strip\_tags() around the returned value of `$row->field_date` like:

```
strtotime(strip_tags((string)$row->field_date));

```

or use "Strip HTML tags" option checkbox under "Rewrite Results" in the "Configure field" dialog.

---
Tags: views, datetime
---


# Question
Title: Customizing menu link output (add badge)
I am new to drupal. I want to customize menu link

```
<ul class="nav nav-tabs sub-menu"><li class="menu-1308 first active"><a href="/" class="active">Top</a></li>
<li class="menu-1309"><a href="/all">All Posts</a></li>
<li class="menu-1310 last"><a href="/discussed">Discussed</a></li>
</ul>

```

to

```
<ul class="nav nav-tabs sub-menu"><li class="menu-1308 first active"><a href="/" class="active">Top</a></li>
<li class="menu-1309"><a href="/all">All Posts<span class="badge">42</span> </a></li>
<li class="menu-1310 last"><a href="/discussed">Discussed</a></li>
</ul>

```

Just add `<span class="badge">42</span>` next to "All Post" menu link.

# Answer
This is the function you'll need: https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_link/7

That allows you to overwrite the standard theme function. You could do an if statement to check for that specific menu link ID and do a custom output.

You'll need to put that in template.php within your custom theme and replace "theme\_" in the function name with the name of your theme
> 0 votes

---
Tags: theming, routes
---