# Question
Title: Use a search bar (exposed filter) to search for different node fields
I am trying to make an advanced search with exposed filters and views in drupal.

I am trying to achieve the following:

On the left textfield, the user would input whatever he wants to search, and the views will only search by the field selected in the list at the right (field\_A in the picture example). (In short, the column by which to search would be the one selected in field to the right)

NOTE: field\_A, field\_B, etc, would be all from the SAME node type.

I can make it work easily if I only have 1 field to search by (this field is set by interface when you configure the autocomplete functionality in drupal).

What I want is to be able to dynamically supply the field to search by, because said field will depend on what the user chooses from the combo box at the right (as explained in the note, this combo box will have different choiches field\_A, field\_B, field\_C....etc).

Would it be better to create a custom module instead of using Views with exposed filters?

Thanks.

# Answer
> 0 votes
Views with exposed filters, and then a bit of custom js should do the job fine.

Basically loop over the fields that are there and use them to build a select so users can choose which field to search. The existing fields names relate to the query string key that we need to use.

Something like this should suffice:

```
(function($) {
  Drupal.behaviors.viewsSearchBar = {
    attach: function(context, settings) {

      // Build the HTML for the new field we are adding.
      var newField = '<div class="views-exposed-widget views-widget-filter-combined-search" id="edit-combined-search">';
      newField += '<input type="text" class="form-text" maxlength="128" size="30" value="" name="combined-search-text" id="combined-search-text">';
      newField += '<select id="combined-search-field">';

      // Loop over the existing widgets to add options to our new select.
      $('.views-exposed-widgets .views-exposed-widget').each(function(){

        var title = $(this).find('label').text().trim();
        var value = $(this).find('input').attr('name');

        if(title && value) {
          newField += '<option value="'+value+'">'+title+'</option>';
          // This this widget
          $(this).hide();
        }

      });

      newField += '</select></div>';

      // Add our new field.
      $('.views-exposed-widgets').prepend(newField);

      // Create a submit function for the views search form.
      $('.view-filters form').submit(function(e){

        // Stop the form doing it's default action.
        e.preventDefault();

        // Build the new URL.
        var baseURL = window.location.protocol + '//' + window.location.host + window.location.pathname;
        var field = $('#combined-search-field').val();
        var text = $('#combined-search-text').val();

        // Off we go...
        window.location = baseURL + '?' + field + '=' + text;

      });

    }
  };

})(jQuery);

```

Further work that needs to be done:

* Check if there is already a search argument in the query string and set the default value of the custom search field and select.

---
Tags: search, views
---


title: Boost Cache, External CDN?

text:
# Question
Title: Boost Cache, External CDN?
I have been thrown into a Drupal 6 environment, helping a client whose site has been running terribly for some time now. Among other issues, they had a ton of traffic and were serving it all locally, so we aim to implement a CDN.

Our CDN of choice is Incapsula, who operate much like Cloudflare if you're familiar with them. At their most basic, they can cache static content. Should be simple.

What I'm finding is that when Incapsula's caching is enabled, the cache never updates. If you go through the public address to the site, you will see old content. It's not just old images and CSS, entire pages will be missing if they are added after the cache is enabled. If you bypass the proxy, you see the correct content. Manually clearing the cache from within the Incapsula control panel does not resolve the problem, I can only do that by actually disabling the cache. Of course, while it is enabled, the site flies!

Complicating this, they have Boost installed and enabled. I am new to Drupal, newer to Boost, and I am attempting to understand how the caching works but have not made much progress. Are there specific settings within Boost that might affect this? It feels like a header is misconfigured. Any thoughts and advice are appreciated!

# Answer
> 0 votes
If the CDN caches whole pages you can most likely disable boost.
https://drupal.org/project/advagg \- Needed for D6 CSS/JS
https://drupal.org/project/imageinfo\_cache \- Should help with imagecache generation

# Answer
> 0 votes
I work at Incapsula.

This does sound like a cache header issue. (perhaps Drupal Boost assigns prolonged "maxage" values?)

One way or another, you can override these settings using our Advance Control options. http://www.incapsula.com/blog/popping-the-hood-on-website-acceleration.html

One of the selectors there allows Incapsula to automatically override existing maxage and no-cache directives, using its own cache header logic.

You can also manually set your own caching settings: for all resources and for specific resource groups (e.g. all resources set to refresh each 5 minutes and all \*.jpg files set to refresh once a day)

Moreover, you can also configure refresh rates for specific resources (e.g. all resources are refreshed every 5 min, all images are refreshed once a day and a homepage banner updated once a month)

I'll be happy to provide more case-specific assistance but, to do that, I\`ll need to know the domain name.

---
Tags: 6, caching, cdn
---


# Question
Title: Cannot get Colorbox trigger to Display image as a link and link to Body of node
I am using Colorbox and Colorbox Node modules in combination with Views.

I would like to link images (displayed in a view) to the respective body fields of the nodes.

In my view, I am trying to use a Colorbox trigger field. I would like it to display an image and link it to the Body. However, the image seems to be opeing up a new page and displaying the same image... How do I get it to display the body of the nodes instead?

I've got the trigger field set to Image Popup is set to

I've ticked Rewrite the output of this field, and set the text to

I've also ticked the Output this field as a link option, and set the Link path to: http://mysiteurl\[path\] I've also set the Link class to colorbox-node

What am I missing in order to get the Image to link to the Body of the node, and display it in a pop up, not a full new page?

# Answer
The order of the fields are important when you're using 'Rewrite the output as field' option.

In my views, I took the following fields

1. Path - (Exclude from display)
2. Image
3. Title

In the rewrite the output as field option, I did the following thing with the help of tokens from Replacement Patterns.

`<a href="[path]" class="colorbox-node" data-inner-width="600" data-inner-height="600">[field_profile_image]</a>`

And yes, this did work.

I'm able to get my page's body in popup when ever I click on an image.
> 1 votes

---
Tags: views, javascript
---


# Question
Title: Ldap group configuration - Derive from attribute
I am using Lightweight Directory Access Protocol (LDAP) and I have a question about how to put Active Directory users in a certain role based on an attribute such as memberOf.

In version 1.0, you could say in drupal authorization under II.B. DERIVE DRUPAL ROLES that you could look for memberOf or ... and when the user that logs in, has the particular role in that attribute, he receives the role that is defined in part IIA.

For example, you can have this in section IIIA - Role Mapping: CN=Head,OU=Roles,OU=Accounts,DC=Domain,DC=be|beheerder

How can we do the mapping in version 2.0? My groups that I have, are stored in the active directory in extensionattribute14

Kind Regards

# Answer
I've handled this by calling a update user account function during validation against the AD.

First fetch the attributes of that account:

```
$filter = "(sAMAccountName=" . $username . ")";
// This is where you will need to add in extensionattribute14.
$attributes = array('sAMAccountName', 'givenName', 'sn', 'description', 'telephoneNumber', 'userAccountControl', 'distinguishedName', 'memberOf', 'proxyAddresses', 'Mobile', 'facsimileTelephoneNumber', 'mail', 'employeeNumber');
$result = ldap_search($conn, $ldap_base_dn, $filter, $attributes) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($conn, $result);
$entryid = ldap_first_entry($conn, $result);
$attrs = ldap_get_attributes($conn, $entryid);

```

And then then call the update account function (`$attrs` from above is passed in as `$values`):

```
/**
 * Makes updates to the users account based on values passed from the AD
 * @param  object $account
 * @param  array $values
 */
function update_user_account($account, $values) {

    // ...
    // Code here to update other values from the AD
    // ...

    if(isset($values['memberOf'])) {

        // Loop over groups.
        foreach($values['memberOf'] as $k => $group_dn) {

            switch($group_dn) {
                case 'CN=GRPHO Intranet Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][8] = 'Editor';
                    break;
                case 'CN=GRPHO Intranet User Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][9] = 'User Editor';
                    break;

                // etc. etc.

            }

        }
    }

    // add back in any roles that this user had that are not controlled from the AD
    if(isset($account->roles[3])) $updates['roles'][3] = 'administrator';
    if(isset($account->roles[15])) $updates['roles'][15] = 'site admin';

    user_save($account, $updates);

}

```
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: How can I prevent placeholders to wrap the value with single quotes in db_query?
I want to run a select query using db\_query. Here is the code:

```
$nid_array = array(24,34,56,7,8);
$list_of_nids = implode(',',$nid_array);
$query = "  SELECT *
            FROM {table_name} as t
            WHERE t.nid IN (:list_of_nids)";
$placeholders = array();
$placeholders[':list_of_nids'] = $list_of_nids;

$result = db_query($query, $placeholders)->fetchAll();

```

This query does not return any results. Although if I do not use placeholders & replace `:list_of_nids` with `$list_of_nids`, then I get proper results.

I believe that when using placeholders the value of `:list_of_nids` is taken as the $list\_of\_nids wrapped with single quote, which is causing problem here.

I want to use placeholders. So, how can use it without wrapping the value with single quotes.

# Answer
You're imploding your array into a string, so PDO will (correctly) put quotes around it. PDO can handle arrays just fine, though, no need for manual manipulation:

```
$nid_array = array(24,34,56,7,8);

$query = "  SELECT *
            FROM {table_name} as t
            WHERE t.nid IN (:list_of_nids)";

$placeholders = array();
$placeholders[':list_of_nids'] = $nid_array;

$result = db_query($query, $placeholders)->fetchAll();

```
> 4 votes

---
Tags: database
---


# Question
Title: How to add a select menu to a form with the ability to insert new values?
I need to add a select field to a form, but I also want the ability to add more values to select field later on. How can I accomplish this in Drupal 7?

I heard (read) some place that you can accomplish something like this with a custom content type? but isn't there any better method to do this?

# Answer
> 0 votes
What sort of form?

If it is a node creation form simply add a field of type "term reference" and base your select on a a taxonomy vocabulary.

If it is a custom form then I would still use a taxonomy vocabulary to hold the terms but manually populate the select:

```
$my_vocabulary_vid = 5;
$terms = taxonomy_get_tree($my_vocabulary_vid);
foreach($terms as $term) {
  $options[$term->tid] = $term->name;
}

$form['select'] = array(
  '#type' => 'select',
  '#title' => t('Selected'),
  '#options' => $options,
);

```

# Answer
> 0 votes
As a first step, You can use Select or Other module to collect values from user if not available...

Project page says

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

As a second step, You need to read this values on hook\_node\_presave and insert it into select list available options using code like below..

```
// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);

```

---
Tags: 7, forms
---


title: Advanced Views Filter

text:
# Question
Title: Advanced Views Filter
I would like to build a view (slideshow) of profiles, which is relatively easy to do. However I would like to filter them based on a node field of the page the view will be displayed on. I defined a new content type called Category, where I describe categories in more detail. One of the node fields is called category.

My profiles also have a field category. The idea is that when a user views the node Category A, I would like to display a view showing all the profiles belonging to Category A. When the view Category B, I would like to display all the profiles belonging to Category B.

Can this be done via Contextual Filters? If so, how?

I'm not sure if this helps but the Category values are stored in Taxonomy.

# Answer
> 0 votes
Sorry for the confusion with the comments above. So hopefully the system will accept this as the answer:

In summary make sure you following all steps provided in the answer including:

5. Under "When the filter value IS in the URL or a default is provided" check "Specify Validation criteria"
6. Select the vocabulary being used.
7. Under "Filter Value type" pick term name converted to term ID"
8. Checking "Transform dashes in URL to spaces in term name filter values" will insure that any auto generated path alias' that have converted spaces to dashes are properly handled. Try your view with this checked and unchecked.

# Answer
> 0 votes
1. Add contextual filter on term id
2. select **Provide default value**
3. select type **content id from url**
4. also change your path to **\[your\_path\]/%**

---
Tags: views
---


# Question
Title: Add help text to checkbox options on node form
How can I add help text to each option on checkbox option on drupal node form. I do not want to add this from UI while adding values for the field. Using hook\_form\_alter I do not believe we have option to add description to options of a checkbox field.

Example: "which game you want to play" is the checkbox field.

which game you want to play?

\[\] cricket

-- cricket is awesome.

\[\] football

-- football is more than awesome.

# Answer
I tried to do this first by overriding checkboxes theme hook **theme\_checkboxes($var)** with preprocess hook **template\_preprocess\_checkboxes($var)** but there was not any option to set *#suffix* property to individual checkbox, Then i figured out that **theme\_checkboxes** theme hook call the **theme\_checkbox** hook for individual checkbox then i tried to override **theme\_checkbox($var)** with **template\_preprocess\_checkbox($var)** but that also didn't worked, I was able to set *#suffix* and *#field\_suffix* property on individual checkbox but that was not rendering because individual checkbox's *#processed* property was already set to True, I tried by setting that *false* but no success :(

I tried by setting **pre\_render** callback and **process** callback but too didn't worked, May be i was making some mistake.

This is preprocess hook for checkboxes theme hook:

```
function template_preprocess_checkboxes($variables) {
  $variables['element']['element_name']['#printed'] = FALSE;
  $variables['element']['element_name']['#processed'] = FALSE;
  $variables['element']['element_name']['#suffix'] = 'This is help text';
  $variables['element']['element_name']['#pre_render'][] = 'mymodule_checkbox';

  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'][] = 'form-checkboxes';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
}

function mymodule_checkbox($var){
  $var['element']['#suffix'] = 'this is help text added by pre render callback';
}

```

Then i tried the same with template\_preprocess\_checkbox($var)

```
function template_preprocess_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';

  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  if ($variables['element']['#parents'][0] == 'parent_field_name') {
    $variables['element']['#attributes']['#processed'] = FALSE;
    $variables['element']['#attributes']['#field_suffix'] = t('This is simple help text');
    $variables['element']['#suffix'] = 'another suffix';
  }

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

Can someone help me too on this?
> 1 votes

# Answer
you can do it like this:

```
function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == 'yourformid') {
   $form['your_checkbox_field'] = array(
     '#field_suffix' => t('Field help text.')
   );
 }
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: Add translation only for a particular content type
I don't have much experience in Drupal and I am trying to create multilingual content for a particular content type. I want to switch the language inside the content instead of changing the whole site language. I have used the i18n module to do this but the whole site gets changing. For example I am using right to left languages like Arabic, Farsi etc. I am using views to list the items for this content type.

# Answer
> 1 votes
It's by design...

Drupal Content translation using modules like i18n and locale works for complete site... For example if you are using Arabic language and if you add a arabic translation for a particular node, if you are viewing arabic version of node complete site changes from right to left..

As a work around..If you just want to add translations i would suggest use modules like Entity reference and node clone to connect english version with other versions and use select box to choose language.. You need to add links to redirect user to other versions based on above reference logic.. Keep in mind by implementing above you will loose Drupal powerful Multilingual feature..

---
Tags: views, nodes, i18n-l10n
---


# Question
Title: Altering Create New account tab link in user login page
I tried using form alter for menu of tabs in /user page, that shows

"create new account", "login", request password

is it possible for us to alter the link so that the create new account can go to "customlink" instead of "user/register"

in drupal 7?

thank you!

# Answer
> 2 votes
Well, you could use `hook_menu_alter()` to change the call back function of that menu item:

```
function MY_MODULE_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'my_custom_function';
}

```

And then you could redirect to a new page in the callback:

```
function my_custom_function() {
  drupal_goto('customlink');
}

```

---
Tags: theming, routes
---


title: Add new variable in Computed field

text:
# Question
Title: Add new variable in Computed field
Can I add new variable in Computed field? The added variable will be used only in the computed field

# Answer
Yes you can

```
Computed Field is a very powerful field module that lets you add a custom "computed
fields" to your content types.

```

> These computed fields are populated with values that you define via PHP code.
> 0 votes

---
Tags: entities
---


# Question
Title: Stylesheet for specific page overwritten by standard css
In my subtheme.info I have :

```
stylesheets[all][] = css/style.css

```

And in my template.php I have:

```
function subtheme_preprocess_page(&$vars) {
    $path = current_path();

    if ($path == 'user/login') {
        drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css");
    }
}

```

But when I load the page, my `style.css` is declared after my `login.css`. So my styles in `login.css` are overwritten by `styles.css`. How can I make sure the `login.css` is declared after the `styles.css`?

# Answer
Add weight to the CSS:

```
drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css", array('weight' => 100));

```

See the `drupal_add_css()` API page for more info. The **group** option may also be relevant as this also affects the weight.

Also if the specificity of a rule in style.css overrules a rule in login.css it won't matter what order the CSS files are included.
> 3 votes

---
Tags: theming, 7
---


title: Private 'My Files' in Drupal Commons

text:
# Question
Title: Private 'My Files' in Drupal Commons
I am using the latest release of Drupal Commons and I have Private Files configured and working.

I would like to allow users to upload files to their individual user profile, which only the individual user can view/download after upload. For example, a user may upload 3 files to their profile, but these should be private and not visible or accessible to any other site user.

With Private Files configured, I thought this may be possible via a File field on the user profile, but I have been unable to restrict view to the document owner.

Has anybody acheived a similar result with Commons (with or without addional modules)?

Thank you

# Answer
> 1 votes
I've done this before using the IMCE module. The description from the module page says:

> IMCE is an image/file uploader and browser that supports personal directories and quota.

So spot on for your needs.

---
Tags: users, 7, files
---


title: Show nodes related to referenced node

text:
# Question
Title: Show nodes related to referenced node
I have 3 content types: "Files", "Actions" and "Templates".

* In each "Files" node there's a entity reference to an "Actions" node
* In each "Templates" node there' a entity reference to an "Actions" node

How can I setup a view that shows a list of links to "Templates" nodes on a "Files" node page, based on the entity reference to an "Actions" node for this specific "Files" node?

Edit - I couldnt get Felix' answer to work, so here's a more detailed description of my case:

I have a node called "BAG001", this node has content type "Files.
I have a node called "Procedure A1", this node has content type "Actions"
I have a node called "Form A1", this node has content type "Templates"

In "BAG001" I make an entity reference to "Procedure A1" (field name is "field\_action")
In "Form A1" I make an entity reference to "Procedure A1" (field name is "field\_related\_action")

On the "BAG001" page there's should be a views generated block, showing all templates related to "Procedure A1". In this case that would be "Form A1".

I tried setting up a view using the following settings:

* 1) Relationship -\> Entity reference: field\_action
* 2) Relationship -\> (Content entity referenced from field\_action) Entity Reference: Referencing Entity \[with a relationship to (1)\]
* 3) Contextual filter -\> Content: NID \[with a relationship to (2)\]

# Answer
> 1 votes
1. Create a view that shows a list of templates.
2. Add a relationship to the actions content type (Entity Reference: Referenced Entity via field\_related\_action).
3. Add a relationship to the files content type (Entity Reference: Referencing entity via field\_related\_action).
4. Create a contextual filter based on the current nodes nid. When you create the filter then When the filter value is NOT available select Provide default value and choose content ID from URL. Also this filter should be for the second join to the file node type.
5. Set that view to show in a block on each files page.

# Answer
> 0 votes
1. Set reference field in Files content type to display Actions
2. Set up corresponding entity references between Actions and Templates
3. Create a display for Actions, that will display only corresponding entity references of Templates.
4. Use this display in 1.

---
Tags: 7, entities
---


title: CDN JS -- cannot seem to weight it

text:
# Question
Title: CDN JS -- cannot seem to weight it
I'm adding external JS in my Drupal 8 site (//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js) and I cannot seem to weight it using `hook_js_alter`. I can weight it if I throw it in a themename.libraries.yml file but then it gets rendered in every page. Ideally I want to only render the script in the home page. So this works:

```
function MYTHEME_js_alter(&$js) {
  if (drupal_is_front_page()) {
    $leaflet = '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js';
    $js[$leaflet] = drupal_js_defaults();
    $js[$leaflet]['data'] = $leaflet;
    $js[$leaflet]['type'] = 'external';
    $js[$leaflet]['every_page'] = TRUE;
    $js[$leaflet]['weight'] = -100;
  }
}

```

... but it weights it last and I'd like to weight it so it loads much earlier.

if I load it via a theme.libaries.yml file, it weights it lower but it renders on every page.

```
MYTHEME-corescripts:
  version: VERSION
  js:
    //cdn.leafletjs.com/leaflet-0.7.2/leaflet.js: {}
    js/scripts.js: {}

```

I'm open to this method if I could somehow add context to the YAML file to indicate only fore the home page.

# Answer
> 0 votes
The method below works superbly. `hook_page_alter` is the way to go and the `#attached` method. (as suggested in a comment instead of `hook_preprocess_page` I didn't know this would work for external js but it does. Pretty cool. With this method and a nested array with weight, it works as expected.

```
function MYTHEME_page_alter($cache) {

  if (drupal_is_front_page()) {
    // Render leaflet only on the home page
    $leaflet = array(
      '#attached' => array(
        'js' => array(
          '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js' => array(
            'group' => JS_LIBRARY,
            'weight' => -999
          ),
        ),
      ),
    );
    \Drupal::service('renderer')->renderRoot($leaflet);
  }
}

```

Also of note is that we use `JS_LIBRARY` instead of `JS_THEME` here.

---
Tags: 8, theming, cdn
---


# Question
Title: Conceptual Question...Link to an exposed filter result created by a view in Drupal 7
I haven't been able to find the answer by searching, so i thought I would pose this question, I realize there may be more than one right answer, but basically I want to link to a specific result of an exposed filter without having to disable ajax.

I have a block created by a view on a panels page which will have the latest 4 magazine issues. (image and link) I want to link to a specific result in the exposed filter, when the user clicks-through.

The exposed filter has year (-3+3) and season which has the taxonomy terms (fall, winter, spring, summer) The default (when terms are not selected) is to show 4 of the latest magazine issues sorted by most recent. Since there are only 4 issues per year and the year will be relative to "now"; Would the way to go about this be to clone the view with the exposed filter page 4 times for each season? How would one re-write the link to go to that specific result in the exposed filter? I'm sure there are other options, to achieve this, so please let me know.

Thanks.

# Answer
You could disable ajax, and then set your exposed filter to the relevant values for each link, and then save the url of each page.

Then re-enable ajax however use the links you previously saved to create hard coded links to the view with specific filters.

This works because even if ajax is enabled you can still pass in arguments via the query string.
> 1 votes

---
Tags: views
---


# Question
Title: How to save current User Points as field at moment of adding a node?
The registered users on my website can create nodes from a content type called 'Stuff'. I'd now like to display the author's User Points he/she had when he/she created the node. That means: the value shouldn't be updated when the author's User Points change in the future.

How can I do that? Can I do a similar thing for comments?

Can this be done with a code/dynamic/preprocess field, provided by the Display Suite module?

---

@arpitr's tip for using the Computed Field module seems a pretty good idea, but as I replied to his answer, I don't know anything about PHP. I tried the following code, but it doesn't work.

```
global $user;
$entity_field[0]['value'] = "userpoints_get_current_points($user->uid)";

```

# Answer
> 0 votes
I've achieved this by adding a new integer field 'Userpoints' to comments and nodes. After that, I created a rule for the events "After saving a new comment/new content" and used the action "Set a data value" to set the 'Userpoints' field's value.

# Answer
> 0 votes
Simply add one more field to the Stuff content type and use Computed Field module for adding that field.Since field is on content type so its value will be added while adding the node with the value of user points user will have while creating it,afterwards it will be same or depends on php code computing value for this field.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

---
Tags: 7, nodes, comments, display-suite, userpoints
---


# Question
Title: How can I catch the current node object and make changes into it before it is rendered?
I have a content type with multiple fields.

On the node display page I want to do some modification on this node (like. changing label text etc.) and I want to do it for display only. Nothing should change in the database.

I want to know how can I do this? Where exactly can I catch the current node object and make changes into it before it is rendered?

# Answer
`hook_node_view_alter`

> This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.
>
> If the module wishes to act on the rendered HTML of the node rather than the structured content array, it may use this hook to add a #post\_render callback. Alternatively, it could also implement `hook_preprocess_node()`. See `drupal_render()` and `theme()` documentation respectively for details.
> 2 votes

# Answer
You should use the preprocess hook for this task.

For example, you can add in your theme :

```
function yourtheme_preprocess_node(&$variables) {

  if ($variables['view_mode'] == 'full' && $variables['node']->type == 'your_node_type') {
    // Change the $variables['node'] whatever you want here
  }
}

```
> 2 votes

---
Tags: 7, nodes, theming
---


# Question
Title: Ubercart Node/Product Field access to Role and purchaser
I have an Ubercart ecommerce Drupal 7 site I'm building. The user can either subscribe (monthly/annually) or purchase node by node (pay as you go).

I need to GRANT the subscriber or purchaser access to the main body field of the product node only, as teasers and image fields etc will be used elsewhere on the site. (This rules out a few node\_access options)

I would like to combine the permissions in my own custom module, as the I can't see any contrib permissions modules that fit my needs. e.g. Node access product.

Is there an simple custom way to ALLOW access to a field after I have checked if the user has:

a) Purchased this node, or
b) is a subscriber with access (I'm using uc\_recurring for ROLE assign on purchasing a subscription).

I think it could due done manually in a module checking directly for current logged in users role(s) and purchases (nid's) and seeing is the logic plays out, but will this be slow on performance when there are 1000's users and 1000's products?

Please let me know if you need any more information or if I'm on the right track.

# Answer
I think the Field Permissions module may be able to handle all your needs.

Whilst you couldn't have a different permission for the teaser text of a node you could just separate this out into a separate field and then apply an individual permission there.
> 0 votes

---
Tags: ubercart, users
---


title: Creating a new user role with Drush

text:
# Question
Title: Creating a new user role with Drush
I can do loads of user-related stuff with Drush, but I can't see how to create new user roles. Is it possible to do this with Drush?

# Answer
This functionality is available in Drush 8.x-6.x:

```
 role-add-perm (rap)   Grant a specified permission to a role.
 role-create (rcrt)    Create a new role.
 role-delete (rdel)    Delete a role.
 role-list (rls)       Display a list of all roles defined on the system.  If a
                       role name is provided as an argument, then all of the
                       permissions of that role will be listed.  If a
                       permission name is provided as an option, then all of
                       the roles that have been granted that permission will be
                       listed.
 role-remove-perm      Remove a specified permission from a role.
 (rmp)

```

Unfortunately, this has not been backported to the 7.x-5.x branch, so it probably won't be in the soon-to-be-released Drush-5.9, and isn't in Drush-5.8. For now, you'll have to use the dev branch to get it.
> 8 votes

# Answer
To get a list of all drush based commands just type `drush` at the command prompt and it will list all the set of commands available.

`drush help [command]` to view command-specific help.

Run `drush topic` to read even more documentation.

**Drush user specific commands**

> User commands: (user)
>
> user-add-role (urol) Add a role to the specified user accounts.
>
> user-block (ublk) Block the specified user(s).
>
> user-cancel (ucan) Cancel a user account with the specified name.
>
> user-create (ucrt) Create a user account with the specified name.
>
> user-information Print information about the specified user(s). (uinf)
>
> user-login (uli) Display a one time login link for the given user account (defaults to uid 1).
>
> user-password (upwd) (Re)Set the password for the user account with the specified name.
>
> user-remove-role Remove a role from the specified user accounts. (urrol)
>
> user-unblock (uublk) Unblock the specified user(s).
> 4 votes

# Answer
Here's a Drush script I made to use with Drush 5.9. Just name as `user_roles.drush.inc` under `~/.drush` and then `drush cc drush`.

```
<?php
// user_roles.drush.inc
// author: yuvals

function user_roles_drush_command() {
        $items = array();

        $items['roles-delete'] = array(
                'description' => 'Delete one or more user roles.',
                'arguments' => array(
                        'ids' => 'Comma delimited list of user role IDs (rid).',
                ),
                'examples' => array(
                        'drush roles-delete 30,31,32' => 'Deletes the specified user roles.',
                        'drush roles-delete' => 'Prompts for selection of user roles to delete.',
                ),
                'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
        );

        $items['roles-list'] = array(
                'description' => 'Lists user roles.',
                'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
        );

        return $items;
}

function drush_user_roles_roles_list() {
        foreach (user_roles() as $rid=>$name) {
                        drush_print(sprintf("%-7d\t%s", $rid, $name));
        }
}

function drush_user_roles_roles_delete($ids = NULL) {

        $roles = user_roles();

        if ($ids == NULL) {
                $options = array();
                foreach ($roles as $rid=>$name) {
                        // keys must be string otherwise array_merge inside drush_choice_multiple overwrites them
                        $options['.'.$rid] = $name;
                }
                $selection = drush_choice_multiple($options, FALSE, 'Choose which user roles you would like to delete.', '!value');
                if ($selection == null) {
                        return;
                }
                $ids = array();
                foreach ($selection as $id_string) {
                        $ids[] = intval(substr($id_string, 1)); // hack - remove '.' prefix; see above
                }
        }
        else {
                $valid_ids = array();
                $ids = explode(',', $ids);
                foreach ($ids as $id) {
                        $id = intval($id);
                        if (isset($roles[$id])) {
                                $valid_ids[] = $id;
                        }
                }
                $ids = $valid_ids;
        }

        if (count($ids) == 0) {
                return drush_log(dt('No user roles to delete.'));
        }
        $message = dt("The following @number user roles will be deleted:\n", array('@number' => count($ids)));
        $role_table = sprintf("%-7s%s\n", dt('rid'), dt('name'));
        foreach ($ids as $id) {
                $role_table .= sprintf("%-7d%s\n", $id, $roles[$id]);
        }
        $role_table = sprintf("%-7s%s\n", dt('rid'), dt('name'));
        foreach ($ids as $id) {
                $role_table .= sprintf("%-7d%s\n", $id, $roles[$id]);
        }
        $message .= $role_table;

        if (drush_confirm($message)) {
                foreach ($ids as $rid) {
                        user_role_delete($rid);
                }
                drush_log(dt("@number user roles were deleted:\n@role_table", array('@number' => count($ids), '@role_table' => $role_table)));
        }

}

```
> 1 votes

---
Tags: drush
---


title: Add subtitles to register form

text:
# Question
Title: Add subtitles to register form
I'm trying to add some titles in my registration form. This is a part of my registration form:

But now I would like to have some titles like the following:

I know that you can alter the registration form like this:

```
function mytheme_form_user_register_form_alter(&$form, &$form_state, $form_id) {

}

```

But I don't know which attributes or ... to use.

**UPDATE:**

I'm now trying out the markup.

This is what I do:

```
function xmed_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['mail'] = array(
        '#markup' => '<p>testtttinnng</p>',
        '#weight' => 116
    );
}

```

But this just replaces my email content ...

# Answer
You can use Field group Contributed module...

Project page says..

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
> 2 votes

# Answer
You have several alternatives:

* Use #markup element. The markup element you can add arbitrary HTML to the form. Just place your markup in the right place using the #weight attribute (form elements are sorted by this value).
* Use a fieldset element, wrap your element inside and theme that fieldsets. you can create a fieldset for every header and then move the form elements inside each corresponding fieldset.
* Use the #prefix and/or #suffix element's attributes, where you can also put HTML code.

Example using the markup:

```
function xmed_form_user_register_form_alter(&$form, &$form_state, $form_id) {

    $form['account']['pre_mail_markup'] = array(
        '#markup' => '<p>testtttinnng</p>',
        '#weight' => 100
    );

    $form['account']['mail']['#weight'] => 105;
}

```
> 1 votes

---
Tags: theming, users, forms
---


title: Changing file name on upload

text:
# Question
Title: Changing file name on upload
I'm trying to automatically add prefixes to uploaded file names so they can later be processed by non-drupal scripts. I want to do that while the user is uploading files during creation/editing of a node.

To do that I am using `hook_file_validate($field)` where I check if the file is correct and then using `$field->destination` I define a new file name.

Surprisingly my issue lies in getting context to generate the proper file name (`nid` of the node,`nid` of the parent group, or info from other fields). When I upload a file, only part of the website is reloaded by javascript and `hook_file_validate` is triggered before `hook_form_alter` . Whene it is triggered I have no access to any data that would tell me where am I.

So far I have tried:

```
$_REQUEST['destination']

```

while defined (not a typo) when the whole form is loaded, it is undefined when the file field of the form is reloaded

```
$_GET['nid']

```

again - undefined

```
arg(0); arg(1); arg(2);

```

returns `file ajax field_quest_file` which is not very usefull

I can access `uid` but it is not enough for me to create unique file names.

# Answer
Following on from my comment suggesting you do this in an additional submit handler something like this should work:

Add the new submit handler:

```
function misc_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    $form['actions']['submit']['#submit'][] = 'rename_files';
  }
}

```

And then in the new submit handler:

```
function rename_files($form, &$form_state) {

  $node = $form_state['node'];

  global $user;

  // Loop over the uploaded files. Be sure to re-name field_files to the name of
  // your file field.
  foreach($node->field_files[LANGUAGE_NONE] as $item) {

    // Load the file object
    $file = file_load($item['fid']);

    // To set the destination first remove the filename from the stream wrapper
    // URI.
    $destination = str_replace($file->filename, '', $file->uri);

    // Modify this line to the name of your group field.
    $group = $node->field_group[LANGUAGE_NONE][0]['value'];

    // And then append the group, uid and put the filename back on the end.
    $destination .= $group.$user->uid.$file->filename;

    // And finally rename the file.
    file_move($file, $destination);
  }

}

```
> 4 votes

# Answer
Instead of renaming the files I used a different approach and change their destination folder.

I do it from the level of `hook_form_alter` where I have full access to POST/GET arguments and the values in other fields of the form.

```
function myModule_form_alter(&$form,&$form_state,$form_id){
    switch($form_id){
        case 'nodetype_node_form':
            //prepare whatever prefix you want
            //in my case gid/uid/
            $dest_folder = _make_destination_folder($form);
            //findout which file will be added next
            //the form is rebuild each time a file is uploaded
            $delta = form['field_files'][LANGUAGE_NONE]['#file_upload_delta'];
            //instead of renaming files just change the destination folder
            form['field_files'][LANGUAGE_NONE][$delta]['#upload_location'] = 'private://'.$dest_folder;
            break;
    }
}

```

This way files end up in an unique, non random and predictable place before the node is even saved. A bonus of this approach is that I will have the files sorted in folders based on group and user
> 1 votes

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


# Question
Title: Related nodes by taxonomy term in a view block of drupal7
I want to show related nodes to the current node in a block using taxonomy terms. In my site say x is my taxonomy vocabulary and x1,x2,x3,x4,x5,x6 and x7 are the taxonomy terms under it. A node could be tagged with any of these taxonomy terms. Say node T is tagged with x2 and x3. node W tagged with x3, x1 and x5. node c tagged with x2 and x6. node R tagged with x2 and x7. F tagged with x4,x6. H tagged with X2,x5. Now when the node T is displayed I want items having any of the taxonomy terms similar to the current node i.e. X2 or x3 but the priority should be x2 i.e. list all the related nodes with x2 as tag first and then only with x3. so in the above case i need related nodes in the order C R H W? How is it possible by using views in drupal 7?

# Answer
> 0 votes
There will be a significant amount of customization (in the form of a module) to get this done through views. I've created a sandbox module that you can install to get things working and so you can play around with it (see views.api.php in the views module).

Once enabled you should find a new contextual filter value called "**The node whose taxonomies you want to relate**". This contextual filter default will take the current node ID and return nids of nodes that share the same terms in vocabularies that you select. Therefore, please set the view display as a block.

If you need to know how to group by term using views, please see this answer.

---
Tags: views
---


title: Drupal fetching object

text:
# Question
Title: Drupal fetching object
I am trying to fetch an object:

```
$field_name= 'field_test';
$json_code = $node->$field_name['und'][0]['value'];

```

NOT WORKING

```
$json_code = $node->field_test['und'][0]['value'];

```

WORKING

I must have variable because it's every time different field name

any solution?

# Answer
Your PHP is incorrect for what you're trying to accomplish.

Drupal has `field_get_items()` for this purpose, though:

```
$items = field_get_items('node', $node, $field_name);
...

```
> 5 votes

# Answer
Clive is right about `field_get_items()` but if for some reason you absolutely want it the way you wrote it, then this will work ( notice the curly braces ) :

```
$json_code = $node->{$field_name}['und'][0]['value']

```

Though you should replace `['und']` with the constant `LANGUAGE_NONE`, e.g. :

```
$json_code = $node->{$field_name}[LANGUAGE_NONE][0]['value']

```
> 2 votes

---
Tags: hooks
---


# Question
Title: Cann't delete the CSV file after imported by Feeds module
We uninstalled the "Feeds" and "Job Scheduler" modules, after a successful imported csv data by Feeds. However, the csv file is still maintained in "media" list. When we try to delete that file, it say "The file xxx.csv is in use and cannot be deleted". Is there a way to delete that, or do we have to delete from FTP?

# Answer
> 2 votes
The "file still in use and cannot be deleted" means Drupal's still managing the file, so don't remove it via FTP because that basically bypasses Drupal and could cause other issues related to Drupal expecting a file to be somewhere and it's suddenly not there. So I'd recommend finding a solution that involves working via the UI and not directly on the file system.

Is the file attached as a field to an item of content somewhere? That would result in "file still in use". If so, delete the item of content, clear cache a few times and check again.

# Answer
> 0 votes
Just in case, run the file through `file_usage_list()` to be absolutely sure it's not used anywhere else. You never know.

If only Feeds comes back as a result, you can then always run the file through `file_delete()`, though you'll have to use the `$force` parameter.

---
Tags: feeds, media
---


# Question
Title: Is there a way I can display one image field if another one does not exist using visibility rules in node template?
I can do something like this with a text field, because I can compare it to an empty string, but I can't figure out how to do it with an image field.

Visibility rules supports content:exists, but this only applies to the content the rule applies to, not another field.

**Is there a way I can display one image field if another one does not exist?**

# Answer
> 1 votes
I would suggest using views to create a block based on the filter criteria where the first image field is empty.

# Answer
> 0 votes
**Use a View with the "Views Is Empty" module**

It seems there is no way to filter for an empty image or file. One way to filter for the existence of an image/file in a view is to add a relationship and also require the relationship. This only works if the image/file exists, but there is no converse (a test for it NOT existing).

The "Views Is Empty" module enables a view to display one image/file if it exists and another if it doesn't.

To use this, you:

1. Add both image/files to the view.
2. Exclude these from the view
3. Add the "View Is Empty" field
4. Select the two image/files in the settings for this new field.

In this solution, the view is added to the Node Template rather than either of the fields.

# Answer
> 0 votes
Let's say the two fields are called 'field\_use\_if\_present' and 'field\_fallback' and your content type is 'article'. Then you can use this code in custom module named 'yourmodule':

```
<?php
/**
 * Implements hook_node_view
 */
function yourmodule_node_view($node) {
  if ($node->type === 'article') {
    if (empty($node->content['field_use_if_present']) {
      $node->content['field_use_if_present'] = $node->content['field_fallback'];
    }
    // Don't use this next line if you're managing
    // show/hide/display of field_fallback with some other functionality.
    $node->content['field_fallback'] = array();
  }

}

```

---
Tags: nodes
---


# Question
Title: Theming and overriding taxonomy term/vocabulary page
I have a taxonomy vocabulary (Authors) which is used only for the Books content type. What I would like to achieve is to create a file (taxonomy-term--authors.tpl.php) in which I can customize the HTML markup.

1. Currently when I create the file I can only more static markup instead of modifying the output of the books which contain the specified term.
2. I also tried to use the mytheme\_preprocess\_page() and give a template suggestion but when I add content to the file it's not rendering how I would expect. It does not include header/footer styles and other stuff.

I also tried using Views module but the behavior is similar to first point 1.

# Answer
> 2 votes
You can have full control over the taxonomy/term/ID page by intercepting the menu call with hook\_menu\_alter() and let the content be generated by a custom function.

This allows you to completely customize the taxonomy term page. You can check for a certain vocabulary ("Authors") and have a custom generated page for that vocab and leave the others untouched.

You can have fine grained control over how results are displayed using view modes and templates.

No contributed modules are needed.

Here is an example to be used in a custom module. The custom content is generated using Drupals EntityFieldQuery because it is a lazy and robust way of generating a list of content, but anything goes here. .

```
/**
 * * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$menu) {
  if (isset($menu['taxonomy/term/%taxonomy_term'])) {
    $menu['taxonomy/term/%taxonomy_term']['page callback'] = 'YOURMODULE_taxonomy_term_page';
    $menu['taxonomy/term/%taxonomy_term']['access arguments'] = array(2);
  }
}

/**
 * Callback function for taxonomy/term/%taxonomy_term.
 *
 * @param $taxonomy_term object
 * @return * Themed page for a taxonomy term, specific to the term's vocabulary.
 */
function YOURMODULE_taxonomy_term_page($term) {
  $voc = taxonomy_vocabulary_load($term->vid);
  switch ($voc->machine_name) {

    case 'SOMEVOCUBALARY':

      // here you generate the actual content of the page
      // could be done e.g. with an entityfieldquery as follows

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
              ->fieldCondition('field_gallery', 'tid', $term->tid)
              ->propertyOrderBy('sticky', 'DESC')
              ->propertyCondition('status', 1);
      $result = $query->execute();
      if (!empty($result['node'])) {
        $build['content']['nodes'] = node_view_multiple(node_load_multiple(array_keys($result['node'])), 'teaser'); // output the node teasers. you can control the markup of the 'teaser' view mode with a template in the theme folder
      } else {
        $build['content']['status']['#markup'] = t('No results found for term ID !tid.', array('!tid' => $term->tid));
      }
      return $build;

    // If the term page is for an other vocabulary then use Drupal's default taxonomy page
    default:
      module_load_include('inc', 'taxonomy', 'taxonomy.pages');
      return taxonomy_term_page($term);
  }
}

```

# Answer
> 1 votes
Try this code:

```
/**
 * Implements hook_preprocess_taxonomy_term().
 */
function YOURTHEME_preprocess_taxonomy_term(&$variables) {
  if ($variables->vid == YOUR_VOCABULARY_ID) {
    $variables['theme_hook_suggestions'][] = 'taxonomy_term__authors';
  }
}

```

# Answer
> 0 votes
You can use the Taxonomy Views Integrator, or its working patched version.

Navigate to yoursite.com/admin/structure/taxonomy/yourtaxonomyvocabulary/edit and choose your view and view display for every vocabulary you have.

# Answer
> 0 votes
Each term has link taxonomy/term/TERM\_ID and if you want vocabulary based theme(customize HTML markup) on terms pages then you can use "Taxonomy Views Integrator" module.

On particular vocabulary edit page you can select views template. And in that views template you can write customize html so, that pages with taxonomy/term/TERM\_ID get themed.

---
Tags: 7, taxonomy-terms, theming
---


# Question
Title: setting comments unpublished by default for a content type?
I want to open the comments for a content type by should be unpublished by default. Currently the comments are published by default.

Is there any way to accomplish this task. There is no option in the comments settings of the

# Answer
If you don't want users to add comments without admin approval then you need to disable the below permission...

**Skip comment approval**

Once you disable it users would be able to post comments but they will not be visible to other users until the comment is approved by an admin.

This would set the permission for the entire contents and not for a specific content type.

If you want to set it for a particular content type then you would need to look into one of the contributed modules

commentaccess

Allow anonymous comments per node type

Comment Permissions \- Stable Version only for 6 does not have a stable 7 version yet
> 6 votes

# Answer
You can make a custom module to do this.

```
<?php
/**
 * Implement hook_permission
 * Defines a new permission that can be selected per role at the page
 * admin/people/permissions
 */
function MY_MODULE_permission() {
  return array(
    'skip required comment approval' => array(
      'title' => t('Skip "Require comment approval"'),
      'description' => t('For nodes with "Require comment approval" set, this user\'s comments skip moderation'),
    ),
  );
}

/**
 * Implement hook_form_alter for BASE_FORM_ID node_form
 * This modifies all node add/edit forms
 */
function MY_MODULE_form_node_form_alter(&$form, &$form_state) {
  // Move 'Require comment approval' field into the comment settings fieldset
  if (isset($form['field_require_comment_approval'])) {
    $form['comment_settings']['field_require_comment_approval'] = $form['field_require_comment_approval'];
    unset($form['field_require_comment_approval']);
  }
}

/**
 * Implement hook_comment_presave
 * This hook runs before a comment is saved to the database, allowing us to
 * modify the comment as it is being saved
 */
function MY_MODULE_comment_presave($comment) {
  // If the parent node has the field "Require comment approval" checkbox set,
  // make the new comment's status set to "unpublished"
  if (empty($comment->cid)) {
    $node = node_load($comment->nid);
    if ($node && ($items = field_get_items('node', $node, 'field_require_comment_approval'))) {
      $item = !empty($items) ? reset($items) : array('value' => FALSE);
      if ($item['value']) {
        $account = user_load($comment->uid);
        // Comments for users with the 'skip required comment approval' permission
        // skip this step
        if ($account && !user_access('skip required comment approval', $account)) {
          $comment->status = COMMENT_NOT_PUBLISHED;
        }
      }
    }
  }
}

```

The code relies on a field added to your individual content types with the machine name `field_require_comment_approval`. This field can actually be set to true or false per node, allowing some nodes to require comment moderation and other nodes to allow comments posted to skip validation.
> 1 votes

---
Tags: 7, nodes, comments
---


title: If points equal value: reset to zero

text:
# Question
Title: If points equal value: reset to zero
I use the User Points module. I've set a rule that add 10 points per content viewed. This was easy. THEN I want to check if user points is greater than 100 and, if it is, send an email to admin, AND set points to that user back to zero.

# Answer
Download the Rules module and import the following rule:

```
{ "rules_reset_points" : {
    "LABEL" : "Reset points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Points" ],
    "REQUIRES" : [ "php", "rules", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "global $user;\r\n$num_pts = userpoints_get_current_points($user-\u003Euid, \u0027all\u0027);\r\nif ($num_pts \u003E 100) {return TRUE;}" } }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "userpoints-transaction:user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "loaded_points" : "Number of points in the specified category." } }
        }
      },
      { "data_calc" : {
          "USING" : { "input_1" : [ "loaded-points" ], "op" : "*", "input_2" : "-1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "userpoints-transaction:user" ],
          "points" : [ "result" ],
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Prevent more than 100 points.",
          "operation" : "Add",
          "display" : 0,
          "moderate" : "approved"
        }
      }
    ]
  }
}

```

Adapt the actions to your needs, add another action "Send mail" after installing the Mime mail module (this article may help you in doing that) and you're done!
> 2 votes

# Answer
* User hook\_userpoints($op, $params = array())

Use this hook to act upon certain operations. When other modules award points to a user, your hook will be called, among others.
* $op = "points after"
* Read user points and check for \> 100 condition
* Use userpoints\_userpointsapi() to reset points
* Deduct 100 points

$params = array ( 'uid' =\> $user-\>uid, 'points' =\> -100, ); userpoints\_userpointsapi($params);
* Send Email to admin using hook\_mail
* Above functions has been clearly explained in Readme.txt file inside module folder.
> 1 votes

---
Tags: userpoints
---


# Question
Title: Custom content type displayed without theme
Working in Drupal 7, I've created a custom content type "Announcement", intended to be distinct from the regular Article type. I haven't added any custom fields or anything esoteric.

The thing works, I can create Announcements and they show up as teasers in a blocks view I have set up for the purpose.

But when I click the teaser link, the announcement page is displayed as a basic HTML page - no theme. I'm using the Marinelli theme and it displays everything else just fine.

Here's the view, located in a sidebar, looks fine:

---

Clicking the link....

---

What am I missing?

# Answer
I gave up in the end, deleted the content type, recreated it, and it worked. So something must've gone wrong when I first created it, but I never saw an error indication.
> 0 votes

---
Tags: nodes
---


title: Field To Display Message

text:
# Question
Title: Field To Display Message
Is there any Field to display Message and Images instead of taking values ??

In Drupal Commerce I have created few fields to take Custom Measurements on Order Settings page.

Now I need to display a Picture and a text message on the page where I am taking measurements.

# Answer
> 1 votes
You can use Markup module using which you can add text or HTML which will display a picture..

Project page says

> This module adds the ability for site admins to add "Markup" widgets to the form. These essentially let designers of cck content-types insert additional markup into the node/edit form to display to content-authors. This is the equivalent of adding additional elements to $form of the type '#markup'.

---
Tags: 7, entities
---


title: Organic Group Content type name

text:
# Question
Title: Organic Group Content type name
I am using the Organic Groups module and am following the readme file. I am on step 2:

> Create a new content type via admin/structure/types/add. Call it "Group", and define it to be of Group type.

Just curious, can I call it another name rather than " Group"? like "Site", or something else...

Thanks!

# Answer
> 0 votes
Yes, you can call it whatever you want. It's a regular content type like any other, i.e Page, News, Event, Blog post, etc.

Perhaps this will help: Absolute Beginner's Guide to Organic Groups (OG)

Cheers,

---
Tags: organic-groups
---


# Question
Title: How to get MEDIAN of value in a view field
I have 5 integer fields and I want to show the MEDIAN result for those fields in my content view. How to get the result?

# Answer
> 2 votes
You can use Computed Field module to achieve this.

About Computed Field

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

# Answer
> 0 votes
You can also achieve this by implementing`hook_node_presave`.

> Act on a node being inserted or updated.
>
> This hook is invoked from `node_save()` before the node is saved to the database.

---
Tags: views
---


# Question
Title: Drupal 7 Domain Access Module Gives 500 error, WSOD for subdomains
I am attempting to get Drupal 7's domain access module working. I have the original domain that the site was built on, and 2 more domains, all configured from a local apache virtual host configuration.

I can log in and configure with the original domain name "localhost", but when I try to log in with any of the other domains I configured I get a 500 Internal Server Error.

Domains Configured (for local use): 1)localhost 2)drupalx.domainaccess.com 3)drupaly.domainaccess.com

This is the domain configuration page for domain's in Drupal. Note I have 3 domains configured, localhost, drupalx, drupaly.

I know that the domains I set up work because if they did not then this next image would have a warning saying that the domain module could not access files on the domain name. I also verified this by using the drupalx/drupaly domains and I was able to access css files in a subfolder of the drupal install using these domains.

Here is the home page for the drupalx domain. The only page that can be accesssed is the home page.

If I try to go to any other page in drupalx or drupaly I get a 500 error, WSOD.

Here is my virtual host setup

I don't have any drupal reports on this, and my apache logs only gave the 500 error info

ie: 127.0.0.1 - - \[24/Apr/2014:16:54:46 -0700\] "GET /user/register HTTP/1.1" 500 530

# Answer
OK, might as well add a tentative answer on this one.

Add your subdomains using ServerAlias within the same single VirtualHost, because they all have the same document root.

```
ServerName www.example.com
ServerAlias drupalx.example.com
ServerAlias drupaly.example.com

```

Fix the stray rewrite stanza in virtualhost scope.

e.g put it inside the Directory block.

```
<Directory "C:\xammp\www">
  <IfModule mod_rewrite.c>
    RewriteEngine on
    # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
  </IfModule>
</Directory>

```

However, the latter isn't really needed if using the default .htaccess file in your doc root. Alternatively, remove .htaccess and copy its contents to the Directory block instead.
> 2 votes

---
Tags: 7, domain-access
---


title: Don't sanitize the more link in a view?

text:
# Question
Title: Don't sanitize the more link in a view?
Currently any HTML added to the "More link" output in a view is sanitized. This is undesirable for me. How can this be changed so that this field is not sanitized?

# Answer
> 1 votes
The most direct way would probably be to do something along the lines of...

```
function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='THE_VIEW_YOU_ARE_LOOKING_FOR' && $display=='THE_DISPLAY_YOU_ARE_LOOKING_FOR') {

     $vars['more']= // the exact html you want to have in your more link

  }

}

```

If you would rather work with just templates, you can copy `views-view.tpl.php` to your theme and name it appropriately, eg, `views-view--VIEW_NAME.tpl.php`, and then modify the following in it:

```
<?php if ($more): ?>
  <?php print $more; ?>
<?php endif; ?>

```

to whatever you want `$more` to be.

Clear theme registry/caches and you should be all set in both cases.

ADDITION DUE TO COMMENTARY:

Gotcha. However, the more link is generated from inside the view display plugin via `render_more_link()` and it eventually creates it by calling up a theme template via...

```
return theme($theme, $path, check_plain($this->use_more_text())); // D6

```

or

```
return theme($theme, array('more_url' => $path, 'link_text' => check_plain($this->use_more_text()), 'view' => $this->view)); // D7

```

...both implementations of which `check_plain()` the text entered via the UI.

So, in order for this to work via the UI, you will most probably need to craft up a new views display plugin without that `check_plain()` in there.

It also goes without saying that you will need to have implicit trust in the folks working with the UI to not enter any errant HTML in there.

# Answer
> 0 votes
I use this solution for more links with exposed filters in the url.

```
function mvo_blocks_preprocess_views_view(&$vars) {
  if($vars['more'] != NULL) {
    $display = $vars['view']->display_handler;
    if(!$path = $display->get_option('link_url')){
      $path = $display->get_path();
    }
    $vars['more'] = theme('views_more', array('more_url' => $path, 'link_text' => check_plain($display->use_more_text()), 'view' => $display->view));
  }
}

```

---
Tags: views
---


title: custom permissions for score quizzes

text:
# Question
Title: custom permissions for score quizzes
I need your help I need to make a very custom way of scoring quizzes and need some opinions and ideas.

I'm making a job applicants website, when you try to apply to a job in the website you have to take a quiz, and if you pass it your resume is sent to the creator of the job.

The complex part is that the quiz for the job is bound in the job content type with an entity reference field, the creator of the job can choose the quiz with an autocomplete field.

Now, I already have that part until the applicant finishes the quiz and then notify the creator of the job (instead of the creator of the quiz) if the applicant passed the quiz.

What I do not know how to do, is that the result of the quiz must be scored by the creator of the job, and not by the creator of the quiz.

A quiz can be reference to unlimited jobs, but when a quiz is bound into a job and somebody applies to a job, and answer the quiz, the results must be scored by the creator of the job instead of the creator of the quiz.

Any ideas how to achieve this?

# Answer
> 1 votes
When the quiz is completed I guess you need to email the job creator. You could do this using hook\_node\_insert().

E.g.

```
function hook_node_insert($node) {
  if($node->type == 'quiz') {

    // Get the job nid from the quiz nid
    $job_nid = db_select('field_data_field_quiz', 'q')
      ->fields('entity_id')
      ->condition('field_quiz_target_id', $node->nid)
      ->condition('entity_type', 'node')
      ->condition('bundle', 'job')
      ->condition('deleted', 0)
      ->execute()
      ->fetchField();

    $job = node_load($job_nid);

    $job_author = user_load($job->uid);

    drupal_mail (
      // The name of your module
      'my_module',
      // An arbitrary mail key, that you decide (used in hook_mail())
      'new_quiz_submission',
      // The destination mail address
      $to->mail,
      // The language that the mail should be sent in (requires translation if not English)
      $to->language,
      // Some parameters we can use in hook_mail()
      array (
        'account' => $job_author, // Pass the user account to hook_mail
      )
    );

  }
}

function my_module_mail($key, &$message, $params) {
  // The key allows for a module to define multiple mails. This
  // key needs to be the same as the first parameter in drupal_mail() above
  if($key ==  'new_quiz_submission') {
    $message['subject'] = t('New Quiz submission');
    // Each element of the body array becomes a new line in the email.
    $message['body'][] = t('Hello @user', array('@user' => format_username($params['to'])));
    // Adding an empty string to the body array adds an extra line in the email
    $message['body'][] = '';
    $message['body'][] = t('A user submitted a quiz. To see the results <a href="#link-to-site">click here</a>.');
  }
}

```

I pretty much just copied and pasted the code for sending simple emails from here.

I would create a view with a contextual filter that shows all of a particular authors quizzes that need scoring and then the link the in the email could just link to that view.

When they marked the quiz then I would also use a boolean field to mark the quiz as scored.

---
Tags: 7, quiz
---


# Question
Title: View block listing nodes with lower/higher Nodequeue position
I'm trying to build up two blocks for nodes with a Nodequeue position, one above the node listing nodes with lower Nodequeue position and one below the node listing nodes. It should look like a list of linked titles and a full node display in between:

* Node A (Linked title only, Nodequeue position: 1)
* Node B (Linked title only, Nodequeue position: 2)
* Node C (Current full node display, Nodequeue position: 3)
* Node D (Linked title only, Nodequeue position: 4)
* Node E (Linked title only, Nodequeue position: 5)

Clicking the title of "Node D" should result in this:

* Node A (Linked title only, Nodequeue position: 1)
* Node B (Linked title only, Nodequeue position: 2)
* Node C (Linked title only, Nodequeue position: 3)
* Node D (Current full node display, Nodequeue position: 4)
* Node E (Linked title only, Nodequeue position: 5)

I've tried Contextual Filters in Views, but couldn't find a way to limit the list to nodes with lower/higher Nodequeue position.

Any Ideas?

# Answer
For sorting the nodes according to their position in a nodequeue follow these steps:

* Add a relationship "Nodequeue: Queue".
* You might want to select "Limit to one or more queues (recommended)" from the options provided and select appropriate nodequeue.
* Save.
* Click "add" in the sort criteria. Select "Nodequeue: Position"
* Select ascending/descending depending on the positions.
* Save.

And as for the other requirement that you posted "Current full node display"; I think this could be handled with adding the fields in the view, and controlling their display using JS.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Views don't display any result until the exposed form is submitted
I have a view that display content on my website, but now (i don't know why) my view show results only when i submit the exposed form.

I would like my view display all result by default.

Any idea ?

# Answer
I found what was the matter !

I used a field in my view in the exposed form. But, after creating my view, I re-use this field in another content type with different label name.

Adding fact I use translation for this (taxonomy) field in my view too...

I simply **delete and re-create the exposed field to solve** my problem.
> 0 votes

# Answer
I think you have marked the exposed filter as required.

Uncheck the "Required" checkbox right below the "Expose this filter to visitors, to allow them to change it" checkbox.
> 1 votes

---
Tags: views
---


# Question
Title: Need help with PHP: Show an image field when video field is empty
I have been working with Drupal for some months now but I have not coded anything in it so I need help.

**Situation**: On my homepage there are 3 rows that contain blog teasers. On the first row the first video (youtube/vimeo) and the first image of the blog is shown. They are all styled responsively and it works fine. I use a view to do this.

**What needs to change**: When there is a video in the blog, I want to exclude the image. So Video = No image, No video = Image, No video and No image = just the teaser text (which is always present).

**What I have tried**: Tried the Views Conditional module. Doesn't work since the replacement variable (example \[photo\]) does not contain the image itself.

Tried Views If Empty module. The logic works but messes up my CSS in a lot of ways and impossible to make it look like it should.

**Solution?**: I think that what I need is a PHP part in my View. I have no experience at all with making this. What I have tried is visible below. (messes up the homepage).

```
if (empty($fields[$row->field_alg_video_1]->last_render)) {
          $this->last_render = $fields[$row->field_alb_fotos]->last_render;
        }
        else {
          $this->last_render = '';
        }

```

I just threw some stuff together from the net. Can anyone help me out? :)

# Answer
> 3 votes
Trust on Views empty field settings :-)

Hide the image and the test field. Configure the video field empty setting telling that should show the image field: use the right token, something like this:

```
[field_image]

```

Then configure the image field empty setting with the text field.

So, if there's no vídeo Views will try to show the image field. When rednering the image field Vies will show the image if it's present, or the text field if image is also empty.

---
Tags: 7, views
---


# Question
Title: Why drush fails to rsync between my two local instances?
I'm trying to synchronize two local drupal repositories using the following command:

```
drush rsync

```

My environment: \- drush 6.1 \- Mac os X 10.9 \- drupal 7.24

I have followed standard security recommendations for Drupal and configured permissions with:

```
MBPC:files pc$ pwd
/Users/pc/Sites/mysite.dev/sites/default/files
MBPC:files pc$ ls -al
total 8
drwxrwx---+ 8 _www  staff  272 18 jul  2012 .
drwxr-xr-x+ 4 pc    staff  136 23 nov 15:08 ..
-rwxr-----+ 1 pc    _www   477 21 nov 15:19 .htaccess
drwxrwxr-x+ 3 _www  staff  102 18 jul  2012 color
drwxr-xr-x+ 3 _www  staff  102 22 nov 09:53 ctools
drwxr-x---+ 3 _www  staff  102 23 mai  2012 pictures
drwxr-x---+ 3 _www  staff  102 23 nov 16:24 private
drwxr-xr-x+ 2 _www  staff   68 24 oct 17:37 styles

```

The user `pc` is a member of the `_www` group.

The `.htaccess` file contains (following the latests Drupal security warnings) as follows:

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

There is a similar `.htaccess` file in the private subdirectory.

I'm using the following command:

```
$ drush rsync @mysite.dev @mysite.local

```

and I get this error message:

```
You will destroy data from /Users/pc/Sites/mysite.local/ and replace with data from /Users/pc/Sites/mysite.dev//
Do you really want to continue? (y/n): y
rsync: failed to set times on "/Users/pc/Sites/mysite.local/sites/default/files": Operation not permitted (1)
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/color" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/ctools" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/pictures" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/private" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: mkstemp "/Users/pc/Sites/mysite.local/sites/default/files/..htaccess.bVe3a4" failed: Permission denied (13)
rsync: failed to set permissions on "/Users/pc/Sites/mysite.local/sites/default/files/styles": Operation not permitted (1)
rsync: failed to set times on "/Users/pc/Sites/mysite.local/sites/default/files": Operation not permitted (1)
rsync: failed to set permissions on "/Users/pc/Sites/mysite.local/sites/default/files/styles": Operation not permitted (1)
rsync error: some files could not be transferred (code 23) at /SourceCache/rsync/rsync-42/rsync/main.c(992) [sender=2.6.9]
Could not rsync from /Users/pc/Sites/mysite.dev// to /Users/pc/Sites/mysite.local/                                                              [error]

```

# Answer
> 4 votes
You cannot change the file timestamps or change permissions by being a member of a group, you have to be the file owner, or root. If you cannot be the other of that file, you might need to avoid trying to set permissions at all.

So you may try to modify your drushrc file (e.g. sites/default/drushrc.php) and add the following arguments for rsync command:

```
$command_specific['rsync'] = array('mode' => 'rlptzO', 'verbose' => TRUE, 'no-perms' => TRUE);

```

If running rsync on remotes, edit your aliases.drushrc file (e.g. sites/default/aliases.drushrc.php) and add something like:

```
$aliases['mysite.dev'] = array(
    // here are your settings such as uri, root, remote-host, etc.

    'command-specific' => array (
      'rsync' => array('mode' => 'rlptzO', 'verbose' => TRUE, 'no-perms' => TRUE),
    ),
);

```

# Answer
> 2 votes
This is really a permissions issue, not a Drush / Drupal question, but here goes. (Clive is right, but here's a little more detail.)

I was skeptical about your claims about not being able to find the answer with google, so I searched myself for `rsync: failed to set times` and was surprised that I could not easily find the answer to this.

If you are doing a remote rsync, then you only need write access to the target file to successfully do the copy, but you need to be the owner of the file to set the times. Since you have different owners for different files, setting the times on everything will be difficult, unless you want to rsync as root. I don't really recommend that; my preference is to make all of my files owned by a special user, www-admin, and set the group to something the web server belongs to. I then set the group write bit on files and directories that should be writable by the webserver, and clear it everywhere else.

With this setup, you just need to make sure that the remote user in your Drush alias is www-admin -- or continue using 'pc', if you prefer, but make 'pc' the owner of everything & you'll be okay.

**Update:**

When using this permissions scheme, it is also helpful to add the following to your drushrc.php file:

```
$command_specific['rsync'] = array('mode' => 'rlptz');

```

This will cause drush to use the flags `-rlptz` when calling rsync. See `man rsync` for details on the various rsync mode files available.

---
Tags: drush, database, files
---


title: How to debug merge query?

text:
# Question
Title: How to debug merge query?
I have a simple merge query, with one key and three fields, something like:

```
$query = db_merge('product')
->key(array(
  'id' => $id_product,
))
->fields(array(
  'name'   => $form_state['values']['name'],
  'symbol' => $form_state['values']['symbol'],
  'weight' => $form_state['values']['weight'],
));

```

Usually it works all right, but some combinations of data passed to it and data already in database cause me headache. I'm sure I would be able to know what's wrong and why, if only I could grab actual SQL query that goes to my database.

Usually I would do:

```
  kpr((string)$query);

```

It works well for insert for example, because insert has `__toString()` well implemented. Sadly, implementation of `MergeQuery::__toString` is somewhat nonexistent:

```
public function __toString() {
}

```

It isn't even a proper implementation of this magic method, as it should always return string, but OK, I can assume it was on purpose. Anyway, this changes nothing: I can't simply cast it to see it.

What other options do I have, to see queries generated by `db_merge()` / `MergeQuery` for database interaction debugging?

# Answer
A `MergeQuery` just runs a `SELECT` and `INSERT` internally - there isn't a single query string available, so the `__toString()` method doesn't make sense (which is probably why it's short-circuited).

`SelectQuery` and `InsertQuery` both implement `__toString()` fully, so your best bet for debugging would be to temporarily add some code to `MergeQuery::execute()` to dump the `$select` and/or `$insert` query before they're run, so you can inspect the query string.
> 3 votes

# Answer
Ok, I realise that this is going against the principle of OOP however...

```
function debug_merge_query($query, $show_placeholder_values = false) {

  // Unprotect object.
  $query_arr = (array) $query;
  $query_str = json_encode($query_arr);
  $query_str = str_replace('\u0000*\u0000', '', $query_str);
  $query_arr = (array) json_decode($query_str);
  //pdie($query_arr);

  if(!isset($query_arr['table'])) {
    drupal_set_message('You cannot execute a merge query whilst it is being debugged.');
    return false;
  }

  // Extract variables
  $table = $query_arr['table'];
  $fields = array();
  $first = true;
  foreach($query_arr['insertFields'] as $k => $v) {
    if($first) {
      $condition_key = $k;
      $condition_val = $v;
      $first = false;
    } else {
      $fields[$k] = $v;
    }
  }

  // Build select query.
  $select_query = db_select($table, $table)
    ->condition($condition_key, $condition_val);
  $select_query->addExpression('1', 'expression');

  if($show_placeholder_values) {
    dpq($select_query);
  } else {
    dpm((string)$select_query);
  }

  $row_exists = $select_query->execute()->fetchField();

  if($row_exists) {
    // Build update query.
    $update_query = db_update($table)
      ->fields($fields)
      ->condition($condition_key, $condition_val);

    $update_query_str = dpq($update_query, TRUE);

    if($show_placeholder_values) {
      $update_query_str = replace_placeholders($update_query_str, $fields);
    }

    dpm($update_query_str);

  } else {
    // Build insert query.
    $fields[$condition_key] = $condition_val;
    $insert_query = db_insert($table)
      ->fields($fields);
    $insert_query->preExecute();

    $insert_query_str = (string) $insert_query;

    if($show_placeholder_values) {
      $insert_query_str = replace_placeholders($insert_query_str, $fields);
    }

    dpm($insert_query_str);

  }

}

function replace_placeholders($query, $values) {
  $x = 0;
  foreach($values as $k => $v) {
    $replace = is_numeric($v) ? $v : '"'.$v.'"';
    $query = str_replace(':db_insert_placeholder_'.$x, $replace, $query);
    $query = str_replace(':db_update_placeholder_'.$x, $replace, $query);
    $x++;
  }
  return $query;
}

```

So to test this function you can use the following code:

```
$id_product = 1;

$query = db_merge('product')
  ->key(array(
    'id' => $id_product,
  ))
  ->fields(array(
    'name'   => 'test',
    'symbol' => 'apple',
    'weight' => 12,
  ))
  //->execute()
  ;

debug_merge_query($query, true);

```
> 1 votes

---
Tags: 7, database, debugging
---


# Question
Title: How to add data attributes to view list <li> tags?
I have a HTML-list view, which generates `li` tags for my content. I want to add a `data-` attribute to each list item dependent on the content. How to achieve this?

# Answer
Override **style output** template file using theme information in views.....

Override file with below code..

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */
?>
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>
    <h3><?php print $title; ?></h3>
  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li data-attr="" class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

```
> 3 votes

---
Tags: 7, views
---


# Question
Title: Getting the error "$().once is not a function"
till today noon my site working fine but after that suddenly my site was struck and in error console it give me below error.

> Error: TypeError: $(...).once is not a function Source File: modules/overlay/overlay-child.js?mixmsl on Line: 111.

```
/**
 * Modify forms depending on their relation to the overlay.
 *
 * By default, forms are assumed to keep the flow in the overlay. Thus their
 * action attribute get a ?render=overlay suffix.
 */
Drupal.overlayChild.behaviors.parseForms = function (context, settings) {
  $('form', context).once('overlay', function () {
    // Obtain the action attribute of the form.
    var action = $(this).attr('action');
    // Keep internal forms in the overlay.
    if (action == undefined || (action.indexOf('http') != 0 && action.indexOf('https') != 0)) {
      action += (action.indexOf('?') > -1 ? '&' : '?') + 'render=overlay';
      $(this).attr('action', action);
    }
    // Submit external forms into a new window.
    else {
      $(this).attr('target', '_new');
    }
  });
};

```

# Answer
The standard `$` alias is not used in Drupal 7, to provide the best possible support for no-conflict jQuery.

You need to wrap your code in a closure like so:

```
(function($) {
  // Add code using $ as an alias for jQuery here...
})(jQuery);

```

See Managing Javascript in Drupal 7 for complete examples and explanations.
> 5 votes

# Answer
```
(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {

/////// Place your code after this

Drupal.behaviors.textarea = {
  attach: function (context, settings) {
    $('.form-textarea-wrapper.resizable', context).once('textarea', function () {
      var staticOffset = null;
      var textarea = $(this).addClass('resizable-textarea').find('textarea');
      var grippie = $('<div class="grippie"></div>').mousedown(startDrag);

      grippie.insertAfter(textarea);

      function startDrag(e) {
        staticOffset = textarea.height() - e.pageY;
        textarea.css('opacity', 0.25);
        $(document).mousemove(performDrag).mouseup(endDrag);
        return false;
      }

      function performDrag(e) {
        textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
        return false;
      }

      function endDrag(e) {
        $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
        textarea.css('opacity', 1);
      }
    });
  }
};

/////// place all your codes after this
  }
};

  })(jQuery, Drupal, this, this.document);

```
> 0 votes

---
Tags: 7, modal-dialogs
---


title: How to theme D7 search results

text:
# Question
Title: How to theme D7 search results
The default search results in D7 seem to include details of the node author, date, number of comments as seen here but I don't want these in my search results.

I have copied search-result.tpl.php and search-results.tpl.php to my theme file. I have added

```
print '<pre>'. check_plain(print_r($info_split, 1)) .'</pre';

```

to search-result.tpl.php. The result is here ie showing the array with \[user\] \[date\] \[comment\] etc

What do I need to do to exclude author / date / number of comments from the search results? If it involves my theme's search-result.tpl.php what should be the contents of search-result.tpl.php ?

# Answer
* Copy search-result.tpl.php into your theme folder..

Override above tpl using below code..

```
<?php

/**
 * @file
 * Default theme implementation for displaying a single search result.
 *
 * This template renders a single search result and is collected into
 * search-results.tpl.php. This and the parent template are
 * dependent to one another sharing the markup for definition lists.
 *
 * Available variables:
 * - $url: URL of the result.
 * - $title: Title of the result.
 * - $snippet: A small preview of the result. Does not apply to user searches.
 * - $info: String of all the meta information ready for print. Does not apply
 *   to user searches.
 * - $info_split: Contains same data as $info, split into a keyed array.
 * - $module: The machine-readable name of the module (tab) being searched, such
 *   as "node" or "user".
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Default keys within $info_split:
 * - $info_split['module']: The module that implemented the search query.
 * - $info_split['user']: Author of the node linked to users profile. Depends
 *   on permission.
 * - $info_split['date']: Last update of the node. Short formatted.
 * - $info_split['comment']: Number of comments output as "% comments", %
 *   being the count. Depends on comment.module.
 *
 * Other variables:
 * - $classes_array: Array of HTML class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $title_attributes_array: Array of HTML attributes for the title. It is
 *   flattened into a string within the variable $title_attributes.
 * - $content_attributes_array: Array of HTML attributes for the content. It is
 *   flattened into a string within the variable $content_attributes.
 *
 * Since $info_split is keyed, a direct print of the item is possible.
 * This array does not apply to user searches so it is recommended to check
 * for its existence before printing. The default keys of 'type', 'user' and
 * 'date' always exist for node searches. Modules may provide other data.
 * @code
 *   <?php if (isset($info_split['comment'])): ?>
 *     <span class="info-comment">
 *       <?php print $info_split['comment']; ?>
 *     </span>
 *   <?php endif; ?>
 * @endcode
 *
 * To check for all available data within $info_split, use the code below.
 * @code
 *   <?php print '<pre>'. check_plain(print_r($info_split, 1)) .'</pre>'; ?>
 * @endcode
 *
 * @see template_preprocess()
 * @see template_preprocess_search_result()
 * @see template_process()
 *
 * @ingroup themeable
 */
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?></a>
  </h3>
  <?php print render($title_suffix); ?>
  <div class="search-snippet-info">
    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
    <?php endif; ?>
  </div>
</li>

```
* Clear Cache

Author / date / number of comments from the search results is getting rendered using below code

```
<?php if ($info): ?>
  <p class="search-info"><?php print $info; ?></p>
<?php endif; ?>

```

which we removed from above overridden tpl....

You can also remove it using below function in your theme template.php

```
function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
}

```
> 4 votes

---
Tags: theming, search
---


# Question
Title: How to use Hierarchial Select Module for select field's of webform module?
Answer is to use Hierarchial select module for dynamic options list based on the previous select box value

*How do I use Hierarchial select module in my webform module for select fields?*

# Answer
Seems like webform doesn't support Hierarchical Select module...

You can use Webform Conditional module to create dependent fields...

Project page says

> This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.
> 1 votes

---
Tags: webforms, taxonomy-terms
---


# Question
Title: How to log all outgoing links generated in a view?
What is the most lightweight method of tracking all outgoing links generated in a view. By lightweight I mean that I don't want to have to load a module such as `statistics` that will potentially slow down my site due to it going above and beyond my needs.

Basically I would need to record the data into a database using the following structure:

```
product_id | uid | timestamp

```

The product id is associated with each link and is a separate field. The purpose would be to create sets of clicked links for each user, product, etc. This could in turn be used as a dataset for subsequent user/item analysis. I would imagine I would need to use some sort of callback function.

Can anyone provide an example or any hints?

# Answer
You could use jQuery to attach a click event to each link that triggers an ajax request to record the click.

The problem with this is that the page may redirect before the ajax request has had a chance to fire so you will have to prevent the default action of the click, and then perform an ajax request with async=false, and then provide a call back function to redirect to the links destination.

Not exactly lightweight...

Another option is to define an outbound link function in PHP that will accept the final destination as a argument. So the link would look like `/outbound?dest=http%3A%2F%2Fwww.google.com`.

Then in that function you can record the click, and then redirect them on to the destination passed in...
> 0 votes

---
Tags: views
---