# Question
Title: How to inline edit node fields in a view
I have a table view of content node fields, and I need to be able to edit them inline. It looks like the Edit module would work, but I'm not sure if it works with views. When the user clicks on a field in a result row, they should be able to enter the new value, and the data for that field in that node should be updated. It also needs to be compatible with the Field Validation module.

EDIT: This also needs to work with the Addressfield module.

# Answer
Use the Editable Views module for inline editing

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
> 10 votes

# Answer
jEditable inline content editing module also works perfect. I used this module, by using this we can make inline edits at node output and views output too.

> The jEditable module provides integration between Drupal's CCK module and the excellent jQuery plugin, jEditable. It is implemented as a CCK formatter, which makes inline editing possible through regular **node displays**, **Panels**, **Views**, or anywhere else you can place a CCK field.
>
> Currently supported features are "click to edit" functions for text fields, number fields, date fields, node reference fields and workflow transitions.

For installation see README.txt under module directory.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to use jEditable module with Computed Field module?
I've done some computations using Computed Field module like the follows.

**First**

**Second**

**Total**(first+second) (computed field)

I've installed jEditable inline content editing module to do inline edit at node display. How to use this module with computed filed. Here is my problem

Lets say I've node like the following

**First** \- 35

**Second** \- 4

**Total** \- 39

If I change the value of **First** from 35 to 38 (using jEditable field) and save, it's updating the filed, but the value of **total** remains the same. I'm getting correct result when I **refresh** the page. (Ofcourse, I know the reason). I need to get updated value of total whenever I change the values of first/second. How can I achieve this?

For better understand I've added images

# Answer
> 1 votes
The jEditable, is based on an ajax request, and it works only for your first field, it's normal what you see there untill you refresh page to see changes...

here some snippets that can help :

1- create a callback menu item :

```
function MYMODULE_menu(){
$items['edit_total/ajax'] = array(
    'title' => t('Edit Total AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'edit_total_ajax',
    'access arguments' => array('access content'),
  );
return $items;
}

```

2- create the callback function that will return the new total field :

```
function edit_total_ajax(){
    $data = array();

    if(isset($_POST['first']) && isset($_POST['second'])){
        $first = $_POST['first'];
        $second = $_POST['second'];
        data['total'] = (is_numeric($first) && is_numeric($second)) ? $first + $second : "undefined";
    }
    drupal_json_output($data); // return data as json output, this is the best return for me!
}

```

3- Now you must have a simple jQuery snippet to send the first and the second value :

```
$(function(){
  // you can add here an event handler (on submit for examle)
  jQuery.ajax({
       type: "POST",
       url: '/edit_total/ajax', // the same that made in hook_menu
       dataType: 'json',
       data: { first: $("YOUR_FIRST_SELECTOR").val(), second: $("YOUR_SECOND_SELECTOR").val()  },
       success: function(data){

                 if(data.total !== 'undefined'){
                        $("YOUR_TOTAL_SELECTOR").text(data.total) // this is will change the text value of total field by the new one !
                    }
                 }
       });
});

```

---
Tags: 7, entities
---


# Question
Title: How do I construct the JSON data with session info for creating node?
I am using Drupal 7 and the Services module 7.x-3.2. I am using Postman for Chrome (a http client) to test the API.

What I want to do is log in a user and create a node with the user using the Drupal service API.

I logged in the user with JSON POST request to http://example.com/api/user/login.

>

I successfully got the JSON result.

```
{
    "sessid": "KrZjlcY3rFr8v6iLoskcVQN9DmDWsg5yZqIjBeydEBY",
    "session_name": "SESS9fe39db36ccd7afd64e034fefa0129e1",
    "user": {
        "uid": "31",
        "name": "test_user",
        "mail": "services_user_2@example.com",
        "theme": "",
        "signature": "",
        "signature_format": "filtered_html",
        "created": "1352985941",
        "access": "1352991170",
        "login": 1352991510,
        "status": "1",
        "timezone": "",
        "language": "",
        "picture": null,
        "init": "services_user_2@example.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        },
        "rdf_mapping": {
            "rdftype": [
                "sioc:UserAccount"
            ],
            "name": {
                "predicates": [
                    "foaf:name"
                ]
            },
            "homepage": {
                "predicates": [
                    "foaf:page"
                ],
                "type": "rel"
            }
        }
    }
}

```

Then I tried to create an article via the API by sending the JSON POST request. (The user has the permission to create *Article* nodes.)

>

I got a *401 Unauthorized* response.

I guess I need to include the session cookie information to send the POST request, to create a node.

I have the session information previously returned.

```
"sessid": "KrZjlcY3rFr8v6iLoskcVQN9DmDWsg5yZqIjBeydEBY",
"session_name": "SESS9fe39db36ccd7afd64e034fefa0129e1",

```

How can I utilize it to make a successful JSON POST request for creating a node?

# Answer
```
{
   "title": "Just another drupal Post",
   "type": "Article"
}

```

notice no comma after the type:article tag so that your json works.
> 2 votes

# Answer
Hope this will help you,

* To make the HTTP requests, Im using the Firefox add-on POSTER.

```
{
  "type" : "article",
  "title" : "Test article with language",
  "language" : "und"
}
```
* If node is created successfully you will get a response with a link.
* Examples

```
{
  "type": "article",
  "title": "Test article",
  "body": {
    "und": [{
      "value": "test body!"
     }]
  },
  "language" : "und"
}

```
````
{
   "title":"Review",
   "type":"establishment_review",
   "field_establishment":[
      {
         "nid":{
            "nid":"[nid:26686]"
         }
      }
   ],
   "field_fivestar_value":[
      {
         "rating":"20",
         "target":"0"
      }
   ],
   "field_review":[
      {
         "value":"comments about the restaurant"
      }
   ]
}

````
* You can refer this
* I have answered How do I POST a new node using the Services module question. You can refer for more information.
> 2 votes

# Answer
You need to set `cookie="sessionname=sessionid"` value in headers, where sessionname comes from the endpoint/user/login URL.
> -1 votes

---
Tags: 7, services
---


# Question
Title: Access licensed files only after admin changes order status to completed
I watched the Commerce File screencast which shows how to create a downloadable file as a product. It appears to be for version 7.x-1.x but currently the recommended version is 7.x-2.x which has since changed significantly.

I'm trying to achieve the same outcome as the screencast whereby the user can only see his licensed files after the order has been changed to completed by an admin. Currently, the moment the user submits his order, he can already see his files. I tried checking the checkout rules, however, the only event option closest to what I want to achieve is "After updating an existing commerce order", and that did not work either.

How can I prevent users from accessing the licensed file until the order has been processed?

# Answer
Sorry I don't have time to watch the screencast.

You could create two rules, the first which trigger when an order is payed in full, this rule could change the order status to pending.

Then you could make another rule which triggers when an order is saved, with the condition that it is in the pending state, it is changed to completed (which allows access to the files).

This could cause complications if you actually use the 'pending' order status for other workflows, in which case you might need to make a custom status you can use as an in between for your review process (using this module https://drupal.org/project/commerce\_custom\_order\_status).
> 0 votes

---
Tags: commerce
---


title: Taxonomy Menu and Views don't work

text:
# Question
Title: Taxonomy Menu and Views don't work
I have vocab Categories, I created it as a menu with Taxonomy Menus. It lists terms in the sidebar, but when clicked on term, it opens empty page saying 'There is currently no content classified with this term.' I have term Hats & Visors, so path to it is shop/hats-visors/ and I expect it to show the list of hats content. These are my settings (screenshots): https://i.stack.imgur.com/AwqOW.jpg

And to the actual Hat content path is i.e. shop/hats-visors/hat aka /node/5/

# Answer
> 0 votes
You need to associate content with that term.. To do that create a field term reference in content type.. And then edit your content and select term which you would like to associate with your content..

* Login as admin
* Navigate to list of content types "admin/structure/types"
* Choose content type using which your are creating content. Click on Manage Fields next to it.
* Add Term Reference field and choose Vocabulary Categories in settings
* Create Content or Edit your existing content to associate terms to content using above field you have created.

---
Tags: 7, views, taxonomy-terms
---


title: Hiding field groups during registration

text:
# Question
Title: Hiding field groups during registration
I worked out a way to hide fields with field permission module on registration. But have not found a way to hide whole field groups. Is there a module or a particular API which can help with this problem.

# Answer
> 3 votes
you can do this with using hook\_form\_alter

You can do something like this:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_form_name') {
        //do what ever you want
        //$form is an array of form elements, to delete some of them you can just do:
        unset($form['your-element-name']);
        //or and I think it is more "drupal way" to do things you can hide an element using hide function, e.g.:
        hide($form['account']);
    }
}

```

# Answer
> 0 votes
You can try the following simple code:

```
field_group_hide_field_groups($form, array('group_advert_hidden'));

```

in hook\_form\_alter() or similar place.

In example:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function foo_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    field_group_hide_field_groups($form, array('group_advert_hidden'));
}

```

Eventually you may try to use Conditional Fields module to hide the fields, so empty group would be hidden, as hiding field group are not supported yet.

---
Tags: entities, users
---


# Question
Title: How can I use Javascript (Google Analytics) in my "Rewrite Results" in Views?
I'm trying to track downloads as events in Google Analytics for file fields. The links are displayed in Views using "Rewrite results."

I tried the following:

```
<a onclick="var that=this;_gaq.push(['_trackEvent','Download','Windows',this.href]);setTimeout(function(){location.href=that.href;},400);return false;" href=[field_windows]>Windows</a>

```

But the **onclick** part gets stripped out by Views. I know the Full HTML filter does this by default, but how do I get around it?

# Answer
> 6 votes
Views will indeed strip out onclick attributes. You can work with data attributes and use an external JS file to add the onclicks. Example for Views rewrite:

```
<a href="#mylink" data-event-type="Download" data-event-xxxx="Windows">[myfield]</a>

```

External Javascript (jQuery example):

```
jQuery(document).ready(function(){
 if(jQuery("a[data-event-type]"){
   jQuery("a[data-event-type]").click(function(){
    _gaq.push(['_trackEvent',jQuery(this).attr('data-event-type'),...........);
   });
 }
});

```

# Answer
> 4 votes
It would probably be better to add a class to the element and then attach the click event via a JS behavior anyway.

I don't think this field uses text formats at all, but must apply some default level of filtering e.g. `filter_xss()`.

**Edit:** Here's an example that attaches the tracking and download using a class and the link text for the event name.

```
<a class="download-link" href="[field_windows]">Windows</a>

```

Add this to your theme or module JS:

```
(function ($) {
  Drupal.behaviors.triggerDownload = {
    attach: function (context, settings) {
      $('.download-link').once('trigger-download').click(function (e) {
          var href = this.href;
          _gaq.push(['_trackEvent', 'Download', $(this).text(), href]);
          setTimeout(function(){
            window.location.href = href;
          }, 400);
          e.preventDefault();
      });
    }
  };
}(jQuery));

```

# Answer
> 2 votes
You can use the GA Push module.

This module allows you to send events to GA when certain JS events happens. You can define this interactions using its GUI.

# Answer
> 0 votes
It shouldnt be stripping the onclick if you have Full HTML selected. Are you using Ck Editor 4.1 +?

Theres a known issue where tags are being stripped if you dont edit the .js file directly, or add `config.allowedContent = true;` into the Advanced Content Filter settings.

From the CKeditor project page:

> Note for CKEditor 4.1+ users
>
> If you are using CKEditor 4.1+, you should adjust Advanced Content Filter settings. If you have any trouble implementing this feature, you can turn it off by setting:
>
> config.allowedContent = true;
>
> in the Custom JavaScript configuration field of the Advanced Options setion for your CKEditor profiles.

---
Tags: views, javascript, input-formats
---


title: Check for empty field

text:
# Question
Title: Check for empty field
I'm using the following method to check whether a variable is set before printing

```
if (isset($content['field_name'])):
print render($content['field_name']);
endif;

```

But when the field is empty, unknown is printed.

Is there a Drupal method for checking empty variables?

# Answer
> 2 votes
$content\['field\_name'\] is always set. You can check if it's empty.

```

if (isset($content['field_name']) && !empty($content['field_name']):
  print render($content['field_name']);
endif;

```

---
Tags: entities
---


title: Show two copies of same menu

text:
# Question
Title: Show two copies of same menu
Let's say I have Main Menu and I want to show it in header and in footer, to achieve that I can use Menu Block module, but using it lets say I disable one link in Main Menu, it also disables it in the clone menu in the footer. How do I have multiple copies of same menu, but with different disable options for each, and when adding new links it would update both, but at the same time be able to disable links separately on each menu?

Let's say both menus have Home and Events links. I want to show Home and Events in just header menu and disable Events in footer? And if I decide to add new link, it will add up in both menus at the same time and then again I will be able to disable it in only one of them if needed.

Makes sense?

# Answer
> 1 votes
> How do I have multiple copies of same menu, but with different disable options for each

Drupal doesn't support anything like that, and I must admit it doesn't make sense to me that it would.

As soon as you have two menus that need to show different things, you need two menus. Setting arbitrary rules on how that second menu should partially sync itself with another, arbitrary, menu, is a conceptual nightmare. I can't even imagine what the UI would look like for that.

---
Tags: 7, routes, blocks
---


# Question
Title: Change name of a tab for a specific content type
I have a content type Organizations which is an OG Group. I would like to change the default tab name "View" only for this OG group(or content type). Tab tamer module helps with it but it does not allow the change of the name of tabs for a specific content type.

I use sky theme(an Adaptive theme). I wrote the following code in the theme template file,

```
function sky_preprocess_page(&$vars) {
  if ($vars['node']->type == 'organization') {
    foreach($vars['tabs']['#primary'] AS $index => $tab) {
      if($tab['#link']['title'] == t('View')) {
        $vars['tabs']['#primary'][$index]['#link']['title'] = t('Organization Home');
      }
    }
  }
}

```

But this doesn't help too

# Answer
> 6 votes
You can use `hook_menu_alter()` to change the name of tabs for a specific content type. For example:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  unset($items['node/%node/view']['title']);
  $items['node/%node/view']['title callback'] = 'MYMODULE_view_tab_title';
  $items['node/%node/view']['title arguments'] = array(1);
}

function MYMODULE_view_tab_title($node) {
  if ($node->type == 'organization') {
    return t('Organization Home');
  }
  return t('View');
}

```

Remember clear Drupal cache.

# Answer
> 1 votes
There is a module for that: Tab Name Tweaker. Here is a quote about it (from the module's project page):

> Allows admins to override the name of the 'View' and 'Edit' tab on node pages.
>
> Possible use cases:
>
> * 'View' or 'Edit' is not descriptive enough.
> * Organic Groups: when the normal 'View' tab serves as an overview or landing page rather than a specific piece of content.

# Answer
> 0 votes
See `theme_menu_local_task()`.

Here's how you can change the "View" tab link to something else based on node's content type:

```
function sky_menu_local_task(&$variables) {
  $link = $variables['element']['#link'];

  // Rename the "View" tab for certain node types
  // Check if the link title is "View"
  if ($link['title'] == t('View')) {
    // Make sure we are on single node page
    if (arg(0) == 'node' && arg(1)) {
      $node = node_load(arg(1));
      // Do this for specific content types
      if ($node->type == 'page') {
        $link['title'] = t('Check me out');
      }
    }
  }

  // Continue building the local task link
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";

}

```

---
Tags: 7, routes
---


# Question
Title: Is it possible to change the "view type" from a "content view" to a "search view"?
I have recently installed the Search API module and associated modules to build a better site search.

My current search function is basic out of the box search but there are is lot of custom HTML and CSS to make the search results look good. Therefore I am wondering if I will have to manually redo everything when making a dedicated "search view" (a type of view enabled by the Search views module) or if it there is some way to clone/copy my previous "content view" but change it's type.

I have looked for answers and it was not possible in Drupal 6 but I am running Drupal 7.

# Answer
> 1 votes
You can use Display Suite search module to use search view like content view. Display Suite module have a submodule namely search that extend the search results for Drupal core or Apache Solr.

**Steps:**

1. Install Display Suite Search Module after downloading from above link.
2. Go to content type's manage display and check the search result option that you find under custom display settings on vertical tab after that save it.
3. Now Go to Search result display mode local tab link and configure your display of fields as you want and save it.

**For Manage Core search result :**

1. Go to admin/structure/ds/list/search and choose option 'search result' in view mode and save it.
2. Go to admin/config/search/settings and chose option Display Suite Search for ACTIVE SEARCH MODULES and Default search module.

*Now search using core search form. This will display differently as core search result.*

**Now Manage Search api Search result :**

1. Go to view of desired search index views.
2. Choose Format show as Rendered entity
3. Go to Format show setting option and choose option 'Search result'
4. Now save this views.

*After that you can see search api result is as you configure previously on manage display.*

---
Tags: views, search
---


# Question
Title: How do I set the node path with a contextual filter?
I'm creating a simple job board for my company in Drupal 7 w/ Views. I have a view which creates a page that lists all available jobs. Within each job is a truncated description which I have set to trim and display a "Read More" link which goes to the details of the job posting.

To generate the "Read More" link, I am using a contextual filter which pulls the \[nid\] and in the 'body' section I have the "Read More" link set to node/\[nid\]. This works exactly the way I need it to.

The issue I'm having is that I have created another page within the view to display the full job posting. And instead of going to www.mydomain.com/node/3166, I want it to go to something like www.mydomain.com/jobs/current/posting/3166. (I'd like to use the nid as some jobs might have the same title).

I go into this view and set the path to 'node/%' and the view shows up formatted and everything when details are clicked, however, setting this bombs out ALL of my other content within the site. So I tried setting the path to something like 'jobs/current/posting/%' and I just can't get it to work.

Does anyone know what I'm doing wrong and/or have a solution or workaround?? TIA

# Answer
* First of all you don't need Contextual filter in your first case where you are generating link as "node/\[nid\]" , what you need is replacement pattern. Todo this you can simply add nid to fields list and place above read more link and use the pattern.
* Change read more link to "jobs/current/posting/\[nid\]"

Regarding what you are trying to solve

* You cannot have a view with path "node/%" since it's already taken by node module to render node pages. It will conflict with node module and as you said "bombs out ALL of my other content"
* In your view set path as 'jobs/current/posting/%'
* Add a contextual filter nid and set provide default value to content id from URL as shown below.
> 2 votes

---
Tags: 7, views
---


title: Set node to flagged by default

text:
# Question
Title: Set node to flagged by default
I'm using flags on my site as a way of filtering content through views, when a user views a certain node content type, I have a rule setup which resets the value of my flag and sets it against that user for that node, the views will reference this information and change their output accordingly.

The problem I have at the moment is what happens when anonymous users enter the site for the first time, they have no flag set, and thus none of the views show anything, until they travel to one of these special nodes.

What I'm looking for is: is it possible to set a flag to a default value, so that everyone has this node tagged until it gets changed?

# Answer
* You need to use another flag to identify anonymous visits.
* Flag value is always boolean , true or false. So you cannot have a default value to identify whether it's visited by anonymous.

What you can do is use a rule

* Check visitor is anonymous
* If yes set a flag called "anonymous\_visit" to that particular node
* Use above information in your views to display nodes

Above rule sets flag on view of a node, If you want to add flag by default to a content then your rule event should be on node create add xx flag to node...

You can also use flag api with node api hooks to achieve above.. See flag api below example..

Flagging or Unflagging an item You use the $flag-\>flag() method to either flag or unflag an item. Example:

```
<?php
$flag = flag_get_flag('bookmarks') or die('no "bookmarks" flag defined');
// Flag node #456:
$flag->flag('flag', 456);
// Unflag node #456:
$flag->flag('unflag', 456);
?>
The signature of this $this->flag() method is:

<?php
function flag($action, $content_id, $account = NULL, $skip_permission_check = FALSE)
?>

```
> 0 votes

---
Tags: 7, views, flags
---


# Question
Title: How to update relative image paths on domain migration? (Incorrectly generates previous)
**Problem**

*(Found the same problem recently, re-wrote question to be more general and useful)*

I recently had to change the domain of my site.

On changing it I've found Drupal fails to update the domain of the URL in a lot of the images on my site.

So for example, I changed from domain1 to domain2:

The path for a background image in a CSS file would originally be:

```
background-image: url (https://domain1.com/sites/all/themes/tefltheme/images/empty1.gif)

```

After changing the domain it would remain:

```
background-image: url (https://domain1.com/sites/all/themes/tefltheme/images/empty1.gif)

```

Nothing I do seems to cause this to re-generate. Has anyone else run into this? Where is Drupal storing this information?

**What I've done**

* Clear caches
* Flush memcache, varnish and drupal
* Wipe all Advagg files and re-generate
* Set the base URL in settings.php

On the back-end it recognises my URL has changed for example `/admin/config/system/site-information` shows domain2 in all the prefixes.

(I can fix this by putting an exact path in all my CSS etc, but obviously I'd prefer to avoid this.)

# Answer
> 0 votes
The problem was to do with the File System.

If you've got image urls which use it to generate part of the URL these don't reset as you would expect.

Drupal appears to cache this in some place which isn't cleared by any of the regular cache cleans.

Entering an incorrect path for the file system and then changing back to the correct one fixed all the image generation for me.

# Answer
> 1 votes
If your CSS file and "images" folder are in "mytheme" folder, the CSS string should be:

```
background-image: url(../images/homepagenew4.jpg);

```

# Answer
> 0 votes
Image links in CSS are not stored in the database. That would be in the CSS file. Using a browser "inspect" the code by right clicking on the background in Chrome for example. Navigate the DOM to find the css reference to the background image. It will show you the CSS line where you need to update. Make sure you have aggregate CSS turned off in the performance section of the admin configuration. Also, make sure ANY links you generated ANYWHERE are always relative links. There are rare exceptions, but I don't know of any worth mentioning there.

The home icon is not set in the database. It is taken from the `settings.php` file located in `sites/default/settings.php` (or when you first setup Drupal). Change the `$base_url` to `mysite.net`. Clear caches, `admin/config/development/performance`. If you still can't get it with this information, please update your post to include more information about how you set things up and what you have tried.

---
Tags: 7, media, migrations
---


# Question
Title: Print key value as a class along with the label for a list field?
I have a node with a field which is a List (integer). I can print the value in node tpl with the following:

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

```

However I also need to style each result differently. For instance one of the options is 'large' and I want to add a background image to every 'large' result.

How can I do this? I was thinking if I could print the key value as a class along with the label the I could easily do the rest with CSS.

# Answer
You should not actually want to do this in your node.tpl file. Drupal uses a system of (pre)processors to alter variables before they get rendered. That is where the logic should go.

Have a look at this topic that has a lot of explanation and references https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates

Once you have your output ready you should be able to do the styling with CSS.
> 0 votes

---
Tags: theming
---


# Question
Title: entityform list fitting to selected node
After searching the web for hours I'm hoping to find the answer here for my problem.

So here is my goal: I defined a content type, travel which contains a multiple values textfield for additional services and a entityform for booking additional services (e.g. train ticket to the travel starting point). Each travel node has of course different number of additional services, after clicking on 'booking additional services' the form appears which should include a checkbox for each additional service to select by the customer.

I defined a text list in the form for the additional services. Now my question is, how can I generate a list of additional services for the particular travel in my form. I can only set the possible values for the list in the field settings but these values depend on the particular travel!

Could you give a hint?

# Answer
> 0 votes
Drupal uses static forms by default, therefor one step doesn't influence another step. You are probably looking for a thing called conditional fields.

You should be able to use the Conditional Fields module for this. Although I am not entirely sure it it works on all form types.

---
Tags: nodes, entities
---


# Question
Title: How to set form element order with field_attach_form (and why does it do it?)
**Problem**

I'm attaching the user register form to the add node form using hook\_form\_alter (for a custom content type). (Forcing an anonymous user to register when they create a node.)

My solution to this problem, has been to put a large chunk of the user register code into `hook_form_alter` (because I'm a "great" developer).

While this works in a custom form, in `hook_form_alter` the following function

```
 field_attach_form('user', $form['#user'], $form, $form_state, $langcode);

```

Causes the register fields to always appear in the middle of the form. (#weight does nothing.)

Reading through the documentation, it appears this function always puts the fields at the top of `$form_state['values']` and you can change it by setting the `#parents` property on the incoming `$form` parameter.

**2 Questions:**

1. Why does the order in `$form_state` effect the display of my form? I thought the `#weight` property in the form elements determined this.
2. I don't really understand how to set the parents property. Do I need to create a parent which encompasses all of the standard node add form, and then set this new form relative to that?

**More code in case it's wanted.**

```
mymodule_form_alter (&$form, $form_state, $form_id) {

...

if (user_is_anonymous($user)) {

    $admin = user_access('administer users');

    $form['administer_users'] = array(
       '#type' => 'value',
       '#value' => $admin,
    );

    $form['#user'] = drupal_anonymous_user();
    $form['#user_category'] = 'register';

    $form['#attached']['library'][] = array('system', 'jquery.cookie');
    $form['#attributes']['class'][] = 'user-info-from-cookie';

    $account = $form['#user'];
    $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

    $form['#validate'][] = 'user_account_form_validate';

    $form['account'] = array(
      '#type'   => 'container',
      '#weight' => 61,
    );

    .... //form elements for user reg like password, username email etc. go in here...

    $langcode = entity_language('user', $form['#user']);
    field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
    foreach (field_info_instances('user', 'user') as $field_name => $instance) {
      if (empty($instance['settings']['user_register_form'])) {
        $form[$field_name]['#access'] = FALSE;
      }
    }

}

```

# Answer
I can't really offer much explanation here but here's my solution. I suspect it has something to do with having a single form create two entities and how you need to separate that to allow both to be created.

The above created both, but didn't order the form correctly. The solution below does both.

The solution came from bundling up everything to do with user registration and attaching it inside a form container as opposed to just putting it in the form.

As I mentioned in the question, the documentation says this function always attaches to the top of the form, so you position the form container at the bottom then put it in that.

Here are the updated sections of my code, only two sections changed, the rest stayed the same. So you can just add the following parts to the code above.

```
   ....

   $form['account'] = array(
     '#type'   => 'container',
     '#weight' => 61,
   );

   //The new form container I added is below

   $form['user_reg'] = array(
     '#type'   => 'container',
     '#weight' => 62,
   );

   ....
   //added variables for clearer reading
   $account = $form['#user'];

   //The crucial part is the third parameter. This attaches it to a container rather
   //than the standalone form
   field_attach_form('user', $account, $form['user_reg'], $form_state, $langcode);

```
> 0 votes

---
Tags: 7, users, forms
---


# Question
Title: What would be the parameters for a services to receive a JSON file?
This might be sound like a very foolish question ...

I want to expose a service to receive a JSON file from client side in GET or POST format through which I can send an email. What should be my initial algorithm?

I know I need to implement `hook_services_resources()` to create a resource for the services.

But I don't get what would be its parameters and what would be there in resource api \[\].

# Answer
```
drupal_json_output($resultsarray);

```

you will get json data
> 0 votes

---
Tags: services
---


title: Varnish Cookies with Authcache

text:
# Question
Title: Varnish Cookies with Authcache
**Problem**

I'm setting up Authcache to work with Varnish as a backend.

It comes with an excellent default.vcl which is very well documented. It has the following section on cookies. Varnish skips the cache if cookies are enabled, so the following example would appear to remove all cookies so it can cache.

However I've found if I un-comment this section Authcache stops caching. If I leave it commented out then it continues to cache and cookie functionality seems to work. (e.g. I have cookies which remember the state of facets across page refreshes and they continue to work).

Isn't this the wrong way around?

(I'm using Authcache debug to test for caching).

```
// * Example 2: Remove all but
  // * - the session cookie (SESSxxx, SSESSxxx)
  // * - the cache invalidation cookie for authcache p13n (aucp13n)
  // * - the NO_CACHE cookie from the Bypass Advanced module
  // * - the nocache cookie from authcache
  // *
  // * Note: Please also add the has_js cookie to the list if Authcache Ajax
  // * is also enabled in the backend. Also if you have Authcache Debug enabled,
  // * you should let through the aucdbg cookie.
  // *
  // * More information on:
  // * https://www.varnish-cache.org/docs/3.0/tutorial/cookies.html
  // */
  //if (req.http.Cookie) {
  // set req.http.Cookie = ";" + req.http.Cookie;
  // set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
  // set req.http.Cookie = regsuball(req.http.Cookie, ";(S?SESS[a-z0-9]+|aucp13n|NO_CACHE|nocache|aucdbg)=", "; \1=");
  // set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
  // set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");
  //  if (req.http.Cookie == "") {
  //   unset req.http.Cookie;
  //  }
 //}

```

# Answer
> 0 votes
Copy pasta of Znerol's excellent answer to the incorrect bug I raised:

> The VCL shipping with Authcache Varnish needs to be adapted for Authcache Debug. The widget uses a cookie (aucdbg) with a unique value for each request in order to distinguish between cache hits and misses.
>
> By default the standard cache policy kicks in for anonymous users. I.e. requests having a cookie will be passed to the backend by Varnish. When you use ab for testing, no cookies will be sent along with the request and therefore the cache actually kicks in. When testing with the browser, the aucdbg and js cookies are added by JavaScripts and therefore the requests are bypassing the cache.
>
> Look for Example 4: Trigger key-retrieval for all users, including anonymous. in vcl\_recv and enforce key-retrieval for all users. When this fragment is enabled, requests for anonymous users will be handled exactly like those for authenticated users and the default varnish cache policy will be disabled.

Un-commenting section 4 in the Authcache `default.vcl` solved this problem.

---
Tags: 7, caching, proxies
---


# Question
Title: How do I create product and product display once, like in Commerce Kickstart?
In Kickstart you just go Add Product and it creates both, the Product for admin area product list and the Product Display. How do I do that in regular Drupal install with regular Commerce module? Because now I have to go each time to create the actual product for admin product list and then go create a product display for users. Isn't that a bit annoying?

I cannot use Kickstart, it's too late already and it's too big and overcrowded with too much of not needed features.

# Answer
This is through the contributed module Inline Entity Form.
> 1 votes

---
Tags: 7, commerce
---


title: Add a read more link to product list

text:
# Question
Title: Add a read more link to product list
I have a view with a grid displaying rendered entity of product list for my product display index. Is it possible to add a read more link to the product list display with a link to the product. I have tried to create this in several different ways, by creating a link in the content type fields, however that would require manual completion. I appreciate that if I was using fields in views I could add the link there. I'm hoping there is a solution to adding to the product list. I have also looked at adding it manually to node.tpl.php, but I am unsure of where to define the variable instead of $teaser. Many Thanks in advance.

# Answer
Fixed, I added all of the required fields from product list to teaser, then modified the css accordingly.
> 0 votes

---
Tags: 7, commerce
---


title: query has no result for anonymous

text:
# Question
Title: query has no result for anonymous
I have below query , when it run with non-registered user return null but with any register used with any role has result .
also non-registered user has permission to view any product

```
$result = db_query("SELECT * FROM {node} node
LEFT JOIN {field_data_field_course_ref} field_data_field_course_ref ON node.nid = field_data_field_course_ref.entity_id AND (field_data_field_course_ref.entity_type = 'node' AND field_data_field_course_ref.deleted = '0')
LEFT JOIN {commerce_product} commerce_product_field_data_field_course_ref ON field_data_field_course_ref.field_course_ref_product_id = commerce_product_field_data_field_course_ref.product_id
WHERE (( (node.nid = :nid ) )AND(( (node.status = '1') AND (node.type IN  ('course_display')) )))
", array(':nid' => $nid));
      $coursePIDs = array();

      //get node product variation

      foreach ($result as $record) {
        $coursePIDs[$record->field_course_ref_product_id] = $record->field_course_ref_product_id;
      }

 ym($coursePIDs);

```

any idea?

# Answer
My usual answer for this is product access permissions haven't been set that would allow anonymous users to view all products, but since you're creating this query directly it isn't clear to me that that would be getting in the way. I suppose Drupal is still running query altering on this and somehow alerting the product module that it's involved?

A simple way to rule that out would be to grant anonymous users permission to view any product of any type and see i they get results. But really seeing the query actually run by Drupal would be useful.
> 0 votes

---
Tags: commerce, database
---


title: entity_export - where can it be used?

text:
# Question
Title: entity_export - where can it be used?
I want to make use of the entity\_export function for data migration. I see on the doc page http://drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity\_export/7 that

```
Note: Currently, this only works for entity types provided with the entity CRUD API.
```

How would I know if a module fits this criteria? Is it simply if it has the entity module as a dependency?

# Answer
If the module has been properly written en utilises the full Entity CRUD API there should not be a problem. In most modules this should be the case.

However the Entity module does more (like exposing entities to Views). If the dependency was only used for such a specific case, it might be possible that the module comes with un-exportable entities.

If you want to narrow this down you could search the module for `HOOK_entity_info()` (change hook to module name) and see what `controller class` is used. If it is `EntityAPIController` it is likely to utilise the CRUD API.
> 1 votes

---
Tags: entities
---


# Question
Title: How to find out a node's comment status (open, closed) from node ID?
Having a view of comment fields here that is embedded into another view via Views Field View module. The comment view has a contextual filter: the nid. Works quite nice.

Now I want to hide the view if comments ain't allowed (per node). Of course I have the node's ID as $argument. How can I check the comment status from that to specify the validate criteria?

# Answer
The following code should do the trick:

```
$node = node_load($argument); // load the node object based on the nid
if($node->comment == COMMENT_NODE_CLOSED) {
  // comments are closed - hide the view
}

```

There are 3 constants that define the different comment states:

For more information see the Node object reference.
> 6 votes

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


# Question
Title: Connect to Intersystems Cache DB via ODBC
I'm trying to connect to an external data source within out intranet site. The database is Intersystems Cache. Our web-servers are running Cent OS 6.4, so I have setup the necessary unixODBC drivers to connect to it and this is successfully working. What I'm struggling to work out is how I access this data from within Drupal.

I know I could just call odbc\_connect within my code, but this isn't the Drupal way. I also loose the benefits of Memcached etc.

Would it be possible to use PDO's ODBC driver, which I think Drupal uses anyway?

Thank you.

# Answer
As @Bala said you want to try to install the PHP ODBC driver. Drupal does not use this driver by default (a drupal install may use MySQL, Postgres, or I believe MsSQL on install if those drivers are found by PHP).

Once the ODBC driver is installed for PDO, you can inform Drupal of your 2nd database by following the Multiple Databases Documentation. Bala linked you to a previous example I gave using ODBC to an MsAccess database file -- you're request is simply a different DBMS vendor. The same approach should work InterSystems Cache DB by following the concepts in the documentation page linked about.

Note that ODBC is a slow interface as its essentially a wrapper to your client Database. Its not as fast as a full native DBMS driver. Keep that in mind when querying and using your data.
> 1 votes

---
Tags: database
---


title: show preview and not all page/forms

text:
# Question
Title: show preview and not all page/forms
I need to show only the preview and not all page and forms

I made a new window after clicking preview but I see ALL page (a duplicate) including header, footer and form compiled. I need to show the preview only.

```
function node_form_build_preview($form, &$form_state) {
  $node = node_form_submit_build_node($form, $form_state);
  $form_state['node_preview'] = node_preview($node);
}

```

can someone help?

# Answer
If you dont like what Drupal is doing by default for this preview feature, override it in your site theme, there is an example of this in the `node_preview` Drupal 7 API node\_preview() comments.

**the comment incorrectly titles the function THEME\_Node\_preview() it should all be lowercase**

```
  /**
   *Output customized node preview on node edit and add forms.
   *
   * @return
   * This just outputs the Full node ignoring the teaser mode.
   */
  function YOURTHEME_node_preview($variables)
  {
      $node = $variables['node'];
      $elements = node_view($node, 'full');
      $full = drupal_render($elements);
      $output = '<div class="preview">';
      $output .= '<h3 class="post-preview" >' . t('Preview of your posting') . '</h3>';
      $output .= $full;
      $output .= "</div>\n";
      return $output;
  }

```

If that still doesn't look right you could try altering this code further to:

* provide an override to node.tpl.php or node--preview.tpl.php using theme suggestions for drupal's theming layer functions.
* alter the results of `$full` above using Regular Expressions to hack off the beginning and end of the HTML page content.
> 0 votes

---
Tags: entities, 6
---


# Question
Title: How do you theme specific fields in on a content type?
Currently I want to theme a taxonomy field in my content type and expose the TID and the Term name with link. The default sections only give me one or the other. Is there a setup where I can expose the TID, Term name, and Link?

Below is a screenshot of the teaser view display mode.

# Answer
You could use field.tpl.php

If your field is called **field\_series** then you will need to create:

/mytheme/anyfolder(optional)/field--field-series.tpl.php

If you inspect the variable $element then it will contain everything you'll need (tid, name, see drupal\_get\_path\_alias for the link)

Don't forget to clear the cache once the new template has been created.
> 1 votes

# Answer
Felix is right on. If you want a UI for this for some help and flexability look at Fences.

> **What it's doing**
>
> Behind the scenes, the Fences module is remembering which custom tpl file you want to use for each field. This is set in the field configuration itself — not in the display (or view mode) configuration. That way, every time to output this field, it will use this custom tpl.
>
> Fences ships with a bunch of tpls files. Look inside the module to see which ones, and to see the markup for each of those. If you would like to change that markup, make a copy of any tpl file, put it in your custom theme, and edit away. Drupal will automatically use the copy in your theme instead of the copy in the Fences module files (once you clear the cache).
>
> If you would like to make more things — and add to the list of possibilities — make more tpls files of your own, and place them in your theme. Use the fences naming convention, and Fences will automatically find them, and add them to the list available in the dropdown for field configuration.

Or jump in and try out DisplaySuite which allows you to customize fields, or whole Node displays ...

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
>
> By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Retrieve field value using PHP + Search API + Views?
I haven't had this problem in the past but I'm trying to retrieve a field value in a Views PHP Field for a view I made for Search API. I'm using the code below but I tried with 'nid' as well.

```
$stream = $data->_field_data['vid']['entity']->field_stream['und'][0]['value'];

```

You can see the var output here. I'm trying to get field\_stream but am having no luck...

http://www.ovwrc.com/waste-search?search\_api\_views\_fulltext=poop%20poop

# Answer
Run $data though dmp to inspect the array and see what values are available.

Search Krumo may be useful as I expect that array will be huge!
> 0 votes

---
Tags: search, views
---


# Question
Title: Why is the Edit View link not appearing in Panels?
I've got a Views block display placed inside a Panels pane. It works well, and I wanted to add two similar blocks, so I cloned the View and changed the necessary settings. The original block has the cogwheel "Edit View" contextual link, but the clones do not. Any ideas? I can still go to Structure -\> Views -\> name to edit, but it's much easier to use the contextual link. If anyone knows why it isn't appearing and how to get it back, I'd appreciate it!

# Answer
> 0 votes
I discovered the answer by accident yesterday. When adding a Views block to a Panels pane, Panels will ask you if you want the "Master" or "Block" display. I'm not sure there's a difference in the output at all, but if you select the "Block" display, the contextual cogwheel "Edit View" link will not show up. If you select "Master", it will. Unfortunately, you can't change the display once it has been added, so you need to remove the "Block" display and re-add it, selecting the "Master" display. This could cause you to have to redo some work, if you had spent any time configuring things already.

---
Tags: views, panels, navigation
---


# Question
Title: Can I do a scrollable calendar/events listing with a Drupal module?
I have the FullCalendar module installed, and it's pretty easy to use that to put a little calendar display in a block (making it look good is another matter).
But can I use it to make an events display like the one on Metromix?
(Sorry, I guess I'm too new to post an image! Please see the link above)

I can make FullCalendar display a week's worth of events, but that's not really what's happening here. As you can see in the example, the user can scroll left or right to get different days to display, have a particular day in the list selected, and have that selected day's events displayed below. Those are the parts that aren't clear how to do with FullCalendar (if it's possible at all).

Can FullCalendar do this? Is there another module that can do this? Or do I have to do this kind of thing by hand?

Thanks in advance for any pointers!

# Answer
> 1 votes
Yes, I believe that you can do that with the full calendar module.

In the example link you posted when you click left or right though the months an ajax request is actually happening returning the next months set of events.

The full calendar module also has ajax support.

To turn ajax on on your calendar you need to look at a setting called Use AJAX under the advanced section:

There is a similar question, AJAX in a calendar view block, which may also be of interest.

---
Tags: 7, datetime, javascript
---


# Question
Title: In Drupal 7 how to expose TID (term id) as a selectable field on the manage display section of the taxonomy page?
How can I expose the TID of a the term as a field via the manage display section of the taxonomy page?

# Answer
You can use Display suite, and create a custom field.

1. Install ds and ds\_extras.
2. Configure ds\_extras to enable custom fields.
3. Activate a display suite layout for your taxonomy term display.
4. Create a custom field, where you can put the tid as a token.
> 0 votes

---
Tags: 7, taxonomy-terms, entities
---


title: Display nodes by a date field from/to

text:
# Question
Title: Display nodes by a date field from/to
I have a content type with a Date text field. User can enter from and to dates to control when this node will display. In my views filter, I'm adding both the from and to fields. 'From' is less than or equal to now and 'To' is greater than or equal to now.

The resulting query is not combining the range of dates, so all nodes show up in the result set.

Can I resolve this with just Date module? I don't want to use scheduler.

Drupal 6
Date 6.x-2.9

# Answer
You need to select Method of handling multiple date fields in the same query as AND in the view exposed field setting.

Click on the * icon next to field in exposed filters section as shown below to complete above setting.
> 2 votes

---
Tags: views, datetime
---


# Question
Title: FAPI initial checked state for #type => radio
Drupal FAPI reference doesn't have a working example for #type=\>radio. How can I indicate that I want the element to be rendered in a checked state?

```
$form['my_radio_button'] = array(
  '#type' => 'radio',
  '#default_value' => TRUE,
  '#title' => t('Checked by default.'),
);

```

I've tried #default\_value TRUE, 1, and different combinations of #value, but nothing seems to work. Thanks!

# Answer
I may be totally remembering this wrong, but I'm pretty sure you want to add "checked" as an attribute.

# attributes =\> array("checked")
> 3 votes

---
Tags: forms
---


title: hook_context_default_contexts() ?

text:
# Question
Title: hook_context_default_contexts() ?
I used Bulk Export to export all my Context definitions into my module in a function that implements hook\_context\_default\_contexts(). However, my default context definitions do not appear if I delete the ones in the database.

Does this hook no longer work in Drupal 7?

# Answer
> 3 votes
Here's the piece I was missing:

```
/**
 * Implementation hook_ctools_plugin_api().
 *
 * Makes module compatible with context 3.
 */
function MY_MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'context' && ($api == 'plugins' || $api == 'context')) {
    return array('version' => 3);
  }
}

```

# Answer
> 1 votes
It does work in Drupal 7, here you can see an example of a valid code from export created by Features module:

```
<?php
/**
 * @file
 * vw_product_search.context.inc
 */

/**
 * Implements hook_context_default_contexts().
 */
function vw_product_search_context_default_contexts() {
  $export = array();

  $context = new stdClass();
  $context->disabled = FALSE; /* Edit this to true to make a default context disabled initially */
  $context->api_version = 3;
  $context->name = 'shop';
  $context->description = '';
  $context->tag = '';
  $context->conditions = array(
    'path' => array(
      'values' => array(
        'shop' => 'shop',
        'search' => 'search',
      ),
    ),
  );
  $context->reactions = array(
    'block' => array(
      'blocks' => array(
        'facetapi-WVeJBMTHZn1PCfPfrIPnjg1v8m19Gkqd' => array(
          'module' => 'facetapi',
          'delta' => 'WVeJBMTHZn1PCfPfrIPnjg1v8m19Gkqd',
          'region' => 'sidemenu_left',
          'weight' => '-10',
        ),
        'facetapi-H24ObDRB0Wq0KpRW1qalIgb7TvlKP7aj' => array(
          'module' => 'facetapi',
          'delta' => 'H24ObDRB0Wq0KpRW1qalIgb7TvlKP7aj',
          'region' => 'sidemenu_left',
          'weight' => '-9',
        ),
        'facetapi-GxgmQn2y5194O1hZ7qJIROIO63v5BKtG' => array(
          'module' => 'facetapi',
          'delta' => 'GxgmQn2y5194O1hZ7qJIROIO63v5BKtG',
          'region' => 'sidemenu_left',
          'weight' => '-8',
        ),
        'facetapi-zNmFD0ELaD0hTUYX9jyfnhkzHkz5GVvQ' => array(
          'module' => 'facetapi',
          'delta' => 'zNmFD0ELaD0hTUYX9jyfnhkzHkz5GVvQ',
          'region' => 'sidemenu_left',
          'weight' => '-7',
        ),
        'facetapi-kSPIS0vKCobobG533MMOWru8Q42SmByu' => array(
          'module' => 'facetapi',
          'delta' => 'kSPIS0vKCobobG533MMOWru8Q42SmByu',
          'region' => 'sidemenu_left',
          'weight' => '-6',
        ),
        'quicktabs-shop_facets' => array(
          'module' => 'quicktabs',
          'delta' => 'shop_facets',
          'region' => 'sidemenu_right',
          'weight' => '-8',
        ),
      ),
    ),
  );
  $context->condition_mode = 0;
  $export['shop'] = $context;

  return $export;
}

```

Make sure that your module is enabled, that the hook implementation is correct and your caches flushed.

---
Tags: importing-exporting, chaos-tool-suite, 7
---


# Question
Title: HTML inside mini-pager navigation control labels
I'm trying to customize the output of the mini-pager controller (the "next" and "previous" link with arrows) in a view. Actually, it is possible to insert custom text for "previous"-link in the view pager options, in the "tag" section. I tried to add inside the form (for a test), this:

```
<i class="icon-chevron-left"></i>

```

The resulting output is

```
<a href="front?page=1"><i class="icon-chevron-right"></i></a>

```

So actually I think it filters HTML. Do you think it's possible to include HTML?

# Answer
I just spent the last 2 hours trying to solve the same problem, using many different approaches, but I finally managed to get it right.

You just have to override the theme\_pager\_link function in your theme by copying the code content to template.php and change the return (last line), removing the **check\_plain()** function of the **$text** variable, leaving it like:

```
return '<a' . drupal_attributes($attributes) . '>' . $text . '</a>';

```
> 1 votes

---
Tags: views, theming, paging
---


# Question
Title: Drupal 7 - How do I disable media queries for selective pages?
I have a custom theme and currently have media queries setup for my site and I want to disable media queries on certain pages on my site. How can this be done?

# Answer
> 3 votes
There are a few options, but this is not necessarily Drupal specific.

1) move your media query CSS in to its own file(s) and load them only on the pages you want using templates.

2) Use templating to set a class on your tag, and create a new CSS rule that wraps all your media query stuff.

```
@media () {
body:not(.no-media-query) {
    //media query stuff here
}

```

3) Use javascript to set the "viewport" meta tag to a certain width.

---
Tags: 7, theming
---


title: extract views $row values

text:
# Question
Title: extract views $row values
i have created a views filtring contents. i want to use custom tpl and get values of $row variable. How can i extract these valuse?

for example:

```
<?php foreach ($rows as $id => $row): ?>
   <div class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></div>
<?php endforeach; ?>

```

i have tried

```
<?php print_r($row); ?>

```

but no solution.

# Answer
I am facing same problem and get solution as below. Create a tpl as give in **Style output** under theme information.

```
$arr_rows = $view->style_plugin->rendered_fields;
<?php foreach($arr_rows as $key=>$arr_row) : ?>
<?php print $arr_row['field1']; ?>
<?php print $arr_row['field2']; ?>
<?php print $arr_row['field3']; ?>
<?php endforeach; ?>

```
> 4 votes

# Answer
Why don't you use views\_get\_view\_result() ?

https://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/7

Just get results and go trough array - it doesn't matter are you using template or not.
> 1 votes

# Answer
It sounds like perhaps you need to use a different tpl.php.

If you're using a variant of unformatted.tpl.php, try using fields.tpl.php which will give you access to each field output by views.

Ie views-view-fields--view-name.tpl.php

Or I suppose, at a push, you could try work with $view-\>result\[$id\]
> 0 votes

# Answer
You should checkout this answer for the question Create template file for views block which steps through how to identify which templates are "suggested" (or available to be overridden) as well as *the* common mistake of not re-scanning view template files (which is required when views tpl files are added/deleted)

The process for creating templates for views is the same regardless of your view display (page, node, attachment etc)

Following the linked answer's process also provides you with the "default" tpl files which includes a large block of comments outlining available fields in template and how to use them.

*If you just want the data of your view (vs. rendering the data as a template) you should revise your question and provide more details (and I'll do the same)*
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to compare with a rules condition vote:uid to 10 instances?
**Principle**: limit user's votes to 10.

**Modules used**: Voting API, Rate (or maybe Plus1)

**Context**: Users can vote on projects with 10 possible votes to distribut on all projects, by 1 to 10 votes on each project of their choices, up to a total of 10 votes.

When a user has distributed 10 votes, he loses the permission to vote. To swith the permission with rules, I create a role "Voter". All users have the role by default.

At that point, I have this:
\- Event : content is viewed (of type project)
\- Condition : site:current-user:uid equals vote:uid
//And now I'd like to say something like "AND vote:uid appears 10 times in the 'votingapi\_votes'.'uid' SO
\- Action : Add/remove user role to simple AU (without vote permission)

So how to compare with a rule condition vote:uid to 10 instances?

# Answer
In the scenario you describe, a simple solution could be to create a profile field to store the number of votes per user. This field will be:

* set to 0 as a default value
* incremented when the user votes (you can use Rules for that, there is an action called "Set a data value")
* compared with your defined maximum (ex: 10) in Rules, so that when the user reaches 10, something is triggered (ex: Remove user role: "Voting User")

You can then set the voting API permissions to this role ("Voting User"), and use it as a display condition to hide the voting buttons (Plus 1 or Rate).

Hope it helps! Cheers
> 1 votes

---
Tags: rules, rating, database
---


# Question
Title: How to write a module that changes user role when account is created
I am writing a module called "Applicant" and I want it to add a role called "applicant" to a user after the user creates their own account.

**applicant.info**

```
name = Applicant
description = Handles Applicant User Actions
core = 7.x

```

**applicant.module**

```
<?php
function applicant_user_insert(){

}

```

What would I include inside of the hook in applicant.module to access the current user's roles and add "Applicant"?

# Answer
see api page for reference. Replace the values for your "Applicant" role:

```
/**
 * Implements hook_user_insert().
 */
function applicant_user_insert(&$edit, $account, $category) {
  // id of role (probably not neccessary, added here to avoid multiple assertions)
  $key = 3;
  // role's machine name
  $role = 'administrator';
  $account->roles[$key] = $role;
}

```
> 1 votes

# Answer
Don't re-invent the wheel! https://drupal.org/project/registration\_role

Also I think you want to look at user\_presave, rather than user\_insert. https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook\_user\_presave/7
> 1 votes

---
Tags: 7, users
---


# Question
Title: No matter which size is my viewport, the narrow.css file is the only one triggered with IE7 and IE8 in my Omega site
I´m using Omega theme in D7. After configuring all the .css files to achieve an adaptive design, I realize that **ie7 and ie8 looks like hell**.

The problem? The different css files (that have different codes according to different mediaqueries) are not triggered.

**No matter which size is my viewport, the "narrow.css" file is all I see.** Not even the default.css

Is there a workaround to this?

Thanks!

# Answer
You can load css file by using this code:

```
drupal_add_css(path_to_theme() . '/css/ie8.css', array(
  'weight' => 999,
  'browsers' => array('
      !IE' => FALSE,
      'IE' => '(lt IE 9)&(!IEMobile)'),
      'group' => CSS_THEME)
);

```

== 2nd option ==

try Respond.js module

> This Drupal module provides IE 6-8 support for responsive themes.
> 1 votes

# Answer
I ran in to this issue last week and respondjs, for whatever reason, didn't work for me. I ended up using Omega 3, Delta, Context, and Context Useragent together to fix the issue.

1. Add a new template in Delta (Appearance -\> Delta -\> Add).
2. Give your template a title and select your Omega theme from the dropdown and save it.
3. On the next screen click the "configure" option for your template. This will bring up an Omega layout configuration screen.
4. Uncheck the "Enable the responsive grid" box and save it. This gives you a non-responsive version of Omega that will work in IE LTE 8.
5. Add a new context (Structure -\> Context -\> Add).
6. Give it a name.
7. Select "Useragent string" as a condition and enter "MSIE 8" in the field.
8. Select "Delta" as a reaction and select your newly created Delta template.
9. Repeat 5-8 for IE7 (use MSIE 7 for step 7).
10. Clean up the issues with an IE LTE 8 stylesheet.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: 7 - Attachments are not showing in search results for non admins when using apache solr attachments
I am using apache solr search module in my site, and using local Tika extraction for indexing attachments.

When I logged in as admin I can able to search attachments as well as nodes, but if I logged in as other user attachments are not showing up in search results, only nodes are showing.

Do I need to do any settings for this? I have provided Seach permissions for all the users in people tab.

Any help will be appreciated, Thanks.

# Answer
One dirty hack for this problem is: **Disable Apache Solr Access module** and than the file search should work fine for other users as well.

But first check if there are permission available for Solr Access, if not than you may try this hack and see if this works.
> 1 votes

# Answer
If you need the Apache Solr Access *and* the attachments, see the issue here which has a patch: https://drupal.org/node/1782936
> 0 votes

---
Tags: 7, users, search
---


# Question
Title: Drupal says "There was a problem creating field ZZZ: Table field_data_field_ZZZ already exists"
I've run into this periodically: I'm working on a new site and go to add a field that I've created at some point in the past only to find out that it's not available. When I try to add a 'new' field (usually using the same title & machine name, because they pop up when I start typing), I get this message:

> There was a problem creating field ZZZ: Table field\_data\_field\_ZZZ already exists

There are several posts out there on this issue, but none of the solutions really tell the whole story.

Why did this happen and how do I fix it?

# Answer
> 7 votes
**Problem**

It's possible that something else could cause this, but it doesn't seem too likely.

The problem comes from using backup\_migrate to recover or overwrite your database when there is some degree of disparity in the fields in the different databases. Here's one example of how things can get out of sync:

1. I start by building out a complex set of content types on my local machine.
2. I copy the database over to a staging site periodically so I have a stable copy and so other people can do other things.
3. I forget that I added some fields on my localhost.
4. I use backup\_migrate to grab the latest copy of the database. (This is where things start to go wrong - it could happen without a dev/staging scenario too, if, for example, you roll-back to an earlier backup of your own database. There are probably many ways things can get out of wack like this.)
5. I then see that my field is missing - doh.
6. When I try to recreate the field I get that rotten message. *You tell me it exists, but you won't let me add the rotten field??!?*

**What's going on**

The problem is two-fold:

1. Backup\_migrate doesn't drop all the tables when you restore a database so the `field_data_field_zzz` and `field_revision_field_zzz` tables are not removed.
2. However the `field_config` table and the `field_config_instance` tables are completely replaced. This is where Drupal keeps track of the fields that have been created, so now it has no idea that `field_zzz` ever existed.

**The immediate solution:**

Take a look at the known fields (the contents of `field_config`). Any fields that are not listed there need to be cleared out of the database, if you want to recreate them. Just drop the `field_data..` and `field_revision..` tables from the database. Now you can go about your business as usual.

**..and the haunting:**

The problem is that fixing this on your local machine does not fix the problem on other instances of your website. For instance, if you clean things up and push them up to a staging server, that server is not going to delete unused tables either. Then at some point in the future you'll grab a copy of that database and experience the pain all over again. You will google the same query, end up at this post again and call me rotten names for giving you a solution that failed.

**The definitive solution:**

Frankly, understanding the problem is the biggest step. The second biggest step is to make sure you fix *all* instances of your site. So once you have a nice clean version of your site, you'll want to

1. drop all the tables on your other site(s)
2. go to install.php and create a blank drupal site
3. enable backup\_migrate
4. now when you restore your clean db, you won't have all that baggage
5. repeat on each site (we usually have multiple localhost/dev installs, then a staging and live site)

In reality, there are a lot of reasons this may not be feasible, but now you should know enough to create your own work-around.

---
Tags: 7, entities
---


title: Multilingual Valid Path (Domain Access)

text:
# Question
Title: Multilingual Valid Path (Domain Access)
I have a path controlled by page manager & domain access selection rules.

Let's say I'm on the Main (US) version of the page, and I need to know of the spanish version of the page is valid.

/contact-us

/es/contact-us

I've tried things like drupal\_valid\_path, drupal\_lookup\_path, etc.

The only option I've found is to do something like menu\_get\_item() Then hack the global language, call the callback from menu\_get\_item with

```
//hack global language here
$router_item = menu_get_item($path);
$page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
if (MENU_NOT_FOUND != $page_callback_result) {
   //url is not valid
}
//set global language back to original

```

Is there a simpler more generic way to programmatically do this? If there were some function like drupal\_valid\_path that would just say if the path results in 404 or not, that would be great, though I haven't found something like that yet.

# Answer
> -1 votes
We use the Link Checker modules on our sites. This would scan all links and give a report back as to which are broken, if any. I don't see any reason why this would not work on any site, including multi lingual.

Whether or not you use the module, you should be able to look at the code to get an idea of what functions and logic it's using to create similar functionality, if you're looking to do it programmatically.

---
Tags: 7, domain-access, chaos-tool-suite
---


# Question
Title: Product variations getting same name as product
I did google this and found the following:

https://drupal.org/node/2146759

however, I cannot seem to find the fields they are indicating. Maybe I have the wrong version of commerce?

# Answer
Okay, I guess I was unfamiliar with the terminology. Here is what I did to find this, in case it helps anyone else. First go to Structure (which because I have the kickstart installed is actually in Site Settings under the Advanced column) then go to content types. Find the product type you want to edit, go to manage fields, edit the product variations and down the page a bit is a checkbox called "Auto generate the product title".
> 0 votes

---
Tags: commerce
---


# Question
Title: Is there a token I can use to display a node's view mode?
I am trying to use Rules to send an email with the results of the submission of a node. Is there any way to place the entire contents of the node using a token?

```
e.g. [node:teaser]

```

# Answer
Look at the Advanced Entity Tokens module.

> Advanced Entity Tokens (AET) Creates a Token for each of your entity items.
>
> Through AET you can query the DB for entities using Tokens.
>
> **Examples**
>
> * \[aet:node:1\] will return the 1st node with the token view mode (or full if token is not available).
> * \[aet:file:1:view-original\] will return the 1st file entity with the original view mode.
> * \[aet:taxonomy\_term:1:name\] will return the 1st node title field (note that this level of chaining is done by the formal token implementation of the node entity in token/token.tokens.inc -\> token\_token\_info()).
>
> **Real World Examples**
>
> * Displaying a node inside a block: This could be done using Node Block OR you could insert a token inside a block you create through the Blocks interface that retrieves a certain node (or a property inside a node, \[aet:node:\] or \[aet:node::body\]) with no extra code.
> * Displaying a File Entity (image) inside a title field: I'm not sure how this could have been done without custom code, BUT with AET you could easily insert the Token for a specific File Entity (\[aet:file:\]) and your entity will be displayed. AET defaults to the Token view mode if available (full otherwise), but you could just as easily specify a view mode of your own (\[aet:file::view-teaser\]).
> * I'm saving this spot for real life examples other Drupal users had (or thought of having) for this module.
> 2 votes

---
Tags: rules, tokens
---


title: Code for Social Button

text:
# Question
Title: Code for Social Button
The social button module allows us to use tokens so the share button can target the node url instead of the page url, when we are using views to display content. However, I'm not sure how the code and tokens should be used to achieve this. My code for the addthis button is as follows:

```
<div class="addthis_counter addthis_pill_style"></div>
<script type="text/javascript">var addthis_config = {"data_track_addressbar":true};</script>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-52a0220165a70d6d"></script>

```

The code I'm currently using (as shown above) shares the entire page instead of the node which the button is attached to. Social buttons module allows the addition of a field to the content type so the button is tied to the particular content node and I'm trying to get the button to share the content in the node rather than the page, which is a view listing.

So my question is, how do I use tokens in the code for the share button?

# Answer
> 0 votes
I managed to target the individual content nodes using the following code. Hope this helps someone.

```
<a href="http://www.addthis.com/bookmark.php"
    class="addthis_counter addthis_pill_style"
   addthis:url="[node:url:absolute]"
   addthis:title="[node:title]"></a>

```

---
Tags: social-network
---


title: Redirects within hook_user_login

text:
# Question
Title: Redirects within hook_user_login
I'm writing a module that redirects the user on login and am having trouble getting anything to work. Here is what I tried within hook\_user\_login:

**submission.info**

```
name = Submission
description = Handles Redirect to node/add/page on Login
core = 7.x

```

**submission.module**

```
function submission_user_login(&$edit, $account) {
  //$_REQUEST['destination'] = 'node/add/page';
  //$GLOBALS['destination'] = 'node/add/page';
  //$edit['redirect'] = 'node/add/page';
  drupal_goto('node/add/page');
}

```

# Answer
> 7 votes
Try to change `drupal_goto` with $\_GET\['destination'\], e.g.:

```
function submission_user_login(&$edit, $account) {

   // Redirect user to to desired location.
   $_GET['destination'] = 'node/add/page';
}

```

Hope this will work.

# Answer
> 1 votes
You can use Login Destination module to redirect user after login. This module have many customization for redirecton of user. For more info go through the documentation of module.

# Answer
> 0 votes
You can use Rules module to do this very easily..

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

OR

You can use below code to redirect inside hook\_user\_login implementation ..

```
function YOURMODULENAME_user_login(&$edit, $account)  {
  $GLOBALS['destination'] = 'node/add/page';
}

```

You also need to implement hook\_drupal\_goto\_alter to perform redirect

```
/**
 * Implements hook_drupal_goto_alter
 */
function YOURMODULENAME_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  // Note that this functionality cannot be backported do 6.x as Drupal 6 does
  // not call drupal_alter for drupal_goto.

  // This actually may be used also by templates.
  if (isset($GLOBALS['destination'])) {
    $destination = $GLOBALS['destination'];

    // alter drupal_goto
    if (is_array($destination)) {
      $path = $destination[0];
      $options = array();
      if (count($destination) > 1) {
        $options = $destination[1];
      }
    }
    else {
      $path = $destination;
    }
  }
}

```

---
Tags: 7, hooks, users, redirection
---


# Question
Title: How to make a contextual filter optional
I'm making a contextual filter, to pass along an argument from a panel to a view, using `Content: Has taxonomy term ID`.

This is so that it pulls in a keyword from a URL.

However, I want it to work so that when no keyword is passed in, it goes based on the last URL parameter.

For example:

www.example.com/tech/startup

It should pull ONLY things with both tech and startup if this is passed.

However, if the URL is just:

www.example.com/tech

Then it should show ALL articles with the tech taxonomy term.

How do I do this?

# Answer
> 7 votes
You can use Exceptions setting in views like below

And point your menu link to www.example.com/tech/all instead of www.example.com/tech

---
Tags: views, panels
---


title: Add class on cck image field(img tag)

text:
# Question
Title: Add class on cck image field(img tag)
I want to add a class on cck image field output img tag, not on field wrapper div. How can i do it?

# Answer
I think you should use Field Formatter CSS Class module for this. Module page says :

> The Field formatter CSS class module allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.
> 1 votes

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


title: image hover with views

text:
# Question
Title: image hover with views
I have created 2 image-fields in my content type image-main and image-hover. The image-main is an album display and when you hover the album cover it must change to the image-hover.

How can I get this working.

# Answer
yes, this is sounds good, you can nicely use the replacement pattern for the views, and there is nice tutorial for css3 hover effect you can use this. Click here After adding two field to your view hide the first image field and use the replacement pattern of the next field.In that replacement pattern you can put the variables as like bellow..this is just an example

```
<div id="cf">
 [fieldone]
 [fieldtwo]
</div>

```

then this two image will wrap with a div now you can add class name to the image tag as shown in the example.Hope this will help you.
> 0 votes

---
Tags: views, media, javascript
---


title: Active trail when view has argument

text:
# Question
Title: Active trail when view has argument
Let's say I have the view with arguments. My path to view page is `/products`. The path that contains argument eg. `3` looks like this `/products/3`.

Now as the view is displayed without arguments and the `product` path is in the main menu - active class for menu item is displayed correctly, however if I add path with argument `product/3` and link it in my menu then there's not active item.

How to extort Drupal to show active item?

# Answer
There are couple of modules for this.

1)Menu Position

Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

2) Menu Trail By Path

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1 Menu Items with these paths will get the active-trail class on them and expand accordingly.

blog blog/category1 blog/category1/article1

**Note:** I'm not sure about(didn't use) **Menu Trail By Path** module. but I used Menu Position module and works great for me.
> 2 votes

---
Tags: 7, views
---


title: Registration help

text:
# Question
Title: Registration help
In drupal 7 I want to register function hook. when we click on register submit the values need to store in another database's table and with that inserted id need to store in user table. how we can write custom module for that

I wrote custom module like :

```
function hook_user_save($account, $edit = array(), $category = 'account') { // custom code

}

```

but it not working

# Answer
if you want to store the data during user registration try hook\_user\_insert
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to prevent views from loading the results upfront
I have views block with exposed filters and ajax enabled which was rendered in home page, the problem is when the block is loaded with exposed form views is loading the results too. However I want the results needs to be shown only when the user clicks on the submit button.

If I enable input required, this will work, but the client doesn't want this.

# Answer
Here is the way to solve your issue:

1. Add Contextual filter of "Global: Null" type
2. In "When the filter value is NOT available" section check "Provide default value" and specify "Fixed value" and "all". Notice! If view still display results - then try select "Raw value from URL" here.
3. In "When the filter value IS available or a default is provided" section check "Specify validation criteria" and select "PHP code"
4. Specify this code

if (count($view-\>exposed\_input)) { return TRUE; }
5. In "Action to take if filter value does not validate" select "Display all results for the specified field" value
6. Don't forget to add any "No results behavior"!

Now results will be shown ONLY if filters are sent. View will be empty on first display.
> 5 votes

# Answer
1. Edit your view and click on advanced to reveal more options
2. in the Exposed form block click on Exposed form style - basic
3. click on the option "input required"

You're done.
> 4 votes

# Answer
Add an exposed filter and hide it( using css etc). When somebody clicks "Apply" then change the hidden filter value using Javascript and submit.

Initially set the exposed filter value to not to generate any View results
> 0 votes

# Answer
```
  $view = views_get_view("VIEW NAME");
  $view->set_display('DISPLAY ID');
  $view->init_handlers();
  $form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );
  $form = drupal_build_form('views_exposed_form', $form_state);
  return drupal_render($form);

```

Just add the above code in a block.
> -2 votes

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


# Question
Title: Create role for changing user accounts and not admins
I am developing a documentation site for a client. The site has the option of *Who can register accounts?* set to *Visitors, but administrator approval is required*.
So, currently only *Admin(user1)* is doing the user approval procedure.

Our client has a customer services team which handles this account approval procedure currently. So, if I create a new role (say moderator) and give it permission to administer users (blocking/unblocking, changing role of a particular user), then they will also be able to modify admin users' account; and this is not expected.

Is there a way(any module or either) to restrict moderators to administer only few roles and not admins' role? Is there any other way to do this?

I am looking something similar to this sandbox project, but I want different set of permissions.

# Answer
As far as I can see, the accepted workaround is not secure. It would not prevent editing the administrator account via direct URL such as user/2/edit.

Maybe try the User Protect module:

> This module allows fine-grained access control of user administrators, by providing various editing protection for users. The protections can be specific to a user, or applied to all users in a role.
> 1 votes

# Answer
This module might be what your looking for. http://drupal.org/project/administerusersbyrole

With it you will get permissions for any role to change any other role. Here is a screen shot of it in action on the permissions page.
> 2 votes

# Answer
There is role\_delegation stable for D7.

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
> 2 votes

# Answer
**Work around:**
I created a new role *Manager* who will manage the user administration (approval of the pending users who are *blocked*, depending of their criteria).

I gave "Administer users" permission to this role. And in *admin/people* used a hook\_form\_alter to hide the list of users with administer users permissions.

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_admin_account') {
        global $user;

        if(!in_array('administrator', $user->roles)) {
            $result = db_query("select uid from {users_roles} where rid=3"); //rid=3 for administrators

            foreach($result as $temp) {
                unset($form['accounts']['#options'][$temp->uid]);
            }
        }
    }
}

```

This way users with only administrator role will be able to edit other administrators :)
Any suggestions or feedback would be highly appreciated.
> 0 votes

# Answer
Did you see the Advanced User module? Which allows to filter users list and apply action on them like block/unblock. Details from its project page:

> The advanced user module allows the filtering of users based on the user.module fields and optionally the profile.module fields. The fields available for filtering can be configured using the module settings. Eg. Site admin may search through 1000s of users to display all users who have not accessed their account.
>
> Once the group of users with selected common denominators are filtered, the module can be used to perform functions that email, block, unblock, add or remove roles, or delete. Another nice feature is the ability to notify administrators or other roles, by email, of user account creation or profile changes.
> 0 votes

---
Tags: 7, users
---


# Question
Title: The "more" link does not direct to the page
I am very new at using Drupal some of the answers I see here seem to be the solution but I don't understand the terminology, so if some could explain in simple terms step by step I would be grateful. The problem is that I create a press release which appears on the front page as expected together with a "more" link, however, this does not direct one to the actual article but back to the page I am already on. Please if someone could help me and guide me through the procedure to fix this I would be very happy. Ian

# Answer
> 0 votes
I guess what's been bothering you is the "preview" of you nodes.

First, by default, your new "content" ( i guess you are using articles) are promoted to the front page, but that's not where you can find all of them, especially the older ones. It's works like a "latest news" page.

Second, those articles are shown as a "preview", only the first few lines of its content can be read. The "more" link send to the full content of your article.

This link appears even if the article is short enough to be completely read in preview mode, because, only inside the page with the full content you can, for example, add comments etc... etc...

Maybe you didn't notice this because right now the articles you are writing for testing purpose are just too short

---
Tags: navigation
---


# Question
Title: view query alter : Subselects/query don't work with out brackets
I was trying to alter a view query with a subselect that looks like:

```
$subquery1 = (db_select('users_roles', 'r')
   ->where('r.uid = users_node__users_roles.uid and r.rid=10'));
$subquery1->addExpression('COUNT(r.rid)', 'rid');
$query->add_where(1,'1', $subquery1, '<>');

```

where $query is the main query. But when i run the view, the query

> ...AND (1 \<\> SELECT COUNT(r.rid) AS rid FROM users\_roles r WHERE (r.uid = users\_node\__users\_roles.uid and r.rid=10))...

if i put brackets for the sub select query it will working fine. ie;

> ...AND (1 \<\> (SELECT COUNT(r.rid) AS rid FROM users\_roles r WHERE (r.uid = users\_node\__users\_roles.uid and r.rid=10)))...

So my question is; How can i put the subquery inside brackets? sorry if my question is stupid?

Thanks in advance, PREM

# Answer
I had found the soln myself; put NOT IN instead of \<\>. NOT IN will make the value part inside the brackets
> 0 votes

---
Tags: users, views, database
---


title: Adding multiple menus entries to a view

text:
# Question
Title: Adding multiple menus entries to a view
We have a view with a page attached to it. By default the settings screen pictured below lets you add only a single menu entry for the view.

Is it possible to have this featured in two or more menus as menu links?

# Answer
> 1 votes
Yes, you can add as many menu items as you like in the menu administration section of the website.

1. Go to admin/structure/menu
2. Click the "add link" link for the menu you want to add an item to
3. Add the menu item to the path you are using for you view.

---
Tags: views, routes
---


# Question
Title: How to find a Data Selector in a rule condition?
**Update 3**: **I just need to know how to find a Data Selector in a rule condition**

In a Commerce Kickstart distribution:

To reproduce:

1) I added a billing field called: "VAT NUMBER" at: "admin/commerce/customer-profiles/types/billing/fields"?

2) I created a Sale Tax at: admin/commerce/config/taxes

3) For this new Sale Tax I clicked at "configure component" to edit the "rule component" for the tax.

4) Now inside the rule: in Conditions I need to check if the field: "VAT NUMBER" is empty

Here is my problem: I don't know which is the **Data Selector** to get the field: "VAT NUMBER" and make the comparation.

I found this screencast which shows how to create a conditional tax based in the address field: http://www.drupalcommerce.org/videos/tutorials/drupal-commerce-condition...

I need to do the same that is shown in the video with the only difference that the condition for the video is based in the **address field** and in my case I need to base the condition to the value of "VAT NUMBER"

**UPDATE**: This post is no the solution that I need, but it might help to put it in the right direction: http://www.drupalcommerce.org/faq/rules-field-data-selection

**UPADE 2** I tried to use the condition "Entity has field" but I can't find which is the right Entity to select to get the condition to TRUE

# Answer
> 2 votes
Found the way:

To drill to the selector I have to create 2 "entity has field" conditions.

1) entity "site:current-cart-order" has field "commerce\_costumer\_billing"

2) entity "site:current-cart-order:commerce-customer-billing" has field "vat\_number"

then I can select the data selector

---
Tags: rules, commerce
---


# Question
Title: show product reference field with both add to cart and render product display format
i want to show product reference field with both add to cart and render product display format how i will do that?

Any help is appreciable.

I mean when i view a product it will show both add to cart form with all type of product variation.

Thank you all in advance.

# Answer
> 1 votes
oh very easy i do it with template just create new template node--product--type--full.tpl.php .

and use this

```
<?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);

      $options = $node->field_product[$node->language];
      foreach($options as $index => $option){
      $cmp_btn = drupal_get_form('properties_compare_add_form_' . commerce_product_comparison_create_key('commerce_product', $option['entity']), 'commerce_product', $option['entity'], $node->nid);
      $content['field_product'][$index]['commerce_product'][0]['cmp_btn']=$cmp_btn;
      $content['field_product'][$index]['commerce_product'][0]['cmp_btn']['#attributes'] = array('class' => array('compare-form' . $option['product_id']));

      }
      print render($content);
    ?>

```

i remove the add to cart button in view an set the display to `render product`

---
Tags: commerce
---


title: how to change views pager links?

text:
# Question
Title: how to change views pager links?
I am using the full pager in views module. I am displaying 40 items per page. The full pager display links like this

```
1 2 3 4 5 next last

```

I want to change it to this

```
1-40 41-80 81-120 next

```

How will I do this? Any idea about this?

# Answer
You need to override theme\_pager function in your template.php

You need to do couple of changes,

* Use global $pager\_limits variable, use in pager list rendering links to alter text data

Use below code which works

```
function YOURTHEMENAME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];

  global $pager_page_array, $pager_total, $pager_limits;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« first')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
          'class' => array('pager-first'),
          'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
          'class' => array('pager-previous'),
          'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
            'class' => array('pager-ellipsis'),
            'data' => '…',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
              'class' => array('pager-item'),
              'data' => theme('pager_previous', array('text' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0], 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
              'class' => array('pager-current'),
              'data' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0],
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
              'class' => array('pager-item'),
              'data' => theme('pager_next', array('text' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0], 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
            'class' => array('pager-ellipsis'),
            'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
          'class' => array('pager-next'),
          'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
          'class' => array('pager-last'),
          'data' => $li_last,
      );
    }
    return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
        'items' => $items,
        'attributes' => array('class' => array('pager')),
    ));
  }
}

```

And the result you can see below.
> 5 votes

# Answer
You can easily do it with Pagerer module, see the demo in action.

> Pagerer is a module providing a collection of pager themes to enhance Drupal and Views standard pagers.
> 3 votes

---
Tags: 7, views, paging
---