# Question
Title: 'path' in array with special characters using imagecache
I have a folder in my sites/default/files directory filled with product jpg's gathered from an external server and back end stock take system.

The files look like this...

* Bread.jpg
* Bakery.jpg
* Cakes+and+Puddings.jpg
* Chocolate+Bars.jpg
* Chocolates+%26+Treats.jpg
* Christmas+Fruit+%26+Veg.jpg

I am using theme\_image\_style in a custom block template to print the images using an image style from Drupal 7's core image handler like so...

```
<?php
    print theme_image_style(
        array(
            'style_name' => 'category_header',
            'path' => 'product_group_images/' . $productcategoryurl . '.jpg',
            'attributes' => array(
            'class' => 'category-header-image'
                 ),
            'width' => NULL,
            'height' => NULL,
        )
    );

?>

```

Where `$productcategoryurl` is the image name inside the product\_group\_images folder.

This all works great where the image is only one word, like `bread.jpg` or `bakery.jpg`

The trouble I am having is the "+" or "&" (%26) in the image names.

I have tried str\_replace to swap the spaces in the product name with "+", but in the path, the "+" is always encoded, and the image is never saved in the new style.

So my path comes out like....

* /sites/default/files/product\_group\_images/Chocolate%2BBars.jpg

Instead of...

* /sites/default/files/product\_group\_images/Chocolate+Bars.jpg

And therefore, no image is created in the /sites/all/files/styles directory.

Is there a way using the "path" in the array to actually use the "+" as a space without encoding it?

I hope ive explained that well enough, its late!

# Answer
I would use a hyphen "-" instead of plus "+" as it is URL safe and the standard MO on Drupal
> 0 votes

# Answer
You might find it easiest to set up a scheduled task that synchronises the files to another location and changes the file names to match the product name along the way.
> 0 votes

---
Tags: 7, blocks, media
---


# Question
Title: How do I configure a view that gets a taxonomy on a node, and retrieves fields from the taxonomy?
I have a view, which only appears when you navigate to certain nodes.

Each node which it appears under, has a taxonomy with a field called 'related\_content\_entity' referencing some related content. The node only has one taxonomy. I need the view to display data from the related\_content\_entity for the current node's taxonomy.

The brick wall which I have seemed to hit, isn't the entity reference, but filtering the results down to the one field referenced in the taxonomy associated with the node.

I get expected behaviour up to this point; creating a required relationship to the entity reference like this:

Gives me this result:

Which is entirely expected. But specifically what I can't figure out it how to filter these results down to the current node's taxonomy field. There's not a single contextual filter which I've tried which would filter the result down to only the node's taxonomy's field.

To put what I'd like to acheive more clearly:

Node-1 is under taxonomy-1, and taxonomy-1 has node-2 as an entity reference (though the entity reference module) in one of it's fields.

When view-A appears on Node-1, I'd like view-A to display the entity reference.

How do I do this?

**Edit:** This is my current set-up. This the input:

And this is the output:

@rooby, thanks for your help, but I don't actually get any results if I add any contextual filter under the sun.

# Answer
Hi,

If you construct your view like the below and get the value from URL, you should be able to achieve.

EDIT: Allow me to guide you step by step:

1. You go to /admin/structure/views
2. You click on `Add new view`, and enter your view's name and description in the related fields in the next screen
3. Choose Content from the Show dropdown and your display format from the `Display format` dropdown and click `Continue & edit`.
4. Add `Content: All taxonomy terms` as a field, make your settings, and click Apply.
5. In the advanced section (to the right most section), add `Nid` as a Contextual Filter and click Apply (all displays).
6. Choose `Provide default value` and `Content ID from URL`, and click `Apply (all displays`

That's all there is to be done. You can test this by passing a node ID in the Preview with contextual filters field.
> 0 votes

# Answer
If you're displaying a view on a node page that is returning data relevant to that node then the view needs to know about the node it is dealing with.

To do that add a contextual filter of "Content: Nid".

In views, block views do not automatically inherit contextual filters from the URL so as far as the block knows there is no filter value available. So the way to get it to get the filter value from the url is configure the "When the filter value is NOT available" setting to "Provide default value".

Then under that select "Content ID from URL". Then if you put that block on a node page the view will pull the node ID from the URL.

Additionally you can also check the "Specify validation criteria" checkbox further down in the contextual filter settings. Then select "Content", the node types of the nodes you are putting the block on and select an action if it doesn't pass validation (often in cases like this you want the "Hide view" option so that if it doesn't get a valid node ID of the relevant content type it doesn't try to use it.

If you choose not relationship for this filter then to show fields from the linked node you need to use the relationship for those fields.

Otherwise you can use the relationship for this contextual filter and no relationship for the fields. It's up to you which way you prefer.

EDIT: It is also possible to use a taxonomy term contextual filter in the same manner but for the default value use "Taxonomy term ID from URL" and check "Load default filter from node page, that's good for related taxonomy blocks" and uncheck "Load default filter from term page" and restrict by your vocab.

In this case the contextual filter is doing the work of the relationship from the viewed node to its term, then you should only need one relationship from the linked node to the term.

These types of views can get a bit complex so you may still have to do some tweaking of your relationships and which fields & contextual filters use which relationships depending on your setup.
> 0 votes

# Answer
Select Taxonomy term in Contextual filter and then use hook\_views\_pre\_view() to pass that taxonomy term argument to the view.

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_view/7
> -1 votes

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


title: Using two arguments in a panels page?

text:
# Question
Title: Using two arguments in a panels page?
Here's what I want to do, for context:

I want to go to `mysite.com/groups/%gid/%nid` and see the node specified by `%nid` with an OG menu and a header pane that get their context based on the %gid. So if I have, say, a "person" nodetype, I can show a person node that belongs to multiple groups with the header and menu of different groups based on the URL. This is useful because then I can change the links that I use in each group's "people" list to keep the header and menu the same after the user clicks on the person.

I am not able to get the two arguments to work together, though.

I have been able to create a Views pane that displays the node by taking nid as a contextual filter, and gets it from the URL via panels. However, when I try to add the `%gid` first, I get all lost. I can't figure out how to use it to tell OG Menu which menu I want, I don't know how to use it to pass the appropriate context to the header minipanel that I've created (that works when a valid context is passed in), and I get "page not found" instead of a person node.

What am I doing wrong? How do I get two arguments in a URL to work together to tell Panels what the context and content should be, respectively?

# Answer
The problem is in this:

```
  $page->arguments = array(
    // Array key must be unique.
    'node' => array(
      'id' => 1,
      'identifier' => 'Node: ID',
      'name' => 'entity_id:node',
      'settings' => array(),
    ),
  );

```

I found workoroud for this problem. Create custom load hook that will be the similar to node or some else you need. Like this:

```
/**
 * Duplicates node load callback because panels can't have two same entities arguments.
 */
function mymodule_custom_load($nid) {
  return node_load($nid);
}

```

So to solve tis, you need to use %mymodule\_custom instead of %node. Hope this will help somebody, because I search the answer for very long time.
> 0 votes

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


title: Add Nested <ul> List into $form

text:
# Question
Title: Add Nested <ul> List into $form
I have something like this. How can I make `$upload_items` be a nested `<ul>` list under `Upload examples`

Something like

```
<ul>
  <li> Upload Ex </li>
    <ul>
      <li> YAY </li>
    </ul>
</ul>

```

What I have now

```
$upload_items = array(
  'PDF',
  'Video',
  'PNG, GIF, JPG, JPEG',
);
 $step_items = array(
    'Upload Examples',
    implode('</li><li>',$upload_items),
    'Describe The Project',
    'Assign Tags',
    'School/Company',
  );
 $form['step_list'] = array(
    '#prefix' => '<ul class="step_list"><li>',
    '#markup' => implode('</li><li>', $step_items),
    '#suffix' => '</li></ul>',
   );

```

Also, what is an easy way to add ids to these `<li>`

# Answer
Using `#markup` is ok, you want to use `theme_item_list` to easily build your list and add html attributes to it: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_item\_list/7
> 2 votes

---
Tags: forms
---


# Question
Title: Adding a views block to a menu? Or adding a menu to a views block?
I need to create a dropdown menu which consists of the menu items and also a views block of recent nodes. Yes this is technically a megamenu, but how would one build it without a megamenu using only menus and views only?

* How do you make a views show up inside a menu? I'd imagine you would need an extra module for it.
* But if you built a views block and did an entity menu call into the views header, that would work too right?
* Or maybe I'm going about the long way of doing it and should just use a megamenu module, which one would be best?

Of those 3 options which would work best with the least amount of work involved?

# Answer
To make views show up inside a menu you can use Menu Views. If you only require the functionality your described it's the simplest and easiest way to do it.
> 2 votes

# Answer
You are looking for menu attach block www.drupal.org/project/menu\_attach\_block module.

Menu Attach Block allows you to attach blocks to standard core Drupal menu items. This is especially useful for creating complex dropdown menus and mega menus.

Any block can be used, including blocks generated by other modules. Blocks generated by Views are particularly good candidates for embedding.

You can choose to replace menu items with Blocks, or keep the menu items and have the block available by clicking a link which is inserted beside the menu item.
> 0 votes

---
Tags: 7, routes
---


title: Printing a form inside a block

text:
# Question
Title: Printing a form inside a block
I have a specific block that has some form logic, intended for newly registered users. And I am a bit lost on what the logic would look like to render the contents for the form inside a hook\_block\_view. I've tried using a theme\_form() call to get errors, mostly string offset and fatal errors from type comparison. I've tried using drupal\_get\_form, with the same results.

Here's the code below. Thoughts?

```
/**
 * Implements hook_block_info
 */
function example_module_block_info() {
  $block['item_select'] = array(
    'info' => t('Select Item'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $block;
}

/**
 * Implements hook_block_view()
 */
function example_module_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case "item_select":
      $block['subject'] = t("Select a book");
      $block['content'] = theme_form('example_module_form_select_item_form');
      break;
  }

  return $block;
}

/**
 * Implements an example form
 */
function example_module_form_select_item_form($form, $form_state) {
  $form['item_type'] = array(
    "#type" => 'select',
    "#title" => t("Make a selection"),
    "options" => array(
      "1" => t("This"),
      "2" => t("That"),
      "3" => t("The Other"),
      "4" => t("Banana")
    ),
  );

  $form["submit"] = array(
    '#type' => 'submit',
    '#value' => t("Save Selection"),
  );

  return $form;
}

```

# Answer
> 0 votes
Try making a function using hook\_form() and calling it in your $block\['content'\] property?

```
$block['content'] = example_module_form($node);

```

# Answer
> 0 votes
You should be able to do something like:

```
/**
 * Implements hook_block_view().
 */
function example_module_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case "item_select":
      $form = drupal_get_form('example_module_form_select_item_form');
      $block['content'] = drupal_render($form);
      $block['subject'] = t("Select a book");
      break;
  }

  return $block;
}

```

---
Tags: 7, forms, blocks
---


# Question
Title: Reset a page with multiple exposed filters
I have a view page which is the main page on my website. It is kind of a search using exposed filters. As I have many exposed filters I installed the module MEFIBS which allows me to split the exposed form into multiple blocks that you can place in different areas. I have enabled Ajax as I use the UI slider from Better Exposed Filters module. I am developing on localhost (D7).

Now, I want to include a reset button to this main page. BEF module provides "include a reset button" but in my case every exposed filter gets an own reset button which is not user friendly (this is due to the MEFIBS module).

I tried this approach by adding a simple html button and the script location.reload(true), expecting that the page reloads not from the browsers's cache rather than from the server. The reloading works but the filter settings don't get reseted and I don't know why.

Does anybody have expierience with that? Any advise what causes this problem? Or maybe another approach?

Thanks, Thomas

# Answer
> 0 votes
Are the query parameters showing in the URL? Perhaps you could simply direct users to a clean version of the page without the parameters...

---
Tags: ajax, javascript, views
---


title: A module to find linkable content

text:
# Question
Title: A module to find linkable content
I am looking for a module that finds related pages for the purpose of linking them internally. For example, we have two pages, both have the name "Kill Bill" in their content, but they are not linked. The module would put the similar content to attention so that the editor can link the two pages. Or something similar to this.

I could implement Solr but it's not the preferred option.

Thanks

# Answer
> 1 votes
You can achieve that using the Remove Duplicates module.

Don't bother about the name of the module. you can use it as following way.

This module helps the administrator to easily find out the nodes according to one of the node fields.

So you can easily find out the same content pages and like those.

---
Tags: search
---


title: Get ID from a URL in drupal?

text:
# Question
Title: Get ID from a URL in drupal?
I have cretad a menu for edit a form in drupal...

**Code:**

```
function pricepackages_menu()
{
    $items = array();
    $items['membership/packages'] = array(
        'title' => t('Add Membership Packages'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_form'),
        'access arguments' => array('access administration pages'),
    );
    $items['show/packages'] = array(
        'title' => t('Manage Membership Packages'),
        'page callback' => 'view_packages',
        'access arguments' => array('access administration pages'),
    );
    $items['package/%/edit'] = array(
        'title' => 'Edit Membership',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_form_update'),
        'access arguments' => array('access administration pages'),
    );
    return $items;
}

```

3rd menu is for eidt purpose...

**The codd to show form i worte is:**

```
function pricepackages_form_update($form, &$form_state)
{
    $form['packagename'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Name',
        '#required' => TRUE,
    );
}

```

Please let me know how can get the value of the id in the url :

**URL :** http://somedomain.com/package/1/edit

I want to get the id 1 from the url and than want to add a select query... please let me know how can i get that value so i can wrote teh select query...

Also do i have to specify a new parameter in the pricepackages\_form\_update() or not?

Thanks in advance...

# Answer
> 0 votes
Try It works for me.

```
$items['package/%/edit'] = array(
'title' => 'Edit data Row',
'page callback' => 'pricepackages_form_update',
'page arguments' =>array(1),
'type' => MENU_NORMAL_ITEM,
'access callback' => TRUE,
);

function pricepackages_form_update($arg){
$my_object = db_select('your table name', 'a')
->fields('a')
->condition('your node id parameter', $arg )
->execute()
->fetchAssoc();
return drupal_get_form('your form menu', $my_object);
}

```

---
Tags: 7, forms, updating
---


# Question
Title: Generate one-time-use custom links for emails and interact with them to accomplish tasks
Is there a module that would auto-generate custom unique one-time-use URLs that timeout after a set time, and can be used to accomplish tasks and progress workflows in Drupal 7?

### Use Case 1

User must click link in email to verify their address is valid.

### Use Case 2

As part of a workflow process users must confirm they wish to complete an action by clicking on the appropriate link in an email message and depending on the link chosen the node would progress to a different state in the workflow

# Answer
You can copy function "user\_pass\_reset\_url" and form "user\_pass\_reset" and customize it for your needs. With first you create custom link and with the second you can get "one-time-link" logic.
> 0 votes

# Answer
I was having some problems generating the one time login URL using the Drupal 7 documentation, This worked for me.

```
$mail = 'someone@yoursite.com';
// Load the user.
$account= user_load_by_mail($mail);
$url = user_pass_reset_url($account);
print '$url';

```
> 0 votes

---
Tags: 7, uri, workflows
---


title: Restrict operations to Specific user

text:
# Question
Title: Restrict operations to Specific user
I constructed my admin/content page using my custom module

Steps i follow 1. retrieve data from multiple tables and displayed it in table 2. I gave edit and Delete options

From admin/user edit and delete options working good

Now my question is i logged in as authenticated user how to disable edit and delete options for admin created pages.Only user will see edit/delete option for his own created pages.Thank you

# Answer
You'll need to implement hook\_permissions(). And you probably also need to read up on user\_access(). The strategy is to create a permission set, grant it for the admin role, and then check for user\_access before you render the buttons. This way the buttons will only show for users who have been granted the permissions.
> 0 votes

---
Tags: 7, users
---


title: Delete boost file?

text:
# Question
Title: Delete boost file?
Is there a way to delete a file of the boost cache? On my site users can submit content and i need that only the previous node of the currently created node to be deleted(flushed). When I flush all my pages after creating a node my site gets slow. So i wonder if this could be made.

# Answer
> 2 votes
You need to install the Cache Expiration module:

This will delete the exact files that were impacted by the content edit.

---
Tags: caching
---


# Question
Title: How do I enable the "print PDF" link on only a specific page?
I have enabled the print module and configured the basic page content type to show a PDF print link under the basic page settings.

On the print module's Links settings page at `admin/config/user-interface/print/ui`, under the *Advanced Link Options* heading, I can specify the paths where I want to show a PDF print link.

But it is still showing a "print PDF" link on all basic pages.

I also tried by disabling the print setting under basic page settings, and only entering the path under print links settings, but then it disable the pdf print link from *all* basic pages -- even from the one I want it to show up on.

# Answer
Check the Link options section at `admin/config/user-interface/print/ui`, making sure you don't have '`content corner`' selected.
> 0 votes

# Answer
Download and install 7.x-1.3 of the Print module instead of 7.x-2.x. In 7.x-1.3 there will be a Link Visibility section in the PDF configuration section that will let you select the pages to display the PDF link on. For some reason this no longer appears in 7.x-2.x, at least I haven't been able to find it.
> 0 votes

---
Tags: 7
---


title: Load old cart order in commerce

text:
# Question
Title: Load old cart order in commerce
As I understand it commerce gets the users highest numbered order that is not yet completed (on the customers end) and uses that when a user adds an item to their cart or views their cart however I created a module that will allow a single user to create many carts (lets call these quotes) for their customers and i need a way for them to be able to go back and edit a previous quote or complete checkout on a previous quote right now i have a list of quotes in a view (any order that has not passed the checkout review page) and I want to add a column containing a link or button that will allow them to load that order number as the current cart I tried using a custom module function with a call to

```
commerce_cart_order_load(1);

```

(from a menu link) which is a previous order on my account however that appears to do nothing

Can anyone explain what I'm doing wrong/ what I need to do to make this work?

I would be perfectly happy doing this with views php if there is a function to set the users cart order that I'm missing, or by storing an OrderID hidden on the users profile

Thank You

# Answer
> 0 votes
After much playing and breaking I wrote some code in a custom module to save the current order to load to the users profile in a un-editable field

```
    function create_new_quote_menu() {
  $items = array();
  $items['create_new_quote'] = array(
    'title' => 'Start New Quote',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  $items['quotes/%/Load'] = array(   // assuming you want to make this dynamic
    'title' => 'Quotes',
    'page callback' => 'create_new_quote_LoadQuote',
    'page arguments' => array(1),   // references %, i'm assuming this is all dynamic
    'access arguments' => array('access content'),  // don't do this, whatever permission you want goes here
    'type' => MENU_CALLBACK
  );
  return $items;
}

function custom_callback () {
  global $user;
  $currentOID;
  $user_full = user_load($user->uid);
  $currentOID = commerce_cart_order_new($user->uid);

  $updateUserParams = (array) $user_full;
    $updateUserParams['field_currentcartorder'][LANGUAGE_NONE][0]['value'] = intval($currentOID->order_id);

    unset($fullUser->pass);
    unset($updateUserParams['pass']);

    user_save($user_full, $updateUserParams);
drupal_set_message(t('You have Created a New Quote #'). $currentOID->order_id,'status');
drupal_goto('moulding');
}

function create_new_quote_LoadQuote($quote_to_load) {
  global $user;
  $user_full = user_load($user->uid);

  $updateUserParams = (array) $user_full;
    $updateUserParams['field_currentcartorder'][LANGUAGE_NONE][0]['value'] = intval($quote_to_load);

    unset($fullUser->pass);
    unset($updateUserParams['pass']);

user_save($user_full, $updateUserParams);
drupal_set_message(t('You Loaded Quote #'). $quote_to_load,'status');
drupal_goto('quotes');
}

function create_new_quote_commerce_cart_order_id($uid) {
  global $user;
  $user_full = user_load($user->uid);
  $orderidentifier = $user_full->field_currentcartorder['und'][0]['value'];
  $orderidentifier = intval($orderidentifier);
  return $orderidentifier;
}

```

excuse my uncommented code and poor module name but I got it working this this code set so I can now create and change orders from my view by pasing Quotes/\[orderid\]/Load via a link

---
Tags: views, commerce
---


# Question
Title: Why do I need to use .live() in Drupal Behaviors?
I am trying to be a good boy and use Drupal Behaviors to manage my JavaScript. My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements. However, I find that I have to use .live() all the time. What am I doing wrong?

Here is a simple example of what I'm talking about:

```
Drupal.behaviors.MySearch = {

  attach: function (context, settings) {

    var searchBox = $('#my-search-box');
    searchBox.append("<input type='text'></input>");
    searchBox.append("<button>Search</button>");

    $('#my-search-box button').click(function(){
      console.log("This does not work.");
    });

    $('#my-search-box button').live('click', function(){
      console.log("This does work.");
    });

};

```

# Answer
> 4 votes
> My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements.

Yes and no. It certainly can be used for that, but it will only work if *Drupal* has invoked the previous AJAX call. If you've just done a `$.ajax(...)`, Drupal won't know about it, and `attachBehaviors()` won't be invoked.

I would guess that your `attach()` method is indeed only being invoked once, as it would explain perfectly why the click handler is assigned once (when the page is first loaded), but not again. The `live()` will always work no matter how many times your `attach()` method is called.

If that is the problem, to fix simply add this to your AJAX success callback:

```
Drupal.attachBehaviors();

```

# Answer
> 0 votes
live() is always the best option because it dynamically bind ajax response but click doesn't. So always use live() or on() function

---
Tags: javascript
---


title: Organic Groups Custom theme/layout

text:
# Question
Title: Organic Groups Custom theme/layout
Hi I would like to give all organic group pages a custom theme and layout. How would I go about doing this? For example, I want the main site pages to follow a certain theme/layout, but when you go to any group page the theme and look is entirely different. Is this possible?

# Answer
The Delta module allows you, via the Context module to make duplicates of your theme settings for any context on your site. This gives you the ability for alternative layouts as a reaction in Context. The Delta module was originally created to compliment the powerful Omega base theme, but now works with ANY theme (3.x Version)
> 2 votes

# Answer
I would like also to have different theme settings for each organic group(Different logo and different background colour).Could you please explain the steps how to do this with Context and Delta modules? Actually what the path should be on the Context module so as to have different theme settings for each organic group? Thanks
> 1 votes

# Answer
Context doesn't let you set a Delta for Organic Groups. OG-Themes module is needed.
> 0 votes

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


# Question
Title: How can I hide specific user from dropdown list of users
Could you please help me with one little question. I'm using Drupal module Support Ticketing System.

When the support ticket is created user can choose from dropdown form for whom this ticket is assigned. Usually it's a list of Drupal site users.

How can I hide a specific user from this list (admin for example)?

# Answer
> 1 votes
One possible solution is to add a new field show/hide Checkbox in account settings and then in drop down show only those whose show/hide field set to show.

This way if your client wants to hide another user go and edit the user and hide it

# Answer
> 0 votes
In your form\_alter() function, run an array\_filter() on the options array for the dropdown.

---
Tags: hooks
---


title: Quicktabs- Drupal7

text:
# Question
Title: Quicktabs- Drupal7
I am newbie to Drupal and just started building website in Drupal-7.

I have created Three Tables Block using View. And I have created tabs using Quicktabs Module. But Tab title displayed as HTML source code in Quicktabs.

Can anyone please help me with that? Or is there any other way to create block that shows tabular data dynamically with tabs on the top?

I have also tried to create view tabs. But it create page with menu tabs and I want a tabular blocks(three different blocks) with tab.

Thanks!

# Answer
> 1 votes
In your QuickTabs instance, try changing the ajax from yes to no.

Ajax-

Yes: Load only the first tab on page view

**No: Load all tabs on page view.**

---
Tags: views, blocks
---


title: What is 'value' type of the field?

text:
# Question
Title: What is 'value' type of the field?
Could you please explain how it works:

```
$form['support']['priority']['#type'] = 'value';

```

On my site this code is used to hide Priority field. But I don't understand the logic (I'm pretty new in Drupal). What is really this 'value'.

# Answer
> 1 votes
Check Form API documentation on this. It looks like someone hid field `priority` from output so users can't see or change it from form, but value of this field still can be used on form handlers.

# Answer
> 1 votes
You need to replace #type with a keyword and the value that is to be associated with that keyword.

For instance, to hide a field you could:

```
$form['support']['priority']['#prefix'] = '<div style="display:none;">';
$form['support']['priority']['#suffix'] = '</div>';

```

This basically wraps the field in a div that is set to not display.

---
Tags: forms, hooks
---


# Question
Title: Retrieveing config for a custom ctools content type
I've created a custom **ctools** content type to make a custom pane for my node/%nid panel. The content type has an edit form with some configuration options for the pane, that I would like to access from a function call from a custom module.

I haven't been able to find where this information is stored in the DB, or how I might be able to access it with some of the ctools functions.

For more context, the form has a toggle between public and private users. And I would like to know when submitting an unrelated form on the page, if that block is set for public or private use, and wanted to get the information directly from what I chose when configuring the pane.

# Answer
> 0 votes
What I think you want might be possible, but it is not easy. The configuration settings are saved in the DB in the panels\_pane table as serialized data in the 'configuration' column. That allows each instance of the pane to have its own configuration. In order to get that you would need to know how to get the specific instance of the pane being displayed, grab the column, and then unserialize it.

You are probably better off figuring out a different way to handle this (if you haven't already).

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


title: Local Task Menu - Add a Page link

text:
# Question
Title: Local Task Menu - Add a Page link
I am trying to figure out the best way to add a panel page navigation item to the local task menu set.

I want to create a Panel Page with QuickTabs to build a simple UX for a non-drupal admin to updated and edit users for there events.

I can add the quick tabs etc. to the panel page, however, I am not sure how to add the menu item to the local task menu tabs.

So, when you edit an event here is what I want the menu to look like...

View | Edit | **Panel Page**

So, **Panel Page** is the new local task menu item for my panel page. I have been searching for a way and change not find it.

# Answer
So, it took a while to figure what I needed was to add a custom local task navigation tab. To handle adding local task you need to learn the hook\_menu() function, right after you learn to build your first hello world module. P.S. having the Test 1 and 2 menu items is what tells Drupal to create the outcomes tab.

```
/**
* Implementation of hook_menu().
*/
function outcomes_menu() {
  $items['node/%node/outcomes'] = array(
        'title' => 'Outcomes',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
  );
  $items['node/%node/outcomes/test1'] = array(
        'title' => 'Outcomes Test1',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('drupalform_form1')
  );
  $items['node/%node/outcomes/test2'] = array(
        'title' => 'Outcomes Test2',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('drupalform_form1')
  );

  return $items;
}

```

Hopefully, this helps someone else.
> 0 votes

---
Tags: panels, routes
---


# Question
Title: Need to know the most essential JS and CSS files for a Drupal 7 page
I am creating a module that has a page that is intended to be a viewer for a certain kind of content. The content itself is a Drupal Book viewer meant to behave like an epub reader. Basically I want this page to be a stand-alone, theme-independent, full-screen "player."

To achieve this effect, I don't want to load the usual long list of CSS and JS files, including those from the current theme as well as any from modules that I am not interested in using. I want the page to load **only** those JS and CSS files that are required for basic Drupal functionality -- e.g. I want Behaviors to work and a few other things, such as overlays.

My question is, what are considered to be the essential JS and CSS files? I realize I can find a way to just dump a list of all files by module. But I am looking for information on importance. I realize this is a little vague and that there are probably a lot of answers that begin with "It depends ..." However, there must be some items that are more fundamental than others.

I am working in Drupal 7 and using hook\_js\_alter() and hook\_css\_alter() to remove (unset) items, and a preprocess function to add items.

# Answer
You can achieve this by making your module load your own html.tpl.php and in that version of the html template, you simply remove references to styles and scripts.

```
<?php print $styles; ?>
<?php print $scripts; ?>

```

For a viewer, you can probably do without the reams of CSS cruft that is loaded by default and add your own bare bones css & js either through a hook or by including it in your custom html template.

```
<?php print $path_to_your_reader_styles; ?>
<?php print $path_to_your_reader_scripts; ?>

```
> 1 votes

# Answer
The answer to this question is that there is no answer. As Clive comments, it depends on what you are doing -- or, more specifically, what your base modules are and which theme you are using. At the moment, there is no registry to look at which will tell you all of the JS files and CSS files you are using, but I suppose one can achieve this effect by setting up a pristine site with all of the basic stuff and, before adding anything, inspecting the js and css arrays.
> 0 votes

---
Tags: javascript, theming
---


# Question
Title: Execute Drupal function in background, maybe with cron, for the duration of a user session
It was too complicated description of the task, so let me edit it and simplify: I need a Drupal 7 function (data collection function) to be periodically triggered in the background but only a while a logged in.

Use case is that we need bunch of data from the remote server to display to the user and it takes long time for all the data to be (1) copied from the remote server, (2) upload to local Drupal database and (3) finally to display to the user. So we don't want the user to wait, but to do some other staff and display the data little bit later when it is ready.

So scenario is like this:

* User logs in to Drupal 7 website and start browsing pages without any delay.
* At the moment when he/she log's in we need to trigger a Drupal function in a custom module that starts to perform steps (1) and (2) in the background. So user again doesn't feel any delays.
* When the data is pulled and uploaded to the local Drupal 7 database, the system starts displaying it to the user.

Is it so difficult or impossible for Drupal to trigger a function in the background independently of whatever user is doing on the website only for the period of time while he/she is in the session?

# Answer
> 3 votes
## Preface

While doing web development, **if user is browsing** can only be measured with two methods: 1. User last access time is less than A\_PRE\_DEFINED\_AMOUNT (say 5 minutes) **or** (more accurately in some cases, as the user might be just reading the same page without refreshing) user's last heartbeat time is less than A\_PRE\_DEFINED\_AMOUNT **or** or the most accurate, combination of both (js might be disabled on some browsers).

And while doing Drupal development, running a task periodically, means a cron task. **but** sometimes these tasks are better handled outside of Drupal.

The problem originates from the fact that Drupal does not have an always running server. Usually NodeJS is used in combination for such tasks, and it performs better (usually when resources on the server is limited). When the NodeJS has the data ready, it uploads it to drupal by calling a URL which you have previously defined in a custom module, say http://example.com/my/module/upload/data. It will use HTTP POST to authenticate and send data.

But anyway, here is the pure Drupal solution:

## The custom module part:

* Create a custom module.
* Define a new entity type in your module (recommended) using a project like entityspice, model or plain entity api.
* OR just use hook\_schema() and define a table for your module in database (though entity is recommended).
* Define a custom rule action in your module, when called it should write the current user id (uid) in the table you just defined. If you have created a new entity type you can use the already existing rule **create a new entity**.
* Or just use nodes or a field in user profile but be careful about access checks. It's your call.
* Create another rule action, triggered on cron (using rules\_scheduler), in this action: fetch user's last access time, if it's more than 5 minutes, fetch the entity we talked about just above and remove it (more explanation on this later).
* OR instead of rule action, define a cron task in your module. it should: check user's last access time, if it is more than 5 minutes, remove his/her uid from your custom table.
* Or instead of checking user last access time, create a custom JS loaded on every page for logged in users which sends a heartbeat. It is simply done by defining a custom path in your module such as example.com/my/heartbeat/path and fetching that URL using HTTP GET (using ajax) on the server in your custom path's handler function, you should check current user's UID who is sending the heartbeat and update the last access time of the user. (or perhaps create your own entity/table/field for storing last heartbeat time).

Congrats! first part done. now you know if you should process data or stop processing data for user. You know you should while their UID is in your custom table.

## The processing of data:

Still this part of question is unclear: who will fetch data? is there a large amount of data, or does it take long for data to become ready? if the former, you might face PHP execution time outs, if the later, you might be fine. Any way, to do it in Drupal, you should create a custom cron task which is again, possible in rules. in this cron task, check every uid which is in the custom entity/table we talked about above and fetch data for, and upload it to local database.

Your cron task should check two conditions: 1. is user uid still in table? 2. is data ready? if 1 is false, cancel fetching data. If 2 is false, just pass for now.

If there is a large amount of data being fetched and user has left the site, you probably won't be able to cancel it as there is no true multi-threading in PHP. how ever there is a register\_tick\_function which might do the job: if the uid of current task is removed, call die(). I don't know if die() in registered tick function works, however if data is being fetched for other users too, they will be canceled!!

# final note:

**DO** Install Elysia Cron (optional but highly recommended). If you are planning to run cron on short periods it will take the load off of your server drastically.

# Answer
> 0 votes
Cron won't help you, it executes the jobs in system(machine) level, at specified time, it doesn't care about someone is viewing the website, how many minutes he/she sits.. You should look for client side solutions, which interact with browser (JavaScript, or it's framework JQuery...), may be setTimeout or setInterval can help you..

Some thoughts:

```
function MYMODULE_menu()
{
  $items['PATH'] = [
    'title' => 'TITLE',
    'page callback' => 'myCallback',
    'page arguments' => [],
    'access callback' => TRUE, // Bad idea,
    'type' => MENU_CALLBACK
  ];

  return $items;
}

function myCallback()
{
  // buildTheLogic();
}

```

javascript:

```
function someName()
{
  // buildTheLogicHere();
  // may be you call ajax request to that PATH, display the result...
}

setTimeout(someName, 60000);

```

you can also use self-executing anonymous functions with `setTimeout` if you want to repeat the process.

---
Tags: cron
---


# Question
Title: Downloading a feed's embedded images to server and rewriting paths in html automatically
I'm scraping a some sites into a csv which is then used by feeds importer module to create Drupal content.

Some of the content are html chunks containing html+images in them which go into "body"/textarea kind of fields to be displayed.

How do I use feeds tamper or some other method to

1. **Download these embedded images to server** and
2. **Rewrite the image paths in the HTML chunks to point to server paths**

---

Possible solution:

* Rewrite the paths in the html to internal paths registered via "hook\_menu". When the path is called, if the image is not there, use "system\_retrieve\_file" to download the file and serve it .. Example hook\_menu() implemented at image\_menu. {Thanks Ciss @ drupal-support irc channel} Rewriting would be taken care of by feed\_tamper that I have already.

---

**To clarify - I know that if I use image urls with image fields, the images will be downloaded automatically. However I don't know how to download images that are *within* a HTML chunk.. thanks.**

# Answer
One possible solution is the feeds\_imagegrabber module.

What is does is when the feed is importing it goes to the original web page of the feed item and scrapes the image from the page and imports it into drupal.

Depending on the specifics of your requirements this could be a good easy solution.
> 1 votes

---
Tags: importing-exporting, files, feeds
---


# Question
Title: views filter for current user with a relationship
I know how to create a view that filters nodes that were authored by the current user. What I want to do is filter based on the author of a node that has a relationship with the node.

For example: My view has a filter to show nodes of type A type A has a field that is a reference to type B I want a filter that shows nodes (of type A) where the referenced type B node was authored by the current user.

In D6, I did this by creating a relationship to B, then adding a filter where (B)User=Current (that is, User = current with a relationship to type B). I can't figure out how to do this in D7.

So far I have created a relationship to "Content:Author" which does not allow me to define a relationship to type B. Then I created a filter for "(author) User: Current (Yes)" but this appears to be filtering based on the author if my type A nodes.

I've tried googling, but can't seem to come up with the right keywords.

# Answer
> 1 votes
If I correctly understand the requirement then you are missing the relationship between content type 1 and 2

You need a view of nodes with:

* A filter that only shows node of type A.
* A relationship from node type A to node type B via your reference field.
* A relationship from node type B to its author user.
* A filter to restrict the user author (of content b) to the current user.

---
Tags: 7, views
---


# Question
Title: Cannot replace html.tpl.php with new template in a single module
I am creating a module to handle the reformatting of pages for printing in D7.

The structure of the URL is: `/print/{nid}`

I need to use a separate template than html.tpl.php as I have to get rid of our global header/footer but I still need our javascript and css to load.

I'm at a loss for how to correctly implement this.

I have created a menu\_hook, otherwise I get a 404 page

I have tried using the `$vars['theme_hook_suggestions'][] = 'html__print';` but I get no output

```
<?php
// print.module
function print_menu()
{
    $items  = array();

    $items['print/%node']   = array(
        'title' => '',
        'access arguments' => array('access content'),
        'page arguments' => array(1),
        'page callback' => 'print_process_print',
    );

    return $items;
}

function print_process_print(&$vars)
{
    error_log(__FUNCTION__.' called');
    error_log('node: '.var_export($vars, true));

    $vars['theme_hook_suggestions'][]  = 'html__print';

}

```

My template file is: `sites/all/themes/zen/templates/html--print.tpl.php`

Any help is greatly appreciated.

# Answer
> 0 votes
To create your own template override in a module is not the same as doing it in a theme. Look at Overriding a template file (.tpl.php) from a module.

Put this code in your module, and put the template file in a sub-directory 'templates'. Clear the cache.

```
function MODULE_preprocess_html(&$vars){
  $vars['theme_hook_suggestions'][]  = 'html__print';
}

function MODULE_theme_registry_alter(&$theme_registry) {
  $path = drupal_get_path('module', 'MODULE') . '/templates';
  $templates = drupal_find_theme_templates($theme_registry, '.tpl.php', $path);
  foreach($templates as &$template) {
    $template['type'] = 'module';
    $template['theme path'] = path_to_theme();
  }
  $theme_registry += $templates;
}

```

---
Tags: 7, theming, routes
---


# Question
Title: can we add new column to a view programmatically?
I want to add new field in a existing view programmatically.

I am trying to use hook\_views\_pre\_render().

```
function registration_export_views_pre_render(&$view) {
    if ($view->name=='registrations_export') {
        foreach($view->result as $r => $result) {
        //dpm($result->registration_id);
        $result->registration_id = 1;
        }
    }

}

```

If i add the "registration id" field to view page then i can see registration id field in my output. But i dont want to add in view field add page. I want to field add dynamically.

As per suggestion i have tried this

```
    function registration_export_views_pre_view(&$view, &$display_id, &$args) {
          if ($view->name == 'registrations_export') {
            views_db_object::add_item($view->current_display, 'field',
    'field_data_field_first_name_1', 'field_first_name_1',
$options = array(
            $handler->display->display_options['fields']['field_first_name_1']['id'] = 'field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['table'] = 'field_data_field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['field'] = 'field_first_name_1',

            ), $id = NULL);

          }
        }

```

View export

```
$view = new view();
$view->name = 'registrations_export';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'registration';
$view->human_name = 'registrations_export';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'List of Event Registrations';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'title',
    'rendered' => 1,
    'rendered_strip' => 1,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'registration_id' => 'registration_id',
  'nid' => 'nid',
  'title' => 'title',
  'field_first_name_1' => 'field_first_name_1',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'registration_id' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_first_name_1' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Registration: Registration to Node */
$handler->display->display_options['relationships']['registration_related_node']['id'] = 'registration_related_node';
$handler->display->display_options['relationships']['registration_related_node']['table'] = 'registration';
$handler->display->display_options['relationships']['registration_related_node']['field'] = 'registration_related_node';
/* Field: Field: Salutation */
$handler->display->display_options['fields']['field_salutation_new']['id'] = 'field_salutation_new';
$handler->display->display_options['fields']['field_salutation_new']['table'] = 'field_data_field_salutation_new';
$handler->display->display_options['fields']['field_salutation_new']['field'] = 'field_salutation_new';
$handler->display->display_options['fields']['field_salutation_new']['exclude'] = TRUE;
/* Field: Field: State */
$handler->display->display_options['fields']['field_state']['id'] = 'field_state';
$handler->display->display_options['fields']['field_state']['table'] = 'field_data_field_state';
$handler->display->display_options['fields']['field_state']['field'] = 'field_state';
$handler->display->display_options['fields']['field_state']['exclude'] = TRUE;
/* Field: Field: Payment Type */
$handler->display->display_options['fields']['field_payment_type']['id'] = 'field_payment_type';
$handler->display->display_options['fields']['field_payment_type']['table'] = 'field_data_field_payment_type';
$handler->display->display_options['fields']['field_payment_type']['field'] = 'field_payment_type';
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
//echo \'<pre>\';
//print_r($view->result[0]->_field_data[\'registration_id\'][\'entity\']);
//print_r($data);
//print_r($row->title);
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'registration_related_node';
$handler->display->display_options['filters']['title']['operator'] = 'contains';
$handler->display->display_options['filters']['title']['exposed'] = TRUE;
$handler->display->display_options['filters']['title']['expose']['operator_id'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['label'] = 'Event Name';
$handler->display->display_options['filters']['title']['expose']['operator'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['title']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  7 => 0,
  9 => 0,
  10 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'registrations-list';

/* Display: Data export */
$handler = $view->new_display('views_data_export', 'Data export', 'views_data_export_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '0';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'views_data_export_csv';
$handler->display->display_options['style_options']['provide_file'] = 1;
$handler->display->display_options['style_options']['filename'] = '%timestamp-dd - %timestamp-mmm %view.csv';
$handler->display->display_options['style_options']['parent_sort'] = 0;
$handler->display->display_options['style_options']['quote'] = 1;
$handler->display->display_options['style_options']['trim'] = 0;
$handler->display->display_options['style_options']['replace_newlines'] = 0;
$handler->display->display_options['style_options']['header'] = 1;
$handler->display->display_options['style_options']['keep_html'] = 0;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'registration_related_node';
$handler->display->display_options['filters']['title']['operator'] = 'contains';
$handler->display->display_options['filters']['title']['exposed'] = TRUE;
$handler->display->display_options['filters']['title']['expose']['operator_id'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['label'] = 'Event Name';
$handler->display->display_options['filters']['title']['expose']['operator'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['title']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  7 => 0,
  9 => 0,
  10 => 0,
);
$handler->display->display_options['path'] = 'registrations-list-export-csv';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

/* Display: Data export 2 */
$handler = $view->new_display('views_data_export', 'Data export 2', 'views_data_export_2');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'views_data_export_xls';
$handler->display->display_options['style_options']['provide_file'] = 1;
$handler->display->display_options['style_options']['parent_sort'] = 0;
$handler->display->display_options['path'] = 'registrations-list-export-xls';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

```

Thank you very much.

# Answer
Check out the function views\_db\_object::add\_item().

There is an example at https://drupal.stackexchange.com/a/70649/10729 of using it to add header/footer items but it can be used for fields too.

Where your code goes depends on your situation but I would suggest that the pre\_render hook is too late because the sql has already been executed and you need to add the field before that happens or you won't get the data.

A better example for what you want to do is at http://dropbucket.org/node/1178

In case that link goes away the code is:

```
/**
 * Implements hook_views_pre_view().
 *
 * Add 'Custom text' field.
 */
function hook_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view') {
    $view->add_item($view->current_display, 'field', 'views', 'nothing', array(
      'label' => 'My field',
      'alter' => array('text' => 'My field text'),
      'element_class' => 'my-field',
      'element_default_classes' => 0,
    ), 'my_field');
  }
}

```

If you want to know how to construct the array for the field settings I suggest creating a view via the UI with a field the way you want it, then export the view and see how it outputs that field. You can use that info to create your field array.

**\[EDIT\]** Your current attempt at using the add\_item() function isn't working because you are passing in the wrong parameters for what you want to do.

If you look at the linked documentation for add\_item() it shows what it expects for the parameters (admittedly in this case the docs aren't very good but the parameter names help).

The function definition looks like this:

```
views_db_object::add_item($display_id, $type, $table, $field, $options = array(), $id = NULL)

```

So you are passing in:

* $display\_id: The current display - which is fine.
* $type: "field" - which is fine.
* $table: "views" - this is almost certainly not right. The views table is for special views fields like "Custom text" (which is what that example is adding as per its comment). You need to pass in the table name for the field you want to add. For example if you wanted to add the nid field the table would be "node". If you have a field called field\_firstname then you would probably want the table "field\_data\_field\_firstname".
* $field: "nothing" - this is also probably not right. Again the nothing field is the views "Custom text" field. to go with my table examples would be something like "nid" or "field\_firstname".
* $options: This is likely not right either as it is a copy of the custom text field example with changed values, however the field you want to add probably requires different options to the custom text field. As mentioned before, the best way to work out what to add here is to create a view with the field you want to add set up the way you want it, then export the view and it will give you the settings. for example here is part of a view export for a field:

```
/* Field: Content: Contact Email */
$handler->display->display_options['fields']['field_contact_email']['id'] = 'field_contact_email';
$handler->display->display_options['fields']['field_contact_email']['table'] = 'field_data_field_contact_email';
$handler->display->display_options['fields']['field_contact_email']['field'] = 'field_contact_email';
$handler->display->display_options['fields']['field_contact_email']['label'] = '';
$handler->display->display_options['fields']['field_contact_email'] ['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_contact_email']['type'] = 'email_spamspan';

```

You can see it gives information about table, field, id and other settings which you can use when you are adding your field programmatically.

So compare the values in this array (read the array values, don't just copy and paste, it will help make sense of the array structure) using this field as an example your options would be something like this:

```
array(
  'label' => '',
  'element_label_colon' => FALSE,
  'type' => 'email_spamspan',
)

```

But there are lots of possible options depending on the field type you are using. You can also try with an empty options array at first too.

The views export is full of square bracket array syntax so it converts easily into an array (for more information see http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing).

Programmatically modifying views can get pretty complex so I recommend a lot of reading of PHP docs, Drupal docs, and Views docs. Copy & paste will only get you so far.
> 15 votes

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


# Question
Title: Drupal 7 Views - Add a wrapper around rows for unformatted list from admin panel
I have a views which rendered html like this

```
<div class="content">
<div class="row-1">Some Text here</div>
<div class="row-2">Some Text here</div>
<div class="row-3">Some Text here</div>
</div>

```

Now I want to wrap the rows using a wrapper div like so.

```
<div class="content">
<div class="wrapper-1">
<div class="row-1">Some Text here</div>
<div class="row-2">Some Text here</div>
<div class="row-3">Some Text here</div>
</div>
</div>

```

# Answer
Assuming you know how to override theme templates (that would be a separate question) you can override the views\_view\_unformatted.tpl.php template and make your override something like this:

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

```

You could also override the views-view.tpl.php template instead and in the part that says:

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

```

do something like

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

```

It's up to you which way you want to do it.
> 1 votes

# Answer
You can go to your view under format click on format settings see List section, select one of the list types and type name of your class. li, ol, de tag will be placed where you want it.
> 0 votes

---
Tags: views
---


# Question
Title: Risks of developping your own theme from scratch?
I read several answers about "Is it better to develop your own theme from scratch or extend a existing one?".

Here is my situation: I just got an existing project and I have to debug it and evolve it. I'm in the audit phase and I was wondering if, in a theme developed **from scratch**, you forgot to provide the code for render some elements, are they going to stay hidden?

The specific case in this project is the **absence of drupal status messages**. They never appear. I guess there are plenty of them that are generated by the core, like when you fail at login or something. But they just don't happen.

It is very problematic and I want to fix that.

Is that because developers forgot to render them manually somewhere?

Thanks in advance

# Answer
> 6 votes
> if, in a theme developed from scratch, you forgot to provide the code for render some elements, are they going to stay hidden?

Yes, of course - if you develop a theme and override core templates, anything that's left out will remain left out. There's no magic in Drupal, it's just PHP at the end of the day. Think of it from the other side of the equation - if you were building a theme from scratch, and Drupal kept injecting markup into your templates without your say-so, wouldn't that be a crazy state of affairs?

> Is that because developers forgot to render them manually somewhere?

That's impossible to say from here. Could be that, could be some rogue CSS hiding them, could be a theme override of status messages nulling the output, and a bunch of others besides. The only way to know is to have a look and see what's there.

If the theme follows any sort of convention at all you should be able to look for a variable called `$messages` for the status messages. Usually it's located in page.tpl.php.

What you're essentially asking is akin to *"I've built a car from scratch, if I leave out the brakes with someone else put them in for me?"*. The answer is *"Only if someone intervenes manually; the assembly line won't do it automatically"*.

# Answer
> 1 votes
From my experience, developping you own theme from scratch for **specific needs** (those can't be meet by more general theme) is a good mid-long term solution. But that require some past experience in theming.

For your absence of drupal status message, you can just download some skeleton theme (basic, bootstrap, etc) and have a look how they handle drupal status message. Maybe they just didn't print the output, have you check in the tpl files ?

For example in basic theme, in page.tpl, you have :

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

```

# Answer
> 1 votes
I really like starting from scratch, but mainly after I got a good base theme going.

My approach is to use a few template files from `modules/system/` specifically `html.tpl.php` and `page.tpl.php` that way you have a good overview of available variables.

In your case I'd have a look at the Drupal API docs for page.tpl.php and that way anything that isn't being rendered you can render. (It's unlikely that anything is actually missing just un-rendered.)

---
Tags: 7, theming, status-messages
---


# Question
Title: How do I enable a menu link only when the user has created a node?
In my website the user can create a node. I want a menu link to appear only after the authenticated user has created the node and not before that.

Is it possible to enable a menu link only when the user has created a node?

For example, the menu items that appear when users log in are:

* Item 1
* Item 2
* Item 3

When users add a node, I want another item that points to another page to appear in the menu. If users didn't create a node, they don't have access to the new item.

How can I do this?

I created another role when the user creates a node using the Rules module, and set permissions for the user with the new role to view the new menu item.

# Answer
One possible solution (there are multiple possible solutions) is to use the rules module to assign a specific role to any user that has created a node (because it seems like users who have created a node are kind of in a specific group of users).

Something like (these aren't exact setting names, it's off the top of my head):
event: create a new node
condition: user doesn't already have this specific role
action: grant user this specific role

Then make it so that users without that role cannot see that menu item.

This can be done in a few ways (this is not an exhaustive list):

* Use the menu item visibility module to restrict visibility of that menu item if users don't have that role (be aware that the user can still access the page the menu item points to if they know the url - this is not access control).
* If that item links to a node you can use some sort of content access module like content access to restrict access to that node if users don't have that role. If a user doesn't have access to the node they won't see the menu item pointing to it.
* If the menu item points to a view you can set the view permission settings so it is not available to users without that role. If they don't have access they won't see the menu item.
> 2 votes

# Answer
Here are the steps

For example If you want give permissions for authenticated users to create 'Basic page'

Go to Home » Administration » People (admin/people/permissions) and check the checkbox

`Basic page: Create new content` and `Administer menus and menu items` for AUTHENTICATED USER

That's it now authenticated user can create basic page (node/add/page) with menu item.

If you want to generate URL/path aliases automatically, use the Pathauto module

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
> 2 votes

---
Tags: rules, navigation
---


title: Template files and Machine Names

text:
# Question
Title: Template files and Machine Names
I am trying to create some variables in my template.php file using the form machine names from a content type I created. Then I am creating a node.tpl.php template file that is related to the content type so I can perform the layout I want. I don't think I have the right syntax. Here it is:

```
$node = $variables['node'];
function keevilcontracting_preprocess_node(&$variables) {

 if($variables['type'] == 'project') {
    kpr($variables);
 $variables['title'] = $node->title;
 $variables['coverPhoto'] = $node->field_cover_photo; // 'field_cover_photo is the machine name of the field in my content type form.
 $variables['projectDesc'] = $node->body;
 $variables['additionalPhotos'] = $node->field_additional_photos;
 }

}

```

Any suggestions would be great.

Cheers!

# Answer
> 0 votes
You shouldn't have that

```
$node = $variables['node'];

```

outside your function.

put it as the first line inside your preprocess function.

$variables doesn't actually exist out there (and if it does it won't be the $variables variable you're expecting in this case).

---
Tags: theming
---


# Question
Title: How do you check if table is empty before resetting the auto increment?
I have a database table that a user can add to and remove data from within my drupal module. What I would like to do is automatically check to see if the table is completely empty after every delete, in which case I would like to run an "ALTER TABLE" to reset the auto increment to 1. However I am having trouble building a function that does this for me.

How can I implement a function to automatically detect if all fields are empty, and automatically reset the increment without the need to go into the database and apply ALTER SQL manually?

Here is some of the code...

```
function achievementlist_entry_delete($form, &$form_state) {
foreach(($form_state['values']['table']) as $rows) {
    $num_deleted = db_delete('achievements')
    ->condition('achvmntID', $rows)
    ->execute();
}
    //Here I would like to check the "achievements" database, as well as ALTER TABLE
    //it is empty
}

```

# Answer
**Important:** This is a risky thing to do, particularly on a production site. It could possibly cause problems with your database so be sure that you know your database schema very well and are fully aware of the implications of doing this.

---

You already use db\_delete() so you seem to be familiar with database interaction.

So you just need to query to check for any values. You could use something like:

```
SELECT COUNT(*) FROM achievements

```

and make sure the result is zero, or

```
SELECT 1 FROM achievements LIMIT 1

```

and make sure that no rows are returned.

You can use db\_query().

Then you can use db\_query() again to reset the increment.

For example in mysql it would be:

```
ALTER TABLE achievements AUTO_INCREMENT = 1

```

Since it seems you already know drupal db this isn't really a drupal question. It breaks down into: How do I check a database table is empty and how do I reset an auto increment field.

In both cases searching google for that will get lots of results, including stack exchange answers or your chosen database's manual pages.
> 0 votes

---
Tags: database
---


title: Pagination in apache solr search page

text:
# Question
Title: Pagination in apache solr search page
To control the number of search results showing in a solr site search page there is a text field in **admin/config/search/apachesolr/search-pages/core\_search/edit**

In advanced option tab, there is an option called **Results per page** to specify its count. but I need to alter the pagination displayed in search page. It displays 1 to 9 pagers by default I want them to be 5. what should I alter??

# Answer
> 1 votes
This could be done by using theme\_pager in TEMPLATE.PHP and by applying some if condition to be specific on just the search page

```
if(arg(0) == "search" && arg(1) == "site") {

$variables['quantity'] = 5;

}

```

These two lines did the magic !!!

---
Tags: search, paging
---


# Question
Title: Can I remove write protection for all Drupal files?
Just to prevent hacks, can I remove write protection in all files and directories in my installation, except for in `sites/default/files`?

*I mean I want to chmod to 555 and `chown` them all to `root:root` except for files within `sites/default/files`. For installation/uninstallation I use Drush.*

I'm talking about the **"Config 1: Web server is running as owner"** as described as in What are the most appropriate users and permission levels for Drupal sites on shared hosting?

It seems my four sites are working fine with this. **Is it OK?**

*This is because to ward off hack attacks which place php files in within site folders. This almost saved my site from this Highly Critical hack attack but the hacker was able to place php and execute file within sites/default/files as my .httacces was not protected from running php scripts within the files directory.*

# Answer
> 9 votes
Yes, although it will disable the installation of modules through the web interface (it writes in sites/all/modules), but I would consider that a feature.

You also probably want to use 0644 for files (rw/r/r), and 0755 for directories (rwx/rx/rx). By convention, you don't want files to be executable unless they are really meant to be.

Here is the official Drupal documentation on the issue:
https://www.drupal.org/node/244924

And this answer also has good advice:
What is the suitable file permission for 'files'?

---
Tags: 7, files
---


title: URL rewrite of localisation with nginx

text:
# Question
Title: URL rewrite of localisation with nginx
I'm having trouble with changing the url of a drupal localisation. All urls are clean, but contain a non-clean localisation part; ?q="language", e.g. ?q=de, ?q=fr. The site runs on nginx + mysql + php5.

I want to change this to either site.tld/"language"/page or to no url at all, e.g. site.tld/page.

How to change this in the rewrite rules?

# Answer
This answer should help:
https://serverfault.com/questions/488444/nginx-rewrite-convert-querystring-to-path/488480#488480

I would try something along the lines of:

```
location @drupal {
  if ($arg_lang) {
    rewrite ^(.*)$ $arg_lang/$1? permanent;
  }

  rewrite ^ /index.php;
}

```

The above assumes that requests with ?lang=XX do not have any other arguments, and that the request does not already have the language prefix in the page request (ex: /XX/node/123?lang=XX).
> 0 votes

---
Tags: i18n-l10n, uri
---


# Question
Title: Force initialization of custom field set in CiviCRM
I have created a custom fieldset "Social Profile" in CiviCRM which contains one Yes/No field "Publish my profile" that is set to Yes (value 1) by default. If i edit the fieldset in one contact, i can see my default value is working fine.

Then, I have created a membership page that allow people to become new members. When they fill the form a new CiviCRM contact is created. The form doesn't contains the "Social Profile".

When a new member register, the information Publish my profile is not initialized. After verification, it seems that the custom fieldset is not initialized for the contact - no data in civicrm\_value\_xx for `entity_id = <NEW_CONTACT_ID>`

So my question : Is there a way to force initialization of the custom field set for a new contact ?

# Answer
1. Can you include 'publish my profile' custom field in your membership page?
2. If option 1 is not possible, the next best bet might be to implement the civicrm postProcess hook on membership form and create the custom field record in the form.

Civi only creates custom field records on a as needed basis

alternatively you might be able to do the above via use of mysql triggers (maybe on creation of a contact record?)
> 8 votes

---
Tags: civicrm
---


title: Make tokens expire

text:
# Question
Title: Make tokens expire
Am working on an Organic Group use case where a user can join a group using a one time invitation link sent by email. How do i make the token attached to the email link expire once its used so that the link will be a onetime only link

# Answer
> 0 votes
Take a look at the Deep Link module.

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


# Question
Title: Apache Solr: get list of "More Like This" nodes programmatically
I'm using apachesolr module and it's "More Like This" block.

This block displays only titles of similar nodes as links to these nodes. I need to display rendered nodes with specific view mode. How can I do this programmatically?

# Answer
Here is the solution that I came up with.

```
function mymodule_similar_nodes($node) {
  if (module_exists('apachesolr_search')) {
    $output = '';
    $env_id = 'solr'; // machine name of solr server
    $delta = 'mlt-002'; // "More Like This" block delta
    $block = apachesolr_search_mlt_block_load($delta);
    $solr = apachesolr_get_solr($env_id);
    $context['search_type'] = 'apachesolr_search_mlt';
    $context['block_id'] = $delta;
    $docs = apachesolr_search_mlt_suggestions($block, apachesolr_document_id($node->nid), $solr, $context);
    $view_mode = 'teaser'; // view mode, e.g. 'full', 'teaser'...
    foreach ($docs as $doc) {
      if ($doc->entity_type == 'node') {
        $similar_node = node_load($doc->entity_id);
        $similar_node = node_view($similar_node, $view_mode);
        $output .= drupal_render($similar_node);
      }
    }
    return $output;
  }
}

```
> 0 votes

---
Tags: 7, nodes, search
---


title: Updated site now URL is not working

text:
# Question
Title: Updated site now URL is not working
I updated my site and now the site only shows up in Firefox. I believe it has something to do with the redirect since if I type in mysite.com/mysite then it shows up. I've tried updating the .htaccess file and the default/settings.php files and can't get it to work correctly. Any ideas? Thanks!

# Answer
> 1 votes
Check that the following rule is not commented out in your .htaccess file:

```
RewriteBase /

```

If you have installed Drupal in a folder inside your root it should be:

```
RewriteBase /my_folder

```

---
Tags: redirection
---


# Question
Title: print title and contents on a custom tpl.php template?
im making a custom theme for drupal, and im having a hard time trying to understand how to adapt one of my themes to drupal 7.

Right now im having an issue because i need to set some classes on all the blocks of a sidebar. i decided to make a block--sidebar.tpl.php file and there i set all the structure of the blocks.

So far so good but now, the block shows up, but im unable to get the title and contents of the block correctly. How can i achieve this?, thank you.

# Answer
> 0 votes
A different approach would be to:

1. Use the Block Class module - which will also allow you to add more classes per block.
2. Use CSS to apply the same styling to all blocks in the sidebar:

`.sidebar .block { border: 1px solid #ccc}
.sidebar .block-title {color: blue}`

---
Tags: theming, blocks
---


# Question
Title: How to do simple subtraction in Computed Field?
I'm trying to calculate the price difference between old price and new price, and if the price has dropped to display by how much, both Nominally and in Percent.

So, basically these are 2 simple formulas that should look like this:

> NOMINAL PRICE DROP = field\_price\_original - field\_price\_new
>
> PERCENTAGE PRICE DROP = ( (field\_price\_new - field\_price\_original) / field\_price\_original ) * 100

I tried setting this up through Rules (unsuccessfully), but it seems that doing it through Computed Field will not be so heavy on the server. Using Computing Field I have the following formula:

> $entity\_field\[0\]\['value'\] = array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_price\_original'))) - array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_price\_new')));

The number is set as float, 10.2. But for some reason it doesn't work.

Can someone please help and provide the correct syntax for Computed Field?

# Answer
> 1 votes
As per the documentation of computation field module to calculate the difference of two fields you need to use the PEAR:

```
$path = '/pathToPearsParentDirectory/pear/PEAR';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'PEAR.php';
include_once "Text/Diff.php";
include_once "Text/Diff/Renderer.php";
include_once "Text/Diff/Renderer/inline.php";

$diff = &new Text_Diff('auto', array(array($node->field_nameOfOneFieldToCompare[0]['value']), array($node->field_nameOfOtherFieldToCompare[0]['value']))); $renderer
= &new Text_Diff_Renderer_inline();

$node_field[0]['value'] = $renderer->render($diff);

```

More info about it available here http://arencambre.com/blog/2009/05/17/how-i-got-field-diffs-working-with-drupal-pear-text\_diff-and-dreamhost

# Answer
> -1 votes
```
$entity_field[0]['value'] = $entity->field_price[LANGUAGE_NONE][0]['value'] - $entity->field_cost[LANGUAGE_NONE][0]['value'];

```

---
Tags: entities
---


# Question
Title: Commerce- How can I modify order details with hook_commerce_paypal_wps_order_form_data_alter()?
I want to modify the information Commerce sends to PayPal so that the order description on PayPal describes the product, not the order (users on my site can only order one of two products, so I think that is more useful).

This is what I want to change:

These strings are in the Commerce Website Payments Standard submodule. I am using the `hook_commerce_paypal_wps_order_form_data_alter()` function as suggested in the answer to this question.

However, in the API, there is no example for this function (I also looked at the Commerce Examples module but didn't find anything), and I'm a bit lost about how to handle it.

The string I want to override is defined in `commerce_paypal_wps_order_form()` in this section:

```
    // Define a single item in the cart representing the whole order
    'amount_1' => commerce_paypal_price_amount(commerce_currency_convert($amount, $order_currency_code, $currency_code), $currency_code),
    'item_name_1' => t('Order @order_number at @store', array('@order_number' => $order->order_number, '@store' => variable_get('site_name', url('<front>', array('absolute' => TRUE))))),
    'on0_1' => t('Product count'),
    'os0_1' => commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()),
  );

```

I want to change `item_name_1` to `t('My string')` and remove `on0_1` and `os0_1`.

I tried this:

```
function MYMODULE_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $data['item_name_1'] = t('My string');
  unset($data['on0_1']);
  unset($data['os0_1']);
}

```

But nothing is changed, even after clearing the caches. I'm having a really hard time debugging this because it is called immediately before the redirect to PayPal, so even if I use `dpm()` I'm not able to see it.

# Answer
When you can not see the HTML output of debugging tools such as dpm(), you should use the utility function dd() instead. The logging data will be stored in a file called drupal\_debug.txt which you can inspect later.
> 1 votes

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


# Question
Title: How to find users with password same as their username
How do I find users which their password is equal to their username in Drupal 7?

# Answer
If you are trying to do this while they are registering, there are good modules for the task, a simple search finds Password policy module, It is also on S.O:

> A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.

However for already registered users, you have to hash their username as a password and compare it to their actual hash stored in database, if they are the same, you have cracked their password!

Hashing the passwords, The Druapl way user\_hash\_password()
like this:

```
$user = user_load($id_of_user);
if($user->pass == user_hash_password($user->name)) {
  block_and_punush_lazy_user($user);
}

// maybe use it like this:
for($uid=2; $uid< MAX_UID_IN_DB; $uid++) { // FROM 2 ONLY!!
  if($user = user_load($uid) {
    if($user->pass == user_hash_password($user->name)) .... // Punish
  }
}

```

A more quick solution is to do it solely in database using it's hashing functions. You should check the password.inc in user module and extract the hashing algorithm. implement the same function in mysql and do a:

```
SELECT `uid` FROM `users` WHERE `pass` = MY_CUSTOM_HASH_FUNC(`name`);

```

And **DO** make a backup of your database before doing these stuff.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to create a multi step form that can be saved/edited by multiple users?
I need some tips on how to implement a form with these specifications:

* Multi steps. for example the user completes section 1 then clicks next to go to section 2 and so on (can be tabs or anything similar).
* It can be saved, so users can come back to continue also multiple users can edit
* Some users can add a new form to the site (with a different title for a new set of users)
* Users should have different permission levels to interact with these forms (creator, editor or view only).

I've been looking at webform. But it doesn't seem to offer what I need. Because it doesn't use native Drupal fields. I need a form that stores data in Drupal standard format. This allows me to expand my form's capabilities (For example using views). Are there any combination of modules that can be helpful here?

# Answer
> 0 votes
The Multistep module adds multiple-step functionality to CCK forms. It does so by assigning a step number to each fieldgroup within the content type and hiding all the groups that do not belong to the current step. The user can then use different submitting buttons that will redirect to the previous, next, or current step.

For further reference look into this link.

# Answer
> 0 votes
With Webforms, it is possible to create forms that span more than one page. These forms are known as multistep, or multipage forms. and also with expected features.

ref link: Creating multistep webforms

# Answer
> 0 votes
Webform supports:

* multistep forms
* allowing who can submit the form (under form settings)
* choosing to allow users to "save" the state of the form

The create/edit/view permissions can be controlled with Drupal's core permissions scheme.

Who has access to which webform will have to be configured using other content access modules (check the screenshot).

---
Tags: forms
---


title: Drupal Lookup Path Change

text:
# Question
Title: Drupal Lookup Path Change
I am displaying demonstration sites with iFrames and in page--demo.tpl.php I have a possibility to get NID only from path. So I managed demo's number will be the same as NID and now I have a code:

```
print drupal_lookup_path('alias',"demo/".$node->nid);

```

It works correctly but I would like to transfer that link to /node/$node-\>nid.

Is there any way to do so? I tried to print $node-\>nid underneath, but it prints wrong number (36 instead of 34).

Thanks!

# Answer
> 0 votes
```
$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
print $path[1];

```

---
Tags: uri
---


# Question
Title: Why there are random line breaks in emails sent through drupal?
I noticed drupal includes line breaks in emails it outputs.

For example in `admin/config/people/accounts` we can customize message users receive when they signup and/or when they forget their passwords etc..

The thing is, when the emails are sent to the users, they contain line breaks that seem to be completely random and arbitrary.

I first thought the problem came from the webmail provider, so i tried with different services (gmail, hotmail, yahoo etc.. )

Any suggestions on how to fix this ?

Thanks

# Answer
> 0 votes
It seems it's drupal's mail processor that inserts all these line breaks.
I fixed the issue by installing MimeMail (and MailSystem).
It allows the use of html to format all outgoing emails.

I hope this will be helpful to somebody out there.

---
Tags: 7, emails
---


# Question
Title: Migrating a Drupal Node.js website from localhost to web server
Due to specific website feature requirements, which do not seem to be possible in Drupal 7 without Node.js integration, I am strongly considering to integrate Drupal 7 with Node.js modules offering real time interactivity. I understand the basic concepts however I have never actually used Node.js on a website before. I have installed Node.js on my computer under Program Files (Windows) and begun testing the integration with a test website on localhost (WAMP).

My concern is for when I later will need to migrate a client's website to an actual web server. I would like to ask those who have had some experience with such Drupal/Node.js integration, what is a streamlined workflow for migration. For example, I am wondering if Node.js should be installed into the same folder as the website directory instead of Program Files, so that when testing is finished I will be able to ftp the entire website directory with the Node.js installation without needing to reinstall Node.js and reconfigure everything. I am not sure if copying everything over would work or if Node.js needs to be installed again separately on the web server?

I would like to get a clearer understanding of this process before I make the leap into Node.js integration with future client websites. I believe Node.js integration introduces some great new features however it could potentially be a giant can of worms if not handled properly.

# Answer
The typical NodeJS setup usually involves a Linux server and a nginx web server/proxy that delegates the requests to the application running on a specific/semi-random unprivileged port. In other words, nginx will have a site declaration (vhost) for your Drupal and a another site declaration for your NodeJS application. Your NodeJS application runs in the backgrounds and listens for requests from nginx.

NodeJS itself is usually installed through the Linux distribution's packaging system, similarly to PHP.

On the filesystem, I would treat the two applications as separate projects, in two separate directories on the server. It's pretty rare to find developers who have a good understanding both Drupal/PHP and NodeJS, so keeping it separate will make it easier for other people eventually working on that project to familiarize themselves with the environment.
> 2 votes

---
Tags: nodes, migrations
---


# Question
Title: Drupal Commerce Shopping Cart Form Alter
I'm trying to use hook\_form\_FORM\_ID\_alter() in my theme's template.php file to change the 'Remove' button in the Commerce add to cart form to an image button. To do this I'm using the following code:

```
function tempestra_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
  foreach($form['edit_delete'] as $item) {
    if($item['#type'] == 'submit') {
      $item['#type'] = 'image_button';
      $item['#src'] = base_path() . drupal_get_path('theme', 'tempestra') . '/images/search.png';
      unset($item['#name']);
      dpm($item);
    }
  }
}

```

When I look in the array printed by `dpm()` everything is as it should be, however the HTML for the image button isn't printed.

Thanks in advance.

# Answer
> 4 votes
Simple mistake, you don't change `$form` but only `$item` if you did

```
foreach($form['edit_delete'] as &$item) {

```

or

```
foreach($form['edit_delete'] as $key => $item) {
  ...
  $form['edit_delete'][$key] = $item;
}

```

it should work.

# Answer
> 2 votes
```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form') !== FALSE) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Buy now'),
    );
  }
}

```

---
Tags: 7, forms, commerce
---


# Question
Title: Problem with trailing slash and global redirect
I have a site with some languages, with language prefix enabled. I wanted the homepage url will be with trailing slash (i.e /en/), so i installed the trailing slash module.

I also want that users who entered my site without language prefix will redirect to the url with the prefix (i.e www.mysite.com -\> www.mysite.com/en/), so i istalled th global redirect module, which works well without the trailing slash module.

When the two modules enabled, the redirection in the home page not working. Does someone has solution for this?

# Answer
> 0 votes
if you are looking to redirect your users site or visitors to the right language you can do this without global redirect module to do that

1. install \[Localization update\]\[1\] , \[variable\]\[2\] , \[Internationalization\],
2. after install modules active Locale , Localization update , Internationalization , Variable
3. go to Configuration \> Languages \> detection and selection
4. the 1st option URL u can choose between (Path prefix or domain) the 2nd option is Browser and here u can Determine the language from the browser's language settings. if your browser's visitor is English he will go to English site .... the 3rd option is User in this option the site Follow the user's language preference.

that's all

---
Tags: i18n-l10n
---


# Question
Title: Updating view content (in block) based on field data from page it's displayed on
I'm struggling to achieve something in Views that would be quite simple in PHP itself - hoping for some pointers.

I have created a view, displayed as a block, which appears at the bottom of each page with a content type of 'article'. This block shows the latest 4 articles added to the site based on publish date. It shows max 4 items (provided at least 4 articles exist and are published).

This works - however I've been struggling to extend this functionality to meet two new client requests:

* The view should exclude the currently viewed article if loaded on the page of one of the 4 latest articles added; **\[SOLVED THANKS TO ANSWER BELOW\]**
* The client wishes to 'override' the items shown in this view in some cases. Here I've added a field to the content type named 'field\_related\_articles' which is a entity reference field. The admin can now select up to 4 articles from the database which should show in this view. However it is optional, and the default behaviour is to show the 4 latest articles still. If 1 article is specified the 3 latest articles should then appear. If 2 then those 2 plus the latest 2 articles make up the view.

I've been advised to have two views then use an 'attached' display to stitch them together, then remove the extra results (if applicable) in code in a template file. But I'm struggling settling this up.

---------- EDIT : to add some clarity to second point ----------

The view is intended to always show 4 article teasers. In it's default state this should be the latest 4 articles added to the site. This is now working.

The complexity comes in that on each 'article' content page it should also be possible to specify up to 4 articles (using an entity reference field) to show in this view instead. I've added the field to the content type 'field\_related\_articles'.

So when the view is included on an article page it needs to check if any values are specified in 'field\_related\_articles' - if so they should be the results in the view. If less than 4 nodes have been specified, the view should then show the latest X articles to make up to 4 in total.

# Answer
To avoid the article you're on :

Click on the "advanced" tab. Click on add under "contextual filters". Choose Content:nid. Under "when the filter variable is not available, choose "provide default value". From the drop down menu select "content id from url". Scroll all the way down to the bottom of the window and click on the "More" link. Click "Exclude"

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

The second problem can be done by adding 2 Sort Criterias. The first will be on 'field\_related\_articles' - and then by date. I find displaying the SQL output in admin really helps to see what is happening backend.
> 0 votes

---
Tags: views, nodes
---