title: Correct way for Attributes in Commerce

text:
# Question
Title: Correct way for Attributes in Commerce
I am building a small web site which offers photography services. So, basically, I offer some services and these services do have some additional options (attributes). For example, service:

* Single product on photo
* Group products

And attributes:

* Delivery: standart or rush (+$5)
* Background color: white or black (+$1)

I found at least three ways how to add attributes, but a little bit confused which way is correct.

**My question**: which way is correct and better for me? I like the Commerce Pricing Attributes module because it is more understandable, but as we can see this module is not very popular.

# Answer
> 0 votes
Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. Especially because of the ***auto creation of product display nodes***. This module provides the backoffice functionality present in Commerce Kickstart (V2). It contains these sub-modules:

* Commerce Backoffice **Product** (commerce\_backoffice\_product).
* Commerce Backoffice **Order** (commerce\_backoffice\_order).
* Commerce Backoffice **Content** (commerce\_backoffice\_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

**Note**: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).

# Answer
> 0 votes
There are always different ways to do things in Drupal. Drupal Commerce (DC) is the shining example of this. DC allows for project attributes out of the box using fields on product types that are set to be attributes (this creates an AJAX field as a select option in the add-to-cart form). This is an example of attributable fields. You will notice the price and the photo changes when you change the video type. You can also handle some attributes with line items added to an entire order (this is how shipping is done). If you have global attributes, the best way would be a line item added to the entire order.

You list delivery and background color; I am going to assume these would be global attributes that would apply to any order in your store. These would be prime candidates to use line items added to the order. But this also depends on how you are going to allow your customers to purchase products.

I would need more infomration about how you want to setup your shopping experience to be able to completely answer the question.

DC is an extremely powerful and flexible shopping cart. But it is complex.

---
Tags: commerce
---


# Question
Title: Controlling node's content using field setting
In a module I am developing I wish to control display of a link in node's content depending on user's choice. I want to display this option to user(whether he wants to display the link on particular node) when he is on a path like this `/node/{node}/edit` with other options(menu settings, comment settings) available on that page. On doing some research I managed to find out that usage of field plugins would be required. This I am saying because comment module implements `FieldType` plugin and displays option of type open, close, hidden comments. But now I am not able to move further because I am not able to understand how will I keep track of option selected by user for different nodes. It would be great if any one can throw some light on this, some code or reference to similar usage by other custom module would be of great help. Thanks.

# Answer
> 0 votes
You don't need your own field types for this like comment adds.

You can use checkboxes, radios, lists, whatever you want that makes sense for you.

Moving them into the sidebar requires some form alter code in the node forms that moves them into fieldsets. `path_form_node_form_alter()` is an example that defines a fieldset and moves a field into it.

Then all that's left is custom preprocessing/twig checks.. check the value of those fields and then display whatever you want.

---
Tags: 8, entities, plugins
---


# Question
Title: How to setup Advanced Content Filter to not remove drupal-entity tags?
I use CKEditor to create content. And Media Plugin to upload and manage images.

Now I have a problem that as soon as I activate `Advanced Content Filter` in CKEditor settings, my images are removed. I think problem is, that they are implemented like this:

```
    <drupal-entity class="media-element" data-entity-embed-display="image:image"
        data-entity-id="2589" data-entity-type="file" data-fid="2589"
        data-media-element="1"></drupal-entity>

```

I tried to insert `drupal-entity` in `extra allowed content`, but it doesn't change anything.

As long as I do not save this node with activated ACF the images are shown on my website. This is because first I created nodes with deactivated ACF.

# Answer
Try this :

* admin/config/content/ckeditor/edit/Full-\>
* Advanced Options -\>
* Custom JavaScript configuration -\>
* Paste in: **config.allowedContent = true;**
* Save
> 0 votes

---
Tags: entities, wysiwyg
---


# Question
Title: Determine whether a field has changed during hook_node_submit
Basically I need a way of checking whether a node field changed during some event hook...I am using hook\_node\_submit() but this doesn't seem to work:

```
$form['field_status']['und']['#value'] !== $node->field_status['und'][0]['value']

```

Produces equality all the time...any suggestions on which hook and how I would check equality when I know a value has changed it should fire off an email...

Alex

# Answer
> 1 votes
As said from @Clive, the only way is to compare the value in `$node` with the value contained in `$node->original`.

As far as I can see, that value is only available in `hook_node_update()`, `hook_node_presave()` and every hook invoked from `node_save()` which receive the saved node as argument (but only when a node is updated), since `entity_load_unchanged()` is called from `node_save()` (which also unset `$node->original` before exiting). If you need it in `hook_node_submit()` you could simply add the following code in your implementation.

```
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

```

Since you are checking for field properties, the other, more general, hook would be `hook_field_attach_submit(hook_field_attach_submit($entity_type, $entity, $form, &$form_state))`. With this hook, `$entity` would contain the field value before the node has been edited, and `$form_state` contains the submitted values.

---
Tags: hooks, nodes
---


# Question
Title: How can I stop JavaScript from being cached during development?
I have a Drupal 8.00-beta11 site and am trying to dynamically add JS to a page, so that I don't have to clear the cache every time I edit the JS file. I have a custom module (lets call it my\_module) in drupal\_root/modules. My javascript file is in drupal\_root/modules/my\_module/js/my\_js.js.

I have a my\_module.libraries.yml file as follows:

```
my_module:
  version: 1.x
  js:
    js/my_js.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui

```

In my my\_module.info.yml I have:

```
name: My Module
type: module
description: ...
core: 8.x
libraries:
  - my_module/my_module
package: Custom
version: 0.1

```

This loads the JS succesfully, but I need to clear the cache everytime after I edit it to see the changes.

In order to avoid doing this, I added the following to my buildForm function:

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'my_module') . 'js/my_js.js',
);

$form['#attached']['library'][] = 'my_module/my_module';

```

I also placed the following in drupal\_root/modules/my\_module/my\_module.module:

```
<?php

  function grid_tools_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_module/my_module';
  }

  function grid_tools_page_build(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_module/my_module';
    $path = drupal_get_path('module', 'my_module');
  // Add JavaScript/CSS assets to all pages.
  // @see drupal_process_attached()
    $attachments['#attached']['js'][$path . '/js/my_js.js'];
  }

?>

```

However, none of this has worked and I still need to clear the cache to see my changes. How do I avoid having to clear the cache every time?

# Answer
I'm assuming you have to clear caches because your JS file is being aggregated? Can't think of a different reason.

That has absolutely nothing to do with how you add your JS file (Most of what you tried shouldn't even work, use #attached\]\[library).

Instead, it depends on the separate settings to aggregate JS or not. You can find them on the Performance settings page. Aggregation is also automatically disabled if you use the provided `sites/example.settings.local.php` as your `settings.local.php`, which I strongly recommend when doing development, also for the other things it does like enable verbose error logging and disabling render caching (but keep in mind to always test your code with render caching too).
> 2 votes

# Answer
It won't work because you are using libraries and they will get aggregated and cached. To have really dynamic JS I would suggest loading the content of the JS file into header within script tags in hook\_page\_attachments\_alter(). See the system\_page\_attachment() for more information on how you could do it.

But this is really bad idea. Instead I would suggest you clear the CSS/JS cache by running the \_drupal\_flush\_css\_js() if you don' want to flush all caches.
> 0 votes

---
Tags: 8, caching
---


# Question
Title: How to code a views filter to exclude parents that have children
I am using the Project Modules.

Some projects have no tasks others can have one or more tasks. In SQL terminology this is a one-to-many relationship, I believe.

I think the generated SQL joins Tasks node type and Projects node type.

I am using grouping so that tasks belonging to the same project are grouped together and projects without tasks are also grouped together. The problem is that projects that have tasks appear twice--in the "header" above the tasks associated with that particular project AND in the list of projects without tasks. I want the project title to appear only in the header above the tasks associated with that particular project.

There is an Entity Reference that links tasks to projects utilizing the field\_data\_pmtask\_pmparent table. I am not using this in my view.

How can I code a filter to omit projects that have tasks from the list of projects that have no tasks?

My View

# Answer
> 1 votes
The following is designed for Projects and Tasks, but would probably work for any Entity Relationship with optional children of a parent.

To create a view that lists all parent nodes (in this case Project content type) whether they have children (in this case Tasks) or not use the following methodology.

The output will be all Projects with Tasks listed below them if they have Tasks.

Create a View for Projects. The Format chosen was Table, but other options would probably work.

Table Settings should include Grouping field Nr. 1 set to Content: Title. Check all the boxes Hide Empty Column for each field.

In the Fields section of the View do not list fields that are in the Project data type. Use only those in the Task data type. The Project title will automatically be retrieved because of the relationship in the Task data type that points to the owning Project. Filter Criteria should be set to Content Type = Project.

Click Advanced on the View page then click Add (next to RELATIONSHIPS). Click the drop down box and select Entity Reference. Select "A bridge to the Content entity that is referencing Content via pmtask\_parent". Type Tasks into the Identifier blank. This establishes a BACKWARD reference to Projects. Require this relationship should NOT be checked because there are Projects without Tasks. You must read the Entity References very carefully. Some are very similar to each other.

There appears to be no way to find a list of all Entity References in Drupal except to add an existing field to a content type (Manage Fields) and to click the drop-down arrow next to it to select a field. Entity References are preceded by the term Entity Reference.

From the database perspective, the pmtask\_parent Entity Reference is an index (or pointer) to the parent database record. In this case, the Project. Traditionally relational databases would create separate tables for Tasks and Project, but Drupal does things differently with both stored in the node table. The field\_data\_pmtask\_parent table serves as the linkage between the two node types.

Above from https://www.drupal.org/node/2533748.

---
Tags: views
---


# Question
Title: How to restore complete database keeping the site in maintenance mode in Drupal 7
I need to restore complete database in a regular basis (weekly). I am using pure PHP + system call to mysqldump and mysql to backup and restore full database. The restore process takes 2 minutes. What would be the correct procedure in order to keep the site in maintenance instead of getting a Drupal database error? Is there some sequence of table restoration?

For example, I use UPDATE variable SET value = 's:1:\\"1\\";' WHERE name= 'maintenance\_mode';" just before the restoration, but obviously as there is a DROP TABLE if exists maintenance\_mode in the SQL backup file, the site will show an error instead of the maintenance screen for a moment, and maybe in more occasions if there are incongruences among the different tables as they are updated.

I was thinking of controlling the process with the .htaccess, forwarding all traffic to a static HTML maintenance page.

**Update**: I have created my own module as there are many other tables which are outside Drupal and the product has to be specifically integrated with the requirements of the customer. So I cannot use the Backup and Migrate module (as suggested in one of the answers).

# Answer
Add a maintenance-page--offline.tpl.php page to your theme , and whenever the connection to DB is lost drupal will show this page instead of an error , but designing this page you cant use formal variables which are used in theme like $title or $styles and ... cause these are stored in DB and in your situation there is no access to that , so you must add them using php or just implement some strings .

Check this page for more help : Theming the Drupal maintenance page
> 1 votes

# Answer
Check the documentation for theming the maintenance page.

You can set up a maintenance page template specifically for when the database is unavailable, template : maintenance-page--offline.tpl.php

And a plain maintenance page (template : maintenance-page.tpl.php)

Setup your maintenance templates and then do your restore with the mysql command.

Drupal should be able to handle all request during the maintenance process gracefully.

Have a read of the docs, set the maintenance templates up and have a go.

And do say how it went. It'd be interesting to read your feedback.
> 0 votes

# Answer
Consider using module Backup and Migrate as a possible alternative. From the modules project page:

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

Apart from the benefits you get from the module, I think it's worth trying to see if it may server as a work around ...
> 0 votes

# Answer
After reading the answers and the documentation, I found that these steps have to be followed:

1. Change the permissions of the settings.php file in site/default, so it is writable. From 0444 to 0777.
2. Add or uncomment the following lines in the settings file: $conf\['error\_level'\] = ERROR\_REPORTING\_HIDE; $conf\['maintenance\_theme'\] = 'bartik';
3. In bartik theme (or any other that you define in settings), located in themes/bartik, copy the files which are in the folder themes/bartik/templates, maintenance-page.tpl.php and page.tpl.php renamed to maintenance-page--offline.tpl.php.
4. Configure the maintenance-page--offline.tpl.php that you have copied to themes/bartik so it has no PHP errors, which means defining all the variables used in the file, or removing the variables not needed. If it contains errors it will not be rendered.

Thanks to all for the suggestions.
> 0 votes

# Answer
After making a complete test of the process, I find that the solutions proposed do not work in this case. The offline maintenance mode maybe is conceived for the situation when the database is not reachable or the connection is lost. But when I run the complete process of restoring the database, I first see the especial customized page, after several seconds a complete blank page, after some more seconds a "The website encountered an unexpected error. Please try again later." error and finally, when the mysql restore is complete, the working site. So this promising solution proposed by some users has failed completely.
> 0 votes

---
Tags: 7, database, maintenance-mode
---


# Question
Title: How make a template for designer for user registration?
I am looking for a "user-register-form.html.twig" for custom position of field in the page with twig.

This is what i would like for the designer :

```
<div class="row">

  <div class="col-md-6">
    {{ form.field_name }}
  </div>

  <div class="col-md-6">
    {{ form.field_surname }}
  </div>

</div>

```

Someone know how to make a custom user form template ?

# Answer
> 1 votes
Your approach is good, you just need to add the `{{ form|without('field_name', 'field_surname') }}` at the end of the file. And the file would be more like a form--user-register.html.twig since it is a form so that is the first keyword. The issue with this is that it won't look like you would like to since you would have to position all fields from the form on proper places and make sure you get all of them which makes is quite tricky if you would remove or add new fields to user profiles and make them dis/appear on the registration form.

Depending on the outcome you are looking for there are a multiple ways of achieving the goal. You could alter the form and wrap specific fields in a custom theme handler, processor or after builder, or you could alter the builded render array, etc...

---
Tags: 8, theming
---


title: Multipage form not multistep

text:
# Question
Title: Multipage form not multistep
Can anyone help me to make multipage form not multistep. Suppose On front page i have two fields select service and select location and a button and after selecting both clicking on button opens a new form on new page.

# Answer
> 1 votes
You can use Webform module and create multiple separate forms.

On submission of first (on front page), you can redirect users to another page (another webform) based on their selection using custom redirect in webform settings and tokens `[submission:values:?]` that use data from webform that has been submitted. You just have to set "key" on selects in your form properly.

---
Tags: forms
---


title: node_access by specific role?

text:
# Question
Title: node_access by specific role?
I am trying to build a list of node ids that have view access for a specific role. Is this at all possible? I currently have an array of all 'page' content type nodes "pages".

I now need to loop through these and see if they have a specific role enabled, if so get the id and display the link on a page if the user has access to that page.

I know I can do that using the following example. But this just checks if the user has view access, and the user could have access from another role they have which my list would not be accurate for what I am trying to achieve.

```
if(node_access('view', $nodeid, $user)){
    // do something
}

```

Or is there a way to check if a specific users role has view access rather than just access in general.

The reason I am trying to do this, is I am trying to get the list of specific pages dynamically if a role is given to that node "page".

Sorry if my terminology is off I am not super familiar with drupal.

# Answer
This is what I ended up using, it could probably be optimized a bit but it works.

```
<?php
if ($node = menu_get_object()) {
  // Get the nid
  $currentNode = $node->nid;
}
if (in_array("Gold Member", $user->roles)) {
    echo '<div id="title"><h1 class="title display">Free Courses for Gold Members</h1></div>';

    echo '<ul class="course_page_ul">';
        $role_type = 'Gold Member';// Texas Member
        $getRole = db_query("SELECT rid FROM role WHERE name = '%s'",$role_type);
        while ($roleid = db_fetch_object ($getRole)) {
          $roleids[] = $roleid;
        }
        //Get the ID of the role type we are using from the array
        foreach($roleids as $roleId){
            $role_id = $roleId->rid;
        }

        $node_type = "page";
        $result = db_query("SELECT * FROM node WHERE type = '%s'", $node_type);
        $nids = array();
        while ($obj = db_fetch_object ($result)) {
          $nids[] = $obj;
        }

        $idsToInclude = array();
        foreach ($nids as $pageId) {
            $page_id = $pageId->nid;
            $realm = 'content_access_rid';// content access
            $grant_view = 1; // Has view
            $result = db_query("SELECT * FROM node_access WHERE nid != '%d' and nid = '%d' and gid = '%d' and realm = '%s' and grant_view = '%d'",$currentNode, $page_id, $role_id, $realm, $grant_view);

            while ($obj = db_fetch_object ($result)) {
              $idsToInclude[] = $obj;
            }
        }

        //var_dump($user->uid);
        //var_dump($nids);

        foreach($idsToInclude as $id){
            $courses = $id->nid;
            $nodeid = node_load($courses );
            if(node_access('view', $nodeid, $user)){
                echo '<li class="course_link"><a href="/node/'.$courses .'" title="">'.$nodeid->title.'</a></li>';
            }
        }
    echo '</ul>';
}

?>

```
> 1 votes

---
Tags: 7, theming, users
---


# Question
Title: How to remove author name from blog post url?
When a user publishes a blog post the user's name is included as part of the blog link or url:

> www.example.com/blogs/**author**/post-name

What I want is that:

> www.example.com/blogs/post-name

**How can I remove that author name from the url?**

# Answer
> 0 votes
It can be fix by using URL aliases in your drupal site. go to **admin/config/search/path/patterns** in that you can able to see text box as **Pattern for all Blog entry paths** in that change the pattern as **blogs/\[node:title\]** and use can able to use different tokens to change the patterns.

After configuring the pattern you need to update the url aliases in the content panel then only it will get the update to blog content type...

# Answer
> 1 votes
For **Drupal 6**; you can go to **admin/build/path/pathauto** page and change URL alias pattern for Blog content type (under Node paths settings).

You can make it **blogs/\[title-raw\]** or anything else you want.

**Note**: The picture above shows how to do change URL pattern. But, the URL pattern isn't what you want. The URL here something like that: term/blog-post-13.html.

# Answer
> 0 votes
It can be done by changing URL alias pattern for "Pattern for all Blog paths" to "blogs/\[title-raw\]" here "admin/build/path/pathauto" in "Node paths" fieldset

---
Tags: 7, uri
---


title: Define variables for template files

text:
# Question
Title: Define variables for template files
I am trying to move the first chunk of code including the PHP logo call, and the breadcrumbs into the header region. I have created the block, and made it capable of reading PHP. I understand I need to write a preprocess function in template.php, but I am not sure how this is done. I am working in Drupal 7.

Can anyone show me an example, and explain how this works, or point me in the right direction?

# Answer
> 4 votes
Defining a variable in a `template_preprocess()` function is straightforward:

```
/**
* Implements hook_preprocess().
*/
function yourthemename_preprocess(&$variables, $hook) {

    $variables['your_variable_name'] = "some value";

}

```

In your template file, you would just output it directly, for example using the following code:

```
<?php print $your_variable_name; ?>

```

I'm not sure this answers your real question, but I could use a little more information. Why are you trying to move the logo/breadcrumbs using a preprocess function? Which theme are you using? If you're moving these around, it is usually easier to just edit the page.tpl.php file in your theme, and work with them from there.

# Answer
> 3 votes
**Just an addition to your answer:** Depending on the use case, you have to use a more granular preprocess hook. Using the hook in your example, the page performance seems highly decreased. And it does not work for me in the page.tpl at all.

This work´s for me:

```
function THEMENAME_process_page(&$variables) {
  $variables['your_variable_name'] = "some value";
}

```

---
Tags: 7, theming
---


title: Create node content from external HTML

text:
# Question
Title: Create node content from external HTML
After a few attempts browsing the web, I don't figure out how to download HTML from a given url, and create node content from it.

What I would achieve is quite simple :

* Have a link-like field in my content type
* The source code of this page is downloaded either in the `Body` of the content, either in a MHT-like file
* Viewing the node displays it either in the `body`either\` in an IFrame.

The content creation would happen mostly from a dedicated script creating a new content through Drush, filling only the `Title` and the link field.

The main goal of this is to save short-lived webpages in a drupal website, and ideally being able to index them.

I'm open to any ideas : module, coding, whatever. Don't hesitate to give me advice !

Thanks

# Answer
This would have to be done using a custom module. I do not know of a contributed module that would perform this. Probably because a module like this could be seen as a huge copyright infringement lawsuit waiting to happen.

But if I were to do this I would use GuzzleHttp as the engine to pull down the content. Then take that content and create a new entity using entity\_create(). Where you have to focus your efforts will be sanitizing the information you "guzzle" off the web so that you do not create security issues in your site from XSS, SQLi, or other vulnerabilities. The process would be triggered on node-save.

This is just the basic idea, I cannot explain how to write the entire module as that would be pages of content.
> 1 votes

---
Tags: 7, navigation, files
---


# Question
Title: How to always print submenus from menu module?
I'm using Drupal 7.35, with the stock menu module. I've set up a menu that has multiple submenus, and ran into something interesting: the submenus only are printed to HTML when you're on that menu's parent page.

For example, let's say this is my full menu:

```
- Link 1
  - Link 1.1
  - Link 1.2
- Link 2
- Link 3
  - Link 3.1
  - Link 3.2
  - Link 3.3
- Link 4
  - Link 4.1

```

Each submenu shows up only if you're on that menu's parent item. So, when you're not on any of those pages, the Menu is printed like this:

```
- Link 1
- Link 2
- Link 3
- Link 4

```

If you're on the Link 1 page, or any children thereof, it prints like such:

```
- Link 1
  - Link 1.1
  - Link 1.2
- Link 2
- Link 3
- Link 4

```

If you're on Link 4, it looks like this:

```
- Link 1
- Link 2
- Link 3
- Link 4
  - Link 4.1

```

I want all the menu items to always be printed. How do I do that? Is this normal behavior, because I'm pretty sure I didn't have this issue on the other Drupal site that I've worked on.

# Answer
> 1 votes
One of the solution is to use Menu Block. It allow you to display any menu items based on depth. So you have all the control. To list all the menus, in Menu Block you can change the "Maximum depth" to Unlimited.

--- **Updated 07/06/15 10:25am** ---

You may need to use the Advanced options in your situation. Then check the "***Expand all children of this tree***". See below screenshot for details.

---
Tags: routes, navigation
---


# Question
Title: Domain Access + Domain i18n = Site names not translating in other languages?
I have 4 languages and 2 domains: site.com site.eu I set up languages in these domains like:

* site.com - english (default)

br.site.com - brazilian

site.eu - german

fr.site.eu - french

When I try to type Site Name for french and brazilian it does not save the line. but it save Slogan. So Drupal use default site name of default language for both Brazilian And French sites: br.site.com and fr.site.eu

this instruction did not help me http://reyero.net/drupal/internationalization\_domain\_access\_multilingual\_variables\_for\_each\_domain

There are Realms information that I've found. But how to configure correct I do not know.

# Answer
I'm assuming you're using the "Domain Access" module. And even though you didn't explicitely mention it, you also use the i18n module. If my assumptions are correct, then be aware of what's mentioned on the project page of the "Domain Access" module:

> If you use the contributed i18n module suite, you should use the Domain Variable module instead of the provided Domain Configuration and Domain Settings modules.

Therefor I think you should try the Domain Variable module, to check if it fixes you issue.
> 0 votes

# Answer
i fixed with this:

1. add all the domains you have to the domains: so not only site.com and site.eu but also br.site.com and fr.site.eu and all others subdomains
2. set up in the every domain settings need name.

and think i've found one more method:

in domain access settings admin/structure/domain/settings there is checkbox: Override site name with name of domain.

when i uncheck this the site name translations started work!
> 0 votes

---
Tags: i18n-l10n, domain-access
---


# Question
Title: Where is the button that will translate all countries from Countries module in all my 10 languages?
After installation of Countries module I rest only 15 countries that I've translated one by one with Google Translate and my hands.

It's a pity cause my site is viewing and using in other countries too. But I need the automatic translation of country list in 10 site languages.

There is one more question that does not have an answer: How to translate all the country names provided by the Countries module in one shot?

And google also shows this: https://www.drupal.org/node/2096581 But if I try to upload this translations it does not change anything cause by default language is russian.

One professional developer said that here I can get de database http://dev.maxmind.com/geoip/geoip2/geolite2/ and using https://www.drupal.org/project/smart\_ip I can translate my list of countries. But I do not believe in my power.

Please let me know if I can have solution of: How to translate countries list in several languages?

# Answer
> 0 votes
For large tasks like this consider automating. and not just using "Drupal". Can you make a CSV file of your countries list? Then write a small Bash, PHP, Ruby or any script to ask Google for the translation(s) 1 by 1. Then given your new big CSV file of English + 10 other columns of languages. Loop through the file rows and do a database insert to Drupal to create the translations ...

From the final CSV of country terms translated I would then try to use the Feeds or Migrate module to import them to Drupal, if I didnt want to write much code.

---
Tags: i18n-l10n
---


title: View translation path

text:
# Question
Title: View translation path
I have a View with an path like **example.com/en/news**. I translated the view with Views translation. Works like a charm. But how and where do I translate the path to something like **example.com/de/neues**?

# Answer
An alternative would be to use i18n\_page\_views module - it is a display plugin that installs an item labeled `i18n page` into the **+Add** (display) button menu. It's like a `page` display extended by fields for entering a path for each enabled language.

While it does not offer any tool to convert existing displays into i18\_page type, it's quite easy to do that manually - just export your existing view(s), change the type of the display in a notepad and re-import w/override.

Regretfully, the module does not offer UI for creating translated menu items - this also has to be done manually.

At any rate, it's advisable to bind all translation paths (created manually as jdu suggested, or created automatically) into a translation path set (`admin/config/regional/i18n_translation/path/add`). I found that without it the `i18n_get_path_translations` function worked whimsically.
> 1 votes

# Answer
a very simple way would be to add a new alias yourself by accessing "/admin/config/search/path"

however, if you have translation set up correctly, that path should already exist. I think maybe your translation set up is done in a non-standard way. could you describe it in detail?
> 1 votes

# Answer
Use the Path Translation module.
> 0 votes

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


# Question
Title: Is there any alternative to devel themer?
I am using Theme developer module for theming. The module is pretty good, but still it is very buggy. Is there a less buggy alternative?

# Answer
> 29 votes
Not really.

Since Drupal 7.33 release there is now simple support for alternative template support and themeing function alternatives listing in Drupal (core) by adding a setting in `settings.php`.

> Added a "theme\_hook\_original" variable to templates and theme functions and an optional sitewide theme debug mode, to provide contextual information in the page's HTML to theme developers. The theme debug mode is based on the one used with Twig in Drupal 8 and can be accessed by setting the "theme\_debug" variable to TRUE (API addition).

So in settings.php you set:

```
$conf['theme_debug'] = TRUE;

```

Then view the source of your page and you will see comments in your HTML as `<!-- THEME DEBUG -->` that list out function and template suggestions for the current Node.

Example Output for `/admin/structure/views`:

```
<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--admin--structure--views.tpl.php
   * html--admin--structure.tpl.php
   * html--admin.tpl.php
   x html.tpl.php
-->
... lots of HTML ...
<!-- THEME DEBUG -->
<!-- CALL: theme('region') -->
<!-- FILE NAME SUGGESTIONS:
  * region--page-top.tpl.php
  x region.tpl.php
-->
<!-- THEME DEBUG -->
<!-- CALL: theme('toolbar') -->
<!-- BEGIN OUTPUT from 'modules/toolbar/toolbar.tpl.php' -->

```

This is a backport of Drupal 8 Twig helper functionality built into Drupal 8 (largely I guess because devel\_theme has no Drupal 8 release).

---
Tags: debugging
---


# Question
Title: How to translate the URL alias (path) for an English version to an Arabic version?
I have a dual language site (English and Arabic). In the English version I added a URL alias: `projects/commercial`.

But I can't find a way to have that translated to the Arabic version. I need that because the path is used by a breadcrumb module.

Any suggestions?

**Edit**: I am using pathauto, but my problem is that the URL is for a view that lists certain projects based on contextual filters. So I added the alias projects/commercial instead of projects/7 the breadcrumb works fine in English but not in Arabic

# Answer
> 2 votes
# For URLs related to nodes, users or taxonomies

Consider using the Pathauto i18n module for this. Excerpt from its project page:

> ... by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

This module contains 3 submodules which can be used to enable separate functionality for each entity:

* pathauto\_i18n\_node (for nodes).
* pathauto\_i18n\_user (for users).
* pathauto\_i18n\_taxonomy (for taxonomy).

**Example (also from project page)**:

When you create node without pathauto\_i18n:

* English alias: en/articles/first\_article
* Italiano alias: not exist
* Deutsche alias: not exist

When you create node with pathauto\_i18n:

* English alias: en/articles/first\_article
* Italiano alias: it/articolo/first\_article
* Deutsche alias: de/artikel/first\_article

# For URLs related to views or panels

Use the `i18n_path` (Path Translation) sub-module of the i18n module. Refer to its Community documentation for more details about it.

# Answer
> 1 votes
Maybe the Path Translation module could help? Excerpt from its community documentation:

> The Path translation module, part of the Internationalization (i18n) package, allows you to map together existing pages that are translations of each other. This will allow users to use the language switcher to navigate between the associated pages.
>
> The module is meant to be used as a last resort to translate paths that can't otherwise be mapped together as translations. For example, paths to translated nodes can already be linked with the Content translation module and paths to translated taxonomy terms can be linked with the Taxonomy translation module. Path translations should be used to link generic paths, such as those provided by Views or Panels.

# Answer
> 0 votes
If you are using pathauto module, this could be easily taken care of.
In my site, I have two languages : English and Spanish Enabled. Pathauto is configured to use the path `content:[node:title]`.
I created a node in English with title "Transliteration", the URL to the page was : `http://mysite/content/transliteration`.
I then went ahead and translated the content to Spanish. The path to the node became : `http://mysite/es/content/transcripción`.
So, pathauto will honour the changes, if you use the translated node title as a token.

There are other ways to translate breadcrumbs in any site. I prefer using Path Breadcrumbs module. It has a `Path Breadcrumbs Translation` sub module which helps in translating breadcrumbs.

---
Tags: i18n-l10n, path-aliases
---


title: Get an item in a list of taxonomy

text:
# Question
Title: Get an item in a list of taxonomy
Hello Drupal Community,

I am creating a menu which has a link to an "editorial". I created a taxonomy named "edito" and created articles (content type) that are tagged with this taxonomy.

I need to recover the last article tagged with this taxonomy in the menu as a link (see image attached). Does anyone have an idea of how to achieve this ?

Thanks,

# Answer
> 1 votes
You should not try to hard-code the URL to the item in the menu item edit screen.

You should add a View to your Menu.

Views allows you create a view including a filter to show only recent content.

You can then add a filter for a specific Content Type, User or whatever. And you can limit the View to show only `N items`.

You can insert the View of new items into your menu with the help of 3rd party modules, an example is Menu Attach Block, see the project page for a list of similar helper modules.

---
Tags: routes, tokens
---


title: Keyboard hotkey for "Flush all caches"?

text:
# Question
Title: Keyboard hotkey for "Flush all caches"?
Is there any easy way to create a **keyboard hotkey** to flush all caches in a Drupal site?, instead of going to Admin menu Drupal icon and click that time and again? Thx.

# Answer
> 3 votes
If you've enabled the search bar component on Admin menu you can search your way to it.

1. Enable the Search Bar component on the configuration page (**/admin/config/administration/admin\_menu**).
2. Type "flu.." or enough characters to list only the "Flush all caches" menu item.
3. Press the tab key to highlight and the enter key to trigger the "Flush all caches" menu item.

# Answer
> 2 votes
Devel module also has such feature , you can access that link by enabling module and placing development block somewhere in your access .

Devel has many other facilities for working with drupal .

---
Tags: caching
---


# Question
Title: How do I add typekit fonts to a D8 theme?
Having looked over the existing D8 documentation on adding JS to the `<head>` of a page, I'm still not sure how to go about it?

What is the correct way to achieve this on every page for my theme:

```
<script src="//use.typekit.net/abc0abc.js"></script>
<script>try{Typekit.load();}catch(e){}</script>

```

Regarding inline JS, from the latest D8 documentation:

> In the case of front-end/styling (e.g. hosted font services), the JS belongs in the theme. Put the JS directly in your html.html.twig file. In the case of fonts, this will also allow you to put it right in the place that gives you the best (and fastest) end user experience, because it allows you to prevent a FOUT (Flash Of Unstyled Text) while the font is still loading (fonts loaded through JS must be listed in the HTML before the CSS)!

So, I guess the inline JS goes directly into `html.html.twig`, but what about the external file?

I have this in my theme files, but it's not adding the external file to any pages:

mytheme.info.yml

```
libraries:
  - mytheme/typekit

```

mytheme.libraries.yml

```
typekit:
  version: 1.x
  js:
    //use.typekit.net/abc1abc.js: { type: external }

```

# Answer
For put the library to the header you must user `header: true`, then:

mytheme.info.yml

```
libraries:
  - mytheme/typekit

```

mytheme.libraries.yml:

```
typekit:
  version: 1.x
  header: true
  js:
    //use.typekit.net/abc1abc.js: { every_page: true }
    js/custom.js: { every_page: true }

```

js/custom.js:

```
try {
  Typekit.load();
}
catch(e) {
}

```
> 3 votes

---
Tags: theming, 8
---


title: Rewrite Output of Date/Time Field

text:
# Question
Title: Rewrite Output of Date/Time Field
Currently I have a Date/Time field that outputs in a Block View as:

```
Friday, April 25, 2014 - 4:00pm to 6:00pm

```

But i would like to output it as something like this:

```
Friday, April 25th from 4pm to 6pm

```

I was hoping that I would be able to do this by changing the way that the field outputs in the `Rewrite Output` option, but I did not find a way to get the the right machine names of the field I need to parse everything out as planned.

Does anybody have any other better ideas that would possibly work for this? Thank you!

# Answer
> 1 votes
Drupal 7 allows you to create custom date formats on your configuration page under "regional and language" "date and time." Once in admin/config/regional/date-time click the "Formats" tab. Then click "add format." You can now define custom dates using the variables available on the PHP date website. The drupal config page includes a link to the PHP date website as well.

I believe the output you are looking for would be: l, F dS, Y - ga (values from the PHP date website)

Once saved go back to the date and time config page and click "Add date type." Type in a name for your new display and select your new format.

In views you can now select the new custom date format you just created as your output.

# Answer
> 1 votes
If you are using a view the best thing you can do is utilize what is already there.

Date formats `/admin/config/regional/date-time/formats/add` . After creating your Date formats you can assign them to a human readable name at `/admin/config/regional/date-time`

Here is the PHP Manual for formatting dates. play around with it. there is a live preview in drupal it's way easier then it seems.

1. You can add a date format for `Friday, April 25th`, a format for `4pm` and a date format for `6pm`. The reason you need 3 date formats is because you cannot add phrases like **from** into a date format string.
2. Now that you have 3 date formats you can add your date field 3 times in the view.
3. Assign the first date value the date-format of `Friday, April 25th`, the second as `4pm` and the last as `6pm`.
4. for the last two date fields, exclude them from display and move them above the first date field in the `re-arrange fields`.
5. Rewrite the first date field to be:

`[YOUR_date_field_1] . ' from ' . [YOUR_date_field_2] . ' to ' [YOUR_date_field_3]`

6. This will output your desired date field `Friday, April 25th from 4pm to 6pm` the **PROPER WAY**

# Answer
> 0 votes
What I ended up doing was manipulating the view field, by grabbing the `.tpl.php` file from the `views/theme` directory called `views-view-field.tpl.php` and then copied it into my theme directory as `views-view-field--field-event-date.tpl.php`.

There I changed the `print $output;` line and changed it to:

```
$stuff = explode(" - ",$output); // Array ( [0] => Friday, April 25th [1] => 4pm to 6pm )
print $stuff[0] . ' from ' . $stuff[1];

```

Unfortunately, I am not sure if this is the correct way of going about all of it, but it does seem to do the trick. I also do not see any immediate threat of hurting anything else because it is only changing that specific field in that view. I will not mark this answer as correct only because I do not believe this would be the correct `Drupal Way` of going about this, but it did work for me.

Please let me know if anyone has any better ideas. Or if anyone thinks that this is a suitable way. Thanks!

---
Tags: 7, views, datetime
---


# Question
Title: How to make view mode available only to selected bundle?
I have three taxonomy vocabularies which means that I have three bundles of the vocabulary entity type. I have a few view modes for them and one of them has to be available only to one of those vocabularies.

The method responsible for getting available view modes is `\Drupal\Core\Entity\EntityManager::getAllDisplayModesByEntityType()` but it does not distinct between bundles, only entity types.

Is there a way I can make that view mode restricted for that one particular vocabulary or this is just not possible?

# Answer
> 0 votes
No, there is not. A view mode is not bundle-specific.

That hardly matters, because a view mode doesn't do anything unless you actually enable it and configure field formatters for it, resulting in a view display. If you don't then it just falls back to the default view display.

---
Tags: 8, entities
---


# Question
Title: As a site builder, how can I learn when modules I use are (going to be) deprecated?
I have a site that uses a relatively large number of modules (100+). I do my best to keep up-to-date but recently I have become a little alarmed because I found that Heartbeat and Custom Breadcrumbs, two modules I use on my site, are likely to be deprecated in the near future.

I learned about Heartbeat's deprecation by visiting the module's page by chance when I was checking the documentation. I learned about Custom Breadcrumbs possibly being deprecated from a comment here on *Drupal Answers*.

At the time I installed these modules (early last year), they were the most popular in their respective categories. Heartbeat's maintainer was active and making releases every few weeks.

Now, a year later, they are being deprecated in favor of other modules. I understand the reason for this, and I'm happy to migrate my site over to the replacement modules (well, maybe not happy, but I'll do it)-- however, I can't do this if I'm not informed that modules are going to be deprecated. I only found out about these two by chance!

Is there any central resource that keeps track of deprecated modules? Since I use so many, checking issue queues or even module's pages is not really a feasible option.

# Answer
> 6 votes
You could subscribe with RSS to tag data on projects such as:

That can give you notice of deprecation assuming the relevant tag has been assigned to the project.

# Answer
> 1 votes
# There is a module for it

I'm assuming that this question is about D6 (possibly even still D5?). In that case, apart from the prior answer, you may want to look at the "Upgrade Status" module also. Here is an excerpt from its project page:

> ... checks the list of projects you have installed and shows their availability for the new version of Drupal core, which can be one of the following:
>
> * **Available**: A stable release of this project is available.
> * **In development**: A development release of this project is available, which can be installed for testing purposes.
> * **Not ported yet**: There are no releases available for this project.
>
> Clicking on any of the modules' boxes will show you notes about upgrading the project, as well as a link to download the new version.

I've used it on quite some D6 sites in the past (to get an idea of the feasibility to upgrade all contributed modules to D7). It worked great.

By the way, there is a D7-dev version of this module also, so I'm assuming that's a good sign for whenever D7 tp D8 is on the horizon ...

# Use the data on Drupal.org

Some more pointers to some other questions that I beieve might help aso to answer this question here:

# Bonus tip

Even though not part of this question here, often times when you're considering upgrading you also want to have an idea of "Are there any tweaks (hacks) in any of our contributed modules that we need to be aware of?". Especially if somebody else first created the D6 site, and you're in charge of the D7 upgrade. Guess what, there's a module for it, it's called Hacked! ... Great module also I think ...

---
Tags: 7
---


# Question
Title: How can I use session variables in a report created with the Forena module?
I've installed Forena Reports. It's basically working, but I have some questions (see bottom of post to get right to it).

### What I want to accomplish is the following

I want an anonymous user of the module page to be able to export their recommendations as a CSV file with a link like 'download now' or something.

Here's the staging environment for the tool I'm talking about, so you can see how it works: http://staging.grantstation-pathfinder.com/pathfinder.

### So, as you can see, here's what I have so far

I have a custom module that's a multi-step form. The module prints out each page of the form. The user selects one option on each page (3 pages total) and on the final page submits the form. The module then redirects the user to a 'recommendations' page (page 4 - modulename/recommendations) where some custom SQL prints out to the page recommended resources for that user based on their selections in the form.

The values the users select are saved in session variables.

Here's how those variables get stored as sessions in the form itself. (This is the second page of the form, but they are all basically the same.)

```
function pathfindertool_first_form($form, $form_state) {
 // .. some code, some other fields, directions, etc.
        '#default_value' => isset($values['role']) ? $values['role'] : NULL,
        '#options' => array(
        t('Grant Writer'),
        t('Nonprofit Administrator'),
        t('Nonprofit Founder'),
        t('Consultant'))
    );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
      );
      return $form;
    }

    /**
     * Submit handler for the first form.
     *
     * @see pathfindertool_first_form() above
     */
     function pathfindertool_first_form_submit($form, &$form_state) {
      $values = $form_state['values'];

      // Save values to the form storage, add the next step function callback
      $form_state['rebuild'] = TRUE;
      $form_state['storage']['role'] = $values['role'];
      // submit code
    }

```

On the recommendations page I call SQL and use the session variables to determine which recommendations to display to users.

Here's how I set the session variables and redirect the users to the recommendation's page.

```
$form_state['storage']['topic'] = $values['topic'];
// set session variables to be used on recommendations page
$_SESSION['role'] = $form_state['storage']['role'];
$_SESSION['level'] = $form_state['storage']['level'];
$_SESSION['topic'] = $form_state['storage']['topic'];
// when user clicks 'submit' redirect them to recommendations page
$form_state['redirect'] = 'pathfinder/recommendations';

```

I successfully installed and configured the Forena module, and it displays my tabular data from the SQL file I created with the parameters I manually set. The CSV download works too. That's all fine.

How do I ensure the Forena modules uses the session variables set by the user in the multi-page form (and not my predefined parameters)?

# Answer
I'm not (yet) sure about this one, because of the "*session variables*" that aren't clear enough to me (yet) ... Below are a few techniques (features) that you may want to consider to get it to work.

# 1. Using JavaScript and/or Skins

A possible solution "might" be to think of some technique you can implement via a JavaScript. And then make that JavaScript available via what in Forena is called "skins" (used for e.g. *theming* a report, like to enable the 'DataTables' plugin if you want, etc).

There are some "interesting" issues in the Forena issue queue with some great examples (ideas) of things you can do (add to Forena) via JavaScripts and/or Skins. HEre are a few of them:

# 2. Specifying Report Parameters as part of the URL

*Report Parameters* are similar to using *arguments* in Views. You can specify them as part of the URL, by first adding a `?`-mark, followed by the name of the report parameter, a `=`-sign, and then the parameter value. So something like `?state=VA` that you append to the report URL.

To see it at work in the demo site, try this example which uses `?state=VA` (watch the URL of it also). Then change the end of the URL to something like `?state=IL`, `?state=CA`, etc. To be complete, you can also specify multiple parameters (+their values) in an URL.

So if you have a way to massage those session variables in a such string added to the URL, then the answer to your question is something like "*pass them as report parameters via the URL*".

# 3. Other approaches

If what is above won't work, then please add more details about those "session variabes" (so that I can refine/rework my answer accordingly).

And if we don't find a real answer, then its time to experience the "support" that comes with Forena, via its issue queue on D.O. ... After all, keep in mind that I'm only a co-maintainer of this module. When I'm stuck (or out of Forena-inspiration), I escalate such questions/issues to David (the module owner and creator or Forena).
> 3 votes

---
Tags: 7, log-messages, forena
---


# Question
Title: Adding a form to Views Bulk Operation for configurable operations
I have a view with a list of nodes that I want to operate with, but I need additional user input for the function. Until now, I have been handing this by having many similar, but slightly different 'Execute arbitrary PHP script' actions. Is there any way to add a sort of form to accept user input other than the nodes to operate on?

# Answer
Instead of running a PHP script. You would have to create a custom module and a custom `Action`. The action may be configurable (requiring a Form) and you can check the form for errors before proceeding.

An example template of what would go into your .module file can be seen at ( am not the author): http://dropbucket.org/node/841

In case that website is taken offline, here is the code sample, which I believe to be self explanitory:

```
/**
 * Implements hook_action_info().
 */
function custom_action_info() {
  return array(
    'custom_action_callback_name' => array(
      'type' => 'entity', // Can be file, term, user, etc.
      'label' => t('Your label'),
      'configurable' => TRUE, //  Needs config form
      'behavior' => array('view_property'), // Uses view access rights
      'triggers' => array('any'), // Works always
    ),
  );
}

/**
 * Return a form definition so the action can be configured.
 */
function custom_action_callback_name_form($context) {
  // Set default values for form.
  if (!isset($context['recipient'])) {
    $context['recipient'] = '';
  }

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#default_value' => $context['recipient'],
    '#maxlength' => '254',
    '#description' => t('The email address to which the message should be sent OR enter [node:author:mail], [comment:author:mail], etc. if you would like to send an e-mail to the author of the original post.'),
  );

  return $form;
}

/**
 * Validate custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient'])) {
    form_set_error('recipient', t('Enter a valid email address.'));
  }
}

/**
 * Process custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_submit($form, $form_state) {
  $form_values = $form_state['values'];
  // Process the HTML form to store configuration. The keyed array that
  // we return will be serialized to the database.
  $params = array(
    'recipient' => $form_values['recipient'],
  );
  return $params;
}

/**
 * Add action callback where you perform the action.
 */
function custom_action_callback_name($entity, $context) {
  // Do the magic here.
}

```

**EDIT**

If you just want VBO validation rules and no form for your action, look at VBO Validation which supplies easy to use Hooks.
> 0 votes

---
Tags: forms, views
---


# Question
Title: Can you prevent a module from being disabled?
Is there any way to prevent Admins from disabling a module. Is there anything that can be done via code?

# Answer
> 4 votes
If you're looking for a per-module solution, add the required property to its .info file.

> As of version 7.x, modules and themes may specify that they are absolutely required and should never be disabled by adding required = TRUE. These modules will be enabled automatically during install. In most cases it should only be used with the Drupal core required modules (e.g. Node, User, etc.).

# Answer
> 1 votes
No code is necessary to do this. You can setup appropriate permissions for your "admins". Create a new role for these individuals that gives them all the rights they need minus the "Administer modules" under "System".

---
Tags: 7, installation
---


# Question
Title: Two levels of options in add to cart form
I am working with a project of sofas. Clients can choose the size and the fabric. In each fabric there are several colours. What I need is that the client chooses the fabric and then the form shows the colors of the selected fabric so the cliente can choose too. Is that posible?

# Answer
> 0 votes
This is not how Drupal Commerce normally works w/ attributes - you typically define all of the possible variants as SKUs, associate them all together on the Add to Cart form, and show a form with both attribute select lists shown at once. You can alter that form to your heart's content, though, hiding one select list until another is adjusted - but note that Drupal Commerce also doesn't support an attribute not having a selection out of the box. This is a technical limitation of how the form is designed to work, but there is an open issue in the queue trying to support that.

---
Tags: commerce
---


# Question
Title: Hide zip in addressfield form on commerce checkout pane?
How can I hide some fields from addressfield module (for example zip code) on checkout process if certain country is selected? E.G. If US country selected then hide postal code field. If CA country selected then show postal code.

# Answer
> 0 votes
Clive is correct. The module already adjusts the form as appropriate. If you aren't seeing this, you must have something interfering with the Ajax based update of the form element.

---
Tags: hooks, forms, commerce
---


title: Webform formatting question

text:
# Question
Title: Webform formatting question
I'm running Drupal 7.34 and Webform 7.x-4.9/Webform Layout 7.x-2.2.

I've put together a webform to be used for customers to fill out their data. If I select Label Display "Above", it disappears and no labels show. If I set it to "Inline" it works better, but the spacing is goofy (see link).

How do I set it so that the "Above" label display works, and how do I control setting up the spacing (so that I can have only one on a line)?

Thanks in advance for any help you can provide.

# Answer
This looks like a CSS issue with your template rather than a Webform/Drupal issue.

The webform module adds a default ".form-item" class to the wrapper DIV around each form element.

Try adding "clear:both;" to that class to force the form elements to vertically stack. Something like this:

```
.form-item {
   clear: both;
}

```
> 1 votes

# Answer
The webform module generates general form markup but it's up to your theme to display it. If your theme is not displaying forms correctly, you can either:

* Switch to a different theme.
* Use your browser's console to inspect elements and add some css to fix their positions.
> 0 votes

---
Tags: webforms
---


# Question
Title: How do I create a link to a view in Commerce Order listing?
I want to create a link on an order dropdown menu in commerce order that is attached to a view. So for example, when you are looking at the list of orders, there is a drop down menu which has Quick Edit, Payment, Delete, etc. I want to another element to this drop down menu which points to a view that I have created.

I have successfully added a link this dropdown menu using the following code, but it links to a form.

```
$items['admin/commerce/orders/%commerce_order/cancel'] = array(
    'title' => 'Cancel',
    'page callback' => 'bh_order_handling_ui_order_cancel_form_wrapper',
    'page arguments' => array(3),
    'access callback' => 'bh_order_handling_ui_cancel_access',
    'access arguments' => array(3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
    'context' => MENU_CONTEXT_INLINE,
);

```

What I want to do is link to a view that I have created at the path admin/commerce/orders/%/takehomeitems.

I have tried the following, using suggestions from http://zufelt.ca/blog/embedding-view-menu-hook-drupal

```
$items['admin/commerce/orders/%/takehomeitems'] = array(
        'title' => 'Take Home Items',
        'page callback' => 'views_embed_view',
        'page arguments' => array('bh_view_customer_donation_line_item','default',3),
        'access callback' => 'bh_donate_takehomeorder_access',
        'access arguments' => array(3),
        'type' => MENU_LOCAL_TASK,
        'weight' => 10,
        'context' => MENU_CONTEXT_INLINE,
        'file path' => drupal_get_path('module', 'views'),
        'file' => 'views.module',
);

```

# Answer
> 1 votes
I needed to call views\_embed\_view in my own page callback because I needed to pass the commerce order id for my contextual filter. Here is what I did:

I first defined the menu item. Note that the path has %commerce\_order instead of just %. This is needed to access the order object which has the id.

When creating the view, I put in in a separate path, not the path I used for the $items. When I tried to use the same path, it didn't work. I think it is because the $items path is needed to create the listing in the dropdown menu.

I defined the path of my view as something that was not admin/commerce/orders/%commerce\_order/takehomeitems It is important that your view have a contextual filter which takes the order id. My path was /admin/hubadmin/takehomeitems/%

See the bottom of my posted answer for the exported view example.

Then in hook\_menu, i defined the following:

```
 $items['admin/commerce/orders/%commerce_order/takehomeitems'] = array(
   'title' => 'Take Home Items',
   'page callback' => '_bh_donate_takehome_lineitems',
   'page arguments' => array(3),
   'access callback' => 'bh_donate_takehomeorder_access',
   'access arguments' => array(3),
   'type' => MENU_LOCAL_TASK,
   'weight' => 10,
   'context' => MENU_CONTEXT_INLINE,
 );

```

I then defined the page callback which calls views\_embed\_view and by passing in the %commerce\_order, I am able to get the order id

```
function _bh_donate_takehome_lineitems($order) {
  return views_embed_view('YOURVIEWNAME', 'YOURDISPLAYID', $order->order_id);
} //DISPLAYID is usually default. To find this out, choose to export your view and look at $handler = $view->new_display('default', 'Master', 'default'); The last parameter is the display id.

```

This creates a item in the dropdown menu of the order which links to a view. The breadcrumb path points to the order.

Here is my exported view that worked for an example.

```
$view = new view();
    $view->name = 'bh_view_customer_donation_line_item';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'commerce_order';
    $view->human_name = 'BH View: Customer Take Home Line Items';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'Customer Take Home Line Items';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'none';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['style_plugin'] = 'table';
    $handler->display->display_options['style_options']['columns'] = array(
        'vendor_user_reference' => 'vendor_user_reference',
        'commerce_product' => 'commerce_product',
        'quantity' => 'quantity',
        'commerce_unit_price' => 'commerce_unit_price',
        'commerce_total' => 'commerce_total',
    );
    $handler->display->display_options['style_options']['default'] = '-1';
    $handler->display->display_options['style_options']['info'] = array(
        'vendor_user_reference' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_product' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'quantity' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_unit_price' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_total' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
    );
    $handler->display->display_options['style_options']['empty_table'] = TRUE;
    /* Relationship: Commerce Order: Referenced line items */
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
    /* Relationship: Commerce Line item: Referenced products */
    $handler->display->display_options['relationships']['commerce_product_product_id']['id'] = 'commerce_product_product_id';
    $handler->display->display_options['relationships']['commerce_product_product_id']['table'] = 'field_data_commerce_product';
    $handler->display->display_options['relationships']['commerce_product_product_id']['field'] = 'commerce_product_product_id';
    $handler->display->display_options['relationships']['commerce_product_product_id']['relationship'] = 'commerce_line_items_line_item_id';
    /* Field: Commerce Product: Vendor User Reference */
    $handler->display->display_options['fields']['vendor_user_reference']['id'] = 'vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['table'] = 'field_data_vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['field'] = 'vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['relationship'] = 'commerce_product_product_id';
    $handler->display->display_options['fields']['vendor_user_reference']['label'] = 'Vendor ';
    $handler->display->display_options['fields']['vendor_user_reference']['element_type'] = '0';
    $handler->display->display_options['fields']['vendor_user_reference']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['vendor_user_reference']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['vendor_user_reference']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['vendor_user_reference']['field_api_classes'] = TRUE;
    /* Field: Commerce Line item: Product */
    $handler->display->display_options['fields']['commerce_product']['id'] = 'commerce_product';
    $handler->display->display_options['fields']['commerce_product']['table'] = 'field_data_commerce_product';
    $handler->display->display_options['fields']['commerce_product']['field'] = 'commerce_product';
    $handler->display->display_options['fields']['commerce_product']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_product']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_product']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['commerce_product']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_product']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_product']['type'] = 'commerce_product_reference_sku_link';
    $handler->display->display_options['fields']['commerce_product']['settings'] = array(
        'show_quantity' => 0,
        'default_quantity' => '1',
        'combine' => 1,
        'show_single_product_attributes' => 0,
        'line_item_type' => 'product',
    );
    $handler->display->display_options['fields']['commerce_product']['field_api_classes'] = TRUE;
    /* Field: Commerce Line Item: Quantity */
    $handler->display->display_options['fields']['quantity']['id'] = 'quantity';
    $handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
    $handler->display->display_options['fields']['quantity']['field'] = 'quantity';
    $handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
    /* Field: Commerce Line item: Unit price */
    $handler->display->display_options['fields']['commerce_unit_price']['id'] = 'commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['table'] = 'field_data_commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['field'] = 'commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_unit_price']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_unit_price']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['commerce_unit_price']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_unit_price']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_unit_price']['click_sort_column'] = 'amount';
    $handler->display->display_options['fields']['commerce_unit_price']['settings'] = array(
        'calculation' => FALSE,
    );
    $handler->display->display_options['fields']['commerce_unit_price']['field_api_classes'] = TRUE;
    /* Field: Commerce Line item: Total */
    $handler->display->display_options['fields']['commerce_total']['id'] = 'commerce_total';
    $handler->display->display_options['fields']['commerce_total']['table'] = 'field_data_commerce_total';
    $handler->display->display_options['fields']['commerce_total']['field'] = 'commerce_total';
    $handler->display->display_options['fields']['commerce_total']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_total']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_total']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_total']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_total']['click_sort_column'] = 'amount';
    $handler->display->display_options['fields']['commerce_total']['settings'] = array(
        'calculation' => FALSE,
    );
    $handler->display->display_options['fields']['commerce_total']['field_api_classes'] = TRUE;
    /* Contextual filter: Commerce Line Item: Order ID */
    $handler->display->display_options['arguments']['order_id']['id'] = 'order_id';
    $handler->display->display_options['arguments']['order_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['arguments']['order_id']['field'] = 'order_id';
    $handler->display->display_options['arguments']['order_id']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['arguments']['order_id']['default_action'] = 'empty';
    $handler->display->display_options['arguments']['order_id']['title_enable'] = TRUE;
    $handler->display->display_options['arguments']['order_id']['title'] = 'Order %1';
    $handler->display->display_options['arguments']['order_id']['default_argument_type'] = 'fixed';
    $handler->display->display_options['arguments']['order_id']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['order_id']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['order_id']['summary_options']['items_per_page'] = '25';
    /* Filter criterion: Commerce Product: Vendor User Reference (vendor_user_reference) */
    $handler->display->display_options['filters']['vendor_user_reference_uid']['id'] = 'vendor_user_reference_uid';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['table'] = 'field_data_vendor_user_reference';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['field'] = 'vendor_user_reference_uid';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['relationship'] = 'commerce_product_product_id';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['operator'] = 'not empty';
    /* Filter criterion: Commerce Line Item: Type */
    $handler->display->display_options['filters']['type']['id'] = 'type';
    $handler->display->display_options['filters']['type']['table'] = 'commerce_line_item';
    $handler->display->display_options['filters']['type']['field'] = 'type';
    $handler->display->display_options['filters']['type']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['filters']['type']['value'] = array(
        'product' => 'product',
    );

    /* Display: Page */
    $handler = $view->new_display('page', 'Page', 'page');
    $handler->display->display_options['path'] = 'admin/hubadmin/takehome-items/%';

```

---
Tags: views, commerce, routes
---


title: How to make FROM and TO filter?

text:
# Question
Title: How to make FROM and TO filter?
I have a height field for users.

How can I make a simple filter in views where visitors can search to and from?

Like:

Search users: From 150cm To 180cm

Thanks, Bruno

# Answer
You can do it from views itself from the filter criteria.

Or if in need of additional options try out the Better Exposed Filters

> The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience
> 3 votes

---
Tags: views
---


# Question
Title: How to add custom text settings to a custom theme?
I'm working on a custom theme called "YingYang". I didn't make the theme, but I have to do some stuff with it. The theme has custom text settings which is bassically some pre-set content.

It looks like this

**Now my question is: How can I create a new text setting for this theme?**

I've been searching for a while in the drupal UI and in the code, but I can't find anything about it.

Thanks!

# Answer
Right now this option in your theme is in configuration setting. I think they done it using some custom module. Edit the module file, add a new text area using following code..

```
 $form['name']= array(
'#type' => 'textarea',
'#title' => t('Main Address'),

```

);

Save the

```
$form_state['values']['name']

```

using **variable\_set('name' , value)** in form submit. Then retrieve variable in template using **variable\_get('name')**.

Another easy method is just edit your theme-settings.php. Add a new textarea field. you will get the field in your **Home » Administration » Appearance » Settings**. You can access that value using

```
theme_get_setting('field name');

```

Hope this will helps you...
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Need Help Finding Permission Needed for Entity Reference Content Type field
I've got a content type called 'resources' in my drupal 7 site. I have authors who have permission to create new resources and edit all the fields.

However, I have recently added a new 'entity reference' field to 'resources'. This field is a select list and the options are 'none' (the default) or 'on the home page'. The authors can SEE this field when they edit or create a new resource, but the only option available to them is 'none'. However, as an admin I can see both 'none' or 'on the home page'. When I select 'on the home page' it puts that particular resource into a VIEW block on the home page of the site. I'd like authors to be able to do this themselves.

I've tried giving authors the permission to edit all Views settings (just to see what would happen) and it didn't help.

Here's how I have it setup:

**Views Block:**

* Access permission, view published content
* Pager: display 1 item
* Relationships: entity reference: GS Resource (identifier: content entity reference from field\_gs\_resource\_2 - require this relationship)

**Content type GS Resource:**

* Entity reference - select list (name: field\_gs\_resource)
* custom permissions: admin/author all have all permissions
* target type: content
* Mode: simple; target bundle: GS resource

**Content type Resource:** (for embedding the field into the main content type used when creating resources)

* Entity reference - select list (name: field\_gs\_resource\_2)
* custom permissions: admin/author all have all permissions
* target type: content
* Mode: simple; target bundle: GS resource

Does anyone have any idea how to give the author the permission they need to edit this field when creating a new resource?

# Answer
> 0 votes
I found the answer to this one. It was the permission 'Bypass content access control' under 'Node'. I gave this permission to the one user role and then removed 'add content' from the shortcut bar so they could only use the link I gave them to create the one specific content type I want them to create.

---
Tags: views, nodes
---


# Question
Title: Without page refresh views exposed filters have to work (without AJAX)
I want to create the Gallery like Example gallery link. Taxonomy filed in views exposed filters. Anyone guide to me?

# Answer
You might wanted to check

1. Masonry Views

> This modules defines a masonry grid view style using Masonry API module.

1. Isotope.js

> Isotope.js provides David DeSandro's Isotope jQuery plugin to Drupal as a library. Isotope is a display plugin that comes with several unique layout modes for content, including the ever-popular "masonry" layout. In addition, the plugin also provides several methods for responding to user events like window resizing and real-time sorting/filtering.

Here is a good tutorial on Building a Dynamic Image Display with Drupal & Isotope
> 1 votes

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


# Question
Title: Programmatically change import URL of reference node
My question is similar to this guy's from drupal.org: https://www.drupal.org/node/2283931

But, I have reference nodes that import content from various URLs and I want after each import, to change the (feeds source) URL of the reference node. I guess I will use `hook_feeds_after_import()` but how am I going to target the reference node instead of the importer and run a function on that source?

# Answer
> 1 votes
Answering my own question, it's basically the same. The `$source` object is the node itself, so in my module I called a hook like this:

```
function MYMODULE_feeds_after_import(FeedsSource $source) {

    //Get the config
    $config = $source->getConfig();

    //Save the current URL
    $url = $config['FeedsHTTPFetcher']['source'];

    //Run a basic check
    if(strstr($url, 'since')){

        //Do some fancy stuff with it and create a new one

        $newurl = 'http://foo';

        //Save the new configuration in the source node
        $config['FeedsHTTPFetcher']['source'] = $newurl;
        $source->setConfig($config);
        $source->save();
    }

}

```

---
Tags: feeds
---


# Question
Title: Custom fileds are not visible on user profile page
I am fetching those value of this fields from database. But somehow, I couldn't be able to see it on user profile view page.

Can anyone help me to solve it out.

# Answer
> 1 votes
There are many things that may be causing this. If you are not using a custom template try going to the display options of the user's profile page (`admin/config/people/accounts/display`) and set the fields to visible there.

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


# Question
Title: HybridAuth hide additional information form for twitter
I'm trying to integrate hybridauth module for social login. Its working fine for Facebook.

But for twitter, after successful sign in, its asking E-mail, first name, last name & gender details.

If I uncheck required information, I won't get email to create user in back-end.

How can we do set up in twitter side to get these details?

Or

Is there any way to get these required informations with out showing the form?

My intention to successfully login into Drupal site after sign in using twitter, with out asking any addition informations.

***After sign in I'm getting below form (Want to hide this form):***

***Drupal back end setting (If i hide, above form wont come but can't get email ID and other details):***

# Answer
> 2 votes
The reason it prompts for that information is the Twitter API doesn't provide it; you can't retrieve user emails through the API; it only provides a single field for a user's real name (thus the prompt for the last name); and it doesn't collect information on a user's gender.

---
Tags: authentication-authorization
---


title: display node owner

text:
# Question
Title: display node owner
A node has a uid field. In a node view I would like to add a field to show the author name with his pictures. I now added a field and using entity referencing to a view with all users where I can select the user of the node, and displaying the entity as a useraccount has the desired result. But now I need to select the author so that's very bad, i could update the field using node\_update hook but this is so ugly I'm out looking for a way how this should be done. So basically I need to display fields form the node owner on the node as a field.

Came up with a different approach created code fields with display suite and used this for the userimage for example, works fine and no extra modules needed using this method.

```
<?php
if ($node = menu_get_object()) {
  $user = user_load($node->uid);
  print theme('user_picture', array('account' =>$user));
}

```

# Answer
In view go to **Relationship Tab** under **Advanced** and add relationship called **Content: Author**. Now you can able to add a field of your author name and picture.

If you need to get particular node author details means you can just add **Content: Nid** under **contextual Filter**.

In Nid Relationship settings select \** Provide default value\** in that select a type as **Content ID from URL**, now have the author details..
> 1 votes

# Answer
What if you create an Entity Views Attachment. Checkout some quick instructions on setting this up: http://megadrupal.com/blog/show-author-profile-block-in-drupal-node.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Different row tpl for every row in a view?
Can I create a different row template for every row in a view? Something like views-view-fields--foobar--0.tpl.php, views-view-fields--foobar--1.tpl.php and so on? My goal is to create a slideshow width different template for every frame.

# Answer
Out of the box with views? No. The row templates apply to all the rows in a given view.

You could do something like this with a custom module though...

You can use hook\_views\_pre\_render to step through your view, like so:

```
function mymod_views_pre_render(&$view){
    if($view->name == "yourviewname"){
      $count = 0;
      foreach($view->result as &$row){
          $row->template = dostuffhere($row, $count);
          $count ++;
      }
    }
}

```

In this example, you would step through each of the result rows and and create printable content. The `dostuffhere()` function would be a routing function that would load in the appropriate template files, which you could define using hook\_theme (example on how to call with a template file is in the comments). The custom .tpl.php files from hook\_theme could be called like with the theme() function.

The routing function would then look something like this:

```
function dostuffhere($data, $row){
switch ($row) {
    case 0:
        return theme('mymodule_template1', array('$row'=>data));
        break;
    case 1:
        return theme('mymodule_template2', array('$row'=>data));
        break;
    //etc...
}

```

Because, in this example, we're using reference variables in hook\_views\_pre\_render, the "template" variable will become available in the row output for the view. So all you really need to do in your row view is to just print out the $template var.
> 0 votes

# Answer
you can able to create a different template foe the fields which are present in the view, you can find the field template reference in , go to advanced tab in the you can able to find **Theme:Information** by clicking the Information Text you can able to find the template for every fields that are available in the view....
> 0 votes

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


# Question
Title: How to rearrange fields in user/%/edit page
I have tried rearranging fields in user/edit page and I succeeded in arranging only few fields.

I cannot move user image field and timezone field. I have used hook\_form\_alter and $form\['#after\_bulid'\] to rearrange field but not working.

This is the code

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id){
  $form['#after_build'][] = 'MY_MODULE_user_profile_form_after_build';
}
function MY_MODULE_user_profile_form_after_build($element, &$form_state) {
  $element['field_user_image']['#weight'] = '';
  $element['timezone']['#weight'] = '';
}

```

I have tried all weight from -10 to 10 but not working. Fileds should be arranged in the order as I specified in the screenshot. Can any one help me?

# Answer
> 1 votes
use nod template as **page--user--edit.tpl.php** and you can able too rearrange the fields by its machine name like as we did for content types...

just try this..

# Answer
> 0 votes
You can use $form\['#pre\_render'\] instead of $form\['#after\_bulid'\]

```
<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['#pre_render'][] = 'MYMODULE_user_profile_form_pre_render';
  }
}

function MYMODULE_user_profile_form_pre_render($form) {
  $form['timezone']['#weight'] = 10;
  return $form;
}

```

---
Tags: forms
---


# Question
Title: How to print the Addthis block code into a template
I've installed the AddThis module and am trying to print the buttons on my template, however I can't get it to work. Here's the I'm using:

```
$addblock = module_invoke('addthis','block_view','addthis_block');
print render($addblock['content']);

```

For the record, If I switch to Bootstrap theme, the links are displayed on the page, if I switch to my own theme (Bootstrap child-theme) it doesn't. I've copied the code verbatim from `modules/node/node.tpl.php` and it still doesn't work.

Any suggestions?

# Answer
> 0 votes
did you enable the **Display Setting** in your **addthis** block configuration because code is good go it working for me, so go and configure the display setting surely it will work.. its under **admin/structure/block/manage/addthis/addthis\_block/configure** enable it as you need by "Basic button or Basic Toolbar"...

---
Tags: 7
---


title: Reducing number of results in pager

text:
# Question
Title: Reducing number of results in pager
As the image shows, the "Last \>\>" page button is not well adjusted, so i want to remove one item from this pager but can't figure out where can i find it to edit. I don't think it's configurable in apachsolr? Can anybody help me with this?

# Answer
> 2 votes
This can be done by using theme\_pager in TEMPLATE.PHP (add it to your theme folder) . the code will be :

```
function theme_pager($variables) {
  if(arg(0) == "search" && arg(1) == "site") {
    $variables['quantity'] = 8;
  }
}

```

# Answer
> 0 votes
If it is a **VIEW**, then change under Pager. Click on **Paged, # items** then change **Number of pager links visible** as per your request.

---
Tags: search
---


# Question
Title: Drupal Rooms Show Booking Unit Name in Confirmation Email
I have had a drupal rooms site running for a few months now, and the client has come back to me asking for the selected room to be shown in the confirmation email sent to the customer.

I have had a look through the available tokens that come with rooms, but there isn't one to display Bookable Unit Name, probably because it can be a multiple value field if more than one room is booked.

Or even a way to display the Rooms Unit name in the line items, then that would print in the notification email under the line items token?

I have gone to products \> room products \> manage display \> line items, but there is nothing there to display the name.

# Answer
> 0 votes
There is a much better way of doing this provided in the Rooms issue queue here... https://www.drupal.org/node/2307413

This can be done with Rules. The idea is you create a rule that modifies the line-item label to add the unit id, unit name, or whatever field you want from the unit to the line item.

Here is an export of a rule we're using to alter the format of the line item for apartment rentals:

```
{ "roomify_lingo_alter_line_item_label" : {
    "LABEL" : "Roomify Lingo: Alter Line item label",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "rooms_booked_unit_id" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "rooms_unit",
            "id" : [ "commerce-line-item:rooms-booked-unit-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "booked_unit" : "Booked unit" } }
        }
      },
      { "data_set" : {
          "data" : [ "commerce-line-item:line-item-label" ],
          "value" : "[booked-unit:name] [commerce-line-item:rooms-booking-dates:duration] reservation - [commerce-line-item:rooms-booking-dates:value:custom:l, M jS Y] to [commerce-line-item:rooms-booking-dates:value2:custom:l, M jS Y] [commerce-line-item:deposit-remainder]"
        }
      }
    ]
  }
}

```

In our case, the value we used from the booked unit was the \[booked-unit:name\], but this could be modified and substituted with other tokens on the unit entity.

The methodology used here requires first checking for presence of the "rooms\_booked\_unit\_id" field in the commerce line item. This has the benefit of once you check for the field, you can then use the field in subsequent actions in the rule, where we can then load the booked unit entity, and subsequently use any fields attached to the entity in other actions on the rule.

# Answer
> 0 votes
You could create a custom token to pull that info in. Hook\_token\_info is the hook that makes a token available.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_token\_info/7

While hook\_token is the hook that actually replaces it.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_tokens/7

Since it's a multivalue field, you may need to include a numeric operator on the end (e.g. node\_room\_field\_room\_number:0) for the delta on the field.

---
Tags: commerce
---


# Question
Title: js file run again when file upload ajaxly
I have a js file that I add it to my form in `hook_form_alter` with `drupal_add_js`, in my js I set a click handler on Html object(lets name it ".myhtml" ), everything work correctly in first load. I have a multi value image field in my form and when try to upload a image ajaxly , my js run again , and when I click on ".myhtml" my click handler called twice ( if I upload two image it fired triple and ... ).

One of my solution was first unbind then bind click,it work but I used `icheck` Jquery plugin for that field,then when I unbind it( icheck plugin ) will not work. So my problem is prevent run js file to again when file uploaded by ajax.

**part of my code** in `hook_form_alter`

```
    $scripts = drupal_add_js();
    $jspatah = drupal_get_path('module', 'tgdev') . '/tgsp.js';
    if(!isset($scripts[$jspatah])) {
        drupal_add_js($jspatah, array(
            'type' => 'file',
            'scope' => 'footer',
            'every_page' => FALSE,
            'weight' => 10,
        ));
    }

```

and part of my js file

```
 (function ($) {
Drupal.behaviors.tgdev = {
    attach: function (context, settings) {
      $(document).ready(function(){
            if($('#edit-field-images .image-preview').length==0){
            $('.form-item-field-feature-und-email .iCheck-helper ').on('click', function () {
                  if($(this).parent('.icheckbox_line').hasClass('checked')) {
                  console.log('checked');
                     getSubsAj('mail');
             });
             }
        console.log($('#edit-field-images .image-preview').length);
        });
      }
    };
})(jQuery);

```

# Answer
> 0 votes
I solve problem with this method **in my js file** :

instead of

```
 (function ($) {
Drupal.behaviors.tgdev = {
    attach: function (context, settings) {
      $(document).ready(function(){
            if($('#edit-field-images .image-preview').length==0){
            $('.form-item-field-feature-und-email .iCheck-helper ').on('click', function () {
                  if($(this).parent('.icheckbox_line').hasClass('checked')) {
                  console.log('checked');
                     getSubsAj('mail');
             });
             }
        console.log($('#edit-field-images .image-preview').length);
        });
      }
    };
})(jQuery);

```

I use

```
 (function ($) {
     $(document).ready(function(){
            if($('#edit-field-images .image-preview').length==0){
            $('.form-item-field-feature-und-email .iCheck-helper ').on('click', function () {
                  if($(this).parent('.icheckbox_line').hasClass('checked')) {
                  console.log('checked');
                     getSubsAj('mail');
             });
             }
        console.log($('#edit-field-images .image-preview').length);
        });
})(jQuery);

```

and everything work correctly !!!

# Answer
> 1 votes
Solution: Using jQuery Once

Drupal 7 integrates the Jquery Once plugin into Drupal 7 core. This plugin adds a simple class to the HTML element to ensure that the behavior is only processed one time. Here is how we would modify our JavaScript to work with the Jquery Once plugin.

```
(function ($) {
  Drupal.behaviors.tgdev = {
    attach: function (context, settings) {
      if($('#edit-field-images .image-preview').length==0){
        $('.form-item-field-feature-und-email .iCheck-helper ').once('click', function () {
          if($(this).parent('.icheckbox_line').hasClass('checked')) {
            console.log('checked');
            getSubsAj('mail');
          });
      }
    }
  };
})(jQuery);

```

---
Tags: forms, ajax, javascript
---