# Question
Title: How to hide username displayed in code with Omega 3 theme
Drupal 7 with Omega version 3 theme generates a username class for the article tag in the HTML code, something like :

`class="node node-page node-published node-not-promoted node-not-sticky author-USERNAME odd clearfix"`.

I'd like to avoid having the username displayed in the code for security reasons.

After investigating, this comes from the code `"omega_alpha_preprocess_node()"` in the `"sites/all/themes/omega/omega/template.php"` where you find the following line:

```
"$vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name); "

```

I copied the code of `"omega_alpha_preprocess_node()"` to the "template.php" of my Omega subtheme, I renamed the "`omega_alpha_preprocess_node()`" to "`MYTHEME_alpha_preprocess_node`" and removed the line "`$vars['attributes_array']['class']`". Unfortunatly, it does not work.

As of today, the solution I found is to remove the line "`$vars['attributes_array']['class']`" from the initial Omega template.php file, which is not the best practice, but it works and the username output as a class of an article tag is no longer displayed.

Can someone help me find a more elegant solution, as I'm not a very experienced Omega developer and I need guidance? Thank you.

# Answer
The theme function your trying to us is theme\_preprocess\_node, and you'r correct in replacing the Omega with \[yourtheme\].

The reason the function isn't getting called though is MYTHEME\_alpha\_preprocess\_node should just be MYTHEME\_preprocess\_node. Alpha is part of the theme name, so if you remove it, the function should start working for you once you clear your cache.

EDIT ---------------------------------

Because drupal's template functions are still hooks, you can't just override the preprocess\_node function, as omega's preprocess function is still going to run. However, what you can do is edit the $vars variable. Make sure you have the & in the param ( ie `function (&$vars)` ) so the vars is a reference.

From there, you should be able to modify the $vars\['attributes\_array'\]\['class'\] array and remove the unwanted class.

So if you put something like this in your code, that should get you close to where you might need to be.

```
function mytheme_preprocess_node (&$vars){
    $count = 0;
      foreach($vars['attributes_array']['class'] as $class){
        if(substr( $class, 0, 7 ) === "author-"){
          unset($vars['attributes_array']['class'][$count]);
        }
        $count += 1;
      }
}

```

EDIT 2 ============================

When I say remove the class from the var, I mean you should just be able to unset the variable (I updated my code snippet to show it inside the preprocess function).

You don't need to copy the whole of the omega\_alpha\_preprocess\_node. What you actually are doing when you define your own theme\_preprocess\_node function is your telling drupal you would like to modify the variables for the node before it processes it. Because your working from a subtheme, the parent theme is still going to run it's own preprocess functions. So that class will always be added via omega. However, because your subtheme's preprocess function is downstream, it will get the &$vars reference with that class already added to it. So instead of rewriting the function, all that is needed is to simply remove the class from the $vars variable that you received in your params.
> 1 votes

---
Tags: users, theming, security
---


# Question
Title: Panels "custom content" argument formatting
I'm using Drupal 7.4 with Panels 7.x-3.0-alpha3. When creating a "New custom content" and using context keywords (eg %node:field-integer), the numeric integer field I'm adding gets pulled through with a comma (eg 7,234 instead of 7234). This also happens when adding Node (tokens) items.

The field in question does not have it's display formatted like that in **Content Types \> Manage Display** either.

I believe that Tokens and Panels Context/Arguments is pulling this from the same location, but I'm not sure where it is configured like that.

I've also tried %node:field-integer-raw and -unformatted, as well as %node:field-integer:raw and :unformatted, but neither of those worked.

# Answer
> 0 votes
Just in case someone came here through a Google search, there is an answer to the specific question.

You can specify the default formatting of tokens by going in the Content Type in question, then in "**Manage Display**" tab, at the bottom of the page under "**Custom Display Settings**" you will have to enable the "**Tokens**" display.

The formatting that you choose for each field in this display will be used whenever you print the field through a token.

You could also use the Advanced Entity Tokens module, which allows you to specify a different view as an "extraction base" for your field formatters.

Edit:

Note that you can also create specific token formatters for profile2 entities by following the exact same method explained above. By default profile2 creates a single Display but there is still a **Custom Display Settings** option at the bottom of the page where you can enable the **Tokens** display and specify the formatters that you want to use for your Profile2 tokens wherever you use them (including Panels).

---
Tags: 7, panels, tokens
---


# Question
Title: How can I substitute field in hook_query_alter?
I have a query, with a date field, let's say it is aliased as *enabled*. And joined table with field *enabled\_for\_website*. In my query alter, I want to substitute global enabled with date specific to website user is viewing (domain access, but it doesn't really matter here).

I tried simplistic approach:

```
function MYMODULE_query_MYTAG_alter($products_query) {
  $products_query->join('website_has_product', 'wp', 'p.idProduct = wp.idProduct');
  $products_query->join('website', 'w', 'wp.idWebsite = w.idWebsite');
  global $user;
  if ($user->uid == 1) {
    $products_query->addField('wp', 'website_enabled', 'enabled');
  }
  $products_query->condition('w.WebsiteName', /*where are we */, '=');
}

```

I'm getting expected error:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1052 Column 'enabled' in order clause is ambiguous

Is there a way to remove other column? `SelectQuery::$fields` is protected, and I see no method to remove / substitute fields in it. I would prefer to avoid extending any classes.

# Answer
`SelectQuery::getFields()` returns by reference, so something like this should do it:

```
$fields =& $query->getFields();
$found_index = FALSE;
foreach ($fields as $key => $val) {
  // Check what's in the field, note the index if it matches the one to remove
}

if ($found_index !== FALSE) {
  unset($fields[$found_index];
}

```
> 5 votes

---
Tags: database
---


# Question
Title: HTML5 Video showing both Source and Flash fallback
I'm experiencing a sudden problem with an embedded HTML5 video on my Drupal site. At first I thought it was a problem with my HTML5 code, but I believe the problem is with the WYSIWYG editor within Drupal.

I have a video in several formats, and want have a Flash fallback for those less fortunate.

Here is my code:

```
 <video width="480" height="320" controls="controls" poster="poster.png">
    <source src="video.webm" type="video/webm" />
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" />

    <object width="480" height="320"
            data="moxieplayer.swf" type="application/x-shockwave-flash">
       <param name="src" value="moxieplayer.swf" />
       <param name="flashvars" value="url=video.mp4&poster=poster.png" />
       <param name="allowfullscreen" value="true" />
       <param name="allowscriptaccess" value="true" />
    </object>
 </video>

```

Everything was working as expected. Then I opened the WYSIWYG editor, Disabled rich-text to get to the HTML, and added the "poster" attribute. I clicked save and, ever since, it has been showing TWO videos: the main source and the Flash fallback.

I found that odd so I removed the poster attribute (going back to what I had before), but the problem remained.

I know what the problem is... It became apparent when I viewed the source in the browser. The source is being rendered like this:

```
 <p><video width="480" height="320" controls="controls" poster="poster.png"><br />
      <source src="video.webm" type="video/webm"></source><br />
      <source src="video.mp4" type="video/mp4"></source><br />
      <source src="video.ogv" type="video/ogg"></source>
    </video>
  </p>
  <object width="480" height="320" data="moxieplayer.swf" type="application/x-shockwave-flash">
     <param name="src" value="moxieplayer.swf" />
     <param name="flashvars" value="url=video.mp4&poster=/" />
    <param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="true" />
 </object>

```

Notice that in the rendered code, "object" is now outside the video tag. I'm guessing that's the problem. For whatever reason it was fine, then I edited the code to add the poster, and rocking the boat has resulted in this issue. I am in "Full HTML" mode when making my edits.

Unfortunately, disabling WYSISWG isn't an option as my customer needs to use it. This is a bit frustrating as I suspect that may be the issue. I'm using TinyMCE 3.5.10.

Does anyone have any suggestions on how to deal with this problem?

Thank you very much!

# Answer
In these kinds of cases, the easy fix would be to add a second text field for "embed code" outside the main wysiwyg area. If you set it to use a new "HTML without linebreaks" text formatter, that'll help eliminate any wackiness on the "Full HTML" default setting.

Protip: use the Better Formats module to stop the user from having to choose a format for this field. That way, they can just paste and forget.
> 1 votes

# Answer
It happened for me too when the "Convert line breaks into HTML" filter is activated in the corresponding text format... although there is absolutely no line break in the video/object tag (?!). But disable the filter fixed the problem.

As I absolutely need this filter to be enabled, I resolved fixing it with a bit of jquery, putting the object back inside the video tag.
> 0 votes

---
Tags: files, theming, wysiwyg
---


title: How to use Content Complete Module?

text:
# Question
Title: How to use Content Complete Module?
Tried to read https://www.drupal.org/project/content\_complete but that didn't give me much so now I'm stuck.

I've set what Content Type + Fields to use and Rebuilt Cache. Then I keep getting this error "You need to provide a completeness data field in the display 'Master'." when I try to create a View. Don't know what Master means here?

# Answer
> 0 votes
the Master display is the 1st Views page that you edit when making a new View. Typically this is a Page or Block in Drupal7. So you have a View somewhere that if you try to save it the View will say you need to supply at least 1 field for the completeness data field. So I suggest going through all of your Views and trying press Save on each 1 (because you dont know which 1 it is apparently or what exactly we're talking about) -- 1 will complain it cannot be saved until you fix this error in it.

---
Tags: views, blocks, 7
---


# Question
Title: Views Slideshow with jCycle - Making it 100% flexible repsonsive
Currently I have the following in my views:

* Title
* Image (size original)

I also currently have my image set at width: 100% via my css file. Now, how do I go about configuring the slideshow to take up 100% width to make the slideshow responsive? I installed the json2.js file to enable the advanced features and I see that there is a "fit" and a "width" option.

Do I set "fit" to 1 or true?

As for the width option, it seem to only take px values only. 100% just gets ignored.

Sure I can go and override this via the css file, but i was wondering if there is a more elegant way of doing it via the provided options in views.

# Answer
An easy way of making the slideshow responsive is by overriding the css something like below:

```
.views_slideshow_cycle_main {
  width: 100%;
  float: left;
}
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame {
  width: 100% !important;
  height: auto;
}
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row {
  width: 100% !important;
  height: auto;
}
.views_slideshow_cycle_main .field-content {
  max-width: 100%;
  width: 100%;
}
.views_slideshow_cycle_main .field-content img {
  max-width: 100%;
  width: 100%;
  height: auto;
  margin: 0;
  padding: 0;
}

```

The changes you where doing might be getting overriden by default styles as those were taking the precedence.

**Reference:** views Slideshow for Responsive design

---

Alternate solution: Give a try to Flexislider module: Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Some features of FlexSlider slideshows include:

* Touch enabled nagivation
* Keyboard navigation
* Configurable slide animations
* Multiple sliders per page
> 1 votes

---
Tags: 7, views, javascript
---


# Question
Title: Get Webform submission count using custom module
I would like to get the submission count of a user using custom code in my module. Which variable stores this?

I tried to do dsm on $node and there was an array for webform inside the $node object but in that array I couldn't find the submission count for the current user. But then, $node shouldn't contain that value, of course. So how do I get this value?

# Answer
Okay. I figured it out.

There is a function webform\_get\_submission\_count in the webmodule includes file that does. Just added these lines and got it my count. Sweet and simple.

```
module_load_include('inc', 'webform', 'includes/webform.submissions');
$mysubmission_count = webform_get_submission_count($node->nid, $user->uid);

```
> 2 votes

---
Tags: 7, webforms
---


# Question
Title: Access currently logged in User profile from search index view?
I have a Product Display listing of indexed nodes that show a "List Price" I want to do math on them (if I can get the multipliers I can do the math) in the view to show a users "Cost" and "Selling Price" the multipliers that I need are on the users Profile however I can't seem to find a way to access the current UID/ users profile fields in this type of view.

a) is this even possible to do? b) can someone explain to me how I can do it?

Thanks in advance t anyone who can help

# Answer
I am assuming you are using views module to create this listing. In that case, this is certainly possible.

But first, I am not sure what you mean by current user. Is this the user who created the particular product? Or is it the currently logged in user?

1. If the user is the creator of the product node, just add a relationship to the user using Relationships section in the View. And then all the user profile fields will be accessible to you in the Fields section. Easy.
2. If you're talking about the logged in user, then you can use views\_php module. Install views\_php and then add a PHP field to your view. In that field's output, write your php code which fetches that particular value. For example, the following code will give you the uid of the user. You can similarly extract more fields from his profile. `global $user;
echo $user->uid;`

You can inspect this $user object using dsm(), which is provided by devel module to inspect where your field lies in this object.

One important thing, write the above code in the output section of the views\_php field, and INCLUDE php tags.
> 0 votes

---
Tags: views, commerce, search
---


# Question
Title: Drupal 7 form alter required field is not working when i used field from "Add existing field"
I have added two fields in to my custom content type using "Add existing field".

For specific URL, I need to set these two fields as Required.

So I have altered my form and set required condition. After setting it, I have printed the form using devel, these fields are having required settings.

```
$form['field_name']['und']['#required'] = TRUE;
$form['field_email']['und']['#required'] = 1;
dsm($form);

```

But required condition is not applied.

That is, I could not see red color required indication as well as its not working in the form submit.

# Answer
Try

```
$form['field_email']['und']['0']['value']['#required'] = TRUE;

```

and if not work then try

```
$form['field_email']['und']['0']['#required'] = TRUE;

```
> 6 votes

# Answer
I ended up needing an additional value set to make this work and thoguht others might benefit from knowing so:

```
$form['profile_personal_information']['field_company'][LANGUAGE_NONE]['#required'] = 1;
$form['profile_personal_information']['field_company'][LANGUAGE_NONE][0]['#required'] = TRUE;
$form['profile_personal_information']['field_company'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;

```
> 0 votes

# Answer
You can use Field Validation module:

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.

Or use hook\_field\_validate in you custom module.
> -1 votes

---
Tags: forms
---


# Question
Title: How to redirect the user to a specific page after node is added/edited by user
I'm trying to create a drupal 7 website where users can upload pictures with a title.

When the user uploads an image with title, it has to be approved by the admin who then publishes it. My question is **after the user uploads the image**, how can I **redirect the user to a different page** which tells the user that the uploaded image has gone for approval by the admin.

# Answer
You can use the Rules module to do that. If you haven't used it before you can take a look at this video tutorial.
> 2 votes

# Answer
I don't know the best way, I'm pretty new myself, but if the image was made as a content type it would be very easy to use revisioning workflow to the content type versus an image. Or to add a rule that when a new content type is created to execute that page or special messaging. Just a thought!
> 1 votes

---
Tags: nodes, redirection, 7, files
---


title: entity reference with multiple values?

text:
# Question
Title: entity reference with multiple values?
I've added a new field to a content type, using the Entity Reference module.

The new field is to allow entry of up to 4 related articles (curated content - chosen by the admin) per article. I've set the field to allow up to 4 values - but using the 'Autocomplete (tags style)' widget it doesn't seem possible to enter more than one option.

Any suggestions/solutions?

# Answer
> 4 votes
To select multiple items with "Autocomplete (tags style)", you must enter a comma-separated list in the text box. Otherwise, if you want to enter the values in separate text boxes, use the plain "Autocomplete" widget type.

---
Tags: entities
---


# Question
Title: Create a module that add text/image to a specific type nodes
So. I need to create a module that add something like text, to all my nodes of type "Article" for example.

**I need a module that do:** \- Find the type of nodes "Article" \- And add a label that says "Made by me ..." And everytime i see articles, they all have the normal fields (title,body,tag,image) and my label..

Its possible?

# Answer
> 1 votes
Various ways of doing this. Either edit your tpl file. Create a node--article.tpl.php in your theme folder (copy the syntax from node.tpl.php) and modify the code to add your desired label. If you need to print username then the global $user is available. Just define it as global and access username as `$user->name`.

Or you could use Panels module. It's very flexible and powerful.

For creating custom module to do this, there are various approaches. One good way is this:

In your custom `mymodule.module` file, use the `hook_node_view` like this:

```
function mymodule_node_view($node, $view_mode) {
    if ($node->type=="article"){
        if ($view_mode == 'full'){
            $node->content['my_extra_content'] = array(
                 "#markup"=> '<strong>Made by me!</strong>',
                 "#weight"=> 100
              );
           }
         return $node;
   }
}

```

After this, `Made by me` should appear at the bottom of each node. If you want it to appear at the top, then just modify the weight and give it some negative value.

---
Tags: nodes
---


# Question
Title: Dynamic view with a field matching a role of User in Drupal 7
On my site, the nodes are restricted based on user's role. Admin selects any number of roles in a field (`field_role`) when creating a node and if any logged in user's role matches one of the selected roles, he/she can access the node.

But this only works, when user clicks on the node and then either can see the node or see an access denied warning.

The problem is that I just don't wanna show the node, if the access is restricted. The nodes are shown through a view as a listing on home page and I am just not sure how to tell the view that if the logged in user doesn't have any of the role selected in "field\_role", then filter out the node from the listing.

Any help.

# Answer
Add field\_role in view and hide it.

Now create a custom php filter using Views PHP Filter

Get the current user role and compare it with field\_role value. Following is the sample code.

```
<?php
  global $user
  $account = $user->uid;
  $roles = $account->roles;
  $field_role = $data[field_role]
  //$data is available in php views filter
  if(find user_role in field_role) {
    return false;
  else {
    return true;
  }
?>

```
> 0 votes

---
Tags: views
---


# Question
Title: how to get logged in username in email body
```
<?php
$to="syz@abc.com";
$headers = "From: no-reply@xyz\r\n" ."X-Mailer: php";
$message="Dear Xyz, i am ".i write a following code here to get current username.";
$subject="Testing";
if (mail($to, $subject, $body, $headers)) {
echo("<p>Message sent successfully! our lawyer will contact you as soon as    possible</p>");
} else {
 echo("<p>Message delivery failed...</p>");
}
exit();
}
<?php global $user; //decl var
if ($user->uid) : //assing
print l($user->name,'user/'.$user->uid); //name output
else :
print l("Login","user"); //if not login this condition
endif;?>

```

i write following code in message body after saving code my contain disappeared.

# Answer
Following is the working version of your code.

```
<?php
  global $user;
  if ($user->uid) {
    $test = l($user->name,'user/'.$user->uid);
  } else {
    $test = l("Login","user");
  }
  echo $message="Dear Xyz, i am ". $test . " I write a following code here to get current username.";
?>

```
> 0 votes

# Answer
Question is not really clear to me but if you want to add the username in massage then here is the way:-

```
<?php

    $user=user_load($uid);
    $message = "Dear Xyz, i am ".$user->name.";
    print $message;
 ?>

```

Hope This Help!
> 0 votes

---
Tags: views
---


# Question
Title: Outputting multiple content fields all wrapped in a div
I'm trying to wrap multiple field items in an HTML container.

So let's say I have "Blog" content type. I have field1, field2, field3, field4 and field5 for this content type.

I want to output field2, field3 and field4 wrapped together in a DIV.

I've been Googling and tinkering for the past 3 hours and I haven't gotten anywhere.

Any help out there?

Drupal 7, Zen subtheme.

I read this and didn't have any luck here either: Wrapping multiple cck fields into a single div tag for theming?

# Answer
> 5 votes
Multiple ways to achieve this.

1. By creating a node tpl file for that particular content type.
2. By creating view.
3. But i think the best and easiest way is creating group in manage display. Check field group module.

**Procedure to create group.**

1. Go to structure-\>content types-\>content(ex-blog)-\>manage displays.
2. Add a new group of div type.
3. Drag the required field like field2 , field3 etc under it.

**Print in tpl file.**

It will be easy to find out if you will update the code snippet of node--case-study.tpl.php file.

I think you need to first check by printing

```
echo '<pre>';
print_r($content);

```

and use this for

```
<div class="y">
  <?php print($content['field1']); ?>
</div>

<div class="x">
 <?php
    print($content['field2']);
    print($content['field3']);
    print($content['field4']);
 ?>
</div>

```

# Answer
> 0 votes
Create a empty file with name \[node-ContentType.tpl.php\] for your content\_type node template file and place it at sites/all/themes/your\_theme/templates. Flush all caches.

In this file you have the access $node variable which contains the all fields in that node. Now wite your custom html to breakdown your fields into differnt divs.

```
<div class="first-pane">
  <?php print $node->field1[0]['value']; ?>
</div>
<div class="second-pane">
 <?php print $node->field2[0]['view']; ?>
 <?php print $node->field3[0]['view']; ?>
 <?php print $node->field4[0]['view']; ?>
</div>
<div class="third-pane">
  <?php print $node->field5[0]['value']; ?>
</div>

```

For further parameters details, try this.

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


title: Open Field Collection in Colorbox

text:
# Question
Title: Open Field Collection in Colorbox
We have a field collection containing an image and three different Text fields. How can we open the whole field collection (= all four fields (= image + texts)) within the colorbox??? The module colorbox-node does not help because we don't have separate nodes (and no URL-pathes to the content).

# Answer
> 1 votes
You can have a look at the Entity popup module, it allows you to define a separate view mode for the popup content and includes an example on how to integrate with colorbox.

# Answer
> 0 votes
Create a field\_collection view and in fields add your field as well as add the Colorbox overlay field. Configure Colorbox overlay to display the fields you want.

# Answer
> 0 votes
I followed this approach:

1) Create a Content Type and added a field as type 'Field collection' (Considering this field collection is not available in your instance. If you want to reuse an existing field collection that also you can go for)

2) Considering you have created a new field collection, now you need to add fields to the field collection by visiting 'admin/structure/field-collections' path

3) Now create a block (I am using custom block) with hook\_block\_info() & hook\_block\_view().

4) In hook\_block\_view() call a function in $block \['content'\] & try to code similar way as below :

```

  $options = array(
    'attributes' => array(
      'class' => 'colorbox-node'
    ),
    'query' => array(
      'nid' => $nid,
      'width' => 600
    )
  );

  $html  = '';
  $html .= l( 'Add FC', 'field-collection/field-collection-name/add/node/' . $nid, $options );
  print $html;

  // Here, field collection name is 'field_collection_name' and we need to replace '_' with '-'

  // Here, $nid is the NODE ID, you want your field collection be associated with

```

5) Considering you have colorbox related modules (colorbox, colorbox\_node) are enabled in your instance

Hope it helps

---
Tags: entities, javascript
---


title: PHPExcel in Drupal 7

text:
# Question
Title: PHPExcel in Drupal 7
I'm trying to export my Webform settings to an Excel file by using the PHPExcel module, but it looks like it's documentation isn't modified for Drupal 7...

When trying to define the two-dimensional array `$data[row][column]` (as mentioned in the API), I keep stumbling upon an errors...

I try to add "John Doe" in Cell A1, "john@example.com" in Cell B1, etc.

```
$data = array(
    1 => array(
        'A' => 'John Doe',
        'B' => 'john@example.com'
    ),
    1 => array(
        'A' => 'Jane Doe',
        'B' => 'jane@example.com'
    ),
  );

```

But nothing ends up in the Excel file. Sometimes the first letter, but nothing more...
What does this module require as `$data`?

# Answer
> 2 votes
The data table shold look like this:

```
 $data = array
    (
        array("Volvo",22,18),
        array("BMW",15,13),
        array("Saab",5,2),
        array("Land Rover",17,15)
    );

```

And whole working example will look like this:

```
function hoook_export_excel() {
    module_load_include('inc', 'phpexcel');
    $data = array();
    $headers = array();
    // First worksheet
    // Get the nodes
    $data = array
    (
        array("Volvo",22,18),
        array("BMW",15,13),
        array("Saab",5,2),
        array("Land Rover",17,15)
    );

    $headers = array("CAR","COUNT1","COUNT2");

    // Store the file in sites/default/files
    $dir = file_stream_wrapper_get_instance_by_uri('public://')->realpath();
    $filename = 'export1.xls';
    $path = "$dir/$filename";
    // Use the .xls format
    $options = array('format' => 'xls');
    $result = phpexcel_export($headers, $data, $path, $options);
    if ($result == PHPEXCEL_SUCCESS) {
        drupal_set_message(t("Ok"));
    }
    else {
        drupal_set_message(t("Error"), 'error');
    }
}

```

This will return Excel:

# Answer
> 0 votes
mbahojlo already answers your question just fine. I just want to add, that it is fairly easy to create your own function to export Excel data. These are two functions (first one is a page callback) which I wrote for my module `webform_invitation`:

```
<?php
function webform_invitation_download_file($nid) {
  //this is the XLS header:
  $xlshead=pack("s*", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
  //this is the XLS footer:
  $xlsfoot=pack("s*", 0x0A, 0x00);

  $codes = db_select('webform_invitation_codes', 'c')
  ->fields('c')
  ->condition('nid', $nid, '=')
  ->execute();
  $node = node_load($nid);
  $data = "";
  $row = 0;
  while ($code = $codes->fetchAssoc()) {
    $data .= webform_invitation_xlsCell($row, 0, $code['code']);
    $row++;
  }
  $filename="codes-".$nid.".xls";
  header("Content-Type: application/force-download");
  header("Content-Type: application/octet-stream");
  header("Content-Type: application/download");;
  header("Content-Disposition: attachment;filename=$filename");
  header("Content-Transfer-Encoding: binary ");
  echo $xlshead . $data . $xlsfoot;
  exit; //this is  important!
}

function webform_invitation_xlsCell($row,$col,$val) {
  $len=strlen($val);
  return pack("s*",0x204,8+$len,$row,$col,0x0,$len).$val;
}
?>

```

---
Tags: 7, importing-exporting
---


# Question
Title: Drupal - user registration form- theming
I need to do theming of user registration form

I m doing in this way

Module file

```
  function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
      $form['#theme'] = 'user_register';
    }

```

Template file

```
function mytheme_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
  );
}

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

```

And then I added user-register.tpl.php with my desired markup, a

```
<?php echo $rendered; ?>

```

Which is working fine . Now problem is that i need to rearrnage order of all fileds

Currently i have following

username, email and password, firstname , last name

I need sequence like username , firstname, email, lastname, password

can anybody tell me how to do this

Thanks

# Answer
> 0 votes
You can skip your preprocess function and render directly in your template file like this:

```
<?php print drupal_render($form['user_register']['username']); ?>
<?php print drupal_render($form['user_register']['firstname']); ?>
<?php print drupal_render($form['user_register']['email']); ?>
<?php print drupal_render($form['user_register']['lastname']); ?>
<?php print drupal_render($form['user_register']['password']); ?>

```

Wrap these lines of code inside HTML if you want to. Use `<?php print drupal_render_children($form); ?>` to render automatically the rest of the fields you haven't rendered yet.

EDIT:

An example:

```
<div id="username">
  <?php print drupal_render($form['user_register']['username']); ?>
</div>
<div id="firstname">
  <?php print drupal_render($form['user_register']['firstname']); ?>
</div>
[...]

```

# Answer
> 0 votes
Look at poll module for a good example of this.

You can simply (with item being something in your form);

```
$form = $variables['form'];
$variables['item'] = drupal_render($form['item']);
$variables['rendered'] = drupal_render_children($form);

```

However there are other ways of achieving this and keeping the rearranging within the UI (*/admin/config/people/accounts/fields* etc) by using `hook_field_extra_fields` \- poll module does this as well I've noticed. It can be used for adding existing base fields which don't otherwise show in the Manage Display UI (like node author, created, updated times, etc) - here's an example for user picture.

---
Tags: 7, theming
---


# Question
Title: Access denied for anonymous users clicking on download link
I have a content type with a file field that has been formatted by display suite. I set the display suite formatter to download link.

This works fine for users who are logged in, but anonymous users get the access denied page. Is there some permission settings or file folder permission settings I need to deal with? Accessing the raw file URL is possible for anonymous users though.

The formatter makes the link become something like this: http://example.com/file/980/download?token=OBVqG5D1va06NDH2\_BcgF0vqwVhhNHsnNYcHYHGQ5\_g

# Answer
This was a bug in the file entity module and the latest stable version has the patch for this issue committed to it. If you had encountered this issue in the past, update file entity to the latest version.
> 1 votes

# Answer
It seems to be a permission issue for anonymous user. Check the permission section. Also give your file folder the required permissions, where the files are being uploaded.
> 0 votes

# Answer
Did you get anywhere with this? I wonder if it's related to jesss' answer over here: https://drupal.org/node/2136453

"Download tokens work for the first anonymous user -- any anons coming after get the 403 error."
> 0 votes

---
Tags: display-suite, files
---


# Question
Title: Avoid username output as a class of an article tag
Drupal 7 generates a username class for the article tag, something like : class="node node-page node-published node-not-promoted node-not-sticky **author-username** odd clearfix".
I'd like to avoid to have the username output in the code for security reason. I have tried the userone module, but it doesn't work for this.
I am thinking about some Jquery code, but a better way would be to avoid the username to be output at all.
I was looking in the core modules but I didn't find the php file that generates this author-\[username\] class. Any help?

# Answer
> 2 votes
I think you can blame Omega for that one, in `omega_alpha_preprocess_node()` you'll find this:

```
$vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name);

```

I think you've got two options:

1. Remove that preprocess function altogether, using `hook_theme_registry_alter()`, and duplicate it into `MYTHEME_alpha_preprocess_node()`, minus the offending line.
2. Implement `MYTHEME_alpha_preprocess_node()`, search through the `$vars['attributes_array']['class']` array, and remove it from there.

# Answer
> 0 votes
I can't see this class on clean drupal installation. check it here so class generate on your theme and their templates. check node.tpl.php and remove statement that generate this class.

# Answer
> 0 votes
One solution is to add the following code in the template.php file of the Omega subtheme and the username class for the article tag in the HTML code will not be displayed (thank you @Jance):

```
function [MYTHEME]_preprocess_node (&$vars){
  $count = 0;
  foreach($vars['attributes_array']['class'] as $class){
  if(substr( $class, 0, 7 ) === "author-"){
  unset($vars['attributes_array']['class'][$count]);
  }
  $count += 1;
  }
}

```

---
Tags: users, security, theming
---


title: Contextual filters multiple value title

text:
# Question
Title: Contextual filters multiple value title
I've added title override %1, to contextual filter. Filter uses taxonomy to get nodes.

If I open page "catalog/1" I get title from term1 with all the content If I open page "catalog/2" I get title from term2 with all the content But if I try "catalog/1+2" I get title "No name" and the content for both terms.

How to define page title as title of first (any) term in the filter?

---

Upd it appears that there's a problem with title override. If I add title override %1, then I have "No name" title for multiple terms...

# Answer
Go to your View. In Contextual filter configuration \>\> More \>\> Check "Allow multiple values". So if selected this, users can enter multiple values in the form of 1+2+3
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to update taxonomy term of a node using services
I have created a new node using Services 3 module successfully, the code is below

```
{

 "type":"page",
"title":"New test page",
"taxonomy": {
       "tid" :"367928"
      }

}

```

Configuration:

Drupal version = 6.26,

url = serviceurl/node,

App = Postman application in chrome,

Method = POST,

data = json.

But when i tried to edit the taxonomy term of the node using same format as below , its not working

url = serviceurl/node/node-id,

Method = PUT,

data = json.

```
{

"type":"page",
"title":"New updated title of the Page",
"taxonomy": {
       "tid" :"367930"
      }
}

```

When I checked the node, the title is getting updated where as the taxonomy term remains the same. I searched a lot on the net, but could not find any solution. Can anyone please help to fix this issue.

# Answer
> 0 votes
I think your JSON format to create node is wrong. Please check the created node. I guess it creates node but with empty taxonomy field.

The correct format to create a node having taxonomy term is like follows.

Assuming that your 'widget type' for 'term reference field' is 'Select list' or 'Check boxes/radio buttons'

```
{
    "title": "my title",
    "type": "page",
    "field_mynodeterm": {
        "und": "3"
    }
}

```

here `field_mynodeterm` is machine name of your 'Term reference field' (which is used in content type).

Similarly you can use the same format to update the node

```
{
    "title": "my updated title",
    "type": "page",
    "field_mynodeterm": {
        "und": "5"
    }
}

```

If you use 'Autocomplete term widget (tagging)' as widget type for term reference field, the JSON format would be the following

```
{
    "title": "my updated title",
    "type": "page",
    "field_mynodeterm": {
        "und": "termname"
    }
}

```

I tested the above scenarios and working fine. Hope this helps.

---
Tags: taxonomy-terms, 6, services
---


# Question
Title: How to create a dropdown list with node ids?
I need to create a dropdown list box which contains the list of node ids of a specific content type. Then after selecting the node id in the dropdown i need the content of the node to be displayed below the dropdown.

Iam new to drupal. Is there any way to create the dropdown list box with the features...?

# Answer
To get all the nodes ID's for a content-type, you can use EntityFieldQuery and node\_load\_multiple:

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mycontenttype')
  ->execute();
$nodes = node_load_multiple(array_keys($result['node']));

```

If you are using FAPI (form API), you can populate your dropdown list with these values easily.

Unfortunately, I can't help with the last part (displaying the node under the form).
> 0 votes

# Answer
Get a list of nodes of a specific type, assuming $type contains your content type, use node\_load\_multiple:

```
$nodes = node_load_multiple(array(), array('type' => $type));

```

Create a select using the Form API in a custom module.
> 0 votes

---
Tags: nodes
---


# Question
Title: Add cutom body class when view is not return any results
I know how to add additional class by preprocess function but I need to combine it with the view. So the new custom class should be added if my view returns 0 results. It looks like I can't use hook\_views\_pre\_build because there's no vars for page elements. Any thoughts how to achieve it?

# Answer
> 1 votes
Might be a little over-kill, but it's the first thing that comes to mind without having to build a custom view in code (which is cleaner imo). I am referencing Views 2 only, might be different in 3.

* Create an empty view page, strip it of everything if you'd like, it just needs to exist.
* In the view you are using, for the no results behavior, choose to include the empty view.
* Using the Context module, add the condition that if the empty view is shown on the page to execute. In the reactions area, add Theme HTML which will allow you to enter in your custom css class to the body tag.

---
Tags: views, theming
---


# Question
Title: How to print a custom region in a custom module's template?
I want to define a region, but the problem is that for different pages, the position of the region would be slightly different. So I can not put the region in `page.tpl.php` and for different custom modules that I have created, I need to put it inside different places depending on the module. So far I have defined the region inside my custom theme, and I have tested the region inside `page.tpl.php` with a custom block and it works fine there. But when I put the code to print the region inside the custom module's template, nothing shows up.

The following code works in `page.tpl.php` but not in custom module's templates:

```
<?php print render($page['sidebar_ads']); ?>

```

### Question

How do I pass the the `$page` variable to a custom modules template?

# Answer
> 1 votes
I am not getting exactly. but your position for other pages are different and different for the front page. why not you make two file

```
page--front.tpl.php
page.tpl.php.

```

You don't need to be worry about region. because region only enable if any block assign in that region!

# Answer
> 0 votes
I use the Context module to use areas in different places based on conditions like which content type, view display, or even a specific node id, among other options. So you can specify several regions but instead of using a block in them automatically, allow Context to decide which types of pages will use which block in which region. This should allow for the dynamic display you are looking for in an easy-to-use module interface.

---
Tags: 7, theming
---


title: How to find and edit front page

text:
# Question
Title: How to find and edit front page
I am new to Drupal and working for a customer. He wants me to change the title of the front page. I just cannot figure out how to get there. I have no problem with the rest of the pages on the site.

# Answer
> 1 votes
What you want is to find the content of the variable `site_frontpage`.

You could:

1. `drush vget site_frontpage`
2. Use devel and it's variable listing
3. `SELECT * FROM variable WHERE name = 'site_frontpage';`

This will tell you where the frontpage is controlled from. Often it will simply be a node that you can edit.

# Answer
> 0 votes
Just go inside currently enable theme in template folder if available or in root folder where you have page.tpl.php make copy of page.tpl.php rename to page--front.tpl.php search "", comment out code.

login as admin-\> clear cache under configration-\>performance

That's it!

# Answer
> 0 votes
Here's what I usually do:

1. Create a node for your frontpage, a basic page that will host your title and body content. Or find the current frontpage node if it's already created. Try searching for the current homepage title in your node content overview page (/admin/content/all)
2. Go to your site configuration (/admin/config/system/site-information) and change the default front-page to that node id or url alias if it has one (node/id or just the alias)

You will be able to edit the title on that node from now on. You might want to create your own template as well and you can apply this template after this step by creating a new page--front.tpl.php file in your enabled theme folder/templates, then clearing your cache. In that template, you can change the layout as much as you'd like and still use a node in the admin to edit the title and content.

---
Tags: 7
---


# Question
Title: Any way to add more than one text entry to select fields
In a form that a site user (i.e. not an administrator) fills out I want to have a section like this (the "\[ \]" represents a checkbox in the form):

**Certifications**

\[ \] Type 1 Certification

\[ \] Type 2 Certification

\[ \] Type 3 Certification

\[ \] Other Type 3 Certifications \[text box entry\]

\[ \] Type 4 Certification

\[ \] Type 5 Certifications

\[ \] Other Certifications \[text box entry\]

So the user would check as many of these as apply to them, and if they had a different Type 3 Certification than the one that was listed, they would check the "Other Type 3 Certification" checkbox AND fill out the text box with the type of Certification that wasn't listed.

And they would also have the option of checking the last text box and typing in other types of certifications in that text field.

I found Select or Other (https://www.drupal.org/project/select\_or\_other), but it doesn't appear to allow for two text options.

Perhaps I should simply do the list of options with Select or Other, put the Type 3 option last in the list, and add Other Certifications as a separate field?

# Answer
> 2 votes
**In my opinion**, the Select Or Other module works with field groups or something. It should allow one "other" value per group. You can do like this:

---

**GROUP GENERAL**

\[ \] Type 1 Certification

\[ \] Type 2 Certification

> **GROUP CERTIF 3**
>
> \[ \] Type 3 Certification
>
> *\[ \] Other Type 3 Certifications \[text box entry\]*

\[ \] Type 4 Certification

\[ \] Type 5 Certifications

*\[ \] Other Certifications \[text box entry\]*

---

---
Tags: entities
---


# Question
Title: How to modify field_suffix after form submit?
I have a form with a custom suffix (#field\_suffix) for a field. I need to change the suffix value after the form has been submitted. Which hook should I use to achieve this ?

**Sample Code :**

```
$form['field_test']['#field_suffix']='Suffix-1';

```

**Edit:** I want to show "Suffix-1" when editing form and "Suffix-2" during display of content.

# Answer
> 0 votes
I found a solution to achieve this functionality.

```
function hook_node_view($node, $view_mode, $langcode) {
$node->content['field_test'][0]['#markup'] = $node->content['field_test']['#items'][0]['value'].'Suffix-2';
}

```

---
Tags: 7, entities
---


# Question
Title: Where is Pathauto's "Strings to Remove" stored in MySQL?
I've tried looking in the "variable" table with `SELECT name FROM variable` but I think it's not there.

Where does the module save that setting?

# Answer
> 4 votes
It's stored in the variable named `pathauto_ignore_words`, you can get it directly like this:

```
SELECT value FROM variable WHERE name = 'pathauto_ignore_words'

```

or using the Drupal API like this:

```
$ignore_words = variable_get('pathauto_ignore_words', '');

```

# Answer
> 0 votes
As @Clive mentioned, it is stored in the variable table, **but only after you save the settings for the first time.**

Before you save the settings, it is not found in the DB. By default it is stored in a constant within the module. See the default ignore list for Pathauto 7.x-1.2

---
Tags: path-aliases
---


# Question
Title: What module or views recipe can display a featured node with different layouts from the rest?
I'm building out a views layout where I need to display a featured node with a different layout from the rest of the nodes being displayed. It looks something like this:

As you can see the middle node is larger than the rest and has body content displayed. What methods are there to output a custom views layout like this?

# Answer
Seem that you can go with the module called **views\_nodes\_split** https://www.drupal.org/project/views\_nodes\_split

**BUT, this is better solution if your using display suite already:** You can just use Display Suite + Views as there is a setting when choosing an output. Display suite lets you pick which view mode to use for each output:
> 0 votes

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


# Question
Title: How to send user created articles to approval queue?
I have an approval queue set up on a member's portal. The approval queues contain five content types that I created, one of them being 'Articles' and it is receiving daily RSS feeds. I'd like to also allow any user created articles to go there too.

The problem I have is that there is an Articles Adhoc page that was created in the views that is taking all of the user created articles.

I have disabled this page but the new articles still aren't going to the approval queues.

I checked around the Redaction module but I am unable to find anything on how to get this done.

# Answer
I'm not sure this is what you need but maybe you can achieve this using Rules. I've created a rule for nodes of type 'forum topic' and this is an example:

1. **Event:** Before saving content of type *your type*
2. **Conditions:** Data comparison -- Parameter: *Data to compare:* \[node:is-new\], *Data value:* true
3. **Actions:**
    * Conditional
        + If: User has role(s): Parameter: *User:* \[node:author\], Roles: *new*, Match roles: any
            - Set a data value: Parameter: *Data:* \[node:status\], *Value:* Unpublished
            - Show a message on the site: Parameter: *Message:* `your message`, *Message type:* Warning, *Repeat message:* false

---

The exported rule: `{ "rules_forum_needs_approval" : {
 "LABEL" : "Forum needs approval",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "rules_conditional", "rules_i18n" ],
 "ON" : { "node_presave--forum" : { "bundle" : "forum" } },
 "IF" : [ { "data_is" : { "data" : [ "node:is-new" ], "value" : 1 } } ],
 "DO" : [
 { "CONDITIONAL" : [
 {
 "IF" : { "user_has_role" : {
 "account" : [ "node:author" ],
 "roles" : { "value" : { "14" : "14" } },
 "operation" : "OR"
 }
 },
 "DO" : [
 { "data_set" : { "data" : [ "node:status" ], "value" : "0" } },
 { "drupal_message" : {
 "message" : "[node:title] needs approval.",
 "type" : "warning",
 "repeat" : 0
 }
 }
 ]
 }
 ]
 }
 ]
 }
}`
> 1 votes

---
Tags: views, 7
---


title: Custom node actions/

text:
# Question
Title: Custom node actions/
I have a view which is rendered as a table, the last column is labeled "actions" which I display both the "Edit" and "Delete" links accordingly.

I need to implement a few more custom operations, I found this as a starting point:

Custom entity operation links

Here is what I have thus far:

**module.module**

```
<?php
  function module_views_api() {
    return array(
      'api' => 3,
      'path' => drupal_get_path('module', 'module') . '/views',
    );
  }

```

**module.info**

```
files[] = views/module.views.inc
files[] = views/module_handler_print.inc

```

**module.views.inc**

```
<?php

  function module_views_data() {
    $data = array();
    $data['node']['print'] = array(
      'title' => t('Print link'),
      'help' => t('Provide a simple link to print the content.'),
      'field' => array(
        'handler' => 'module_handler_print',
      ),
    );

    return $data;
  }

```

**module\_handler\_print.inc**

```
<?php
  class views_handler_field_node_link_print extends views_handler_field_node_link {

    function render_link($node, $values) {
      // Ensure user has access to edit this node.
      if (!node_access('update', $node)) {
        return;
      }

      $this->options['alter']['make_link'] = TRUE;
      $this->options['alter']['path'] = "node/$node->nid/print";
      $this->options['alter']['query'] = drupal_get_destination();

      $text = !empty($this->options['text']) ? $this->options['text'] : t('print');

      return $text;
    }

  }

```

I can see the option when adding the field to VIEWS but when I select it I get the error:

> Configure field: Broken/missing handler

Any ideas???

# Answer
You can try this module: https://www.drupal.org/project/ccl

or create your custom solution based on this code snippet
> 1 votes

---
Tags: views
---


title: Calling hook_entity_view from a theme

text:
# Question
Title: Calling hook_entity_view from a theme
Is there any way to call `hook_entity_view()` from a theme?

I tried adding the implementation to the `template.php` file, but the function is not called.

I know I can do it via custom module, but as it's a rather UI addition, it would make more sense to do through theme.

Thanks!

# Answer
`hook_entity_view()` will only be invoked for modules so no chance of putting it in a theme unless you want to change how something works under the hood.

It's not a problem though, as all alter hooks *are* invoked for themes; so you can use `hook_entity_view_alter()` instead.

> This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete entity content structure has been built.
> 1 votes

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


# Question
Title: Drush command needs higher bootstrap level - Pantheon Drush Alias Setup
I just setup pantheon for one of my websites. So far I've done the following and the site works fine:

Version Drush: 5.3 Local Dev: Ubuntu 12.04

1. Git clone the repo to my local desktop
2. Copy the pantheon.aliases.php file to the .drush directory at ~/home

Now when i do a **drush @pan.chouse.dev pm-list** I get the following error.

> ```
> ~/websites/pan-chouse$ drush @pan.chouse.dev pm-list
>
> Command pm-list needs a higher bootstrap level to run - you will need    [error]
> to invoke drush from a more functional Drupal environment to run thiscommand.
>
> The drush command 'pm-list' could not be executed.                       [error]
> The directory /home/drupalpro/websites/pan-chouse does not contain a     [error]
> valid Drupal installation
>
> ```

I also did a **drush @pan.chouse.dev status** and I get this:

> ~/websites/pan-chouse$ drush @pan.chouse.dev status PHP configuration : /srv/bindings/a59cd0c1631747ef8cda2b5e88fc5124/php.ini
> /srv/bindings/a59cef8cda2b5e88fc5124/php.ini Drush version : 5.10.0
> Drush : /srv/bindings/a59cd8cda2b5e88fc5124/drushrc.
> configuration php

I'm not exactly sure what I'm doing wrong as it should technically work.

# Answer
> 3 votes
Ok so this is how i solved it after 4 days of trying... the docs and support techs on pantheon are not clear which has lead to this confusion and im sure many others too.

To get Drush aliases to work you have to have a **settings.php** file in the sites/default folder. **BUT!** when we use pantheon, we all git clone the codebase to our local. So we all assume that we needed it in our local drupal setup that we cloned which is not the case.

You have to have the EMPTY **settings.php** file on the PANTHEON servers! In order to get it there, you have to switch your account to SFTP mode from GIT. I then logged in to the server via the terminal. Just copy and paste the cli command they give you on the info box.

Once you get inside, you need to goto this folder:

**code/sites/default**

Then I upload an empty settings.php file taken from default.settings.php.

This is what you should see once setup properly:

# Answer
> 4 votes
While sites on Pantheon don't require a settings.php file in order to serve web requests, due to the fact that database credentials are dynamically injected, they will still need a settings.php configuration file present in order to enable the remote execution of Drush commands. With Drush 5 installed locally, there is unexpected behavior with Pantheon aliases run from inside a local Drupal docroot. In addition, the `--strict=0` option needs to be appended to most commands when using Drupal 6 on your local dev environment.

Source: Drush error “Could not find a Drupal settings.php file” or missing system information from status

---
Tags: drush, bootstrapping
---


# Question
Title: How do i share profile user fields in multisite?
I am trying to share user profile fields in a multi-site. In the settings.php I tried like this for users and its sharing the common users fields.

```
$databases = array (
        'default' =>
        array (
                'default' =>
                array (
                        'database' => 'db',
                        'username' => 'root',
                        'password' => 'password',
                        'host' => '170.10.40.150',
                        'port' => '',
                        'driver' => 'mysql',
                        //'prefix' => 'main_',
                        'prefix' => array(
                            'default'   => 'go_',
                            'users'     => 'main_',
                            'sessions'  => 'main_',
                            'role'      => 'main_',
                            'authmap'   => 'main_',
                        ),
                ),
        ),
);

```

Like wise if i try for user profile fields its not working.

```
$databases = array (
        'default' =>
        array (
                'default' =>
                array (
                        'database' => 'db',
                        'username' => 'root',
                        'password' => 'password',
                        'host' => '170.10.40.150',
                        'port' => '',
                        'driver' => 'mysql',
                        //'prefix' => 'main_',
                        'prefix' => array(
                            'default'   => 'go_',
                            'users'     => 'main_',
                            'sessions'  => 'main_',
                            'role'      => 'main_',
                            'authmap'   => 'main_',
                        'field_data_field_name_first' => 'main_',
                        'field_revision_field_name_first' => 'main_',
                        'field_data_field_generic_name' => 'main_',
                        'field_revision_field_generic_name' => 'main_'
                        ),
                ),
        ),
);

```

Any help will be really appreciated in knowing how to share profile user fields or what i am doing wrong.Thanks in advance.

# Answer
**First:** remove from `settings.php`:

```
'field_data_field_name_first' => 'main_',
'field_revision_field_name_first' => 'main_',
'field_data_field_generic_name' => 'main_',
'field_revision_field_generic_name' => 'main_'

```

**Second:** create those fields in every site that will share them and attach them to user entities.

**Third:** Add again to `settings.php`:

```
'field_data_field_name_first' => 'main_',
'field_revision_field_name_first' => 'main_',
'field_data_field_generic_name' => 'main_',
'field_revision_field_generic_name' => 'main_'

```
> 1 votes

---
Tags: users, multi-sites
---


# Question
Title: What query string is used to display products in commerce kickstart?
I am creating a php script to display all the products from commerce kickstart database

But the image is in a table called `file_managed` and the products are in `commerce_products` and i cant seem to figure it out. what query is used to display the products in commerce kicker or how do i select all the product and images from the database using sql?

# Answer
You can use the function commerce\_product\_load which is documented here. I am sorry if you are saying Drupal is not loaded and you have to use a straight php query.
> 0 votes

---
Tags: 7, commerce, database
---


# Question
Title: How to get name, price and image of product using EntityFieldQuery()
Right now i am using this which doen't give me the name of the product or the price or location of the product image.

```
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'commerce_product');
    $query->fieldOrderBy('commerce_price', 'amount', 'ASC');
    $result = $query->execute();

```

which give this result

```
Array
(
    [commerce_product] => Array
        (
            [56] => stdClass Object
                (
                    [product_id] => 56
                    [revision_id] => 55
                    [type] => product
                )

            [50] => stdClass Object
                (
                    [product_id] => 50
                    [revision_id] => 49
                    [type] => testcamera
                )

            [28] => stdClass Object
                (
                    [product_id] => 28
                    [revision_id] => 28
                    [type] => cameras
                )

```

etc...

# Answer
You can now load the product using commerce\_product\_load($product\_id); Then you will see price, fields, etc. You could also put all the product\_id's in an array, then load them all with commerce\_product\_load\_multiple($product\_ids);
> 1 votes

---
Tags: database
---


# Question
Title: Only show view tab for current user profile
I created a HTML table view to show the current "listings" the user has created. I have everything set up (I think), but I am looking in how I can restrict access. The view is suppose to be a tab on the user profile page with the title of "My Listings". I need to only show it to the profile owner and also make it so people can't access it via URL itself (bypassing the tab)

I remember this was doable back in the Drupal 6 days, but my memory fails me.

Path: /user/%/listings (contextual filter % is set to UID)

So if user 1 goes to /user/1/listings They should see a tab next to View | Edit that says "My Listings"

But if user 4 goes to /user/2/listings they shouldn't see the "My Listing" tab. But if they go to /user/4 they should see their "my listings" tab.

Thanks for the help.

# Answer
set your view path to:

```
user/%/listings

```

Add a contextual filter of: author uid, and set 'WHEN THE FILTER VALUE IS NOT IN THE URL' to User ID from logged in user.

Add a menu 'Menu Tab'.

For access you have various options. Here is a simple one.

Install Views PHP and set access to PHP, then add this bit of code in there:

```
global $user;
return $user->uid == arg(1);

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: Updating existing products via Drupal Migrate
I have 2 migrate classes - `ProductsNewMigrate` and `ProductsUpdateMigrate`.

**1)** `ProductsNewMigrate` runs initially, adding products from a CSV file into Drupal. I can confirm this works correctly, the new products are created and a migrate map is set up in the database.

**2)** `ProductsUpdateMigrate` is required to import another CSV (exactly the same structure as in 1.) but with the updated product data originally migrated via `ProductsNewMigrate`.

I just can't get the Update migrate to work.
I receive the error: `array_flip(): Can only flip STRING and INTEGER values`

When looking at the migrate map table for this Migration - `migrate_map_productsupdate`.. I notice `sourceid1` is set to the SKU - which is correct. However, `destid1` and `destid2` (product\_id and product\_revision respectively) are both null values - which could be causing this?

Edit: Also receive the warning message: `"product_id" was used as destination field in "sku" mapping but is not in list of destination fields` when viewing the migrate page!

See the code below:

Code:

```
class ProductsUpdateMigration extends CustomMigration {
  public function __construct() {
    parent::__construct();
    $this->description = t('Import new products from CSV');

    $csvfile = "/drupal/products_updated.csv";
    $columns = array(
      0 => array('sku', 'Product SKU'),
      1 => array('title', 'Product title'),
      2 => array('colour_specific', 'Product colour specific'),
      3 => array('price_group', 'Price Group'),
      4 => array('composition', 'Product Composition'),
      5 => array('width', 'Width'),
      8 => array('price', 'Product Price'),
    );

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'sku' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'SKU/newref',
          'alias' => 'p',
        )
      ),
      MigrateDestinationEntityAPI::getKeySchema('commerce_product')
    );
    $this->source = new MigrateSourceCSV($csvfile, $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationEntityAPI('commerce_product', 'blinds');
    $this->systemOfRecord = Migration::DESTINATION;

    // print_r($this);

    // Mapped fields
    $this->addFieldMapping('product_id', 'sku')
      ->sourceMigration('ProductsNew');
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('commerce_stock')
      ->defaultValue(5);
    $this->addFieldMapping('field_blinds_colour_specific', 'colour_specific');
    $this->addFieldMapping('field_blinds_composition', 'composition');
    $this->addFieldMapping('field_blinds_width', 'width');
    $this->addFieldMapping('commerce_price', 'price');
    $this->addFieldMapping('field_blinds_price_group', 'price_group');
    $this->addFieldMapping('type')
      ->defaultValue('blinds');
  }

  public function prepareRow($current_row) {
    $colours = explode(';', $current_row->colour_specific);
    // // print '<pre>';
    // // print_r($colours);
    // // print '</pre>';
    $current_row->colour_specific = $colours;
    // $current_row->migrate_map_destid1 = 62;
    // $current_row->migrate_map_destid2 = 67;
    print_r($current_row);
    return TRUE;
  }

  public function prepare($entity, stdClass $row) {
  }
}

```

# Answer
Took a slightly different approach to solve this.

1. Upgraded Migrate module from version 2.5 to 2.6
2. Ran upgrades `drush updatedb`, made sure the migration groups were registered (did this via migrate ui)
3. After reading the following articles regarding the new 'trackchanges' hash value option: http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7 & http://www.acquia.com/blog/migrate-26-framework-changes I now applied the following to the migrate in step 1):

```
$this->source = new MigrateSourceCSV($csvfile, $columns, array(
  'header_rows' => 1,
  'track_changes' => 1
));

```

The use of track changes now allows the same CSV to be uploaded, any new rows will create a product. Any changes will be detected via the hash that this option provides in the migrate\_map table - thus causing the particular product to be updated.
> 1 votes

---
Tags: migrations
---


title: Undefined index: und

text:
# Question
Title: Undefined index: und
I have created a custom profile field called "field\_protection". I am using the following code to reference that field but am getting error:

**Notice: Undefined index: und**

```
$is_protected = 0;
   $is_protected  = (int)$act->field_protection['und']['0']['value'];
    if ($is_protected == 1) {
      form_set_error('from', t("Protected !!!"));
      return;
    }

```

# Answer
I like to use EntityAPI module for working with fields. You don't need to worry about some key exists or not. here is an example:

```
$entityWrapper = entity_metadata_wrapper('ENTITY_TYPE (eg. node, user..)', ENTITY_KEY_OR_ENTITY);

$protectionFieldValue = $entityWrapper->field_protection->value();

if (null != $protectionFieldValue /* put your condition */) {
  form_set_error('from', t("Protected !!!"));
  return;
}

```

or here is a way without an EntityAPI:

```
if (isset($act->field_protection['und']) && ($is_protected  = (int)$act->field_protection['und']['0']['value'])) {
    if ($is_protected == 1) {
      form_set_error('from', t("Protected !!!"));
      return;
    }
}

```
> 2 votes

---
Tags: entities
---


# Question
Title: Page--front.tpl.php not working - Tao theme
This should be really simple, maybe I'm just having a moment. Why is my page--front.tpl.php not rendering my home page? I'm using a tao subtheme.

Here's my tpl.php file.

(*There's no other page--front.tpl.php in the tao folder.*)

Here's my front page settings:

And here's theme developer telling me that the front page is using page.tpl.php to load:

I've cleared my cache with drush a couple times and restarted my local server. What else am I missing?

# Answer
I think I see a Windows specific issue here.

Notice how `block.tpl` only has the extension `tpl` and your new file `page--front.tpl.php` has `php` as extension in the filename?

Maybe Windows hides the `php` extension when you list files (and instead shows it under Type)?

Try removing `.php` from `page--front.tpl.php` and see if it still under the Type column shows up as php. If so clear cache and carry on :)
> 3 votes

# Answer
Following steps resolved the issue to create custom front page for Drupal 7.

1. Create a file - page--front.tpl.php. Notice two hyphens instead of one.
2. Clear the cache - Configuration \>\> Development \>\> Performance\>\> Clear all caches
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Different redirect page for registration, login and first time login
Im trying to redirect the user to different pages on login, first-time login and registration. I used the Login Destination module but it only has the option to redirect the user to one page on registration login and first-time login. Is there another way of doing this?

# Answer
I have not tested this but from the documentation page:

> There are no separate triggers for login and registration; instead you can differentiate them by specifying the pages that a user comes from:
>
> * user - the user login form.
> * user/register - the user registration form.
> * user/\*/edit - one-time login link, after the user has set the password.
> * other - the login block or login forms embedded by other modules.

It looks like you can specify both three options you ask for.
> 0 votes

# Answer
Here is a simple approach: \- create a simple module, implement hook\_form\_alter and hook\_user\_login:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // dpm($form_id);
  // dpm($form);
  if ('user_register_form' == $form_id) {
    $form['#submit'][] = 'my_custom_register_callback';
  }
}

function my_custom_register_callback($form, &$form_state) {
  // do some logic, redirect;
}

function MYMODULE_user_login(&$edit, $account) {
  if (null == $account->access /* this user has not been logged in before, he/she is being logged in the first time */) {
    // redirect him/her, eg. drupal_goto('SOME_URL');
  }
  else {
    // redirect him/her to another URL;
  }
}

```
> 0 votes

---
Tags: redirection, users
---


title: Menu creation problem

text:
# Question
Title: Menu creation problem
I am trying to create a new menu link. But the system doesn't allow me to do so.

**The path 'New' is either invalid or you do not have access to it. The path 'testss' is either invalid or you do not have access to it.**

# Answer
> 1 votes
A Drupal menu item can point to external URLs, URLs to files in the filesystem or an internal *path*. The latter has to exist before creating the menu item and access permissions are needed for the user creating it.

A path can point to a node or any other entity, or any path provided by a module (e.g a view from the Views module). Virtually any path can have any number of *aliases* but it's worth using the path in the menu items as aliases may change throughout the lifetime of the site, paths are less likely to change.

# Answer
> 0 votes
Try just using the node and its id like "node/id#", it will pick up the alias if it has one.

# Answer
> 0 votes
You first need to create some content which has the path "new". Create a node and in the "URL Path Settings", give it an alias "new". Now, you should be able to create menu item with that link.

# Answer
> 0 votes
Try creating a content eg article via node/add/article and use the url for the content aka node which is like node/\[node:id\] ; node:id is the numeric id number of the created content.

Drupal needs a valid path to create menu items. The link or path that you provide should exist or should be accessible.

You can go through these articles for a clear idea: https://www.drupal.org/documentation/modules/menu https://www.drupal.org/node/788972

Good luck

---
Tags: 7, views, nodes, routes
---


title: Receive error when printing field

text:
# Question
Title: Receive error when printing field
Hi i've just started building a site on Drupal 7.31 and i'm following my normal procedure i've used loads of times. One of the things I have on most sites is an introduction just beneath the title.

I add an introduction field to the Basic Page content type and in page.tpl.php I print it out using:

```
<?php
    if (isset($node)) {
      if ($node->type == 'page') {

        print '<h2>';
        print render(field_view_field('node', $node, 'field_introduction', array('label'=>'hidden')));
        print '</h2>';

      }
    }
?>

```

It's never caused any problems before, on any previous version but for some reason this time round I get this error:

```
Strict warning: Only variables should be passed by reference in include()

```

Any ideas why?

# Answer
> 0 votes
render function receives an arguemnt as reference, you should pass a variable instaed of function:

```
$var = field_view_field('node', $node, 'field_introduction', array('label'=>'hidden'));
print render($var);

```

---
Tags: theming, entities, nodes
---


title: OG subscribe link rewrite

text:
# Question
Title: OG subscribe link rewrite
How can I remove or rewrite "group/node" and "og\_user\_node" from url when user click on OG subscribe link ?

siteURL/group/node/63/subscribe/og\_user\_node

Is there any module like pathauto where I can use to make this url a custom look?

Thanks.

# Answer
> 0 votes
Well you know that all these requests are made using hook\_menu.

Yes, you should use hook\_menu\_alter Create new module and add hook\_menu\_alter

```
function my_module_menu_alter(&$items) {
    // Unset core path
    unset($items['The_actual_menu_request']);
    $items['your_new_menu_request'] = array(
        'title' => 'OG subscribe',
        ...
      );
}

```

Just pass the same page callback and arguments as the menu request for og subscribe

**EDIT**

Well try this snippet and see if it works, for OG subscribe menu request

Create a custom module. If you do not know how to create a custom module read This

then in your .module file add this code. It should work, I do not know if the 'file' argument needs an absolute path to the file, but if it does not work you just have to change it for the real path in og '../og/og\_ui/og\_ui.pages.inc'

```
function my_module_menu_alter(&$items){
  //unset core path
  unset($items['group/%/%/subscribe']);
  //as an example (taking the example url you provided) I will call the new menu request community/node/63/sign-in
  $items['community/%/%/sign-in'] = array(
    'type' => MENU_CALLBACK,
    'file' => 'og_ui.pages.inc',
    'page callback' => 'og_ui_subscribe',
    'page arguments' => array(1, 2),
    'access callback' => 'user_is_logged_in',
    'title' => 'Join group'
  );
}

```

Greetings hope it helps you, do not forget to mark the answer.

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


title: skip processing html and page

text:
# Question
Title: skip processing html and page
From a module, I want to output "hello world" simply as a string as efficiently as possible when i call /mymodule/helloworld.

ofcourse, using hook\_preprocess\_html and hook\_preprocess\_page i can assign nearly empty templates. the html template should contain `<?php print $page; ?>` and the page template `<?php print render($page['content']); ?>`, and the content could be the string 'hello world'.

however, drupal will still go through all the processes of generating $css in html or `$page['sidebar_first']` in the page. Even if I override `template_process_html` it seems `$variables['page']['page_top']` has already been populated.

How can I skip all the content processing and go straight for the output ?

\[EDIT\] had some usefull comments here, but still not what I want. I forgot to mention, I do want to use a template to print 'hello world'. So as I can override it in a theme, for example.

1. Yes, I can change the delivery callback (either in hook\_menu or in hook\_page\_delivery\_callback\_alter), but what the callback method receives is a render array. I do want to use a node template to render the content as html. I'd have to write my own delivery callback, I guess
2. Yes, I can print out the html and call drupal\_exit(), but then I wouldnt have the luxury of using a node template either

So, still looking.

\*-pike

# Answer
based on comments above and my own edits, i came up with this

```
function my_page_callback() {
    $output =  array(
        'template' => array(
            'data'      => array('dummy'=>true),
            '#theme'    => 'my_theme'
        )
    );
    print drupal_render($output);
    drupal_exit();
}

```

that goes straight for the beef: print the output. it does however use the templating system to create that output. it does not, i think, do all the preprocessing that would otherwise happen.
> 0 votes

---
Tags: 7, hooks, performance
---


# Question
Title: Commerce order confirmation message with shipping service
I'm sending confirmation message of a commerce order via Message Notify. I want to display the selected shipping service in the email.

# Answer
> 4 votes
Assuming that you are using *Commerce Message* module for this.

One way to do this is by adding your own *token*. In your custom module (MYMODULE) add this code (I have too many comments just for educational reasons):

```
// Set arguments for our custom token !order-shipping
function MYMODULE_message_presave($message) {
  if (!empty($message->mid)) {
    return;
  }
  $message->arguments['!order-shipping'] = array(
    'callback' => 'commerce_message_order_shipping',
    'pass message' => TRUE,
  );
}

/**
 * Message callback; Show Order Shipping Service label (!order-shipping).
 *
 * @param $message
 *   The Message entity.
 */
function commerce_message_order_shipping(Message $message) {
  $wrapper = entity_metadata_wrapper('message', $message);
  // Get order id from current commerce message
  $order_id = $wrapper->message_commerce_order->getIdentifier();
  // Get order from order_id
  $order_wrapper = commerce_order_load($order_id);
  // Get the line items. Shipping service is a line item (like product, discount etc)
  $line_items = $order_wrapper->commerce_line_items['und'];

  // Loop through the line items so you find the shipping service
  foreach ($line_items as $delta => $line_item_wrapper) {
    $line_item_id = $line_item_wrapper['line_item_id'];
    $line_item = commerce_line_item_load($line_item_id);
    //dpm($line_item);
    if(isset($line_item->commerce_shipping_service)) {
      // This is want we need, the shipping service label
      $shipping_service = $line_item->line_item_label;
    }
  }

  return $shipping_service;
}

```

Then in your message body add you new token `!order-shipping`.

Notice that this method works for other line items too... Also, it works for other modules that send emails (such as commerce\_email) but with some difference in the hook function - currently `hook_message_presave($message)` -.

Credits to this issue: http://drupalcommerce.org/node/10096

---
Tags: commerce, message-subscribe
---


title: Views Display Mode Toggle

text:
# Question
Title: Views Display Mode Toggle
I'm looking for a way to add the ability for users to toggle one of two view modes. Essentially, looking for a 'list/grid' switch. I've tried using https://www.drupal.org/project/views\_modes but it's failing to switch the URL at all.

If anyone has knowledge of a patch/fork of this project, or a way to achieve this, I'd be grateful!

# Answer
> 1 votes
Display Suite Extras module (part of Display Suite) has an option to do that.

# Answer
> 0 votes
What about creating two separate views, each set the way you want and a link as Global Text in the header of each that directs to the other.

---
Tags: 7, views
---


# Question
Title: How can I write a query to get a list of users who have registered in the last 24 hours?
I'm trying to use PHP to generate a query that fetches the number of users who have registered in the last 24 hours.

Based on the code for the "who's online" block:

```
$authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();

```

I modified it as follows (based on this old D6 Stackoverflow answer:

```
$users_registered = db_query("SELECT COUNT(DISTINCT u.uid) FROM {users} u WHERE u.created >= :timestamp AND u.uid > 0", array(':timestamp' => ($_SERVER['REQUEST_TIME'] - 86400)));

```

However, this results in an error:

> Notice: Object of class DatabaseStatementBase could not be converted to int in format\_plural() (line 1801 of /var/www/om/includes/common.inc).

I'm not great with SQL, so a brief explanation of where I'm going wrong would be much appreciated.

# Answer
It seems to me that you aren't doing anything wrong; it's just that the object you will get back from `db_query()` in your case is not something you can use as is.

Invoke `->fetchField()` method after `db_query()` so that Drupal's DB API returns you one single value.

Use this:

```
$users_registered = db_query("SELECT COUNT(DISTINCT u.uid) FROM {users} u WHERE u.created >= :timestamp AND u.uid > 0", array(':timestamp' => (REQUEST_TIME - 86400)));

```

Also, use `REQUEST_TIME` constant to get current timestamp.

Hope this helps.
> 2 votes

---
Tags: 7, database
---


title: Illegal string offset block region

text:
# Question
Title: Illegal string offset block region
I've made a custom module for Drupal 6 that has a custom form, which works perfectly.

I've tried to add the form in a block using the following code.

```
function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
    switch ($op) {
       case 'list':
          $blocks[0]['info'] = t('BLOCK INFO');
          return $blocks;
       case 'view':
          $blocks['content'] = drupal_get_form('mymodule_form');
          return $blocks;
   }
}

```

I can see the block in the admin page, and I can move the block to the different regions and everything seems to work, except for a list of warnings I get every time I change the region of the block.

> warning: Illegal string offset 'region' in block\block.admin.inc on line 101.
> warning: Illegal string offset 'status' in block\block.admin.inc on line 101.
> warning: Illegal string offset 'status' in block\block.admin.inc on line 102.
> warning: Illegal string offset 'weight' in block\block.admin.inc on line 103.

How can I fix these warnings?

I think these warnings happen because block.admin.inc is trying to access a non existent key ("region", "status"...etc). How can I remove said warnings? I have looked into some threads but their solutions have not worked for me.

# Answer
> 0 votes
The problem was due to the PHP version being used. It seems that Drupal 6 has some problems with PHP 5.4.

# Answer
> 0 votes
Here is the patch page:

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

"The problem seems to be that block\_admin\_display\_form\_submit() handler is just looping through all the form values assuming each value is a valid block settings form array() and when it hits fields relating to the buttons and form ID then it errors because it is not an array." #6

There is a bug, but you see the error in PHP 5.4.

---
Tags: blocks
---


# Question
Title: After migration the login form no longer submits, why?
I have been working on a Drupal 7 site on localhost (via WAMP) for some time now. Recently I wanted to migrate this website onto a new machine and continue working on it there. The steps I took:

1. I exported the MySQL database (SQL file)
2. I did a copy of the entire website (everything in the "www" directory)
3. I installed WAMP on the new machine
4. I pasted the entire website into the new "www" directory
5. I imported the previous database through PHPMyAdmin

Now when I go to localhost the website appears as per on the old machine, but when I try to log in using the previous user accounts it does not work. Specifically, when I type the username and password into the login form and hit the login button, nothing seems to happen. The loading icon appears in the tab but then the fields simply get emptied; there is no message saying incorrect log in details or anything, even if I use login details that I know aren't correct.

In the database the user accounts are clearly there, along with all of the other content. If I click on any links to the previous content I get taken to the content without any issues. Any suggestions on what could be going wrong here?

# Answer
> 1 votes
This is *usually* from `mod_rewrite` being disabled in your Apache configuration. You can manually edit the configuration but if you are using WAMP the easiest method is left-click the WAMP icon in your taskbar, click `Apache`, click `Apache Modules`, and click `Rewrite_module`. Then left-click the WAMP icon again and select `Restart All Services`.

Wait for services to restart... and test.

# Answer
> 1 votes
Please have check with your php.ini file as per old system & your new server by calling php phpinfo(); and look in the "Loaded Modules" for mod\_rewrite.

Please refer this link it may helps you.

---
Tags: database, users, migrations
---


# Question
Title: Main page teaser with module paragraphs?
The paragraphs module is the only module I know which would enable me to create flexible content with floating inline images without using a WYSIWYG editor. I use the beta4 paragraphs version in connection with the Garland theme.

I was able to setup certain paragraph bundles and also a content type where it is possible to add up paragraphs to different type (e.g. text only, text with image etc.) See example below:

However, I failed totally to configure a teaser view which makes sense. The reason: I cannot control the number of paragraph bundles to be shown in the teaser view as ist can be seen here:

In my test site the number fields next to the Fomat field in the above picture is missing. So I can only show the total article or nothing as teaser. How can I fix this?

# Answer
> 2 votes
The “manage display” teaser configuration page did not show the number of paragraphs to be displayed in the teaser view since the "Display Suite" module was not installed. I missed the display suite module because it was not mentioned in the cited article about paragraphs. :-(

It is, however, easily possible to also generate reasonable teaser views without having the Display Suite module installed: Just configure a content type with 2 fields for the page content: The first serves as single teaser/introduction field and the second serves as vehicle to choose among multiple and per CSS differently formatted paragraphs for the following content. The first field I call “intro field” in the following.

For the intro field (to me) there seem to be certain restrictions: If one wants to use a *flexible* paragraph item for this purpose, it seems to be only possible to show or hide the element on the teaser or full content page, respectively. (Within this respect, text\_with\_summary appears to make no sense as element of a paragraph bundle).

On the other hand, one could also use an *unwrapped* text\_with\_summary field as the first part of an article. This enables the full teaser functionality where one can select from mere shortening or providing an alternative abstract. Most important the manage display page will now let you choose “summary or trimmed” as teaser.

---
Tags: nodes
---


# Question
Title: Drush cc all doesn't flush and rebuild templates?
I am trying to clear the cache using **Drush cc all** because I deleted a function in the module/theme files and the site won't render...

I always have to login in as admin, performance \> Clear all caches

This works...what is the equivalent Drush command?

# Answer
> 2 votes
I did not try to reproduce your exact situation, but some operations called by cache\_clear\_all write / remove files from the filesystem. If your filesystem permissions are not correct, then `drush cc all` will do all of the database clearing just fine, but will leave the other operations undone.

There are two potential solutions to this:

1. `sudo -u www-data drush cc all`

Some folks don't like to use 'sudo' with 'drush', but if you run Drush as the webserver user, the cache-clear should work.

2. set the permissions of your webserver files so that the user that you run Drush as can read/write to the filesystem.

I usually make my webserver files owned by a 'www-admin' user in production, and I make them owned by the user I log in as on my development system. I set the group of all files to www-data, and make those that the webserver needs to write to group-writable. This works pretty well for Drush + Drupal access on Drupal 7.

# Answer
> 0 votes
I was invoking drush from any location I was currently in...when I cd'ed into the sites folders accordingly it seems to work. Not sure how I missed that.

---
Tags: drush
---


# Question
Title: Can emails be sent asynchronously via rules? (Using Queue?)
I have some rules set up to send email notifications for forum messages, comments and articles. Sometimes the number of users that need to receive the email are quite large and the page doesn't refresh before the server has sent all the emails. Can the sending be done in the background something? Isn't that what the core module "Queue" is there for?

# Answer
> 0 votes
An easy solution is to go with Queue Mail. It queues all mail sent from Drupal and sends it via a cron job.

If doing this, one should make sure that there is an actual cron job on the server calling the Drupal cron.php regularly, as explained in https://www.drupal.org/node/23714. Otherwise, the occasional visitor might trigger cron and be annoyed by the huge latency. I set it up to call cron.php every 5 minutes, so the notifications are sent within a decent time.

# Answer
> 0 votes
Oh the joys of email. Email is sent via the servers underlying or configured MTA. PHP merely passes-off the email content to be delivered. Depending on your email configuration PHP may wait for bounce notifications for example ... or simply spool the emails to disk and wait for the MTA to flush the outgoing mail folder.

Emails from Drupal though do not need to occur on page-load or form submission. If you want you could use Rules to slowly fill a Queue (a "list") of emails to send out from the "website" periodically.

Depending on how you want to process that Queue, whether in realtime using a Process or Job/Worker library is up to you. Or you could batch up the sending of the emails using Drupal (and/or Drush) and it's built in Cron support.

Or, for instance you could use one of the many email campaign modules for Drupal such as:

to completely offload the work from your server. How you wish to approach this problem, it's feasibility and cost are up to you.

**EDIT:**

This module works to provide Rules to fill Queues using Drupal Entities, Rules Queue. Google is your friend! :D

For some example code that uses `hook_cron` to send Queue'd emails: http://www.jide.fr/english/using-rules-and-the-queue-api-to-batch-send-mass-mails

---
Tags: rules, emails, queue
---


# Question
Title: Difference between function names from Drupal Devel
The devel module in drupal allows us to print variable data using functions like: kpr,krumo,dpm,dsm Can anyone please explain how different is each function from the other

# Answer
Maybe this can help you a bit:

* `dpm($var)` or `dsm($var)` \- displays the information about a variable in the form of system messages using Krumo.
* `dvm($var)` \- displays the information about a variable in the form of system messages using var\_dump($var).
* `dpr($var, $return = false)` \- displays the information about a variable at the top of the page, using print\_r($var, $return).
* `dvr($var, $return = false)` \- displays information about a variable at the top of the page, using var\_dump($var, $return).
* `kpr($var, $return = false)` \- displays the information about a variable at the top of the page using Krumo.
* `dargs()` \- displays information about the arguments of the current function at the top of the page using Krumo.
* `dd($var, $label = null)` \- writes the information about a variable in the file `drupal_debug.txt`, which is located in the temporary directory (admin/settings/file-system).
* `ddebug_backtrace()` \- displays the call stack at the top of the page using Krumo.
* `db_queryd($query, $args = array())` \- this is a debug version of `db_query()`, which displays it at the top of the page after the execution of `$query`.
* `dpq($query, $return = FALSE, $name = NULL)` \- this is an analog to the function `db_queryd()` only available in Drupal 7. Outputs SQL query using `dpm()` with substituted arguments. The first parameter takes an object DBTNG.
> 4 votes

---
Tags: debugging
---


# Question
Title: Leaflet views: how to zoom on the marker while clicking on it in order to get the popup
I am using the module Leaflet and its sub-module "Leaflet views"" in order to get a map displaying markers based on taxonomy terms.

I am able to show a popup displaying the term page while I click on a marker.

Now, my actual requirement is when I click on the marker, the map is zoomed on the clicked marker (zoom of maximum 3 levels) and just after the popup is displayed. So, my map behavior on the marker click event contains two steps: zooming and popup opening.

How can I hook the module in order to enrich my views?

# Answer
> 1 votes
Install and enable jQuery update. Set the jQuery version to \>= 1.7.

Create a module, then create a zoom.js JavaScript file and paste this:

```
(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      $(document).bind('leaflet.feature', function(e, lFeature, feature) {
        lFeature.on('click', function(e) {
          var lMap = Drupal.settings.leaflet[0].lMap;
          lMap.setView(e.latlng,8);
        })
      });

    }
  }
})(jQuery);

```

Use your module name instead of MYMODULE

Then use drupal\_add\_js() in your module to include zoom.js. Note the weight option:

```
  drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/zoom.js',array('group' => JS_DEFAULT, 'weight' => -5));

```

---
Tags: javascript, hooks
---