# Question
Title: "Limit list to selected" and default to all selected?
When I set up an exposed filter with the "Limit list to selected items" option enabled, and select a subset of items in the "Options" list, when the view is presented, non of the selected items are selected by default.

If I turn off the "Limit..." option, then all items (checked and not) are shown, with the checked items selected by default.

Sorry if I'm not describing it more clearly, but I would like a limited list displayed, with all of its items selected by default.

Suggestions?

BTW - I'm using Better Exposed Filters to display the selection items as checkboxes and the exposed form is shown in a block.

Thanks. Bill

# Answer
If you want to define a default value for a limited list of items in a Views exposed filter, you can achieve it by altering the exposed filter in a custom module:

```
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  $filter_field_id = 'my_filter_identifier';
  if (isset($form[$filter_field_id])) {
    $options = array();
    $options['First option value']  = 'First option label';
    $options['Second option value'] = 'Second option label';
    $form[$filter_field_id]['#type'] = 'select';
    $form[$filter_field_id]['#options'] = $options;
    $form[$filter_field_id]['#default_value'] = 'First option value';
  }
}

```

In order to make it to work, you need to uncheck the "Limit list to selected" option in the Views exposed filter. Of course, you also need to know the real values of your list items.

If your Views default value includes multiple options from the list, and you do not want to allow the user to select multiple options at once, you will also need to add a new filter blocking the other undesired options.
> 1 votes

---
Tags: views
---


# Question
Title: Shopping cart delete button is not removing the correct line item.
I have 2 blocks on my shopping cart. The view block for the *Main Product* and another for the *Specials* ( which is an add-on), each block has their own delete button. I use a Views Field View on the *Main Product* block to call the *Specials* blocks. Each specials and main products are connected via node referencing. I can't use just 1 view block to show it like that because I need the added specials to be filtered/shown below the main product where it's connected.

When removing a *specials*, it deletes the line item properly but when I try to remove a *main product* it deletes the special that follows the main product and when there's no more special for that specific main product, it deletes the specials of other main product. It does not delete the line item where the remove is connected. I don't know why it works like that because each remove has their own line item.

# Answer
Sounds to me like both of your forms on the page have the same form ID and use the same numeric key (likely 0) to identify the first item in the form. Thus when you submit it, Drupal doesn't know how to differentiate which form was submitted and makes a best guess, removing the 0th item in that form.

Alternately, if your configuration is generating a form within a form, that's invalid HTML and would explain a similar confusion on Drupal's part for the processing of the form. You would need to find an alternate method for getting the secondary form on the page, such as using the block system to embed the second form on the page.
> 1 votes

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


title: Secure file download from other server

text:
# Question
Title: Secure file download from other server
This is an unusual one. Let's say I have two web servers A and B. How would I go about making a link to a file from a Drupal website on server A to a file on server B such that the link is secure (the link to the file can't be accessed directly/shared)? I would have some control over server B, but it would just be a standard web server.

The reason for wanting this is that I need to serve some files to users behind the "Great Firewall of China", but the website is within China.

# Answer
The first thing that pops to mind is to create a custom module, with a menu callback to obfuscate the real url. This is the same way the drupal private filesystem (`private://`) handles this.

* Create a menu entry in your custom module's `hook_menu()` to obfuscate the real url and perform access checks.

```
function my_module_menu() {
  $items['my-module/download'] = array(
    'title' => 'File download',
    'page callback' => 'my_module_page_callback',
    'access callback' => TRUE, // Let the page callback handle the checks.
    'type' => MENU_CALLBACK,
  );
}

```
* Have the page callback transfer the file and check access. Based on `file_download()`.

```
function my_module_page_callback() {
  $args = func_get_args(); // Get the path elements after `my-module/download`
  $target = implode('/', $args); // Join them into a string.
  $uri = 'http://some-other-server.com/files/' . $target;

  if (function_to_check_if_file_exists($uri)) { // Define this function yourself.
    $headers = array('Content-Type' => 'file mime-type'); // Set the correct mime-type for the file here.

    if (function_to_check_access()) { // Define this function yourself.
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

```

Accessing an url like `example.com/my-module/download/documents/1.pdf` should now serve a file from `http://some-other-server.com/files/documents/1.pdf`.

In order to register the files you will have to construct a file object, set the `uri` to `my-module/download/[remote-path]` and save the file to the `file_managed` table. Then attach the file to a node. There might be better ways for this, but this is what I can think of now.

```
$f = (object) array(
  'uid'         => 1,
  'filename'    => '',
  'uri'         => 'my-module/download/[remote-path]',
  'filemime'    => '',
  'filesize'    => 12345,
  'status'      => 1,
);
file_save($f);

$node = node_load(1);
$node->field_file[LANGUAGE_NONE][0] = (array)$f; // Add a file field on a content type and use the name here.
node_save($node);

```
> 1 votes

---
Tags: files, security
---


title: How to replace URL fragments?

text:
# Question
Title: How to replace URL fragments?
I suppose this is more of a PHP question.

I'm trying to work on some redirects that's outputting:

http://localhost/mysite/?q=node/add/cmsdeliverable%3Ffield\_demo\_id\_reference%3D1208

But what I need is this:

http://localhost/mysite/node/add/cmsdeliverable?field\_demo\_id\_reference=1208 How can I cut the ?q=, and replace the &3F with ?, replace %3D with =

# Answer
You need to enable clean URLs. From the documentation:

For Drupal 7:

1. Navigate to the Clean URLs configuration page (Administer \> Configuration \> Search and metadata \> Clean URLs)
2. Wait for the automated Clean URLs test to run.
3. Check or uncheck the Enable clean URLs checkbox
4. Click "Save configuration"

For Drupal 5/6:

1. Go to the Clean URL's (Administer \> Site configuration \> Clean URLs in Drupal 5) section of the administrative interface.
2. Look for the paragraph that reads as follows:
> This option makes Drupal emit "clean" URLs (i.e. without ?q= in the URL.) Before enabling clean URLs, you must perform a test to determine if your server is properly configured. If you are able to see this page again after clicking the "Run the clean URL test" link, the test has succeeded and the radio buttons above will be available. If instead you are directed to a "Page not found" error, you will need to change the configuration of your server. The handbook page on Clean URLs has additional troubleshooting information. Run the clean URL test.
3. Click on the Run the clean URL test link at the end of the above paragraph.
4. If the test is successful, set Clean URLs to "enabled" and save the configuration. If the test is not successful, use the steps below to fix your server configuration and try again.
> 2 votes

# Answer
Have a look at my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?". It explains how you can use the Rules module for al sorts of URL redirect.

Moreover it also includes lots of details about how the Rules URL Argument module may help to get you close to what you're trying to do.
> 0 votes

---
Tags: uri
---


title: Render element and caching

text:
# Question
Title: Render element and caching
I'm a little bit confused with hide() documentation. It says:

> The first time render() or drupal\_render() is called on an element tree, as each element in the tree is rendered, it is marked with a "#printed" flag **and the rendered children of the element are cached**. **Subsequent calls to** render() or **drupal\_render()** will not traverse the child tree of this element again: they will **just use the cached** children. So if you want to hide an element, be sure to call hide() on the element before its parent tree is rendered for the first time, as it will have no effect on subsequent renderings of the parent tree.

First of all, I want to say I understand that hide() allow to avoid rendering of a specific element.

But documentation says more :

1. By talking about caching element as it is the default behaviour. For me, if #cache property is not defined for an element, when rendering the element will be not be cached.
2. And for me also, **subsequent calls to drupal\_render()** will not use the cached element, because *#printed* property will be checked before trying to get the cached element (#printed=TRUE means return '';) .

I want to get your explanation about this.

# Answer
> 1 votes
Render arrays are trees. If you `hide()` the subtree `P1.P2.P3.P4`, it's stil possible for a supertree (`P1.P2` or `P1.P2.P3`) to have caching enabled (i.e. have `#cache` set).

Also note that just having `#cache` set does not mean that the subtree with that element as a root does not get cached per se. Only when `#cache[keys]` is set is render caching triggered. `#cache` can also just contain cacheability metadata (tags, contexts, max-age) describing the cacheability of that subtree.

See https://www.drupal.org/developing/api/8/render/arrays/cacheability.

---
Tags: caching, theming
---


# Question
Title: How to set type="email" attribute on a Drupal form textfield
I'm doing some mobile forms with Drupal and have an email address textfield that currently has type="text" in the resulting HTML. I'd like this to be type="email" instead so that iOS shows a more useful keyboard when entering the email address.

I tried adding:

```
"#attributes" => array("type" => "email")

```

to my field but it seems to just get ignored by Drupal. Is there a correct and/or supported way to achieve this?

# Answer
> 5 votes
As it stands, Drupal core doesn't support all HTML5 form elements. The Elements module will add some support though, so check that out.

> HTML5 elements (url, email, search, tel, number, range)

# Answer
> 6 votes
Elements which are `input[type=email]` are a builtin as of Drupal 8. They can be added (along with other HTML5 elements and markup) to Drupal 6 or 7 via the Elements module.

As of writing this answer, I found the Element-module docs quite scant; they don't explain that the method for getting an e-mail input-element is slightly different than how it's done in D8. For Drupal 7:

```
/**
 * Implements hook_form().
 * "For long-lasting relief you can count on!"
 *
 * hook_form() functions are passed a form-node,
 * plus extra state-info if present.
 *
 * At the end of the function, the form-node should
 * be returned to the caller.
 *
 */
function mymodule_form($node,&$form_state) {

    $node['primary_email'] = array(
        '#type' => 'emailfield',
        '#title' => t('Submitter'),
    ); // in Drupal 8, it's '#type' => 'email'

    return $node;
}

```

Be sure to have the Elements module enabled before you expect the above to work. Also, if you haven't already, you'll also want to make the form accessible by doing something like:

```
/**
 * Implements hook_menu().
 * "Money back guarantee!"
 */
function mymodule_menu() {

    // create primary menu-entry for module:
    $items['mymodule'] = array(
        'title' => 'My Very Own Module',
        'page callback' => 'mymodule_description',
        'access callback' => TRUE,
        'expanded' => TRUE,
    );

    // create menu-entry for form:
    $items['mymodule/myform'] = array(
        'title' => 'My Very Own Form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_form'),
        'access arguments' => array('Behold, the form.'),
        'file' => 'mymodule.module',
    );

    // ...[maybe add more stuff here]...

    return $items;

```

The other elements made available by Element are listed at cgit.drupalcode.org/elements/tree/elements.module#n7.

# Answer
> 1 votes
Instead of adding a form validation handler to the form, you can add a validation handler to the form element that needs to be validated:

```
$form['email'] = array(
  '#type' => 'textfield',
  '#title' => 'Email',
  '#required' => TRUE,
  '#element_validate' => array('myelement_email_validate')
);

```

The validation handler receives three arguments: The form element being validated, the $form\_state and the $form array for the form containing the form element.

```
function myelement_email_validate($element, &$form_state, $form) {
  $value = $element['#value'];
  if (!valid_email_address($value)) {
    form_error($element, t('Please enter a valid email address.'));
  }
}

```

# Answer
> 0 votes
this is how i have done it:

```
 $form ['group_coordonnees'] ['field_candid_email'] = array (
        '#type' => 'textfield',
        '#title' => t ( 'E-mail' ),
        '#default_value' => '',
        '#required' => TRUE

);

$node->field_candid_email ['und'] [0] ['email'] = $form_state ['values'] ['field_candid_email'];

```

The field type of field\_candid\_email being selected in the back office as email

# Answer
> -1 votes
on Drupal 7 you can:

```
 $form['msg'] = array(
   '#type' => 'text',
   '#attributes' =>array(
     'placeholder' =>  'some text' ,
     'required' => "" ,  //required field
     'type' => "email" ,
   ),);

```

---
Tags: forms, emails, theming
---


title: Flood control IP bypass whitelist

text:
# Question
Title: Flood control IP bypass whitelist
I am utilising Services to open up some login resources on my site and as a result if multiple users incorrectly try to sign in the entire external website will be blocked because of flood control.

Is there a way to add an IP whitelist to the flood so that there can be an unlimited number of requests from those IPs without them being blocked?

# Answer
> 0 votes
Try flood\_unblock module and flood\_control I think both will help you with your requirements, choose the best based on your use case.

---
Tags: users, services
---


# Question
Title: Can we load core css files from custom theme with yml lib?
Is there a way to provide f.e normalize.css within my custom template using a \*.libraries.yml config file? Tried the following, didnt work out. I was just wondering if this would be possbile, for it seems to be nice, while the file comes with drupal8 installation.

```
global-styling:
  css:
    theme:
      css/style.css: {}
    core:
      normalize-css/normalize.css: {}
  js:
    dependencies:
      - core/modernizr

```

# Answer
The first attempt to load the single file `normalize.css` is not correct. If you want to do it this way, you have to use the full path to this file.

But this is not the preferred way to do this. You don't know if in future the position of this file will change. Better use the library already defined in core, as you have done in the second attempt to load modernizr. This will work, if you put the key `dependencies` on the first level of the array, for example see the core library `date`:

```
drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

```

If you look for normalize.css, this is defined in core:

```
normalize:
  remote: https://github.com/necolas/normalize.css
  version: "3.0.3"
  license:
    name: MIT
    url: https://github.com/necolas/normalize.css/blob/master/LICENSE.md
    gpl-compatible: true
  css:
    base:
      assets/vendor/normalize-css/normalize.css: { weight: -20 }

```

And you can use it as dependency in \*.libraries.yml:

```
  dependencies:
    - core/normalize

```

Or as library in the theme.info.yml file:

```
libraries:
  - core/normalize

```

If you use a core library, you don't have to put it in your own library, you can choose the direct way to use it.
> 1 votes

---
Tags: 8
---


# Question
Title: Loading in JavaScript that requires custom vars
I'm rebuilding one of my works modules from Drupal 7 to Drupal 8 and I'm 99% of the way there the one thing I'm stuck on is in some cases I need to load in a external library that changes on a users location and other which is defined in a settings form:

In Drupal 7 I'd simply do it with:

```
drupal_add_js($proto.'://f1.'.$region.'readspeaker.com/script/'.$customerid.'/ReadSpeaker.js?'.$srcparams,array('group' => JS_DEFAULT, 'type' => 'file', 'scope'=>'footer', 'preprocess' => FALSE));

```

But I'm not sure how to achieve this by creating a library in Drupal 8.

# Answer
If the settings are global and don't vary per use, I'd implement hook\_library\_info\_alter() and dynamically set the path there. JW Player does something like that: http://cgit.drupalcode.org/jw\_player/tree/jw\_player.module?h=8.x-1.x#n206

Remember to clear the cache when the settings are changed, so this is updated.

If it's something completely dynamic, or per user or so, you have to either write JS to load it or embed the js tag yourself, e..g with html\_head.
> 1 votes

---
Tags: 8
---


title: Start nodejs server on centos

text:
# Question
Title: Start nodejs server on centos
I install Nodejs integration module in drupal7, then install Nodejs package on CentOS 6.4; In instruction nodejs integration i see: 'In your terminal window, start the node server using the following command:'

```
node server.js

```

but in module directory, i haven't file "server.js"

can anyone help?

# Answer
> 0 votes
The server.js file has indeed been removed from the package. The solution is in the readme:

> # Setup
>
> 1. Install drupal-node.js packge with npm:
>
> npm install drupal-node.js
>
> Make sure to do this outside of your Drupal modules directory, else Drupal may try to process folders containing Node.js module information and fail. Follow the install instructions in the drupal-node.js NPM package. You will need to provide the hostname and port of your Drupal site to the Node.js process, and ensure that the service token matches between Drupal and Node.js.

I suppose they separated the server from the Drupal module to allow more frequent updates. The npm package contains a settings file and `app.js`, which includes `server.js`.

---
Tags: 7
---


title: public file name encoding on windows

text:
# Question
Title: public file name encoding on windows
I have to deploy a drupal 7 site built on Linux on a windows machine. Some (image) files are referenced via the public file mechanism. Some of them have special characters in their names, encoded in UTF-8 (AFAIK)

Files directly referenced are correctly handled by apache, for example: `http://localhost/lv/sites/all/themes/bizz/images/1.pr%C3%A9sentation.jpg` But the ones that are referenced via drupal public files cannot be accessed; for example `http://localhost/lv/?q=sites/default/files/styles/large/public/2.teint%C3%A9_60_380X448_2.png&itok=RvL-USAY` returns a 404

The file exists in the filesystem (as `2.teinté_60_380X448_2.png` and as `2.teint├®_60_380X448_2.png` \[that was the name I got in the zip export file\]) I tried `2.teintÃ©_60_380X448_2.png` (UTF-8 as latin-1) too, but without more luck.

Is there a way to get drupal finds these files without editing all posts ?

# Answer
> 0 votes
I was wrong, `2.teintÃ©_60_380X448_2.png` works, now I only have to write a script that converts all filenames to utf8, and use it as latin-1, great :/

---
Tags: files
---


# Question
Title: Why does Drupal store each custom field in a separated table?
I understand that, in order to add functionality to nodes and node types, extra fields must be created in the database.

Now, I don't see why a one-field-one-table schema is used instead of favouring the schema of just a single table for a content type, and then, in that additional table, all the extra fields. What are the adventages of that approach?

I have a site with 1,000+ tables and is being a mess to administer.

# Answer
Because you can reuse the fields and attach them to more than one content type for example.

You actually get 2 tables for each field: one for storing the current version of the data (`field_data_field_MACHINE_NAME`), and the other one for storing the "historic" (if revisions are enabled) values (`field_revision_field_MACHINE_NAME`). Some content types can have enabled revisioning, meaning that shared fields need to be "flexible" enough to follow up with that, but at the same time store the values for content types with disabled revisioning.

If you had everything in one big table for content types (I think D5 did this), it would be a really big mess to manage, especially if you would share fields between entities (e.g. nodes and users).

Few suggestions:

* See this answer by Clive for more information.
* Inspect this on a clean install just to see how it works. Create 2 content types, add some fields (share some of them) and track what has been changed and how is the data stored in the database. You could probably dig some documentation page, but I think this is the best way to understand the schema.
* Reuse the fields whenever you can in order to optimize the database more. Be aware that there might be some limitations (e.g. list options, file uploads, required or not, etc.) that will not let you customize fields for every instance, so you will have to create new ones.

I wrote this fairly quickly, but I hope I managed to explain it.
> 12 votes

# Answer
Great answer from Aram! Which includes an explanation of how "custom fields" are technically implemented in a Drupal database.

If you wonder where the "schema" (as in the question) originates from, I suggest a higher level of abstraction, which I (still) call the "data model" of which the Drupal database is a technical implementation. And that automatically leads to "Database normalization", a concept introduced by E. Codd. The most important concepts I remember from the time I graduated are these:

I do remember there were even more (like 4NF, etc.).

But the "Rule" we always used to measure the quality of our data model was this:

> "**Everything depends on the key, nothing but the key, so help me ... Codd**" ...

About the actual "creation" of such schemas (diagrams), eg to model many-to-many relationships: back in the 90s (the time of Windows 3.1 and OS/2) there was IBM's "AD Cycle". Part of the "hype" then was to use "CASE tools".

One of them was "**Bachman**", an "expert system" created/inspired by Mr. "*Charles W. (Charlie) Bachman*", who was heavily involved in the creation of IDMS (a DBMS used in mainframes ... still today!). That's also where the "*Bachman diagrams*" originate from (which are still in use today ...).

We used the Bachman tool to:

1. automagically validate our data model (the wait messages was something like "*wait while the bow tie expert advisor is verifying your design*" ...) and
2. automagically forward engineer such datamodel to DBMS implementations for IDMS or DB2 and
3. reverse engineer an existing database implementation (eg hierarchical IMS) to a data model.

It would be fun (interesting) to do some similar reverse engineering today with the Drupal database schema, to see how "Bachman" would evaluate its corresponding datamodel ... and discover possible violations of 1NF, 2NF or 3NF ... (if any).

**Note**: More interesting background info can be found in Add foreign keys to core, as suggested in @mpdonadio's comment below.

PS: I bet Dries, while he was graduating, must also have heard of Codd ... or "*Charlie*".
> 1 votes

---
Tags: entities, database
---


title: Drupal Views page URL problem

text:
# Question
Title: Drupal Views page URL problem
I've created page with Views, which is displaying gallery (image fields).

I've set the path to node/%/gallery.

Page is working when I access "http://example.com/node/9/gallery" but it doesn't work when I access it with alias "http://example.com/event/example-name/gallery"

Any ideas?

# Answer
do not use node/%/.. as your path, this will disturb the default routing system.

> change the view's path to gallery/% or something.

if you want to keep this url, register a local task like here How to add a local task tab to node view?

and in this page callback you can display the view with views\_embed\_view, in this case you will remove the path of the view, or change it to a test-path.

but still, the alias with /gallery needs to be registered too !
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to trigger an email for a buyer or seller who has not performed any activity for 30 days or more?
Is there any way to trigger an email for any buyer or seller who have not had any activity for 30 days or something like that.

Also Sending reminders to users that haven't logged in for 30 days.

Unpublishing content after user has not logged in for 30 days.

Deactivate accounts after user has not logged in for 30 days.

# Answer
> 2 votes
Finally i got the answer here: https://www.drupal.org/project/inactive\_user

**The inactive\_user module provides Drupal administrators with a way to automatically manage inactive user accounts. This module has two goals: to help keep users coming back to your site by reminding them when they've been away for a configurable period of time, and to cleanup unused accounts.**

**And another possible solution is:** Using rules for more advanced functionality would involve something similar to the following

Create a new Rule Set that passes the User and (possibly) a Date argument

Add a Check a truth value condition that verifies something like \[user:user-last-login-raw\] + 2592000 \< \[user:date-in-tz\] (2592000 is 30 days in seconds)

Add a Send a mail to a user action

Save that rule set and then do the following:

Create a new triggered rule for User has logged out event Add a Schedule "your rule set" action and pass +30 days as the Scheduled evaluation date

# Answer
> 1 votes
You can use hook\_cron, you can compare today's date and the seller not having any activity date and send an email.

```
function modulename_cron(){
   //your code
   //compare dates and send email
}

```

# Answer
> 1 votes
Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", which seems like a variation (not a duplicate) of your question. It uses the Rules module and includes a Rule and a Rules Component (both in Rules export format) that should help you to answer your question.

In your case, these tunings would apply:

* Create a variation of the "`field_next_article`" field (as in **Step 1**), and name it something like "`field_next_activity_deadline`" (such name change is not really needed, but makes it more easy to understand your rule).
* Adapt the eMail content in the Rules Component from **Step 2** (how to adapt it is only limited by your own imagination ...).
* Review the "Rules Event" in the rule from **Step 3**, to make it match with what you mean/expect by your "**... any buyer or seller who have not had any activity ...**". If you're fine with using the event "User logged in" then you're good to go. Otherwise, or additionally, you may want to use some other mechanism for the actual trigger of this Rules Component (to send the actual eMail). Here are 2 typical alternatives for such trigger:

+ Create a view (using Views), use the Views Bulk Operations (VBO) module for it, and then trigger the Rules component (from **Step 2**) as a VBO action.
    + When a seller of buyer performs some type of transaction on your site, have that "event" intercepted via Rules (via an extra Rule you'd write), and then use a Rules Action to just update the 30-days deadline of your `field_next_activity_deadline` field.

---
Tags: 7, commerce
---


title: one profile2 profile for 2 users

text:
# Question
Title: one profile2 profile for 2 users
I'm working on a website for the elemantary school of my kids. The parents should have the option to login to the site to consult information (children in classes, addresses of other parents,...).

Currently I've created one 'family' user account where the additional information (second parent, children, class, addresses) is stored in profile2. The problem is that when the parents are divorced the second parent should have also a user account (with a different password) but the profile2 information should be the same. So I need two user accounts with the same profile2 info.

How can I manage this in Drupal?

Thanx!

Jan

# Answer
> 0 votes
For your use case, I'd suggest using Organic Groups or the Group module.

Both modules allow grouping users / content. So each family could be a group with the parents / kids as members. Address information would be stored using a common group page, while the parents could still have different profiles.

In a later stage of your site you could also create groups containing all kids of a class and so on.

---
Tags: 7, users
---


# Question
Title: Drush updates core successfully to 7.32 but is still 7.31
I'm developing a site on Drupal 7 and using **drush 7.0-dev** to keep the core and modules up to date. I've run `drush pm-update` several times successfully in the past, until Drupal core version **7.32** came out. Everything seems to go fine and drush reports no errors, but the version still stays at **7.31** after the update.

Here's the output of two consecutive runs:

```
me@mybox:/var/www/customer$ drush pm-update
 Name    Installed Version  Proposed version  Message
 Drupal  7.31               7.32              SECURITY UPDATE available

Update information last refreshed: Thu, 10/23/2014 - 20:21
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications
to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.32.
Backups were saved into the directory /home/me/drush-backups/customer/20141023172524/drupal.                                                                                [ok]
No database updates required                                                                                [success]
'all' cache was cleared.                                                                                [success]
Finished performing updates.                                                                                [ok]
me@mybox:/var/www/customer$ drush pm-update
 Name    Installed Version  Proposed version  Message
 Drupal  7.31               7.32              SECURITY UPDATE available

Update information last refreshed: Thu, 10/23/2014 - 20:25
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications
to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n):

```

Am I doing something wrong? Why is the core not updating? Where should I start troubleshooting? I haven't tried a manual update yet, because I'd really rather get drush working again. The server is running Debian 7 and PHP 5.4.

# Answer
> 0 votes
I finally figured it out - it was a permission problem. I hadn't noticed some of the directories drush was trying to update belonged to another user. Drush had no write permissions there but reported no errors. A quick `chown` later the update completed just fine.

# Answer
> 0 votes
Try `drush up drupal`. That may do the trick.

# Answer
> 0 votes
I have been having a similar issue updating from 7.27 to 7.45 and I found that by changing my /etc/apache2/site-available adn editing my 000-default.conf file DocumentRoot /var/www

Mine were directing to the /var/www/html originally. Drupal now recognises the updates which I did using Drush but I now have an AJAX HTTP error... Please excuse any ignorance as I am new to Drupal and IT. I hope this helps others who like me found changing permissions does not solve the issue.

---
Tags: 7, drush, updating
---


# Question
Title: How to alter auto-complete exposed filter programmatically?
I created a views to show parent and child term together using autocomplete expose filter .. but its show only one child. I have same child for two different parent.but its show only one child. how to change this programmatically using view query alter. I need such type:

```
Parent . Parent-1
           locality-1
           locality-2
         parent-2
           locality-2
           locality-4

```

I need such type of result on autocomplete expose filter.

# Answer
> -1 votes
Here is a possible answer to this problem. First of all, a litte visual.

To get this working you need the following:

* Configure your View to display the exposed taxonomy filter as a dropdown. autcomplete will not work because you cannot have multiple entries with the same key in the generated JSON array.
* Optional: Install and configure the Chosen module \[https://www.drupal.org/project/chosen\] to get your dropdown to render nicely and offer autocomplete options.
* Optional: You can finally use some custom code for formatting the presentation of your list, here is a sample minimal module that adds the special arrow that you see in the screenshot.

```
define('YOUR_CUSTOM_TAXONOMY_AUTOCOMPLETE_PATH', 'mycustompath/1');
define('YOUR_EXPOSED_FILTER_MACHINE_NAME', 'field_tags_tid');

/**
 * Implements hook_form_alter()
 */
function se_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'views_exposed_form' ){
    if(isset($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]) &&
    $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#type'] == 'select'){
      $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options'] = _custom_update_options_for_taxonomy($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options']);
    }
  }
}

/**
 * Function that update select options for taxonomy filter
 *
 */
function _custom_update_options_for_taxonomy($options = array()) {
  $current_parent = '';
  foreach( $options as $i=>$option ) {
    if( is_int($i) && isset($option->option) && is_array($option->option) ) {
      $option_arr = $option->option;
      $tids = array_keys($option_arr);
      $tid = reset($tids);
      // is this a child of the previous parent
      if( strpos($option_arr[$tid], '-') === 0 && $current_parent != '') {
        $option_arr[$tid] = preg_replace('/^-/', ' ⤷ ', $option_arr[$tid]);
        $option->option = $option_arr;
      }
      // this is a parent node
      else {
        $current_parent = $option_arr[$tid];
      }
    }
  }
  return $options;
}

```

Hope this help some!

---
Tags: 7, views
---


# Question
Title: How to make a theme hook suggestion for blocks according to region?
Since Drupal 8 it is not possible with **template naming conventions** to load a specific **block template according to the region** it is placed in ("Per-region block markup and per-region block templating feature removed"). But I need to have different html for blocks if placed in a certain region. How do I accomplish this?

I've thought about using *MYMODULE\_theme\_suggestions\_block\_alter* but I don't know how to get the current region.

# Answer
You can get region if you get Block Entity.

**.module or .theme file**

```
use Drupal\block\Entity\Block;

function MODULE_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
  }
  /* Use this 'else if' only if you are using page_manager module and want to know which region is the block */
  else if (isset($variables['elements']['#configuration']['region'])) {
    $suggestions[] = 'block__page_' . $variables['elements']['#configuration']['region'] . '__' . end(explode(':', $variables['elements']['#plugin_id']));
  }
  return $suggestions;
}

```

**Edit 1:** Cover page\_manager module case.
> 22 votes

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


# Question
Title: Remove shortlink link and meta tag generator
I try to remove shortlink and generator link from my site.

```
<meta name="generator" content="Drupal 7 (http://drupal.org)">
<link rel="shortlink" href="http://landberg.at/nl/node/109">

```

I used below code in `template.php` but when i look in my source code its still there?

```
function landberg_html_head_alter(&$head_elements) {
    unset($head_elements['system_meta_generator']);
    foreach ($head_elements as $key => $element) {
        if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
          unset($head_elements[$key]);
        }
        if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'shortlink') {
          unset($head_elements[$key]);
        }
    }
}

```

What is best way to remove this?

# Answer
Above code is good but it didn't work because it was overwritten by Meta tag module. I adjust some settings in `Configuration » Search and metadata` and now `generator tag` and `shortlink` is gone.
> 4 votes

---
Tags: 7
---


# Question
Title: How to alter sort handler to keep existing order intact in views
I created a `views` page using `foo` plugin.When a user visit the page the **city** and **Clinic/Hospital** columns by default are being rendered **alphabetically (ASC)** as in below screenshot.

**EDIT:** Let's say for example. **City** is Bangalore and only for Bangalore **Clinic/Hospital(C/H) column** is alphabetically ordered(say Hospitals A,B,C,D...).Then user **clicks on City head**,then for Bangalore **C/H column is alphabetically disordered(ex B,D,C,H...) but records are still correct to Bangalore city means those clinic/hospitals are located in Bangalore** .Same goes for other cities too.What I want is C/H col should be ordered as earlier (alphabetical) City by City but no matter how city is ordered.

When user clicks on **City** head (which is **sortable**),the order of **Clinic/Hospital** goes heywire (no more alphabetical order) like below image:

**Problem:** How can I make my **Clinic/Hospital** order intact even after user clicks on **City** head.

Below is my `views` configuration:

I am using `Drupal 7.41` and `views 3.0`

**Tried so far:**

```
function mymodule_views_query_alter(&$view, &$query) {
   if($view->name == 'list_of_doctors' && $view->current_display == 'page_1' && count($query->orderby) == 1)
    {

        $query->orderby[1] = array(
             'field' => 'field_data_field_clinic_hospital_field_clinic_hospital_value',
             'direction' => 'ASC',
            );
    }
 }

```

}

But after clicking **City** head,whole **table** vanishes.

# Answer
> 0 votes
As I understand you want to be able to use a secondary sort after overriding the default sort by clicking on a column header.

This can be achieved from the front-end using jQuery plugin TableSorter as described here: https://drupal.stackexchange.com/a/125188/22915

Note this won't work for views with pagination.

It can also be achieved with some custom PHP code. Add the following to a custom module and change the CAPITALIZED words accordingly.

```
/**
 * Implements hook_views_query_alter().
 */
function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name === 'YOUR_VIEWS_NAME' && $view->current_display === 'YOUR_VIEWS_DISPLAY_NAME' && count($query->orderby) == 1) {
    $query->orderby[1] = array(
      'field' => 'YOUR_SECONDARY_SORT_FIELD',
      'direction' => 'ASC',
    );
  }
}

```

This code snippet will make sure that, no matter what column you use as main sorting, you always use a certain field as secondary sort. In your case this would be the Clinic/Hospital field (use system name in code).

Note: if the secondary sort field is not a sortable column, you can't use the query alias. So YOUR\_SECONDARY\_SORT\_FIELD needs to be something like: 'field\_data\_field\_name.field\_name\_value' instead of 'field\_data\_field\_name\_field\_name\_value'.

---
Tags: views, hooks
---


title: How to show comment via views?

text:
# Question
Title: How to show comment via views?
I have a content type nodes with comments. I need to show latest comment via views. For this I created a views its just showing me comment status. not comment.

# Answer
> 1 votes
To create a view of comments for a particular content type, what you have to do is create a new view and select `Comments` in 'Show' select list as shown in the pic :

After that go to `Filter Creteria` section and select the particular content type to which you want to show the comments. Also select the `Comment: Approved(Yes)` filter creteria.

---
Tags: 7, comments
---


# Question
Title: How to resend emails that Drupal already sent?
I need to theme emails that happen when a user completes a booking on our site or modifies there booking after this. Is there a way I can resend emails that Drupal has already sent? This would greatly speed things up for me not having to make new or edit existing bookings.

# Answer
> 0 votes
# Step 1: Create a view of all these bookings

First think of a way to create a view (using the Views module) of all those bookings for which you want to resend such eMails.

# Step 2: Create a Rules component for sending an eMail

Create a Rules Component that will be used in **Step 3** to actually send your eMail. Here is an example of such Rules Component to be created:

```
{ "rules_send_booking_email" : {
    "LABEL" : "Send Booking eMail",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Some information about your booking",
          "message" : "This is an update about your booking with reference [user-to-notify:field_about_some_booking] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

It uses (references) some field that was added to the "user" entity with machine name (say) `field_about_some_booking`. Feel free to adapt to any field name you have available. And/or use some other entity (eg a node about a booking?), instead of "user", to which this field might be related to. If you want, you can just import the above Rules Component (in Rules export format) in your own environment (via copy-paste), but make sure the machine name of the field matches with what you have available (otherwise the import will fail).

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

# Step 3: Get VBO involved to actually trigger all the eMails

Transform the view from **Step 1** into a Views Bulk Operations (=VBO) view. And have the actual VBO "operation" ***execute the Rules Component*** that you created in **Step 2**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

**Attention**: the size (volume) that needs to be processed might be another (extra) challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!

---
Tags: theming, emails, bookings
---


# Question
Title: What does the 'export' key mean in a schema definition?
The code below is from the message module. What does the 'export' section mean?

```
function message_schema() {
  $schema['message_type'] = array(
    'description' => 'Storage for user-defined message templates.',
    'export' => array(
      'key' => 'name',
      'identifier' => 'message_type',
      'default hook' => 'message_default_message_type',  // Function hook name.
      'primary key' => 'name',
      'api' => array(
        'owner' => 'message',
        'api' => 'message',  // Base name for api include files.
        'minimum_version' => 1,
        'current_version' => 1,
      ),
      'load callback' => 'message_type_load',
      'save callback' => 'message_type_save',
    ),
    'fields' => array(
      // Although the "name" should be enough as the primary key, the numeric ID
      // is required for the internal use of entity API.
      'id' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Numeric message type ID.',
      ),
      'name' => array(
        'description' => 'The unified identifier for a message type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'description' => 'Description for this message.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('id'),
    'unique keys' => array(
      'name' => array('name'),
    ),
  );

```

# Answer
> 1 votes
`export` is not something that is defined in the Drupal core Schema API. This is most likely a convenient way to store additional data that is used internally in the module or when integrating with another custom module.

# Answer
> 4 votes
These properties are used for implementing ctools export/import APIs.

See How to make configuration objects exportable with CTools.

# Answer
> 1 votes
'export' key is for export feature provided by ctools module. You can find more information from here

---
Tags: 7, database
---


title: How do I enable the Twig extension?

text:
# Question
Title: How do I enable the Twig extension?
In Drupal 8, Admin-Report \> Status report \> Twig C extension: Not available Enabling the Twig C extension can greatly increase rendering performance. See the installation instructions for more detail.

I installed Twig C Extension, but it's reported to not be enabled.

How do I install and enable the Twig extension for PHP, in Drupal 8?

# Answer
This should just work. Make sure to follow http://twig.sensiolabs.org/doc/installation.html#installing-the-c-extension and run the commands from within `/path/to/docroot/vendor/twig/twig`. Next, you should check again that `extension=twig.so` exists in your php.ini file and that Apache has been restarted/reloaded.

To confirm that the extension is being loaded, you can run `php -c /path/to/php.ini -i | grep twig`
> 2 votes

# Answer
In the latest Drupal 8 releases, the vendor/twig/twig/ext directory doesn't exist anymore.

To build the extension, I first globally required Twig, and then compiled the extension.

```
composer global require twig/twig:~1.0
cd ~/.composer/vendor/twig/twig/ext/twig
phpize
./configure
make
make install

```

Then, I edited the php.ini file to add a line about the new extension.

```
extension=twig.so

```

I ran the command on OS X 10.11. In a different OS, the directory where Composer put the packages globally required could be different.

I am using Drupal 8.0.4, but it could be that previous versions didn't have the ext/twig version already. From the other answers given here, I take that Drupal 8.0.1 already missed the necessary directory.

On OS X 10.11, I got the following error:

> PHP Warning: PHP Startup: Unable to load dynamic library '/Applications/DevDesktop/php5\_5/ext/twig.so' - dlopen(/Applications/DevDesktop/php5\_5/ext/twig.so, 9): no suitable image found.
> Did find: /Applications/DevDesktop/php5\_5/ext/twig.so: mach-o, but wrong architecture in Unknown on line 0

Following what reported in Compiling PHP extensions on Snow Leopard with XAMPP, I then tried with the following commands.

```
composer global require twig/twig:~1.0
cd ~/.composer/vendor/twig/twig/ext/twig
phpize
CFLAGS=-m32 CPPFLAGS=-m32 CCASFLAGS=-m32 ./configure
make
make install

```

After restarting Apache, the Twig extension was listed between the PHP extensions.

>

As of today (February 26, 2016), I was not able to compile the extension for PHP 7.0, since `make` fails with a warning and a fatal error.

> /Applications/DevDesktop/php7\_0/include/php/Zend/zend\_hash.h:134:15: warning:
> fastcall calling convention ignored on variadic function
> \[-Wignored-attributes\]
> `ZEND_API void ZEND_FASTCALL zend_hash_apply_with_arguments(HashTable *ht...`
>
> /Applications/DevDesktop/php7\_0/include/php/Zend/zend\_portability.h:231:39: note:
> expanded from macro 'ZEND\_FASTCALL'
> `# define ZEND_FASTCALL __attribute__((fastcall))`
>
> .composer/vendor/twig/twig/ext/twig/twig.c:23:10: fatal error:
> 'ext/standard/php\_smart\_str.h' file not found
> `#include "ext/standard/php_smart_str.h"`
> 1 votes

# Answer
I've just setup a Drupal 8.0.1 site

When I cd to /path/to/docroot/vendor/twig/twig and run composer require twig/twig:~1.0

It creates another vendor folder with psr and symphony in it. Like Simon South, if I run phpize in /path/to/docroot/vendor/twig/twig, it can't find config.m4.

I found that if I cd to /path/to/docroot/vendor/twig/twig/vendor and run composer require twig/twig:~1.0 again, it creates another vendor folder which contains another twig folder with the phpize config.m4 file at

/path/to/docroot/vendor/twig/twig/vendor/vendor/twig/twig/ext/twig

I also experimented with cd /path/to/docroot/vendor, and run composer require twig/twig:~1.0, and it create the needed config.m4 at path/to/docroot/vendor/vendor/twig/twig/ext/twig

Both work, but seems awful confusing for a newbie
> 0 votes

# Answer
A Drupal 8.0.2 Step-by-Step Solution derived from ir4georgia's comment.

I have to use "sudo". ymmv.

```
cd /path/to/docroot/vendor
sudo composer require twig/twig:~1.0

```

The above command creates a "vendor" sub-directory in the "vendor" directory.

Move the "ext" subdirectory of the vendor subdirectory into the original d8 twig directory:

```
sudo mv /path/to/docroot/vendor/vendor/twig/twig/ext /path/to/docroot/vendor/twig/twig/

```

Delete the second vendor directory

```
sudo rm -r /path/to/docroot/vendor/vendor

```

cd to the ext/twig directory

```
cd /path/to/docroot/vendor/twig/twig/ext/twig

```

Run the installation commands.

```
sudo phpize
sudo ./configure
sudo make
sudo make install

```

Add extension=twig.so to php.ini

Restart apache:

```
sudo apachectl restart

```
> 0 votes

---
Tags: 8
---


# Question
Title: How to trigger an email to someone who opens an account but never signs in?
Assume a user visited your site and signed up for an account, but such user never did **Sign in** to your site anymore.

Is there any way to generate mails to such visitors, for letting them know about your products and services?

# Answer
Yes there is a way to use the Rules module for this (as the tagging of your question seems to indicate), as detailed below ...

# Step 1 : Create a Rules Component to send an eMail

Create a Rules Component (say "*Rule1*") for sending an eMail that corresponds to the eMail you have in mind "***... for letting him know about your products and services*** ...". This Rules Component itself will not do anything on its own. Instead it will be used in a subsequent step.

Have a look at "Step 2" of my answer to "How to send an email to an author on a specific date using date field specified in a node?" for an example of such Rules Component.

If you have multiple types of eMails in mind, then create 1 such Rules Component for each of them.

# Step 2 : Schedule an eMail reminder

Create a rule (say "*Rule2*") which uses Rules Event "After saving a new user account" to schedule the execution of the Rules Component created in Step 1, e.g. X days after the new account was created.

Have a look at "Step 3" of my answer to "How can I set a reminder for a specific user to be triggered on a specific date?" for an example of how to schedule the execution of a Rules Component. More specifically the part in the Rules Action that starts with "`schedule`" (for this ignore the part with "`schedule_delete`").

If you have multiple types of eMails in mind (e.g. 1st eMail after X days, 2nd eMail after Y days, 3rd eMail after Z days) then schedule the execution of all these Rules Components right away. Or create a chain whereas the 1st Rule Component (for after X days), will schedule the 2nd Rule, etc.

Attention: if you're planning for multiple eMails, you should use some 'convention' to identify the scheduled eMails. E.g. by using an "`identifier`" (within "`schedule`") that is not just "`[account:name]`", but instead something like (e.g.) "`[account:name]-1`", "`[account:name]-2`" and "`[account:name]-3`".

If nothing happens (i.e. if such newly created user never logs in, you have your desired eMails in place for being sent after X (and or Y, and or Z) days.

# Step 3: Cancel eMail reminders when user logs in

Create a rule (say "*Rule3*") like so:

* Use **Rules Event** "User has logged in".
* Add a **Rules Condition** using "*Data value is empty*" to check if `account:last-login` is actually empty. If that's the case, it implies this user logs in for the very first time, which is exactly what you are interested in. Because from then on, you don't want to send the scheduled eMails anymore.
* Add a **Rules Action** to delete (cancel) the scheduled eMails. Have a look at "Step 3" of my answer to "How can I set a reminder for a specific user to be triggered on a specific date?" for an example of how to delete (cancel) the planned execution of a scheduled Rules Component. More specifically the part in the Rules Action that starts with "`schedule_delete`" (for this ignore the part with "`schedule`").

Attention: if you're planning for multiple eMails, you should use some 'convention' to identify the scheduled eMails to be deleted (cancelled). E.g. by using an "`identifier`" (within "`schedule`") that is not just "`[account:name]`", but instead something like (e.g.) "`[account:name]-1`", "`[account:name]-2`" and "`[account:name]-3`". And of course make sure these identifiers match with the convention you've used in Step 2 (to schedule those eMails).
> 1 votes

# Answer
Account reminder

> Account reminder is a simple module that will resend the welcome email to users who have registered with the site but have not yet logged in. The admin can control the initial time before sending a reminder, the time period between subsequent reminders and the total number of reminders to send. The email that is sent is also fully customization.

Mass Messaging

> This module allows you to send mass messages to users. To compose and select recipients the Views module is used. This allows complex selection queries setup by a administrator. The mapping of the view fields and the subject, recipient, message body and the attachments is done in the view. To send a message the view plus the arguments of the view are put into a queue. The cron does then send the messages in the background.
> 0 votes

---
Tags: 7, commerce, rules, emails
---


# Question
Title: How to know where the value of a field is being stored in
I have a `field_date` in a content type.

I want to do something like this on a `tpl.php`:

`$date->____________` (where the value of the field is being stored)

How can I know this?

# Answer
Sounds as if you are asking how to see what's available to you in a variable.

Install the Devel module, and just use the `dpm()` function:

```
dpm($variable);

```

It will use Krumo to represent the data you pass and display it on the page. If it's an array, it will show you all the elements, same for objects and so on.
> 1 votes

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


# Question
Title: How to create a views export in XLS format?
I have a view that extracts user informations. Now I need to export these results in XLS format. I have tried "views data export", but it is not supported in last Excel versions.

Is there some way that permits me to export data in XLS for the new Excel versions ? Or a good library to use via a custom module ? I'm a senior developer so I have no problem to use PHP and other features.

# Answer
The Views Data Export PHPExcel should suffice:

> This module extends Views Data Export module to allow XLSX files export.

That format is supported by Office 2007 and up.

Or go with what Brady said in comments and use CSV, it should be just as good.
> 2 votes

# Answer
To export views content in XLS format, you have to use Views Excel Export. This will export data in xls format.
> 1 votes

# Answer
Another approach is to use the Forena module, and leave the choice to your website user about the desired output format (CSV, XLS, XML, etc).

Have a look at the Simple Table of States example, and think of it as the equivalent of your "view to extract user informations". And note the hyperlinks in the upper right, which are:

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.

**Disclosure**: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: views, importing-exporting
---


title: How to export posts in excel?

text:
# Question
Title: How to export posts in excel?
I want to export posts with only these data to Excel:

* Post title
* Post URL
* Author
* Publish Date

How can I do so?

# Answer
Use the Forena module to create a "report" that includes the data that you're interesting in (Post title, Post URL, Author, publish Date). As part of the report design, indicate which export formats you want to allow for exporting the data included in it. **XLS** is one of the typical formats that are supported, but their could be other formats enabled also, such as CSV, XML, HTML, etc.

Have a look at the Simple Table of States example, and think of it as the equivalent of your "posts that you want to export". And note the hyperlinks in the upper right, which are:

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.

**Disclosure**: I'm a co-maintainer of Forena.
> 0 votes

---
Tags: importing-exporting
---


title: Acquia Drush Access

text:
# Question
Title: Acquia Drush Access
We are hosting a couple of sites on Acquia Cloud. Up to now I have SSH into the servers when I needed to execute any drush commands, but I want to start using drush on my local dev machine to execute commands on the servers.

Some of the commands work without an problems `drush ac-site-list`, but as soon as a SSH key is required (for example `drush @site.env status` I get a `Permission denied (publickey).` error message. I know this means that the public SSH key being used is not valid, and I also know why this is happening. I have only one SSH key for all the Acquia servers, but because there are different servers for the different sites, and in addition to that I have a couple of 'personal or private' key's; SSH does not know which key to use when I execute Drush.

For other SSH access (SSH in generate to other servers), I use a config file in my .ssh folder with aliases.

The problem is that I do not know how to tell Drush which 'ssh alias' from the .ssh/config file to use.
How can I achieve this?

# Answer
The Drush alias file has an option to provide additional parameters:

> 'ssh-options': If the target requires special options, such as a non- standard port, alternative identity file, or alternative authentication method, ssh-options can contain a string of extra options that are used with the ssh command, eg "-p 100"

Source: https://github.com/drush-ops/drush/blob/master/examples/example.aliases.drushrc.php

To have SSH use the right SSH key you can append it with `ssh -i path/to/key.pem user@server`. So in your alias file you should be able to add:

```
$aliases['alias'] = array(
  ...
  'ssh-options' => '-i path/to/key.pem',
  ...
);

```

I am not sure if you can use the keys defined in `.ssh/config`, because the config file automatically connects the SSH key with the host. So you'd be able to call `ssh user@server` and SSH should append the key. Therefore I doubt it can be used as I'd assume drush will automatically use `remote-host` and `remote-user` to build the SSH connection: `ssh remote-user@remote-host` and the keys from `.ssh/config` shoud be applied at that point.
> 3 votes

---
Tags: drush, ssh
---


# Question
Title: Simple key => value array with QueryInterface
I'm looking at building a simple key =\> value array with a certain type of node I have in order to generate a select list in a form.

The thing is that I have thousands of nodes of this type and the page takes forever to load with the current code I have.

Is there a way to load only certain fields using the QueryInterface in order to cut on loading times? Is there a more efficient way to do this?

```
$query = \Drupal::entityQuery('node')
  ->condition('type', 'product')
  ->condition('status', 1)
;

$nids = $query->execute();

$nodeStorage = \Drupal::entityTypeManager()->getStorage('node');

// Load multiple nodes
$nodes = $nodeStorage->loadMultiple($nids);

$list = array();

foreach ($nodes as $node) {
  $list[$node->field_code->value] = $node->title->value . ' (' . $node->field_code->value . ')';
}

```

# Answer
> 0 votes
The only way I know to do this is similar to what @Ivan Jaros mentions in the comment above. That is to use a Database service instead of EntityQuery service. There is a handy method on the query Statement, `fetchAllKeyed`, that I use all of the time in Drupal 7.

```
$database = \Drupal::service('database');
$query = $database->select('node', 'n');
$query->join('node_field_data', 'nfd', 'n.nid = n.nfd.nid');
$query
  ->fields('n', ['nid']),
  ->fields('nfd', ['title'])
  ->condition('n.type', 'product')
  ->condition('nfd.status', 1)
  ->execute()
  ->fetchAllKeyed();

```

Unfortunately this has drawbacks:

1. Multilingual - you need to do this manually in the query above.
2. Probably not going to work well with non-SQL drivers.
3. Might run into performance issues still because the data is not cached.

---
Tags: database, 8, entities
---


# Question
Title: Load external libraries in a custom block
I need to implement a custom block using JavaScript. These are the steps I took.

1. I created a custom module
2. I created a custom block by creating a class which extends blockbase
3. I created a JavaScript file
4. I defined a library in libraries.yml file and included the JavaScript file
5. I attached the library to the block using *#attached*

So far so good. In the JavaScript file, I am trying to use the open source Datatables library, but I am unable to add it.

This is the code that implements the block.

```
/**
 * @file
 * Contains \Drupal\custom_cms_blocks\Plugin\Block\TopNewsBlock.
 */

namespace Drupal\custom_cms_blocks\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides an 'Active forum topics' block.
 *
 * @Block(
 *   id = "top_news_min_block",
 *   admin_label = @Translation("Top News Min Block"),
 *   category = @Translation("Custom CMS blocks"),
 * )
 */
class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' => 'markup',
      '#markup' => '<table id="example_table"><thead><tr><th>Artist / Band</th><th>Album</th><th>Song</th></tr></thead><tbody><tr><td>Muse</td><td>Absolution</td><td>Sing for Absolution</td></tr></table>',
      '#attached' => array(
        'library' =>  array(
          'https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     );
  }

}

```

Can you explain me how I can include an external JavaScript file in a block?

# Answer
Libraries don't work like that. You need a yourmodule.libraries.yml and define it there.

There's detailed documentation on https://www.drupal.org/developing/api/8/assets#external. The following is an example of how a library is defined.

```
angular.angularjs:
  remote: https://github.com/angular/angular.js
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }

```

Then, the library that you specify is yourmodule/nameofthelibrary, see https://www.drupal.org/developing/api/8/assets#render-array or any of the other examples on that page.
> 5 votes

---
Tags: 8, javascript
---


# Question
Title: In D7, Where can you go to get a list of Access Arguments to be used with user_access()?
Where can I find a list of Access Arguments to be used with `user_access()` ? I went to the permissions page and I'm not sure what I can copy and paste from there to be used as an argument for `user_access()`. So far I only know two: 'access dashboard' and 'access content'

I want to find out how can we get a list of these arguments.

# Answer
> 2 votes
You can get a list of arguments for the site by running this in the terminal:

```
drush sqlq "select distinct(permission) from role_permission \G"

```

Make sure you clear cache after making permission adjustments. As my changes weren't showing.

---
Tags: 7, users
---


# Question
Title: Display all nodes for which user appears as a field on that user's profile?
I have a site with a content type "Projects," which has a field "Project Manager" that takes a user. Is there a good way to display all Projects for which a user appears as the Project Manager for that Project on that user's profile?

Update:

Here is what I have so far in user\_profile.tpl.php

```
...
function my_module_user_view($account, $view_mode, $langcode) {

  $my_field = 'field_pm';
  $uid = $account->uid; // The uid of the user being viewed.
  $query = "SELECT entity_id FROM {field_data_{$my_field}} WHERE {$my_field}_target_id = :uid AND bundle='user'";
  $args = array(':uid' => $uid,);
  $result = db_query($query, $args);
  $nids = $result->fetchCol();
  if (count($nids)) {
    $projects = node_load_multiple($nids); // Load all projects where that user is a PM
    foreach ($projects as $project) {
      $account->content['field_pm_projects'][0]['#markup'] = $project->title;
    }
  }
}
?>

<div class="profile"<?php print $attributes; ?>>
 <?php print render($user_profile); ?>
 <?php print $account->content['field_pm_projects']; ?></span>
</div>

```

# Answer
Add a contextual filter for that entity reference field and in its settings, provide default: uid from url. That will only show nodes where the uids match.

There are two options, "referenced" and "referencing".. I'm pretty sure you want referenced but try both.
> 1 votes

# Answer
If you are using entity reference for the Project Manager field, you could use (Entity)Reference Field Synchronization module and create another companion field ("Managed Projects") on the User profile. The module keeps them in sync so that if you add a username to the Project Manager field, the Managed Project field will populate automatically. The same would go in reverse. Views would be another option.
> 0 votes

# Answer
You have to utilize that reference field of yours. I'll try to give you a rough idea:

```
/**
 * Implements hook_user_view().
 */
function my_module_user_view($account, $view_mode, $langcode) {

  $my_field = 'field_my_field';
  $uid = $account->uid; // The uid of the user being viewed.
  $query = "SELECT entity_id FROM {field_data_{$my_field}} WHERE {$my_field}_target_id = :uid AND bundle='user'";
  $args = array(':uid' => $uid,);
  $result = db_query($query, $args);
  $nids = $result->fetchCol();
  if (count($nids)) {
    $projects = node_load_multiple($nids); // Load all projects where that user is a PM
    foreach ($projects as $project) {
      $account->content['field_pm_projects'][0]['#markup'] = $project->title;
    }
  }
}

```

You will need a second field (`field_pm_projects`) to store that info or you may print them on the theme direct, it depends on what you want to do. The chosen hook/preprocess also depends on the implementation you want to follow.
> 0 votes

---
Tags: 7, users
---


# Question
Title: how to retrieve refrencing parent id with EntityFieldQuery
I am very new to EntityFieldQuery. I understand how you create a query with this class. However, I have a node which is referenced (with Entity Reference) by a parent node. I would like to use EntityFieldQuery to retrieve the parent id. Can this be done?

# Answer
Without extending the class I'm pretty sure not. The reverse relationship isn't defined as a field, so `EntityFieldQuery` won't be able to help.

Don't forget entity reference doesn't define a parent/child relationship, it's literally just a relationship from one entity to another. A single entity can be referenced by any number of other entities, so the notion of a single 'parent' doesn't conceptually exist.

If you want more advanced relationships you might consider converting to the Relation module. It has a `RelationQuery` class which wraps around `EntityFieldQuery` to add relationship-specific functionality.
> 2 votes

# Answer
You can get the parent(s) of a referenced entity using `EntityFieldQuery` like this:

```
<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'PARENT_CONTENT_TYPE')
  ->propertyCondition('status', 1) // published? yes
  ->fieldCondition('field_ENTITYREFERENCE_FIELD_NAME', 'target_id', $CHILD_NODE_ID)
  ->range(0, 10);

$result = $query->execute();
if (isset($result['node'])) {
  $items_nids = array_keys($result['node']);
  $items = entity_load('node', $items_nids);
}
?>

```

You'll need to fill in the parent content type, the name of the entity reference field in the parent type and the ID of the child node in this code. The resulting `$items` array will contain all parent nodes that reference the child. Since EntityReference doesn't prevent it, there could be more than one parent node referencing the same child so you'll have to enforce a 1-to-1/parent-child relationship yourself.
> 1 votes

---
Tags: entities, database
---


title: Proper directory layout for tests

text:
# Question
Title: Proper directory layout for tests
I'm coming across what seems to be contradictory information, and I'm hoping someone here can clarify. The basic question is "what is the correct folder structure for PSR-4 style auto-discovery of classes in Drupal 8, particularly test classes, and how much flexibility is there in that structure?" (I apologize in advance about this, but I'm going to have to partially break up my question into comments, since I don't have enough reputation yet to post all the necessary links.)

I have run across the following conventions I'm about to list in subsequent comments. I'm hoping someone can clarify what the proper layout is. Or will all work? I could spin up a D8 instance and test this, but I'm afraid such a cursory examination would conceal pitfalls of one approach versus the other, in terms of community support.

# Answer
There are three different testing frameworks in Drupal 8.

### 1. Simpletest: Functional, Upgrade and Unit Tests

These should be located underneath `src\Tests` per the documentation linked in the Question comments. This corresponds to the namespace `Drupal\my_module\Tests`.

This is documented best at https://www.drupal.org/node/2166895.

### 2. PHPUnit: Unit Tests

Theoretically these could be anywhere with a phpunit.xml.dist file, but if you need to support running through Drupal's test runner (`run-tests.sh`) or drupal.org infrastructure then these must be placed in `tests\src\Unit` and the namespace corresponds to `Drupal\Tests\my_module\Unit`

### 3. Behat: Behavioral Tests

I think there is a movement to store behavioral tests in a directory parallel to `tests\src\unit`, but no official convention as Drupal core does not utilize Behat yet.
> 2 votes

---
Tags: 8, testing
---


# Question
Title: How to email the webform content to current page author email "Token [current-page:node:author:mail] is not working any more"
I have a content type topic, and a Webfrom "contact" as block which is available for topic content type only.

Any registered user can create topic, and I want to use the Webfrom to contact the topic author.

In the past I had a hidden field inside Webfrom with a token \[current-page:node:author:mail\] to send the Webform information to the current page author email "topic author".

After updating the Webfrom to version 7.x-4.9 the Webfrom stop sending email.

It looks like \[current-page:node:author:mail\] is not available any more.

I will be grateful if someone help me with identifying the right token to access the current page author mail. or suggest alternative way to achieve the same functionality.

Thanks

# Answer
After almost 4 weeks driving us crazy , we have finally found where is the problem. Thing is we were looking in the wrong direction.

Overwrite http://s000.tinyupload.com/?file\_id=06809135818916665525 after updating Token to 1.6. Just extract it on sites/all/modules/token. We don't know why yet. We have completely checked all the change logs, git commits and everything in Webform and finally decided to look in another direction.

You can update the Webform module as suggested by the module maintainers.

So, to have it back working, do the following:

1. Upgrade to Token 7.x -1.6 http://ftp.drupal.org/files/projects/token-7.x-1.6.tar.gz
2. Extract the file http://s000.tinyupload.com/?file\_id=06809135818916665525
3. Clear the cache

The token will be back.

We have obtained all the feedback from this post https://www.drupal.org/node/919760 and the patch applied is https://www.drupal.org/files/issues/token-current\_page\_object\_token-9197.
> 2 votes

# Answer
In order to make token `[current-page:node:author:mail]` working again, you need to apply this patch for Token module.

Source.
> 1 votes

# Answer
If You click email tab in webform,there is token option available. In that we can choose what we needed. I think,this option is suitable for your problem.

\[current-user:mail\]
> 0 votes

---
Tags: 7, nodes, webforms, tokens
---


# Question
Title: Is it possible to use the "Save & Edit" module with Rules?
I've created some rules to send notifications when changes some fields and it works as I expected when the user click on Save button.

After I enabled **Save & Edit** module but I receive notifications both if I click on **Save** and **Save & Edit** .

I want receive a notifications only when click on **Save** .

Is possible? Or is there another approach to achieve the same result?

Thank you in advance.

# Answer
> 2 votes
Just a simple concept: I could imagine using the Rules Forms module with the following Form API conditions:

* Form ID: form\_id == YOUR\_CONTENT\_TYPE\_node\_form
* Clicked button: $form\_state\['clicked\_button'\]\['#id'\] !== 'edit-save-edit'

# Answer
> 1 votes
> Or is there another approach to achieve the same result?

Another approach would be to add a field named "notify me" and of type Boolean

Then in rules Add Condition \>\> Data Comparison \>\> node:field-notify-me \>\> True

So you will receive e-mail only when the notify me is checked.

---
Tags: 7, rules, notifications
---


# Question
Title: Disable submit button if none selected using #states
The code

```
     $form['type'] = array(
      '#type' => 'select',
      '#title' => t('Type of new field'),
      '#options' => $field_type_options,
      '#empty_option' => t('- Select a field type -'),
      // '#empty_value' => 0,
      '#description' => t('Type of data to store.'),
      '#required' => TRUE,
    );

    $form['save'] = array (
     '#type' => 'submit',
     '#value' => t ('Save field'),
     '#states' => array(
       'disabled' => array(
         ':input[name="type"]' => array('value' => 0),
         // Tried value = NULL, value = FALSE - no luck
)),

```

);

The goal is to disable submit button if none selected from drop-down list. Which "value" should I provide? Tried "0", "FALSE", "NULL"

# Answer
> 4 votes
The "#empty\_option" will not give a value, which is needed for #states, a workaround is to add the default as an actual option:

```
$field_type_options = array( 0 => '- Select a field type -');

$form['type'] = array(
  '#type' => 'select',
  '#title' => t('Type of new field'),
  '#options' => $field_type_options,
  '#description' => t('Type of data to store.'),
  '#default_value' => isset( $form_state['values']['type'] ) ?  $form_state['values']['type'] : 0,
  '#required' => TRUE,
  );

  $form['save'] = array (
   '#type' => 'submit',
   '#value' => t ('Save field'),
   '#states' => array(
     'disabled' => array(
       ':input[name="type"]' => array('value' => 0),
      )
    )
  );

```

This allows #states to test the value and disable the item

# Answer
> 1 votes
The proper way to do this (no #empty\_option workaround) is to check for the empty string ('') value.

```
'#states' => array(
  'disabled' => array(
    ':input[name="type"]' => array('value' => ''),
  ),
),

```

# Answer
> 0 votes
You should add the #empty\_value at the same time.

empty\_option is the text empty\_value is the value

```
 $form['type'] = array(
'#type' => 'select',
'#title' => t('Type of new field'),
'#options' => $field_type_options,
'#empty_option' => t('- Select a field type -'),
'#empty_value' => 'blank',
'#description' => t('Type of data to store.'),
'#required' => TRUE,
);

```

Hope it works for you

---
Tags: 7, javascript
---


# Question
Title: How to create a theme date view with CSS styles?
I created my view (datev) that contains two field (date and description). I renamed my template views-view-datev.html.twig and views-view-fields--datev---block.html.twig.
I already have my CSS but I do not know how to use my template theme.

>

I want it appears like this.

# Answer
> I have my CSS to achieve this poster but I do not know how to add ?? how broken down the date for this display

Add 1 more Content: Even Date field.

Then for each Even Date field, select custom formatter.

for the first one put `d` (Note: there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change)

for the second one put `F Y` (Note: there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change)

### Result

**PS:** You can add CSS classes to your field under the fields STYLE SETTINGS, no need to use template files to add css classes.

Then, for example, you add `.cool { border: solid red; }` to your theme's css file.
> 0 votes

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


title: Nodejs integration for Chatroom

text:
# Question
Title: Nodejs integration for Chatroom
I am following the Nodejs integration documentation to set up Chatroom, but am a little confused.

In step 2, do we cd to the folder of nodejs installation, or the drupal nodejs module?

Also, what is the server.js file?

# Answer
> 1 votes
As pointed out by Neograph734 in the answer, the current Node.js integration documentation is outdated, and the working instructions for setting up the node.js server with Drupal is in the Node.js Integration readme.txt file.

First, `npm install drupal-node.js`, and then run `node app.js` in the drupal-node.js folder, where app.js replaces the old server.js in the current Node.js Integration documentattion.

# Answer
> 1 votes
Updated the documentation page.

In step 2, we need to move in to `nodejs` module folder inside your drupal's **sites** directory. Install the dependencies using package manager(npm). Most probably the `nodejs` module is installed at `sites/all/modules/nodejs`.

Also don't get confused by these notation (`path/to/your/nodejs/module/directory`). It used to say that it exist in some directory.

`server.js` holds the code related to your **express** application from configuring your app to starting your app. Express will be installed in your `node_modules` folder when you install the dependencies. `node_modules` will be created in you `nodejs` module(drupal site).

`node server.js` starts the **express** application from the location where **server.js** file is present.

Also you can follow the tutorial links provided by No Sssweat.

# Answer
> 0 votes
> In step 2, do we cd to the folder of nodejs installation, or **the drupal nodejs module**?

In **the drupal nodejs module** (`cd /sites/all/modules/nodejs` then `node server.js`)

Here is an installation video tutorial for Drupal 7

Here is an installation video tutorial for Drupal 8

---
Tags: 7, nodejs
---


# Question
Title: Error using Drupal Feeds to upload a comment in a text field
I am loading data from a CSV file into a content type and everything is working fine except when I try to import a long text field / comment field. The data in the comment field should be treated as straight text.

Here is my data I am trying to upload via feeds:

> LP 8/28/13 strategy: extend to 2020. LP 4/8 LL First Allied rejected concept. LP 4/17 meeting: 5 yrs. LP 9/24/14 strategy: 10 yrs.3/2-Spoke w/Jordan Raines-First Allied last week. Submitted LOI on 3/2.

When I try to upload this, I receive the error message:

> SQLSTATE\[22007\]: Invalid datetime format: 1366 Incorrect string value: '\xFFexten...' for column 'field\_store\_comments\_value' at row 1

> SQLSTATE\[22007\]: Invalid datetime format: 1366 Incorrect string value: '\xFFexten...' for column 'message' at row 1

So my question is, how do I get Feeds import of a text string into a long text field to ignore the date strings in the comment? I do not want the dates treated as dates. I want the dates to be treated as a string of characters.

Or what am I doing wrong?

The CSV file has a comment in it. I know the Feeds map is correct because I put the test "This is a test comment" in the csv and it loaded fine. But when I put the full comment in, it does not work.

Any thoughts?

Thanks,

Dennis

# Answer
I was running into this same issue myself where half of my records were getting cut off when I uploaded them via the Feeds Importer. I found an answer that was posted on a Drupal forum that indicates that the problem is not with Feeds, but with the file itself.

It appears that by default Excel exports your CSV file into ANSI format, which creates issues when there are dates embedded within one of your fields. By using Notepad++ and converting the file into UTF-8 it works. Here is the link which gives more details.

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

NOTE: It also appears that if the file is encoded in UTF-8 BOM, then the CSV file can still be read by Drupal and Excel. Otherwise Excel treats it as a fixed length record.
> 1 votes

---
Tags: feeds
---


title: Change the submit function

text:
# Question
Title: Change the submit function
I am using VBO and I want to change the submit function on my form. I have tried the following code:

```
function a_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
  if($form_state['step']=='views_bulk_operations_confirm_form'){
    $form['#submit'] = 'a_myfunc';
  }
}

function a_myfunc(&$form, &$form_state, $vbo) {
  dpm('Hit');
}

```

The `a_myfunc` is not hit. Instead I go to the normal VBO processing page. How can I change the submit function\>

# Answer
> 0 votes
You're overriding wrong submit handler, normally VBO submit handlers are available under $form\['select'\] key in $form array. You can confirm this in your case by printing $form in hook\_form\_alter(). Make sure to use proper form ID as well before using, you can confirm form ID by printing $form\_id variable available in hook\_form\_alter(). Below is example of altering VBO Form and overriding submit handler (In my case I've only one submit button).

```
/**
 * Implements hook_form_alter().
 */
function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  // Confirm $form_id before using.
  // echo "{$form_id}<br>";
  switch ($form_id) {
    case 'VBO_FORM_ID':
      // In VBO, normally submit handlers are available under 'select' key.
      $form['select']['submit']['#submit'] = array('MODULE_NAME_vbo_submit');
      break;
  }
}

/**
 * Submit handler for Views bulk operations.
 */
function MODULE_NAME_vbo_submit($form, &$form_state) {
  // Do your processing here.
}

```

---
Tags: 7, views
---


# Question
Title: How do you exclude 'drush' & 'drupal console' requirements from a drupal-composer/drupal-project install?
When I create a Drupal project with

```
composer create-project --keep-vcs drupal-composer/drupal-project:8.x-dev myD8 --stability dev --no-interaction

```

it installs

```
Latest version of drush is installed locally for use at vendor/bin/drush.
Latest version of DrupalConsole is installed locally for use at vendor/bin/drupal.

```

I installed & maintain system instances of drush & drupal console.

I don't need the local installs. I don't want to install them to disk at all.

How do you configure the 'composer create project ...' to not require/install drush & drupal console?

# Answer
> 2 votes
You can remove these after the fact:

```
composer remove drush/drush
composer remove drupal/console

```

However, it is recommended that you should use local installs of Drush and Drupal Console when using Drupal 8. If you use global versions of these tools, then you run the risk of running into `dependency hell` \- incompatibilities between requirements of Drush or Drupal Console that do not align with what is used in Drupal 8. When you use a global cli tool to bootstrap Drupal 8, then the cli tool will load two autoloaders. If the same library exists in both autoloaders at different versions -- even just a "dot release" difference -- then you could get into a situation where every command aborts with an unrecoverable error.

If you only maintain a single version of Drupal 8 on your system, and carefully keep the versions of Drush and Drupal Console in alignment with that, then it will typically work, so you may remove the local version if you wish. The diagnostic efforts required when something goes wrong is quite extensive, so be cautious if you make this choice.

---
Tags: drush, installation, composer
---


# Question
Title: How to use field variables in un-formatted view template?
If found this, but I can't manage to apply it to my case. Here goes. (I'm new to PHP coding and Drupal.)

I want to add a HTML link into each row of my unformatted views template. For each row I want the link for the relevant piece of content.

I used the devel dpm to reveal the variables in the unformatted.tpl.php. But I can't find a variable for the link field. (I've added the Content: Link field in views and it's hidden.)

My understanding at the moment is I'll need to set the variable in the relevant preprocess function, which might look like this:

```
 function mytheme_preprocess_views_view_unformatted(&$variables) {
    $link = Location of link field variable
}

```

And then use it in the views template:

```
<?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; ?>
    <?php print $link; ?>
  </div>
<?php endforeach; ?>

```

But I can't find the link information and I can't find similar examples so I've probably gone badly wrong. How would I do that and is my basic understanding ok?

# Answer
Ok so I've managed to get it working with:

```
<?php print $view->style_plugin->row_tokens[$id]['[view_node]']; ?>

```

I tried to use:

```
<?php print $view->style_plugin->row_tokens[$rows['id']]['[view_node]']; ?>

```

But it kept throwing undefined index errors, even though it was valid path from DPM.

rows (array) id (value)

id (the variable I used in the top working solution) didn't show in my DPM. Is that because I was calling it for the views unformatted tpl and id is a global variable?
> 0 votes

# Answer
Previous answer didn't worked for me, as the `row_tokens` array was empty for some reason. Though I managed to access the field using the following:

```
$view->style_plugin->row_plugin->nodes[$view->result[$id]->nid]->my_field_name

```

Here `$id` is the row index, and can be used to get the nid using the `$view->result` array.
> 0 votes

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


# Question
Title: How do I customize the location of a webform for a node type?
I'm customizing a node type and need to add a webform using the webform module. How do I add the webform in a custom location without having a machine name for the webform?

In the code below for example, I want to populate body content followed by the webform:

```
<div id="content">
    <?php print render($content['body']); ?>
    <?php print render($content['WEBFORM?!?']); ?>
</div>

```

And, yes, I know about displays and how you can change the location of a webform there - my node is too customized.

# Answer
> 0 votes
You were almost there. Use the following code.

```
<?php print render($content['webform']); ?>

```

Bear in mind that if you are rendering the webform *before* the line containing `print render($content);`, you would need to hide the output of `$content['webform']` first, and then render it manually. In this case the code would be similar to the following one.

```
<?php
// This would go at the beginning of the .tpl.php file, for better readability.
// Hide the webform from rendering, because we will do it manually.
hide($content['webform']);
?>
<div class="content"><?php print render($content); ?></div>
<div class="webform"><?php print render($content['webform']); ?></div>

```

Generally speaking, I think it is a good practice to always hide elements you want to render separately, just in case at some point you move them before the `render($content)` line.

---
Tags: 7, nodes, webforms
---


title: Drupal 7 SmugMug API

text:
# Question
Title: Drupal 7 SmugMug API
Has there been any work to get SmugMug to work on Drupal 7? I am about to move forward on developing a solution, but wanted to check before I went forward. I do know there was some to work with MediaWorks, but that is a bit of a limited solution and was developed for Drupal 6.

# Answer
2016 and I'm looking into this as well, now with regard to Drupal 8. I'm wondering about hosting the backend of our media assets locally. The lure of using an external system is to get a more light weight cms and an easier migration path. Part of our online core is a photo sharing platform similar to facebook's. So I need something robust. I can't use Google+ because Google does whatever Google wants to do. I can't use Flickr because I can't be sure that it will be around in 3 years. So Smugmug is a logical candidate.

Anyway, for drupal 7 i found a limited media integration to insert smugmug assets the normal way: https://www.drupal.org/project/media\_smugmug . Smugmug also has an extensive api to program against. https://api.smugmug.com/api/v2/doc
> 0 votes

---
Tags: 7
---


title: Where do custom Drush hooks go?

text:
# Question
Title: Where do custom Drush hooks go?
I am attempting to sanitize my database as described in this Acquia guide.

For my site, I need to sanitize all the usernames as well; I would like to sanitize the usernames exactly the same as the e-mail addresses.

The guide suggests using a hook such as this:

```
<?php
/**
* Implementation of hook_drush_sql_sync_sanitize().
*/
function modulename_drush_sql_sync_sanitize($source) {
    $query = "UPDATE content_type_profile SET field_primary_email_email = CONCAT(SUBSTRING_INDEX(field_primary_email_email,'@', 1), '@example.com');";

    $query .= "UPDATE content_type_profile SET field_work_phone_value = SUBSTRING(FLOOR(RAND() * 1000000000000) WHERE uid NOT IN  SELECT uid FROM users_roles WHERE rid=3) AND uid > 0 FROM 1 FOR 12)  WHERE field_work_phone_value IS NOT NULL;";

   drush_sql_register_post_sync_op('my-sanitize-id', dt('Sanitize email addresses and phone numbers'), $query);
}
?>

```

But since this is for Drush, I don't know where to put the hook. I tried modifying the code and adding it to an enabled module on my site, but when I ran sql-sanitize, it didn't pick up the hook.

This is what I did. In MYMODULE/MYMODULE.module, I added the following code:

```
/**
* Implementation of hook_drush_sql_sync_sanitize().
*/
function MYMODULE_drush_sql_sync_sanitize($source) {
    $query = "UPDATE user SET name = CONCAT(SUBSTRING_INDEX(name,'@', 1), '@example.com');";

   drush_sql_register_post_sync_op('my-sanitize-id', dt('Sanitize user names'), $query);
}
?>

```

# Answer
Looking at the drush code this is the function that looks for the "hooks"

```
drush_command_invoke_all('drush_sql_sync_sanitize', 'default');

```

following the path at the end is calling to:

```
drush_commandfile_list()

```

which is going to look for hooks implementations in the next folders:

* The "/path/to/drush/commands" folder.
* Folders listed in the 'include' option (see example.drushrc.php).
* The system-wide drush commands folder, e.g. /usr/share/drush/commands
* The ".drush" folder in the user's HOME folder.
* /drush and sites/all/drush in current Drupal site.
* Folders belonging to enabled modules in the current Drupal site.

So as @Clive suggested probably MYMODULE.drush.inc and MYMODULE\_drush\_sql\_sync\_sanitize should work.
> 4 votes

# Answer
You can run `drush -d status` (or any other command, `-d` for Debug) to see where drush actually looking for the files and what files it's trying to load, e.g.:

```
$ drush -d status
Using the Drush script found at /usr/local/share/drush/drush.launcher using pcntl_exec
Drush preflight prepare loaded autoloader at                         [preflight]
/usr/local/share/drush/vendor/autoload.php [0.01 sec, 2.99 MB]
Starting Drush preflight. [0.01 sec, 2.99 MB]                                                                                [preflight]
Cache HIT cid: 8.1-dev-commandfiles-0-80c764c89cea212b4c95e9b4349fa821 [0.02 sec, 3.06 MB]                                                                                [debug]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.06 sec, 5.67 MB]                                                                                [debug]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.06 sec, 5.67 MB]                                                                                [debug]
Scanning into /usr/local/share/drush/includes/.. for /.*aliases\.drush(8|)rc\.php$/ [0.06 sec, 5.67 MB]                                                                                [debug]
Scanning into /usr/local/share/drush/includes/.. for /self\.alias\.drush(8|)rc\.php$/ [0.1 sec, 5.68 MB]                                                                                [debug]
Scanning into /home/vagrant/.drush for /.*aliases\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /home/vagrant/.drush for /self\.alias\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/../drush for /.*aliases\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/../drush for /self\.alias\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/drush for /.*aliases\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/drush for /self\.alias\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/sites/all/drush for /.*aliases\.drush(8|)rc\.php$/ [0.14 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/sites/all/drush for /self\.alias\.drush(8|)rc\.php$/ [0.15 sec, 5.68 MB]                                                                                [debug]
Scanning into /var/www/sites/default for /.*aliases\.drush(8|)rc\.php$/ [0.15 sec, 5.69 MB]                                                                                [debug]
Scanning into /var/www/sites/default for /self\.alias\.drush(8|)rc\.php$/ [0.15 sec, 5.69 MB]                                                                                [debug]
Bootstrap to phase 0. [0.61 sec, 7.9 MB]

```

Basically you can copy drush files (such as `drushrc.php`, `*.drushrc.php`, `*.drush.inc`) into any of the following locations:

1. Drupal's `drush`, `../drush` or `sites/all/drush` folder relative to your document root (however `sql-sync` validation could not work here).
2. A `.drush` folder in your `HOME` folder.
3. Anywhere in a folder tree below an active module on your site.
4. `/usr/share/drush/commands` (this is configurable).
5. In an arbitrary folder specified with the `--include` option.
> 1 votes

---
Tags: drush
---