# Question
Title: How to change #weight of fields added to user register page by form_alter()?
I have created some fields on my user registration page named like - First Name (machine name - field\_first\_name), Last name (machine name - field\_last\_name) etc..

I want to change their `#weight` according to me to appear at the place where I like them to be from the form\_alter function at my custom module..

For the default name & email I used -

```
$form['account']['name']['#weight'] = 7;
$form['account']['field_first_name']['#weight'] = 8;

```

& it worked..

But If I am using for added fields in this way like -

```
$form['account']['field_first_name']['#weight'] = 6;

```

It's not working...

Can I get any help in this ?

# Answer
Account as a whole is in a group which contains the name password etc. The one we add might be out side of that. That is why it is not effecting the weight.
> 1 votes

# Answer
Or you can copy the field in another "container field" and change the weight , something like this:

```
   $form['profile_one']['account'] = $form['account'];
   $form['profile_one']['account']['#weight'] = 200;

   // Hide login form from this render.
   $form['account']['#type'] = 'hidden';

```
> 0 votes

---
Tags: 7, forms
---


title: Prevent duplicate drupal_add_js calls

text:
# Question
Title: Prevent duplicate drupal_add_js calls
**Issue**: I have an input filter that, when triggered, executes `drupal_add_js`. However, when I view source of the page, I see this command issued twice or more times.

**Question**: Is there something I can do to prevent duplicate javascript commands on a page?

**Code sample**: Below is the sample of the input filter that I'm writing. In some pages, for an unknown reason

```
<?php
function _js_slider_process($text, $filter, $format, $langcode, $cache, $cache_id)
    {

        preg_match_all("/\[slideshow:(#[\S]+)\]/", $text, $matches);

        // If no match return and be done.
        if (!isset($matches[1])) {
            return $text;
        }

        // gather information
        $text_to_remove = $matches[0];
        $elementid = $matches[1];

        // remove filter trigger text
        $text = str_replace($text_to_remove, '', $text);

        // Do we have any matches located in the firs match
        if (isset($elementid[0])) {
            // Inject javascript file
            drupal_add_js(drupal_get_path('module', '_js_slider') . '/' . _JS_SLIDER_JS_FILE_SRC, 'file');

            // Inject options into a javascript variable
            $js_slider_options = array(
                'first' => variable_get('_js_slider_control_first', _JS_SLIDER_HTML_CTRL_FIRST),
                'prev' => variable_get('_js_slider_control_prev', _JS_SLIDER_HTML_CTRL_PREV),
                'next' => variable_get('_js_slider_control_next', _JS_SLIDER_HTML_CTRL_NEXT),
                'last' => variable_get('_js_slider_control_last', _JS_SLIDER_HTML_CTRL_LAST),
                'ctnl_placement' => variable_get('_js_slider_control_placement', _JS_SLIDER_HTML_CONTROL_PLACEMENT)

            );
            drupal_add_js(array('_js_slider' => $js_slider_options), 'setting');

            // Call it
            drupal_add_js('jQuery(document).ready(function () { a = new SlideShow("' . $elementid[0] . '"); a.init(); });', 'inline', 'footer');
        }

        return $text;
    }

```

# Answer
> 3 votes
Safest and most straightforward way is to move js file to module's info file, and include it always. just make sure it works only on elements it should, and on all of them. For this you need appropriate classes.

Other way is to use `['#attached']['js']` of highest possible element, instead of calling `drupal_add_js` manually. if you will set script twice, you will override older instance, so no problem.

If, for reasons unknown to me, you decide you have to call `drupal_add_js` yourself, use `drupal_static` to make sure you didn't call it already. It will require least changes in existing code - and in my opinion is worst solution. But will work. Typical usage is:

```
$mycounter = &drupal_static(__FUNCTION__, 0);

```

That makes `$mycounter` shared among all scopes where it is called, and initialized to 0. Then, you can test if it's still 0, and if it is - add your JS and increment counter with good old `$mycounter++`

---
Tags: javascript
---


title: How to set node id as SKU id

text:
# Question
Title: How to set node id as SKU id
I am using drupal commerce for e-commerce site. When node(product) is created SKU id of the product must be node id. How can I achieve it. Thank You.

# Answer
In Drupal Commerce products are ***entities***, not nodes. If you're looking for a product's SKU to be automatically set to the created product's id, there's the Commerce AutoSKU module which allows you to use tokens (e.g. `[product:product-id]`) to automatically create SKUs.

One caveat from the project however:

> If you decide to use the \[product:product-id\] token, you should be aware that this will cause any new products to be saved twice. This shouldn't be an issue for most people, but if you have rules in place for when a product is saved, you may not want to use this token.
> 0 votes

---
Tags: commerce, nodes
---


# Question
Title: view list on user profile, to show content of that user
I currently have a view that shows on the user profile page (as a block). I got it to show results of the content for the current logged in user.

This works great for normal users as they will only be able to see their current profile page. However, I want it to show the content for the shown profile, not the current user, since admins that view other user profiles will not see that user's content.

Is there a way to set the view to get the uid of the profile page rather than the logged in user?

These are the view settings I have right now are:

```
CONTEXTUAL FILTERS
   Content: Author uid
      Provide default value: User ID from logged in user
RELATIONSHIPS
   Content: Author

```

# Answer
You need to adjust where the contextual filter is retrieving the UID from.

When you provide a value for your contextual filter, you want to retrieve the raw UID value that's coming from Drupal's path system. To do this, look at the **When the Filter Value is not available** section.

Selecting *Raw value from URL* will use Drupal's internal path for the currently viewed page (e.g. **/node/XXX**, **/user/YYY**, etc.). The path component refers to which one of the "subdirectories" in the path to reference (e.g. 1 = "user", 2 = YYY, in the previous example).

In your example, you want a **Path Component** of *2* (i.e. the UID from /user/XXX profile page).
> 2 votes

---
Tags: users, views
---


# Question
Title: Using Drupal 7 Rules, how to react to a file upload and change a node field?
I have spent hours/days trying to figure out how to accomplish this in Drupal 7 using the Rules module, so I will greatly appreciate any help anyone can provide.

**What I am trying to do:**

When a user re-uploads a file to a node, the node should rollback from an Approved status to Pending Review. This requires some kind of automated rule that checks for when a file was updated.

**Here's what I have:**

1. A node called Data\_set with a File field called data\_set\_file.
2. Data\_set nodes also have a field called Status (e.g., Pending Review, Approved).

**My problem:**

When a user uploads and overwrites an existing attachment in the data\_set\_file field, I want the node's Status to change back from Approved (if already) to Pending Review. I am able to use Rules to check for when a user uploads a new file, but there are no rules conditions to check for which file or node file has been *updated*.

**What I tried:**

I created a "NOT Data Comparison" condition between **node-unchanged:field-dataset-file:file:fid** and (Equals/Negate) **node:field-dataset-file:file:fid** However, when updating the file, it did not register a change to the *fid* field (because it keeps the same fid). I also tried the file *size* field with no effect as well. When I tried the file's *timestamp*, it appeared to work at first until I realized that the timestamp updates *every time*, no matter what, that a user saves a node, regardless of whether or not a file was re-uploaded.

I may be going about this the wrong way. Anyone know what's the easiest way to accomplish this? Thanks a million!

# Answer
> 0 votes
**SOLUTION.** After searching online, I found the answer to my own question. I'm sharing this for anyone else with a similar problem:

**The first part is to implement file events.** There is a patch to the Rules module that adds file events to react on (after saving new file, after updating existing file, and before saving file).

Discussion thread: https://www.drupal.org/node/826986

Patch: https://www.drupal.org/files/issues/file\_events-826986-22.patch

1. Copy the patch file to the rules module directory.
2. From the command line, change to ("cd") the rules module directory.
3. Enter: patch -p1 \< file\_events-826986-22.patch
4. On the Rules page (admin/config/workflow/rules) click "Add event" and select the file event to add.

**The next part is creating a rule to react to the file upload.** A problem is that the timestamp on files are updated for every save, not just when it is first uploaded. So, I first opened my custom File Type (in my case "Dataset") and added a custom field using the Date Field Type called *Time Uploaded* (field\_file\_time\_uploaded). I also created a new rule to update this field when the file is uploaded. Note that this rule gets called on the file insert event, which happens before a node is saved.

Below is what the rule export looks like for file uploads:

```
{ "rules_save_file_time_uploaded" : {
    "LABEL" : "File - Save Time Uploaded",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "file_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "file" ], "type" : "file" } },
      { "entity_has_field" : { "entity" : [ "file" ], "field" : "field_file_time_uploaded" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "file:field-file-time-uploaded" ],
          "value" : [ "site:current-date" ]
        }
      },
      { "drupal_message" : { "message" : "The [file:type] file was uploaded." } }
    ]
  }
}

```

This *Time Uploaded* field can then be used by other rules, like when saving a node, to see if the file was updated using a data comparison with the site's current datetime.

# Answer
> 0 votes
Workflow

> This module allows you to create arbitrary Workflows, and assign them to Entities.
>
> Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment and a special workflow tab.
>
> Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published (and becomes visible on your website).

**How we use workflow module**

Creating a Workflow

Editorial workflow with Rules

---
Tags: nodes, rules, files
---


title: Pay to flag a node with drupal commerce

text:
# Question
Title: Pay to flag a node with drupal commerce
Please help achieve the folowing:
I have a content type "proposal" with a field "prépayment\_amount". I want the user who try to flag this node to pay the amount indicated in the field "prepayment\_amount" and when the payment is successful, I want to notify this to the user who created this node, if not the flag is cancelled.

# Answer
> 0 votes
At least a partial answer could be to use Commerce in order to pay for access to a node. A user who clicks the link will be sent to the pay page, and upon completion of payment, the user will be assigned the role which can "flag" that proposal.

I'm not sure this would end up using the flag module, but you could theme it to look flag-ish.

---
Tags: commerce, flags
---


# Question
Title: Rewriting the pager of Views in Drupal 7
I have a Views which I am calling via `views_get_view` and `view->preview`. I am feeding the Views with a form via Form API \- with *no* **exposed** filters - and the problem is that while the number of pages is correct, obviously, when I click on a page, I loose the POST variables and the pagination shows results which are not filtered. How can I rewrite the pager so I simply add as GET the parameters to the URL, so I can filter again when the user selects another page? I would prefer not to use exposed filters as I have some heavy PHP processing and would prefer just to make this modification which I would expect it to be easy but cannot find anything.

# Answer
I found a way, by using the *template\_pager* function in the template.php ( *sites/all/themes/mytheme* ) and modifying the core behaviour to this:

```
function template_pager($variables) {
    $tags = $variables['tags'];
    $element = $variables['element'];
    // next line is modified
    //$parameters = $variables['parameters'];
    $parameters = process_post();
    ...
 } // function template_pager

 function process_post(){
    // specific function
    $parameters = array();
    $parameters_sent = array("param1", "param2");
    foreach($parameters_sent as $key => $value){
    if(isset($_POST[$value]) ){
        if($_POST[$value] != ""){
            $parameters[$value] = $_POST[$value];
        }else{
            $parameters[$value] = 'all';
        } // if
    } // if
  } // if
  if(count($parameters) > 0){
    return $parameters;
  }else{
    return NULL;
  } // if
} // function process_post

```
> 0 votes

---
Tags: 7, forms, search, paging
---


# Question
Title: How to translate the title, axis labels and legend of a chart?
I have successfully created a grouped bar chart using the Forena module. My application supports English, Portugese and Spanish.

But I am not able to translate my chart to Spanish and Portugese. I need to translate the chart title, labels on each axis and the legend.

Here is the chart I created so far:

I wonder how I can translate the following strings in this chart:

1. Biological and chemical indicators
2. Average of indicators
3. Positive biological indicators
4. non responsive chemical indicators

# Answer
Here are the steps to create a translated version of a chart (or more general: a report) using the Forena module:

* Make sure (core) module *locale* is enabled.
* Instead of using the "edit" icon to change the specs of a report, use the "translate" button next to edit. Then select the language to which you want the report (chart) to be translated.
* On the next screen, enter the translated report (chart) title.
* You should get some informational message as in this example (in which I created a 'nl' version of drupaladmin/active\_users, for which I changed the tite from "Active users" to "Actieve Gebruikers"):

> Translation, Actieve Gebruikers has been created. Switch languages to translate.
>
> Your report, nl/drupaladmin/active\_users has been saved.
* After switching your active language to the language for which you want to create a translated version, you'll be able to change anything of the report (charts) specs to the specs of your additional language.
* In your case here, you can now modify those 4 strings

**Bottomline**: tranlating Forena reports is similar to translating nodes.
> 1 votes

---
Tags: 7, i18n-l10n, charts, forena
---


# Question
Title: Want to filter result by using two filters "event start day" and "event start time" in one view for showing upcomming events?
I want to show a view of upcoming events. I have added *event start day* filter to my view, it's showing today's events as well as upcoming events.

This functionality is working fine but problem is that it's showing all events of today not on the basis of time but it's showing morning's event whose time is passed away. It must only filter the values on the basis of *current time and coming time*(current day and upcoming days).

I want to add one more filter *event start time* filter. How to add two filters(event start date and event start time) in one view?

# Answer
You can try this Views between dates filter module. Or you can create filter by selecting event date and time from the content.

**Views Between Dates Filter:**

> This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
>
> Creating this functionality with standard Date filters requires two filters: start date less than or equal (\<=) to the supplied date and end date greater than or equal (\>=) to the supplied date. The problem is two filters means users must enter a date range, when technically selecting "September" is a range: September 1st to the 30th.
>
> It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.
> 0 votes

---
Tags: views
---


# Question
Title: caching issue after updating records into database
I've developed *leave management* in drupal 7 but facing an issue. When leave balance is updated due to calculations then it not shows right value from database due to drupal caching. Once I clean all caches then it shows right values. Is there any way to stop caching or update caching?

Please do some help.

# Answer
> 1 votes
Any well written module that has a cache, should prefix it with cache, meaning that the answer to your question is "Yes".

In the odd event that a module caches data somewhere else, you can check your modules for implementations of hook\_flush\_caches, and see what they remove.

Reference by Letharion

---
Tags: caching
---


# Question
Title: how to create next and previous month menu link in calendar in drupal 7
how to create next and previous menu link in calendar in drupal 7

## Next month \>\> \<\< Previous month

```
             ---- calendar area ----

```

# Answer
Use **Calendar** Module.

From project page..

> This module will display any Views date field in calendar formats, including CCK date fields, node created or updated dates, etc. **Switch between year, month, and day views. Back and next navigation is provided for all views**. Lots of the Calendar functionality comes from the Date module, so any time you update the Calendar module you should be sure you also update to the latest version of the Date module at the same time.

Hope this will help you.
> 0 votes

---
Tags: 7, commerce, datetime
---


# Question
Title: What's the difference between landing pages and panel pages?
I'm trying to create pages (like 'Questions', 'Tags'... on top of this website). I thought the best way to do this is to use the Panels module. The Panels module has two types of pages: landing pages and panel pages.

What's the difference between them and which one's the best to create static pages?

# Answer
I do not see much difference between both, in fact landing page itself a panel page.The only difference I can say is there might be predefined pages like user profile, node template that we can override using panels and thus making them a panel page while landing page is pretty much same as a node with a url to navigate and contents with various ways might be static text, embedded blocks and much more.

Panels should be never be considered as a tool to build static pages as they are resource intensive,instead use nodes for that purpose.There are many reasons why node is preferred instead of panels like node being entity has attached attributes like author, created time, revisions, also there is long list of node api which allows you to hook into node edit/insert/view processes.
> 1 votes

# Answer
panel page mainly use for to create home page, there is a option to check(tick) the check box and option are also there to be.

but in

landing page is similar to panel page,but here is no option of setting the front page.
> 0 votes

---
Tags: panels, 7
---


# Question
Title: How do I show the username field in the user edit form?
I need to show username textfield in user edit form. Normally, it shows only for administrator user. How do I show this for all users' edit form?

# Answer
> 2 votes
Go to admin/people/permissions and select the *Change own username* for the roles you need to be able to change their username.

>

---
Tags: users
---


# Question
Title: no description and image title in insert module
I am using insert module in drupal 6.

How come I have ***no description and image title*** just like this https://www.drupal.org/files/images/insert-module.png

# Answer
> 0 votes
Solution Enable the insert in content type. admin/content/node-type/news/fields/field\_image2

---
Tags: media
---


# Question
Title: preprocess function call - $vars[node_title] does not work as a parameter, while $vars['node-title'] does
I am writing a preprocess function. I provided a linkIt function that does the linking for me:

```
function linkIt($what, $where) {

return '<a href="' . $where . '" class="' . $what . '.-preprocess-field preprocess-field">' . t($what) . '</a>';

```

} If I call it this way:

```
$test= linkIt('XXX', $vars[node_url]);

```

it produces a Drupal error 'Use of undefined constant node\_url - assumed 'node\_url''. If I call it

```
$test= linkIt('XXX', $vars['node_url']);

```

with quotes around `node_url`it works fine.
The former syntax is properly evaluated if I do not pass it as a function paramter, for example in

```
$vars['opis'] = '<a href="' . $vars[node_url] . '" class="opis-preprocess-field">' . t('XXX') . '</a>'

```

Why is it so?

# Answer
Always use quotes around a string literal array index. For example, $foo\['bar'\] is correct, while $foo\[bar\] is not. But why? It is common to encounter this kind of syntax in old scripts:

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in the future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

See PHP:Arrays - Manual Chapter "Array do's and don'ts"
> 1 votes

---
Tags: theming
---


# Question
Title: For the creation of a prepopulate link, how can i strip out slashes if they occur in the title?
```
if(isset($node->field_eventform['und'][0]['nid'])) {
          echo '<div class="field field-name-field-eventform field-type-node-reference field-label-hidden"><div class="field-items"><div class="field-item even">';
          echo '<a href="/node/'.$node->field_eventform['und'][0]['nid'].'/'.$node->title.'/'.$node->nid.'">'.$node->field_eventform['und'][0]['node']->title.'</a>';
        echo '</div></div></div>';
   }

?>

```

With this snippet we prepopulate a webform for events. But when a site editor uses a "/" in the title the link doesn't work anymore. How can I strip out slashes if they occur in the title?

# Answer
```
echo '<a href="/node/'.$node->field_eventform['und'][0]['nid'].'/'.str_replace('/','',$node->title).'/'.$node->nid.'">'.str_replace('/','',$node->field_eventform['und'][0]['node']->title).'</a>';

```

You have to check, if the link works, when you strip the '/', if not, replace the '' in str\_replace with the correct replacement, that your path alias use.
> 2 votes

---
Tags: 7, theming
---


title: Sharing drupal file to a external site

text:
# Question
Title: Sharing drupal file to a external site
We have a site external to our drupal site, but have to use images from drupal site using absolute URL(No way we upload the same images to that site). So we have to provide them with absolute URLs of the images which will be used by the site.

And it should also be possible that we change the images. i.e., If we have to change the image, we have to replace the existing image with the new image with same name.

What is the best way can this be achieved? Anyhow there is going to be a content in our drupal site that contains the image. Will the image URL be the same **ALWAYS** when I remove the image and upload another image with same name?

# Answer
Give File (Field) Paths a try:

> The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.
>
> In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.
> 0 votes

---
Tags: media
---


title: Uninstalling a module

text:
# Question
Title: Uninstalling a module
In order to un-install a module I disabled and deleted the folder from the root module folder. Though I have deleted the module yet it's showing in *module list* page. Why is this? Am I doing wrong?

# Answer
> 2 votes
Simply find the module name, and write the following command in your command-line/terminal/console to disable the module at first (by considering that the current path in your command-line is the Drupal project root directory):

```
drush dis moduleName -y

```

then after the completion of the executing the above command, write the following command to uninstall the module:

```
drush pm-uninstall moduleName -y

```

If you have several modules, you can list their names. For example for three modules, you can write:

```
drush dis moduleName1 moduleName2 moduleName3 -y
drush pm-uninstall moduleName1 moduleName2 moduleName3 -y

```

# Answer
> 1 votes
For uninstalling a module..

1. Disable the module in **Modules Page**.
2. Then **uninstall** module from **Uninstall Page**.
3. Then delete the module files if you want.

# Answer
> 1 votes
This may happen delete/remove the module before disabling in admin side....

Once again add and enable the same module... and Click checked-box to disable and click save configuration button... Now click uninstall link showed in top of the page and delete installed table...

Go to database system table...search module presence , if it is there delete rows and ensure....

Clear cache.... and ensure that cache table is empty....

Now **run cron**.php

---
Tags: installation
---


title: Drupal 8 - url to image

text:
# Question
Title: Drupal 8 - url to image
I can't find how to get image url. I have images in /themes/custom/mytheme/img directory. I think there must be some way to get path to current theme or somethink like that.

# Answer
> 2 votes
You can use `{{ directory }}` for the path to your theme. Then you just need to add /img/yourimage.jpg.

---
Tags: 8
---


title: Revision tab not appearing

text:
# Question
Title: Revision tab not appearing
I have just starting using Drupal today and am going through a tutorial for Drupal 7 (I am using Drupal 8). I have made several revisions; however, the `Revision` tab does not appear when in the `Edit` area. I am logged in as Admin and have permissions for everything. After several revisions I got fed up and decided to delete the node (content) by clicking the `Delete` tab - to my surprise, the `Revisions` tab then appeared to the right of the `Delete` tab. I cannot find any documentation on the `Revisions` tab only appearing once the delete button has been clicked. Is this standard behaviour or is there something that I am missing?

# Answer
> 3 votes
This is a known bug, and is being fixed: https://www.drupal.org/node/2592325. The fix is already present, it just needs test coverage now.

# Answer
> 0 votes
That sounds like a caching problem, possibly the revisions tab is missing cacheability information. It's dynamically shown based on whether there are revisions or not. Which means it needs to be invalidated in case the node changes.

You should open a bug report for core.

---
Tags: 8, caching, nodes
---


# Question
Title: Edit core custom template (page.tpl / template.php / theme-settings.php)
How we add more fields in the **appearance -\> settings -\> "my template"**

So that the background image shows several titles and other information.

I added the fields in **theme-settings.php**, but when i am added new they cannot display at frontend. I changed the print code as well in **template.php**(code below).

```
for ($i = 0; $i < count($banners); $i++) {
        $output .= '{
            "image" : "' . file_create_url($banners[$i]['image_path']) . '",
            "title" : "' . "<h2>" . fancy_title(t('@image_title', array('@image_title' => t($banners[$i]['image_title'])))) . "</h2>" . '",
            "subtitle" : "' . "<h3>" . fancy_title(t('@image_subtitle', array('@image_subtitle' => t($banners[$i]['image_subtitle'])))) . "</h3>" . '",
        },';
    }

```

I tested and if i change 'subtitle' to 'title' i can print that, but not both.

If anyone can give me a hint i would appreciate. Cheers

**EDIT**

The fields that i need to print, are created in theme-settings.php with this code,

```
 // Image title
$img_form['image_title']       = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $image_data['image_title']
);
// Image SUB title
$img_form['image_subtitle']       = array(
    '#type' => 'textfield',
    '#subtitle' => t('subTitle'),
    '#default_value' => $image_data['image_subtitle']
);

```

printed in template.php with this code,

```
 for ($i = 0; $i < count($banners); $i++) {
        $output .= '{
            "image" : "' . file_create_url($banners[$i]['image_path']) . '",
            "title" : "' . "<h2>" . fancy_title(t('@image_title', array('@image_title' => t($banners[$i]['image_title'])))) . "</h2>" . '",
            "subtitle" : "' . "<h3>" . fancy_title(t('@image_subtitle', array('@image_subtitle' => t($banners[$i]['image_subtitle'])))) . "</h3>" . '",
        },';
    }

```

and called in page.tpl.php with this code,

```
 <?php if (theme_get_setting("slideshowType")=="image") : ?>

```

So, the second field created shows in drupal- settings - template, stores the info in the database, but isn't printed correctly in page.tpl

If any more info is needed i will provide it.

Ps. I'm new to drupal and PHP.

# Answer
After reading the answer given, i searched in the code to find how to pass the 2 fields, and after sometime i realized that was the **Javascript** that was in charge to print the variables in the target ID, and not the **PHP**

The original that printed the field:

```
 if (a(vars.slide_caption).length) {
            (api.getField("**title**")) ? a(vars.slide_caption).html(api.getField("**title**")) : a(vars.slide_caption).html("");
        }

```

To print 2 fields:

```
 if (a(vars.slide_caption).length) {
            (api.getField("**title**") && api.getField("**subtitle**")) ? a(vars.slide_caption).html(api.getField("**title**") + api.getField("**subtitle**")) : a(vars.slide_caption).html("");
        }

```

Thank you for your time. Would give +vote, but i don't have permissions. Cheers
> 0 votes

# Answer
If you want to add more items/theme in your home page template, do the following the steps..

1. Create a new **tpl** by editing existing **page.tpl.php**.
2. Add your fields into new **tpl**.
3. Name your new **tpl** as page--front.tpl.php.
4. Put your new template in `current-theme/templates`.

If you want to add more items in your theme options page do it in

**hook\_form\_system\_theme\_settings\_alter()**
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Why does Behat throw an error on "ucan <username>"?
In our Behat tests we delete all test users in a `before-hook`. But sometimes our Behat test throws an error like:

> Could not find a user account with the name vN8eLbrd!
>
> Could not find a user account with the name some.wiredstuff-registration-test\_10706!

Strange thing is that I get this user name direct from database. So I do not understand why this `drush ucan` command can not find it.

```
/** @beforeScenario */
  public function before($event) {
    $this->getSession()->getDriver()->resizeWindow(1280, 1024);

    // List all Scenarios which create the testuser.
    $scenarios = array(
      'Register for testing with Credit-Card',
      'Register for testing with Paypal',
      'Register for testing with valid Direct-Debit',
      'Register for testing with invalid Direct-Debit',
      'Access my subscriptions page',
      'Register for testing',
      'Register and use link from registration mail',
      'Logout',
      'Log in with username and password',
      'Recover your password'
    );

    $users_to_clean = array(
      'test@muster.de',
      'shaka@test.de',
      'some.wiredstuff+behat-registration-test@gmail.com'
    );

    $title = $event->getScenario()->getTitle();

    // Delete Testuser before the Scenario.
    if (in_array($title, $scenarios)) {
      foreach ($users_to_clean as $mail) {
        $user = user_load_by_mail($mail);
        if ($user) {
          shell_exec('drush ucan ' . $user->name . ' -y');
        }
      }
    }
  }

```

Problem with not deleted users is that other tests fail because a test user already exists.

Do you have a clue why this happens?

# Answer
While debugging with xdebug in PhpStorm I figured out that `user_load_by_mail($mail)` loads cached users. `user_load_by_mail()` uses this function:

```
/**
 * Load multiple users based on certain conditions.
 *
 * This function should be used whenever you need to load more than one user
 * from the database. Users are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * @param $uids
 *   An array of user IDs.
 * @param $conditions
 *   (deprecated) An associative array of conditions on the {users}
 *   table, where the keys are the database fields and the values are the
 *   values those fields must have. Instead, it is preferable to use
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
 *   this function.
 * @param $reset
 *   A boolean indicating that the internal cache should be reset. Use this if
 *   loading a user object which has been altered during the page request.
 *
 * @return
 *   An array of user objects, indexed by uid.
 *
 * @see entity_load()
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
 * @see EntityFieldQuery
 *
 * @todo Remove $conditions in Drupal 8.
 */
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
  return entity_load('user', $uids, $conditions, $reset);
}

```

But it calls this function without `$reset == true`. That's why it uses cached user objects and tries to delete an already deleted user.

I fixed this lines with:

```
// Delete Testuser before the Scenario.
    if (in_array($title, $scenarios)) {
      foreach ($users_to_clean as $mail) {
        $users = user_load_multiple(array(), array('mail' => $mail), true);
        $user = reset($users);
        if ($user) {
          shell_exec('drush ucan ' . $user->name . ' -y');
        }
      }
    }

```
> 3 votes

---
Tags: 7, users, drush, testing
---


# Question
Title: managed_file #progress_indicator never finishes
I've been beating myself up on this issue all week. This is my first time using file uploads in custom modules so I'm using managed\_file.

Here's a snippet of it that's being used:

```
  $form['family_fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Family photo'),
    '#description' => t('Upload a family photo, allowed extensions: jpg, jpeg, png, gif'),
    '#upload_location' => 'public://families/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('png gif jpg jpeg'),
    ),
  );

```

The file upload works fine but the 'throbbing' ajax indicator never finishes and the customer is not happy. Looking around on SO I see that I must:

pecl install uploadprogress

And I have locally. Drupal in /admin/reports/status reports:

```
Upload progress Enabled (PECL uploadprogress)

```

No change, even after restarting apache 2.4 on ubuntu. The bad thing is that this project needs to go to Dreamhost shared hosting so I cannot install using PECL. They do point to where I can add "extension = uploadprogrevs" to my .phprc and I have. They have restarted but Drupal on DH does not see it. (FIXED: see edit) Regardless, I have to get some notification to the user that the file upload was successful.

Looking at file\_managed\_file\_submit it describes the function doing a $form\_state\['rebuild'\] at the end, which is ideal. But I don't get that. I don't want to hack a core function so asking around we tried a hook\_file\_presave($file):

```
function calendar_admin_file_presave($file) {
  drupal_set_message('File uploaded');
}

```

But no message at any point, esp. when user clicks "Upload". We have tried hook\_file\_insert and it doesn't seem to work.

We have tried adding #process to the form array:

```
'#process'=>array('file_managed_file_process','_custom_file_process'),

```

with this functions:

```
function _custom_file_process(&$element,&$form_state){
if ($form_state['values']['family_fid']['fid']){
  module_invoke_all('file_presave', $file);
}

```

with no different result.

To further troubleshoot this drupal 7 app I set up a custom content type with a file field. It exhibits this same behavior locally. However, another Drupal 7 app on the same local server, same php 5.4.33 works as expected.

Even if I could get it to work on this app locally, I still will have an issue with Dreamhost shared server. So if I can get a notification to be done when a file is uploaded, I'd be OK. However it seems that Drupal in *this* app #uploadprogress is not working.

What else can I try to at least get a drupal\_set\_message inserted? thx, sam

One part of this is to get the PHP extension uploadprogress installed on Dreamhost and that is successful. Either we figure out why the drupal "callback" functions aren't working, or we can determine what could be causing this drupal 7 app to break this AJAX update when other Drupal apps on the same server don't have this issue?

# Answer
Since you seem to be having trouble with javascript, you might check your install to see if you have the jquery\_update module and check to see if it needs to be updated?
> 1 votes

---
Tags: files
---


# Question
Title: Facebook Share the older version of the article
I using facebook share to share my article to facebook.

Sometimes I edit my article title and image.

While I share it to facebook, the article title and image is still shows the older version of the article.

Anyway to fix this problem?

# Answer
Use Facebook Debugger to clear the cache. The title and image will updated.
> 0 votes

---
Tags: social-network
---


# Question
Title: Drupal 7 Omega responsive theme. How to disable the mobile breakpoint?
I'm aware that responsive design is mobile led and what I am trying to do may not be considered responsible. However, I have an omega theme and the previous developer has (or the theme default) is poorly rendering the mobile only version.

When the site is resized to a mobile width, all the content snaps into one column. Until there is time to consult the expertise of UX and Design experts to implement this properly, I want to disable this one column layout. I want the iPhone to display the site like a normal website with pinch to zoom.

Any ideas how I can turn this break point off?

Thanks

# Answer
You can switch off this via the theme settings. Just go to "Appearance" and click on the settings link next to you omega sub-theme. There in the "Grid settings" switch off the "Fluid layout".
> 0 votes

# Answer
you can try to disable the mobile breakpoint with the breakpoint module.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do I use views to create a block that display image and title
How do I use views to create a block that display image and title. The image is using IMCE module.

I have try create a views, select “node”, under "fields" section select "content" but can't select the imce image.

What is wrong?

# Answer
Use CCK to upload image. In Views, display the image with CCK. (Filter \> Content:Image)
> 0 votes

---
Tags: views, files
---


# Question
Title: Extracting URI value from Image in Views - Getting Index Error
I am trying to create a custom slideshow using Views. **Please not that I am not using the Views Slideshow Module**

What I need to accomplish is to wrap the the relative URL for the images within a container. So, my field template should generate

```
/sites/default/files/background.jpg

```

The problem that I am having is gaining access to the URI so that I can write the raw value into some div tags. So, since that is the area that I am having difficulty with, I am focusing on only writing the URL not all the div containers; that will come later.

As for the image, I have a simple content type that has only two fields: title and the image itself. I have created the view that lists the images I am looking for. Now to customize the field template within the view. Here is my code:

```
<?php
    $node = node_load($row->nid);
    $field_name = "field_image";
    $delta = 0;

    $field = field_get_items('node', $node, $field_name);
    $output = field_view_value('node', $node, $field_name, $field[$delta]);

    print ($output['#item']['uri']);

/* Everything below is for Debugging Purposes */
    print "<br><br>";
    print "Field:  ";
    print_r($field);
    print "<br><br>";
    print "Output:  ";
    print_r($output);
    print "<br><br>";
?>

```

If you look at the output below, I get a URI that says:

```
public://public://sandy_beach_banner.jpg

```

**This is correct.** I will be running it through file\_create\_Url() later as soon as I figure out how to make it a relative link and not absolute.

However, I get the error message:

```
Notice: Undefined index: #item in include() (line 11 of
/var/www2/html/annex/sites/all/themes/mytheme/templates/views-
view-field--banner-slide-show--field-image.tpl.php)

```

Line 11 in my file references

```
print ($output['#item']['uri']);

```

This I don't understand. If I wasn't referencing it correctly, I wouldn't get the URI value I am looking for. So...this confuses me greatly. I am trying to following the example that I found here: Rendering Drupal 7 Fields The Right Way because from what I can tell, this will also work in D8 (I could be wrong). That, and I want to legimately learn how to do this the right way.

Any advice here would be greatly appreciated.

## Output

```
public://public://sandy_beach_banner.jpg

Field: Array ( [0] => Array ( [fid] => 5 [uid] => 1 [filename] => sandy_beach_banner.jpg [uri] => public://sandy_beach_banner.jpg [filemime] => image/jpeg [filesize] => 30663 [status] => 1 [timestamp] => 1444690263 [alt] => Sandy Beach [title] => Sandy Beach [width] => 800 [height] => 200 ) )

Output: Array ( [#theme] => image_formatter [#item] => Array ( [fid] => 5 [uid] => 1 [filename] => sandy_beach_banner.jpg [uri] => public://sandy_beach_banner.jpg [filemime] => image/jpeg [filesize] => 30663 [status] => 1 [timestamp] => 1444690263 [alt] => Sandy Beach [title] => Sandy Beach [width] => 800 [height] => 200 ) [#image_style] => [#path] => [#access] => 1 )

public://public://nyc_banner.jpg

Field: Array ( [0] => Array ( [fid] => 4 [uid] => 1 [filename] => nyc_banner.jpg [uri] => public://nyc_banner.jpg [filemime] => image/jpeg [filesize] => 480360 [status] => 1 [timestamp] => 1444690227 [alt] => NYC Banner [title] => NYC Banner [width] => 1200 [height] => 492 ) )

Output: Array ( [#theme] => image_formatter [#item] => Array ( [fid] => 4 [uid] => 1 [filename] => nyc_banner.jpg [uri] => public://nyc_banner.jpg [filemime] => image/jpeg [filesize] => 480360 [status] => 1 [timestamp] => 1444690227 [alt] => NYC Banner [title] => NYC Banner [width] => 1200 [height] => 492 ) [#image_style] => [#path] => [#access] => 1 )

public://public://hindu_banner.jpg

Field: Array ( [0] => Array ( [fid] => 3 [uid] => 1 [filename] => hindu_banner.jpg [uri] => public://hindu_banner.jpg [filemime] => image/jpeg [filesize] => 508630 [status] => 1 [timestamp] => 1444690189 [alt] => Hindu Banner [title] => Hindu Banner [width] => 2000 [height] => 560 ) )

Output: Array ( [#theme] => image_formatter [#item] => Array ( [fid] => 3 [uid] => 1 [filename] => hindu_banner.jpg [uri] => public://hindu_banner.jpg [filemime] => image/jpeg [filesize] => 508630 [status] => 1 [timestamp] => 1444690189 [alt] => Hindu Banner [title] => Hindu Banner [width] => 2000 [height] => 560 ) [#image_style] => [#path] => [#access] => 1 )

```

# Answer
# Getting the URL from an Image (or Any File)

Let’s say, for whatever reason, you want to get the URL of a file, probably an image, and insert it into the markup of your document. Maybe, you want to use it in a slideshow and you need to rewrite the output so you can embed it within some div tags and assign it some classes for CSS.

You can do with Views **without modifying a template file or writing a single line of code .** And because this module is built into Drupal 8 (unlike D7), you will be able to do this out of the box.

Giving credit where credit is due, it was Jay from www.jay-epstien.com, the creator of the *Drupal Relativity Data Model* who showed me this simple solution. After reading this HOWTO, I encourage you to visit his site.

## Background

I wrote this tutorial because I spent **days** researching this and wanted to save the sanity of anyone in a similar situation. There are tons of posts throughout Stackexchange and on the Drupal API that show you how to accomplish this. I re-wrote my template file per these instructions and while it worked (my original question), it generated an error to which I never got an answer. There is another post that says to use the URL Formatter module.

**Using a module is something I want to avoid as I am not a subscriber to the “there’s a module for that” methodology.** Also note, that URL Formatter module is not D8 compatible and must be rewritten. This solution doesn't need to be.

## How To

We are proceeding under the assumption that you have the Views module installed and that you have created a view to show your desired content. There are lots of tutorials on doing just this so I won’t cover it here.

Your fields can be any format, unformatted list, HTML list, grid, or whatever. For this example, I am going to use an unformatted list. If you are creating a View from scratch, you probably have the Title field already configured as a default. It should look similar to the picture below.

The very first and most important thing that you need to do is **create a Relationship to the File Entity.** In the Views Display and under the Advanced tab you should see Relationships. Let’s add one.

### Select "File Usage: File"

You don’t need to require this relationship, so go ahead and leave this check block blank. The Identifier of “File” is fine, but you can change this to something else if it makes referencing it for you easier.

Let’s add another Field. I use the “File” filter in the selection dialog box to bring up all of my choices that are now available. Pick path.

The very next screen is where all the magic happens. Typically, you will get a URI that looks like

`public://sites/default/files/somepicture.jpg`

If you want, don’t select anything here and try it out and see what you get in your Views Preview pane. But, if you check the box next to “Display download path instead of file storage URI” you will get

`http://www.foobar.com/sites/default/files/somepicture.jpg`

You can now rewrite the output of the field and the link and style it as you like. There are lots of posts and tutorials on how to do that, so I won’t go into it here. Here’s what your Views Display should look like when you are done:
> 10 votes

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


# Question
Title: Getting Image URL in Views with field_views_field
I have an content type called Image that has two fields: Title and Image

I have a Views block created so that it displays the images I want based on my criteria.

What I need is to have the raw image URL available.

```
Example:

/sites/default/files/background1.jpg

```

I found this article Rendering Drupal 7 fields (the right way) and quite frankly, I am at a loss.

From the Drupal API:

```
field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL)

```

I know I have to code the views-view-fields--my\_custom\_view.tpl.php, but everything I do results in an error.

What needs to go in this file so that I can simply get the URL from the image that I am looking for?

Also point in the right direction to a tutorial would be great. Everything I have found assumes you are an expert in Drupal and at this point, everything feels circular.

# Answer
> 4 votes
I was able to do this strictly using Views by creating a relationship to the File Entity.

I have detailed this in another post which can be found here Getting the URL from an Image (or Any File).

This eliminates the need for a URL Formatter module and is D8 compatible out of the box.

# Answer
> 2 votes
Image URL Formatter

> This module add a url formatter for image field. Then you can output image url directly.
>
> Most of the code, maybe more than 90%, is just copy from the drupal core. I think it is stable enough.
>
> I have created a content type, and add an image field instance to it, later i use views to export the data of this content type.And i want to output the data,then i could import it into another drupal 7 site with feeds module. What i need is the url of the image field, but i could not export the image url directly. That is why i create this small module.
>
> **Usage**
>
> (1)After install this module,then you add an image field,then you can goto this bundle's manage display page,here at format column,you can choose "Image URL" instead of "Image".
>
> (2)When you add an image field in your views,then you config the Formatter for this field, here you can choose "Image URL" instead of "Image".
>
> Then you can output image's URL instead of Image itself.

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


# Question
Title: Within a view listing, how can I denote whether a node's date is upcoming, current or past?
I am working on an art gallery site in which we have two views that are filtered based on the date range of an exhibition. One view filters current exhibits (now \>= start date && now \<= end date) and another that filters upcoming exhibitions (now \< start date).

We would like to combine these into a single page view. This is simple enough to do with this date filter: now \<= end date. However, I would still like to denote which events are upcoming (be it a CSS class or by rendering the date field as "Opens on Dec. 12th").

**Is there a way to render/rewrite the date field differently based on the field's value relative to today's date?**

For example, if today's date is Nov. 1, 2015, I would like these two nodes:

* Exhibit #1 (Oct. 1, 2015 - Dec. 1, 2015)
* Exhibit #2 (Jan. 1, 2016 - Feb. 1, 2016)

To render like this:

* Exhibit #1, *Ends Dec. 1 2015*
* Exhibit #2, *Opens Jan 1, 2016*

# Answer
> 0 votes
Following Pierre's suggestion, I installed the "Views PHP" module. Here's how I set up my view:

1. Added my *date* field (field\_dates) and then *Global: PHP* field
2. Make sure date field is "Excluded from Display"
3. Edit the "Output code" of the Global: PHP field to the following

PHP Code:

```
<?php
$start_date = strtotime($data->field_field_dates[0]['raw']['value']);
$end_date   = strtotime($data->field_field_dates[0]['raw']['value2']);
if  (time() < $start_date) {
   echo 'Starts on ';
   echo date("F j, Y", $start_date);
} else if (time() < $end_date) {
   echo 'Open Until ';
   echo date("F j, Y", $end_date);
} else  {
    echo 'Closed on ';
    echo date("F j, Y", $end_date);
}
?>

```

Note, `field_field_dates` is not a typo. That extra `field_` is required for the code to work. Using the values listed in my questions example, the results are:

* Exhibit #1, Open Until December 1, 2015
* Exhibit #2, Starts on January 1, 2016

# Answer
> 1 votes
A possible solution is to use the Views feature "rewrite result" (as explained also in Rewriting view fields), combined with the Views PHP module.

If you're not experienced in PHP, you may want to experiment with only the "rewrite result" feature, which may help to come up with an acceptable compromise for what you're looking for.;

**Note**: The Views PHP module only has an alfa version as of today, but it's used in about 70K sites anyway ... That many sites can't be wrong, right?

---
Tags: views, datetime
---


# Question
Title: how to print sql query of view in runtime
I would like to see **view's sql query that is executed in runtime**. I found this method in google, `hook_views_pre_execute`, but I am really beginner in drupal. Where I have to apply this method, when I put this method as `project_views_pre_execute` in `template.php`, nothing is shown and I don't know why, is it needed to write it in custom module?

Any suggestion is greatly appreciated.

# Answer
> 0 votes
The Devel module provides a SQL query log for debugging/performance testing. You can enable this under **Configuration \> Development \> Devel settings** (/admin/config/development/devel) and by setting **Display query log** option.

Once enabled, the bottom of the page will contain all SQL queries executed in page rendering. For your needs, you'll need to look for `views_plugin_query_default::execute` function calls (the **where** column) to see the SQL query executed for your view.

---
Tags: views
---


# Question
Title: How to use Output as a link and replacement patterns to get friendly URLs
In a View, with a list of fields, I have the **Rewrite results --\> Output this field as a link**, and a replacement pattern **\[title\]**. However, the URL is not completely friendly, although I can substitute white space for dashes **"-"**, it still can have accents or other symbols which simply do not appear when using the module PathAuto and the function ´pathauto\_cleanstring´ in which they are substituted. As the links are completely dynamical, I cannot find any option in the Config of the module to have the patterns substituted.

Summarizing, I have a field "title", and I get the output rewrite as

```
my-page/[title]

```

if I have a node titled "Atención: no beber", I would like to have the URL:

```
my-page/atencion-no-beber

```

and I am getting, instead,

```
my-page/Atención:-no-beber

```

The only way I have found is programmaticaly rewriting the output again, but I am confident that it can be done without a single line of code somehow.

How can output this URL without programmatically rewriting it?

# Answer
If I understand your problem correctly, it sounds like you're trying to redo the aliasing work PathAuto does in Views.

If that's the case, you can add a *Content: Path* field to your view (using the **Exclude from display** option if you don't want it visible) and use `[path]` in your link output to link it to your pathauto alias.
> 1 votes

---
Tags: 7, views, path-aliases
---


# Question
Title: Possible to make image styles (thumbnails) public while original images are kept private in D7?
I love the fact that D7 allows you to choose whether files should be stored in the public or private file system on a per-field basis.

But here's my question: is it possible to have image files that are stored in the *private* file system, while thumbnails etc. created via image styles are stored in the *public* file system, so anyone can access them? In other words, I want to protect the original image files, but not their thumbnails.

By default theme\_image\_style seems to place the generated styles in the same file system (public or private) as the original image, and I don't see any arguments to change that...

# Answer
What about creating 2 fields ? One for storing the thumbnail and let it "public". The other one for storing the original image, mark it as "private" and define a permission for it using field permissions module ?

**Edit** Oct, 26: let's add some code :)
So if your confortable with creating a module, here are the instructions.
Create 2 fields: field\_img\_public and field\_img\_private, one will be on the public filesystem, the other on the private.

Then create a module to store this hook\_node\_presave():

```
function MYMODULE_node_presave($node) {
  //Retrieve the file object from the public image.
  $fid_items = field_get_items('node', $node, 'field_img_public');
  $fid = $fid_items[0]['fid'];
  $img_public = file_load($fid);

  //Create the private path.
  $img_private_path = str_replace('public://', 'private://', $img_public->uri);
  $private_dir = pathinfo($img_private_path,  PATHINFO_DIRNAME);

  //Verify if the private folder exists.
  file_prepare_directory($private_dir, FILE_CREATE_DIRECTORY);

  //Copy the image
  $img_private = file_copy($img_public, $img_private_path, FILE_EXISTS_RENAME);

  //Save the resulting file object.
  $node->field_img_private['und'][0] = (array)$img_private;
}

```

Then you just upload the public image and the private get populated.
> 4 votes

# Answer
There is now Image Style Access to do this.

> Allows granular access control to images and image style derivatives.

*EDIT*: Disclosure - this is my module.
> 3 votes

# Answer
A possible lightweight solution, which is what I ended up going with, is to save the images in the public file system, and simply use a .htaccess file to protect the original image file directory.
> 1 votes

# Answer
Use this function in a custom module if your are generating images from a custom template.

```
function mymodule_image_style_url($style_name, $uri) {
  $filename = drupal_basename($uri);

  $directory   = 'public://styles/' . $style_name . '/public/';
  $destination = $directory . $filename;

  //TODO: You will need to delete destination folders if you want to refresh styles....
  if (file_exists($destination)) return file_create_url($destination);

  $style = image_style_load($style_name);

  if ($style) {

    $image = image_load($uri);

    flog_it($image, "image");

    foreach ($style['effects'] as $effect) {
        flog_it($effect, "effect");

        image_effect_apply($image, $effect);
    }

    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    image_save($image, $destination);
  }

  return file_create_url($destination);

}

```

Then use it in a node template like this:

```
<img src="<?php echo mymodule_image_style_url('image_preview', $node->field_original_image[LANGUAGE_NONE][0]['uri']) ?>" alt="">

```

Instead of using more modules this solution will boost your website when using your image styles from private file images.
> 0 votes

---
Tags: 7, files, media
---


# Question
Title: Route parameter upcasting and route access?
Original problem:

I am trying to do a couple of (seemingly) simple things to convert a module I made in Drupal 7 to Drupal 8 (RC1).

First I will note I am using the File Entity module in Drupal 8, which may or may not be stable/complete.

I want to add a tab on a File entity (much like Edit or Archive) that lets me trigger processes, related to the data contained in the file (its a spreadsheet).

So far, I have been able to stumble through getting a route defined and a tab to appear.

mymodule.routing.yml:

```
entity.file.import_data:
  path: '/file/{file}/import-data'
  defaults:
    _form: '\Drupal\datacenter\Form\ImportDataForm'
    _title: 'Import Data'
  requirements:
    _permission: 'access content'
  options:
    _admin_route: TRUE

```

mymodule.tasks.yml:

```
entity.file.import_data:
  route_name: entity.file.import_data
  title: 'Import Data'
  base_route: entity.file.canonical
  weight: 3

```

Well okay. So far so good. Not the most robust thing in the world, but I am still working my way through unfinished docs and such. From here, I have a new tab on a File entity form, right next to Edit.

First, how can I change the permissions to not be access content, but to check access to see if the current user has access to edit the file in question? If I change \_permission to \_entity\_access: file.update (as I have seen in File Entity) the tab vanishes, and direct URL access returns Access Denied (even as user 1). Do I have to implement something extra to make that work?

Second, I don't seem to be receiving the {file} argument or file entity object in my form builder.

Form class:

```
namespace Drupal\datacenter\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ImportDataForm extends FormBase {
  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'datacenter_import_data_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state, FileInterface $file = NULL) {
    // fields to be defined

    return $form;
  }

 // extra code removed

```

buildForm doesn't have an entity (file) argument. What am I missing? I thought upcasting basically happened if the object ID was in the route (like node, user, etc).

Also, is this even the way to go about it? Basically this screen will do a few things, it will inspect the file object, check to make sure the mime is right, parse the csv or excel data, and read it back on the screen in the form of options. Whatever the user ticks off, will kick off a series of batches. Where would those batch functions go? In this class? In another file? I also see other classes like ContentEntityForm, EntityForm, etc.. which one should I be using?

I have all of this working great in Drupal 7, I am just having trouble getting momentum converting it over and finding what I need.

# Answer
Entities can be upcasted with these methods:

Note: to use `_entity_access` requirement, you must implement one of these options this information. See `\Drupal\Core\Entity\EntityAccessCheck` for internals.

# Controller reflection

Type cast the entity object as a parameter of the controller.

For your form controller, replace:

```
 buildForm(array $form, FormStateInterface $form_state, $file = NULL) {

```

with:

```
 buildForm(array $form, FormStateInterface $form_state, \Drupal\file\FileInterface $file = NULL) {

```

This works with any entity type, not just files.

See `EntityResolverManager:setParametersFromReflection`.

# Using `_entity_view` or `_entity_form` controllers

Entity types found in the path are upcasted automatically if the route definition has `_entity_view` or `_entity_form` as a default.

See `EntityResolverManager:setParametersFromEntityInformation`.

# Add upcasting info to your route

Add the following to your route YAML

```
options:
  parameters:
    my_slug_name:
      type: 'entity:my_entity_type_id'

```

Replace `my_slug_name` with whichever text you used in your route within the `{}`. Usually this is exacly the same as the entity type Id.

Then replace `my_entity_type_id` text with the entity type Id.

I have written something similar for Views Advanced Routing in its README.
> 2 votes

---
Tags: 8, routes
---


title: Apply Imagecache style to raw image url

text:
# Question
Title: Apply Imagecache style to raw image url
I have a site I'm working on where images are inserted into the body of blog nodes and I'm wanting to return these images in a view. I'm using computed field to successfully return the url of the images in the view, but I would like to apply an imagecache style to this before displaying it using

```
<img src = "[computed_field]">

```

Does anyone know the best way to do this? I've been searching around and have not been able to successfully do this yet. Thanks!

# Answer
> 1 votes
It sounds like you should handle this in your computed field's PHP since you're already parsing out the image there.

```
//Assuming $entity is the parsed node in question
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $entity->body[LANGUAGE_NONE][0]['value'], $matches);

//If an image match has been found, build a URI relative to public file base
//Assume image URLs are something like:
// "/sites/default/my_files/some_dir/whatever.jpg"
if(isset($matches[1][0])) {
  $public_dir = variable_get('file_public_path','sites/default/files');
  $uri = file_build_uri(str_replace("/$public_dir/","",urldecode($matches[1][0])));
  $entity_field[0]['value'] = image_style_url('thumbnail',$uri);
}

```

---
Tags: 7, entities, media
---


title: How to setup the oauth module?

text:
# Question
Title: How to setup the oauth module?
I don't know how to setup the outh module right. I found also the question How do I configure the Services OAuth sub-module? but that answer is very old and ends with a "To be continued..." statement.

So far I get out that I need to generate a context (http://example.org/admin/config/services/oauth/contexts) and a oauth connector (http://example.org/admin/structure/oauthconnector). So I think I setted them correctly but I cannot see where the user may access that.

Could you point me to a tutorial or something like that? I'm not able to find the right words to google that myself. Sorry for that!

# Answer
You can try the Drupal Services, REST Server and 3-legged OAuth tutorial here. Just be pay intention in this part :

```
$oauth->fetch("$api_url/node/1");

```

This is just for creating the GET request. If you want to create the POST request. It should be something like.

```
 $oauth->fetch("$api_url/user/vote.json",array('nid'=>10),OAUTH_HTTP_METHOD_POST);

```
> 3 votes

# Answer
I am not able to add a comment on rekire's turtorial request on http\_client oauth2 setup, so i'll just put it here as it also answers the original question.

If you download the http\_client module you'll find a readme.org file in /http\_client/includes/auth/oauth2/ folder explaining some basic settings by examples from within the wsclient module. I'm using both modules successfully now with basic HTTP authentication. For a new client, just started looking into the oauth2 alternative.

Examples shown are: \- server-side flow (authorization endpoint) \- user-password flow \- client-credentials flow
> 0 votes

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


# Question
Title: Simple order cancellation in Drupal Commerce, with 24 hour time limit?
I want to create a way for customers to log in and edit their completed orders (the orders are registrations to classes). Compared to the standard order-edit page I want to remove all options except 'change order status to cancelled'. Preferably a simple page stating the content of the order, then some cancellation 'rules', and then a button saying 'cancel this order'.

Cancellation should then also check whether date/time of the booked class is less than 24 hours away from the moment of cancellation. If \<24 hours, it should either refuse cancellation, or allow cancellation (nice for those on the waiting list), but not refund the cost of the class (paid for using a voucher - using the giftcard module)

Background: the site sells two products: one is a set of vouchers. These vouchers can then be used to buy product 2, which is a registration to a class at a specific date and time. When customers have booked a class, they now get an email with link to their order page. Their they find a button 'edit order', click that and you go to the standard order edit page which shows line-items, billing and shipping etc, and allows all existing changes to the order status. As this page is not made trough either a template or a view, I have no clue how to change what customers get to see and do with their completed order.

Also rules does not allow me to compare the time of the status change with the time/date field of the booked class, so I can't control the 24 hour limit either..

Suggestions are to build a custom module doing the above, but I have no idea how to kick that off..

All/any help massively appreciated

# Answer
> 1 votes
I haven't tested any of this, but you might some of the following useful:

Entity Operations allows you to take a Rule and turn it into a menu tab. This would be one way of getting that onto the order view page.

Something I've really been wanting to try is the Entity action links sandbox:

> Allows actions and rules components to be executed via AJAX links on entity view.

Just note the patches discuss in the Sandbox README.

If you wanted to do the Rules route, these would be probably your best option, because you can use conditions and components to provide some sort of response or action system based on the order status and time.

Otherwise, you'd need to create a custom module with a custom access callback that does the appropriate checks and then executes the action if allowed. (For a developer, I think this would actually be an easier route.) But the rules stuff is intriguing.

---
Tags: commerce
---


# Question
Title: How can I within Drupal 7 make updates to an external MS SQL Server database?
I have an external MS SQL Server database that I can display some of its contents within the Drupal 7 views module via the Views Database Connector module.

How can I within Drupal 7 make updates to an external MS SQL Server database?

# Answer
> 1 votes
Use the Drupal database API to manipulate the data in the other database. You can use db\_set\_active() to switch to the other database.

---
Tags: 7, database
---


# Question
Title: How to programmatically determine whether a node is a og group type node?
Drupal 7, OG

How to programmatically determine whether a node is an og group type node?

# Answer
Or, much faster/easier/supposed-to-be-done-this-way-er: og\_is\_group\_type()
> 2 votes

# Answer
I found a way to do this using `og_get_group_ids()` :

```
og_get_group_ids('node', array($nid));

```

If the result is not empty then the node is an og group type node.
> 2 votes

# Answer
For the 7.x-2.x branch you can use:

```
og_is_group('node', $node)

```
> 0 votes

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


title: How do I group my fields in a view?

text:
# Question
Title: How do I group my fields in a view?
I have a content type (*Staff Member*) with many fields, such as *portrait*, *name*, and *bio*. The *name* and *bio* fields are grouped together under the field group \_text\_fields\_.

I have created a view for this content type.

The view renders each content node like this.

```
<div class="views-row">
  <div class="staff photo"><img src="...." /></div>
  <div class="staff name">John Doe</div>
  <div class="staff bio">John Doe has been with us for 800 years.</div>
</div>

```

However, I want grouped fields to be grouped like this.

```
<div class="views-row">
  <div class="staff photo"><img src="...." /></div>
  <div class="text_fields">
    <div class="staff name">John Doe</div>
    <div class="staff bio">John Doe has been with us for 800 years.</div>
  </div>
</div>

```

I've tried writing a views-view--staff-members.tpl.php template file, but it receives all of the .views-row items as a HTML string.

How might I accomplish this?

# Answer
You don't need to modify your `.tpl`, you only need the Field Group module to group your fields together. With this module you have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or **div wrappers**.

You can read the documentation where you will find some examples.
> 2 votes

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


# Question
Title: How do you find out which module is causing a redirect?
I have a Drupal 7 site and have a bunch of custom modules installed. Currently when I hit a specific node/9283 it gets redirected to another page. I'm not sure which module is causing this redirect. I also check URL Alias and nothing is there for redirection. Its definitely something custom. How would you go about debugging this and figuring out which module/code/function is being loaded on this redirect to another page on the same site?

# Answer
If we're talking Drupal redirects (i.e. `drupal_goto` calls), the Devel module could help out here. In its settings it has a **Display redirection page** option that halts redirection for inspection.

You can use this in conjunction with a `hook_drupal_goto_alter()` invocation to dump a stack trace on the redirection halt page to find the origin of the `drupal_goto` call.

```
function MYMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  ddebug_backtrace();
}

```
> 3 votes

# Answer
What I do is:

1. Clone site do dev environment
2. Xdebug
3. Step by step execution

Simple, once you get your development environment up and running.
> 0 votes

---
Tags: 7, redirection, debugging
---


# Question
Title: What approach for Commerce products, attributes and product displays?
I am building a site, based on Commerce Kickstart. At this moment the site will not have a store, but it's on the horizon and I am trying to prepare the site beforehand for a store launch with as little developer hassle as possible.

My concern is now to wisely design the products and their attributes.

First off, I have two taxonomies. One is obviously a Product tree. A Commerce Product will have only one term reference value possible. Then I have a Usage tree (or call it Applications), which describes how and where a product can be used. A Product Display will have multiple possible term references from that tree.

Now let's say, I have a brand of nails in different sizes: 1,2,3,4. The sizes 1 thru 3 would be tagged as "Home Use" and the size #4 - only as "Construction Use". All sizes would share some fields, such as main description, PDF attachments, images. And these could be fields on the Product level.

For sizes 1 thru 3, I would basically need one product display, speaking in terms of the page contents. And the Add to Cart button would have a list of models next to it: 1 thru 3. I would expect the button to add to cart SKUs mapped for each size.

For model #4 I would like to have perhaps additional set of images and a slightly different description, and the Add to Cart button would not need any select.

This is one possible approach. Another that comes to mind would be to treat all sizes as separate 4 product displays. Then, the Add to Cart buttons would have no attribute selector. This scenario could seem quite simple and obvious - a typical one-to-one relationship. However I am allergic to solutions that are not scalable, I hate cloning data as a slightest text correction would later require N edits on each product display.

So, which way would you go based on your experience? I don't know Commerce well enough but still want to be prepared for it beforehand.

I assume that SKU is something crucial for a successful and non-ambiguous order. But maybe my assumption is wrong.

I'm open for your insights.

# Answer
When thinking about how to handle products and product displays, I prefer to model it after how Commerce Kickstart handles it's data organization:

Product displays are used to organize and present products to the customer and product entities are used to store product-specific information.

> First off, I have two taxonomies. One is obviously a Product tree. A Commerce Product will have only one term reference value possible. Then I have a Usage tree (or call it Applications), which describes how and where a product can be used. A Product Display will have multiple possible term references from that tree.

Product catalog taxonomies influence how products are organized and subsequently found on your site. This would mean this information would go into the Product Display.

> Now let's say, I have a brand of nails in different sizes: 1,2,3,4. The sizes 1 thru 3 would be tagged as "Home Use" and the size #4 - only as "Construction Use". All sizes would share some fields, such as main description, PDF attachments, images. And these could be fields on the Product level.

The "Use" field is a little tougher but I think you're on the right track. Anything that is specific to the individual SKU (product images, PDFs, diagrams, descriptions, sizes, etc.) would be on the product entity. You can still provide filtering using these attributes via Faceted search, but you end up not duplicating information across multiple entities.

I'm not sure how big your product catalog is, but there are some modules you can explore to ease your data management pain:

1. Inline Entity Forms: With IEF, you can create and manage product SKUs within your Product Displays. It makes 1:1 product relationships much easier to manage. It can also do 1:N relationships, but sharing those across multiple products can be painful with this.
2. The opposite of this is Commerce Auto Display, which allows you to create a Product display from within the Product entity form.

If you want to go down this road, IEF is preferred, since it tends to want you to keep only the SKU, price, and other bare minimum fields on the product entity.
> 1 votes

---
Tags: commerce
---


# Question
Title: term reference field with empty select list
We need to make the term reference field select list to have no options because the vocabulary have big number of terms which makes the form loads very slow due to getting the term list from DB and render them.

That field is being updated by ajax so we need it start clean with no DB operation to increase performance and page loads fast.

> ***Implementing***: hook\_field\_attach\_form ***or*** hook\_form\_alter

has no effect as we see the form is built.

what we need i to prevent DB reading list.

```
if($form_id == 'field_ui_field_edit_form'){
      $form['instance']['default_value_widget']['field_brand']['und']['#options'] = array(0 => t('No'));
}

```

Above code didn't change any thing in ***node/add*** form which still list all brands

Is it posible in drupal?

# Answer
> 0 votes
Try with the following code

```
function yourmodule_form_alter(&$form, &$form_state, $form_id){
 if($form_id == 'your-edit-form-id'){
   $form['your-select-feild']['#options'] = array();
 }
}

```

Hope this will help you..

---
Tags: taxonomy-terms
---


# Question
Title: How to create display page depending on role?
I have a role of **shopkeeper** who is able to update the *product info*. But I want to create a different page for specific role of user. How to do this

# Answer
> 0 votes
Try **Front Page** Module

**Features**

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
>
> * **Alias (only 2.x branch)** \- Allows for another Drupal path to be shown as the home page without redirecting the user.
> * **Redirect** \- Allows you to redirect users to a local or remote URL.
> * **Themed** \- Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
> * **Full** \- Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

Hope this will help you..

# Answer
> 0 votes
Content Access

> This module allows you to manage permissions for content types by role and author. It allows you to specify custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

**OR**

Showing different content on the same page to user depending on role could be accomplished with the Panels module like so:

* Install the Panels module and its dependencies.
* Go to admin » structure » panels.
* Enable and edit the page "node\_view" template.
* Click "add new variant".
* Click "continue" on each screen until there is a button with "Add variant."
* Click "Add variant".
* Under panel » content, click the gear in the upper left to add a panel of content for the logged in user to see. Save.
* Click the gear in the upper right of the new content to get a menu. Select visibility rules » add new rule. Select role and set it how you want. Save.
* If you want to show something different to anonymous users, repeat step 6 and 7 to add content and make it visible only to anonymous users.
* Don't forget to save.

it is explain by beth

---
Tags: theming, users
---


# Question
Title: How to add the configuration changes from a website to another website?
This is what I'm trying to do:

I have a **website A** where I make configuration changes and add other stuff. Now I create a **website B**. I would like to add the configuration changes from website A to this website.

I know the **UUID of both websites have to be the same** (like staging & production environment). In "How can I import the configuration on a different site?" they explain how to do this with `drush cget system.site`.

The problem is when I run `drush cget system.site` in my website A I get the following drush error:

> Command config-get needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. \[error\] The drush command 'cget system.site' could not be executed. \[error\] Drush was not able to start (bootstrap) the Drupal database. \[error\] Hint: This may occur when Drush is trying to: * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details. * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

```
Drush was attempting to connect to:
 Drupal version         :  8.0.0-rc1
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  root
 Database name          :  s_1
 PHP executable         :  /Applications/MAMP/bin/php/php5.5.10/bin//php
 PHP configuration      :  /Applications/MAMP/bin/php/php5.5.10/conf/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /Users/myname/.composer/vendor/drush/drush/drush.php
 Drush version          :  8.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/s1
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_bZM1aJhLcWGpFZJEzfEw_pKF4g71jOdkSRti30k540BAwE9GQ4U6p469a9VxyJS4j4JVfC58qg/sync

```

I've installed the **latest version of drush** .. . I'm working with the **release candidate of Drupal 8**. Is there another way to get my UUID? Or do you have a tutorial or a video/blogpost of somebody who already did this?

**UPDATE:**

Ok, I was able to retrieve the UUID from website A and changed the UUID in website B so they have the equal UUID.

After that I changed the system site slogan of website A.

Then I did an export of the configuration in website A. But when I tried to import it in website B I got 137 new files to sync .. . The UUID is different in all files like this:

When I tried to synchronize I got the following error:

# Answer
There was a discussion in the Drush issue queue on allowing config-import to force the adoption of the UUIDs in the imported configuration to be inserted into the database. The problem with allowing this is that this operation is equivalent to deleting all of your configuration (e.g. all of your content types) and then re-creating them, which has the side-effect of deleting all of the data associated with that configuration (e.g. all of the pages in your site). It was thought that erasing a site entirely was too surprising of a side-effect for a config-import operation, even with a --force flag, so this use case will not be supported.

The current thinking is that the right time to force the UUIDs of a site to change would be at site-install time. At the moment, the Drush site-install command does not support this directly; however, there is a configuration import installation profile that Alex Pott wrote that will perform this function. It should be possible to use this from Drush site-install.

In general, though, if your use-case is moving configuration from one site to a different site, you should use features, not the configuration system.
> 8 votes

# Answer
> I have a website A where I make configuration changes and add other stuff. Now I create a website B. I would like to add the configuration changes from website A to this website.

That is not the use-case for Drupal configuration management. Site B should be a database clone of site A in order to sync configuration.
> 1 votes

# Answer
Have you tried the module Features who is able to move a lot of different settings between two sites?
> 0 votes

---
Tags: drush, 8, configuration
---


# Question
Title: Email notification via private message module
I am using private message module to send an e-mail to all users. When I send mail, users can able to see the message in site only after logging in.

There is an email notification settings in private message module. What is the settings to send mail to user using private message?

Below screen shot shows the settings of email notification.

# Answer
> 0 votes
# Part 1:

The answer to the question "**What is the settings to send mail to user using private message?**" is like so: these settings can be used to finetune the eMail to the user who received a "Private message", whereas such eMails are like a "notification" that there is a new Private message waiting on the site (and for which that user must head over to the site to actually read/see the private message).

Compare it so the various eMails a newly registered user may receive after a registration request got approved, which also requires such new user to go visit the site to actually start using the user id (to set a new password, etc).

# Part 2:

Below is a suggestion to address the 2nd part of your question, which you wrote in these 2 comments:

* **But when i am creating message "To" I have specified their user name to send mail,instead of that i want to give "ROLE OF USERS" it is possible to send mail by using user role ?** ...
* **I have posted in above pic in place "To" i want to specify my user roles ...in under one role i have 10 users i want sent a mail for all of that users.**

The Privatemsg Bulkmail module (for D6) would possibly address your question ... Provided "sending a private message" (instead of "sending an eMail") would be OK for your case. *If that's not what you want, then you should not be using the Private message module (that's not what it is for)*. The rest of my answer below assumes that "sending a private message" would be OK.

There are currently no plans for a D7 version of that module. However, I'd use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the VBO module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

In this specific case;

* use Views bulk operations to create the list of your users to be targeted (in this case a list of users that corresponds to your **ROLE OF USERS**).
* use Rules action "Send a message" (provided by Privatemsg module).

PS: yet another great usage of the Rules module, in this case in combination with the Privatemsg module.

---
Tags: emails, privatemsg
---


# Question
Title: How to add only the postal code field to the user registration page?
I have a custom template file successfully rendering the user account creation page. I am using the Location Module, which adds a field (which appears to be a field group) to the user. I want to add **only** the postal code field (zip Code) to the user registration page.

`template.php` code:

```
    function responsive_bartik_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_pass'
    ),
  );
  return $items;
}

```

`user-register-form.tpl.php` code:

```
<div class="responsive_bartik-user-pass-form-wrapper">
<?php
     print render($form['account']['name']);
     print render($form['account']['mail']);
     print render($form['account']['pass']);
     print render($form['captcha']);
     print drupal_render($form['actions']);
     print render($form["form_build_id"]);
     print drupal_render($form['form_token']);
     print drupal_render($form['form_id']);
?>

<p>
   <a href="password">Forgot Password</a>
</p>
<p>Already have an account?<a href="login"> Log in</a></p>
</div>

```

# Answer
> 0 votes
Use this module Postal Code they can allow to only add postal code in user page

> A very minimal D7 Postal Code (ZIP Code) field with validation for one country or a combination of countries

---
Tags: users
---


title: Set permissions to specific node in php

text:
# Question
Title: Set permissions to specific node in php
Is there any way to add a role permission to specific node? I have a block-view Home slider, and I want to **add a php validation to a specific slide**.

I have to edit the `node.tpl` of my slide ? Or maybe the view output `tpl`? I'm in a Drupal 7 installation.

# Answer
> 2 votes
Content Access

> This module allows you to manage permissions for content types by role and author. It allows you to specify custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Nodeaccess

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

If you want to add it by custom code use `hook_node_access`

```
function mymodule_node_access($node, $op, $account) {
  // We are interested to existing objects. When the node is being created, Drupal passed the node type instead of the node object.
  if (is_object($node)) {
    $check = (
      ($node->type == 'node condition')         );
    if ($check) {
      if ($account->uid == $node->uid) {
        return NODE_ACCESS_ALLOW;
      }
      else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

```

# Answer
> 1 votes
THe Node Access Module should allow you to do this, by granting/restricting access by role or user.

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

See if that does it for you.

---
Tags: 7, views, users
---


# Question
Title: Use views as radios (or check-box) options in drupal forms
Here is the scenario:

There is a multistep form for creating a content type "**Support request**".

**Step 1:** In this step, the user enters his/her device model and click next.

**Step 2:** In the next step, a list of technician (technician is a content type) whom has knowledge about that certain device will be shown, in this steps some information about technician is shown (from node) and user can decide which technician to hire.

**Step 3:** In the last step, some information about device problem is submitted by user and the form is submitted.

Now the question :

> Is there any solution to use views in second step? How can a view like this (note that the view output should be filtered based on the device model selected in first step) can be passed as radios options in drupal forms?

# Answer
You can do it using one of listed module :

Views attach

> This module provides two additional Views display plugins, "Profile" and "Node content". These displays do not display on a page but get "attached" to either a user page or nodes of specified types.

Entity Views Attachment

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

View field

> View field provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.
> 0 votes

---
Tags: 7, views, forms
---


# Question
Title: Create a view with checkboxes per role, that generates an email to an admin
I want a registered user to be able to tick rows in a table, and then submit an email to a predefined email address containing the titles of the selected rows.

VBO almost does what I want - in that there is a "send email" option, but on clicking the button it displays a form to be filled in with email address, title subject etc to send the email - I don't want that, I want it just to send a single email when the user clicks the button containing the titles of the selected rows.

# Answer
There is Views Send module, you may try this.

Views Send enables you to send mass mailing from a View.

This module support tokens and Global: Send E-mail with VBO.
> 0 votes

---
Tags: emails, views
---


title: How do I read the node ID?

text:
# Question
Title: How do I read the node ID?
I have few articles that were deleted by accident.

Can I add these again using their nids?

# Answer
> 2 votes
No, Node ids are unique.

But yes you can avoid this kind of issues in feature by using url alias in drupal as you can generate same URL for different node id if current node is deleted accidentally.

Documentation for URL alias https://www.drupal.org/node/120631

# Answer
> 0 votes
No. You cannot add the node with the same id as it was before before deleted.

Node ids are unique and there is no way you can have the same id for the new node.

---
Tags: nodes
---


# Question
Title: Impossible to create content or edit image styles after Backup/Restore
I'm having difficulties with a website that's running 7.14.
I did a backup with backup & migrate, installed a new instance of Drupal (7.40), installed the latest versions of all the modules used in the original website
I then restore the database (using backup & migrate also) but I can't create content or create/edit image styles. Whenever I try, I get this error message:

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

Any ideas on what causes this error? Or how to solve it?

# Answer
How To Update Drupal Core

Follow these instructions:

1. Make a backup of your Drupal instance (database).
2. Download the latest release of your current Drupal version.
3. Extract the \[tar ball or zip\] Drupal package.
4. Set your site on maintenance mode
5. Delete all the files & folders inside your original Drupal instance except for /sites and its sub-folders. This assumes that all of your custom work - including themes - is in the recommended spot - the /sites folder tree. If you have made custom changes elsewhere you will need to either preserve them or plan to replace them later.
6. Copy all the folders and files except /sites from inside the extracted Drupal package \[tar ball or zip package\] into your original Drupal instance location.
7. Some updates do not include changes to setting.php and some do. See There is a way - Comment below for more on this. If the update release includes changes to settings.php you will need to replace your old settings.php in .../sites/default/ with the new one, and then edit the site-specific entries (eg database name, user, and password) in the setting file.
8. If you have modified files such as .htaccess or robots.txt re-apply those changes to the new files.
9. If you have a favicon.ico file that was deleted replace it too
10. Login to your site as administrator or as user no 1
11. Run update.php by navigating to http://...yourdrupalsitename/update.php and follow the process to update your Drupal instance
12. Disable maintenance mode
> 0 votes

---
Tags: 7, backups
---