# Question
Title: How to detect Adblock on my Drupal website?
I want to be able to detect if the user is using adblock plus or any blocking ad extension. How can I do this in Drupal ?

Why ? I'm building a website that is going to contain ads on a block (so far I do not think I would use the adsense module) that block would only be display it to anonymous users. If the user have adblock plus enable on their browser, I would like to show another block that said something similar to this "If you enjoy our content free to ads you should become a member of this site. Ads help us creating more content." I would set a link on that block to encourage user to buy a role to help that website.

So far I notice there is a very popular question at Stackoverflow "How to detect Adblock on my website?". But I was wondering if there is a module or better Drupal way to detect if the user is using adblock plus.

# Answer
As of right now, there are no ad blocking modules on drupal.org, save for the dSero module, which is more of a proxy for the dSero service, thus, not really a solution for detecting adblock usage.

AdBlock detection is simple in practice; include markup regions (e.g. a div & image sized to a standard 728x90 leaderboard ad size) and/or execute JavaScript (e.g. running JS called **ad.js**) that triggers the AdBlocker to hide it, then having some other isolated code check if region was hidden or the JS code was executed.

With that known, any Drupal based solutions are going to involve either finding an existing front-end library (e.g. FuckAdBlock) or creating your own. Given that any popular solution is ultimately self-defeating (e.g. the AdBlock updating its code to check for common Anti-AdBlocking tactics/libraries), you're probably better off creating your own custom front-end solution that catches ad blocking.
> 3 votes

---
Tags: advertising
---


# Question
Title: How to translate views infinite scroll Loading message
I have an Arabic website and I have views infinite scroll module to allow ajax paging.

I want to translate `Loading the next set of posts...`. I have tried to search for it in the translate interface, but I could not find it. I tried to import its \*.po file from this link but also I could not find it. I have tried to search among the module `views_infinite_scroll` files, for that string to change it from the source, but also I could not find.

# Answer
> 0 votes
I'm using webpal pinteros theme, and it has its own `js/views_infinite_scroll.js` file, in-which the message could be translated. However, this solution is not suitable for multiple languages sites.

---
Tags: 7, views
---


# Question
Title: How do I get my accidentally disabled side menu back?
I accidentally deactivated the left side menu for every page. I think it's still there, just deactivated.

How do I get it back?

# Answer
Go to: `admin/structure/block`

Then move to the bottom of the page and search `Navigation` and in the select you must select `Sidebar First`, then go to the bottom and click the `Save blocks` button

See this picture:
> 2 votes

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


title: How do I set the sender name?

text:
# Question
Title: How do I set the sender name?
When emails are sent from my dev drupal site to new users the sender is listed as the first part of the site's email address ("info" from "info@mydomainname.com.au" (screenshot below)). Ideally I would like it to be the site's name. How can I control this? Thank you.

# Answer
> 2 votes
`drupal_mail()` supports a display name in the From: field, but it's up to the whatever module you're using to send mail. If you'd like to force the name, you can use the MIMEMail module.

Once installed, under the **Configuration \> System \> Mimemail** administration menu, you can set the default Name/Email that will be sent.

---
Tags: 7, emails
---


# Question
Title: Is it possible to create web service CRUD operations for contributed modules in drupal 7?
I have using a privatemsg module for chating in our site,

Privatemsg

Services

Is it possible to do a web service CRUD operations through this module?

any suggestions?

# Answer
Yes, the Services module has an API, details of which you can find in the module files. You can use that API to provide CRUD for anything at all. See Creating a resource for Services 3.x for a full module example.

Since private messages are entities, you might also look to the Services Entity API module for inspiration (or, it you're particularly lucky, a pre-built solution, depends what you need, and whether you can use an alpha release):

> This module provides support for all Entity API entity types to Services. All entity types get a standard resource, similar to what Services provides for code entity types such as nodes.
> 1 votes

---
Tags: services
---


# Question
Title: add function on date selected through date popup field
I am using Date popup module for selecting a date in a registration form. Is it possible to fire an event on date select?

# Answer
For Drupal 7, the datepicker is indeed likely to be the one from jQuery UI, and since you may not know in your own javascript if date pickers have been initialized yet, an easy way to trigger your "custom function" is to listen for selection on any date picker on the page.

```
  jQuery.datepicker.setDefaults({
    onSelect: function () {
      console.log('date selected');
    }
  });

```

Refer to the jQuery UI onSelect documentation for more information.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: Why not all menus are available in context settings page?
I want to put main-menu to certain block via context.

But only few menus are available:

I've 3 contexts already, but none of them uses any menu.

# Answer
In the context module, blocks in the *Blocks* reaction are grouped by the module that creates them. In this case, it is the **System** module that provides the **Main Menu** that you're looking for.
> 0 votes

---
Tags: routes, 7
---


# Question
Title: How do I assign a role after user clicks a link?
I'm trying to get a behavior when a link is clicked, a role is applied to a user.

My use case is to allow a registred user to step into another type of user. Example is airbnb.com. You are a renter but once you click a certain menu link you become a host and get new menu items to then list your house.

I want to give permissions and access to certain areas of the site only when someone decides to unlock it.

# Answer
You can use Rules for that. The configuration can be({{}} are placeholders, do not use on the real values):

1. React on event "Content is viewed"
2. Condition: Data comparison (Parameter: Data to compare: \[node:nid\], Data value: {{NID from the node you're using to trigger this role activation}})
3. Action: Add user role (Parameter: User: \[site:current-user\], Roles: {{the role you want to add}})
> 0 votes

# Answer
Flag module + @pedrorocha is quite a good tandem, instead of going to link, everything happen in one place, plus changing your link flag into different text ajaxly.
> 0 votes

---
Tags: theming, users
---


# Question
Title: Associate a content type to a specific group in drupal commons
How is possible to create a content type associated by default to a group in Drupal Commons?

I will try to explain. I have two groups: *literature* and *art*. Literature will have three content types i.e. *poetry*, *fiction* and *novels*. Art will have *painting*, *photography* and *drawings*.

I've created contents types and i've tried to associate them with the respective group by flagging the group and group content checkbox but nothing changed. I also followed the steps described here https://www.drupal.org/node/2014781 but when I try to add some content I still see the "*Post to specific groups*" radio option and select.

Help please!!!

# Answer
> 0 votes
I am assuming you are using one group content type, and "Literature" and "Art" are contents of that group type.

Tell me if I am wrong in my assumption.

You can use hook\_form\_BASE\_FORM\_ID\_alter() to set a default field value for group field based current content type.

```
    function mymodule_form_node_form_alter(&$form, &$form_state) {
      $node = $form_state['node'];
      if (!isset($node->nid) || isset($node->is_new)) {
       global $user;
       $groups = og_get_groups_by_user($user);
          if(is_array($groups)) {
          // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
          if($node['#bundle'] == "poetry" || $node['#bundle'] == "fiction" ||$node['#bundle'] == "novels") {
          $form['group_field_name']['#default'] = $groups[0];  //Whatever index Literature has
          }
          elseif($node['#bundle'] == "painting" || $node['#bundle'] == "photography" ||$node['#bundle'] == "drawings") {
          $form['group_field_name']['#default'] = $groups[1];  // Art's index
          }
          }
      }
    }

```

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


# Question
Title: Is it possible to move product category description alignment in drupal
Can any one suggest me to move Product description from top to bottom in drupal product category page.

Example Like :

1. First all product Image.
2. And Bottom content are shown.

# Answer
This can be also done through the admin dashboard. Follow the below steps:

1. Go to admin/structure/types.
2. Select your content/Product type and manage Display according to your requirement.
> 1 votes

# Answer
create `node--product.tpl.php` to theme the product category page.
> 0 votes

---
Tags: 7
---


# Question
Title: Customize what fields show on Views Exposed Filters Block
I have configured an exposed form block, filtering by taxonomy list. What I need to do is simply display a field image before the taxonomy name. The actual display is `<Taxonomy Term Name>` and what I need is `<Taxonomy Term Logo> <Taxonomy Term Image>`. I have looked on some places, but I couldn't get anything to work.

How can I achieve this?

# Answer
Simply rearrange the fields i.e. put field image before the taxonomy name. You can get the rearrange button at right side of **FIELDS** in view configuration.
> 1 votes

# Answer
There is a `drop-down option` just after the `add field option` you can see the `re-arrange option` from there you can arrange the fields according to you.
> 1 votes

---
Tags: views
---


# Question
Title: Showing block in specific urls and content types
I'm using this code to show block in specific urls and content types.

```
<?php
  $match = TRUE;
  // block is visible on the content types entered here
  $types = array('product_display' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }

  if (strpos($url, "somewhere")) {
    $match = TRUE;
  }
  // copy paste these for additional URLs
  $tids=array_keys(taxonomy_get_children(7));
  foreach($tids as $tid) {
    if (strpos($url, "taxonomy/term/".$tid)) {
      $match = TRUE;
      break;
    }
  }
  return $match;
?>

```

It works but the block shows in some other urls too, any idea why?

# Answer
You could do one more thing over it.

Just remove the block from the assigned region and render that block using `module_invoke()` in the template file `page.tpl.php`.

```
<?php
  $match = TRUE;
  // block is visible on the content types entered here
  $types = array('product_display' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }

  if (strpos($url, "somewhere")) {
    $match = TRUE;
  $block = module_invoke('block', 'block_view', 'block_delta');
  print $block['content'];
  }

```

Render your block with the applied condition as you want. If you just want to display block at some specific urls and content types.

It works well for that!
> 0 votes

# Answer
I would suggest not to use the PHP filter in the block settings. Once thing can be done instead. In your custom module you can create a hook\_page\_alter to remove the block. Yes of course you have to edit the module file if you want to show the block in other sections even in Production but enabling PHP Filter can create issues. Check here and here too.
Anyway, if you want to use the hook then the code will be,

```
function MYMODULE_page_alter(&$page) {
  $node = menu_get_object();
  $region_name = 'sidebar_first'; // The region where the block is placed.
  $block_name = 'system_navigation'; // The name of the block.
  $types = array('product_display' => 1, 'page' => 1);

  // Only the content type condition shown.
  if ($node && isset($node->nid)) {
    if (!in_array($node->type, $types)) {
      if (isset($page[$region_name][$block_name])) {
        $page[$region_name][$block_name]['#access'] = FALSE;
      }
    }
  }
}

```

I've only shown the condition with content type, I am sure that you can add the later 2 conditions with URL & taxonomy terms.
> 0 votes

# Answer
I finally got to obtain a snippet that shows a block in a page if the path contains a given string OR if the page is a node of a given content type. I'm sure it could be improved, but for the moment it serves his purpose and doesn't generate any error.

```
<?php
  // Check proper node type.
  $node = menu_get_object();

  if (isset($node) && ($node->type == 'family' || $node->type == 'species')) {
      return TRUE;
  }

  // Pages to match on (mynotes or mynotes* - using newline character).
  $pages = "mynotes\nmynotes*";
  // Get current alias.
  $path = drupal_get_path_alias($_GET['q']);
  // Compare with the internal and path alias (if any).
  $page_match = drupal_match_path($path, $pages);

  if ($path != $_GET['q'] || $page_match) {

    // Check if match with internal or alias.
    if ($page_match || drupal_match_path($_GET['q'], $pages)) {
      return TRUE;
    }
  }

  else {
    return FALSE;
 }
?>

```
> 0 votes

---
Tags: blocks
---


title: How can I theme field collection forms?

text:
# Question
Title: How can I theme field collection forms?
I have a field\_field\_collection in content type (used to field collection module and have unlimited value). It has a number of fields as in the picture below:

And I want customize theme for it as template as in the picture below:

How I can I achieve that? I tried to write a template for it, but the result is bad. When I click "add another item" the result looks like shown in the picture under my code below.

Here is my code:

```
    <?php
    kpr($form);
    print drupal_render($form['title']);
    $i = 0;
    foreach($form['field_field_collection']['und'] as $items){
    if(isset($form['field_field_collection']['und'][$i])) {
        ?>
        <table border="1" cellpadding="10">
            <tbody>
            <tr>
                <td>
                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_01']);
                    ?>
                </td>
                <td>
                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_02']);
                    ?>
                </td>
            </tr>
            <tr>
                <td>
                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_3']);
                    ?>
                </td>
                <td>
                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_4']);
                    ?>
                </td>
            </tr>
            </tbody>
        </table>
    <?php
        $i++;
        }
    }
?>
<?php
    print drupal_render($form['field_field_collection']['und']['add_more']);
    hide($form['actions']);
    hide($form['additional_settings']);
    print drupal_render_children($form);
?>

```

And here is the result when I click "add another item":

# Answer
If your requirement is to format Field Collection in **Table Format**, then Field Collection Table Module will help.
> -2 votes

---
Tags: theming, entities
---


# Question
Title: User specific permission to add links to a menu
When I **create a content type**, e.g. 'Basic Page' and I want to **add a link** to a menu I do usually the following: Menu settings -\> Provide a menu link -\> choose a menu and its position of the link there

I know, that I can define, which menus are appearing here, in the menu settings section of a content type.

I have **several menus, for specific users**. For now, if they create a new 'Basic Page' they see all the menus, which are set for this content type. So as well, menus from other users. Is it possible to **show just their own menu**, so they do not have access to the other menus?

For now I solve this problem by assigning roles for each individual user, and granting permissions for this 'user role' per 'user menu', by using the Menu Admin per Menu module for D7. It would be much more convenient, to use user specific permissions here.

Is there any way, of doing that?

Thank you in advance!

# Answer
> 1 votes
Check this Menu Per User and let me know if you face any issues.

# Answer
> 1 votes
Custom Menu Permissions

> This module does two things:
>
> 1. It allows for the permission used to access any menu item on the system to be overridden.
> 2. It allows for custom permissions (see hook\_permission()) to be created through the admin interface. These permissions can be used the same as any permissions created in a module using hook\_permission() - ie in modules, templates, and in hook\_menu() callbacks.

---
Tags: navigation
---


# Question
Title: How can I create an event condition for a 404 error?
I set a page for the 404 error. I created the *Data to compare: \[site:current-page:url\]*, *Data value: 404* condition and an action of that condition.

When a non existing page is requested, no action is triggered. I guess it happens because the page URL is https://example.com/wrong, instead of https://example.com/404.

How can I create condition for a 404 error?

# Answer
> 0 votes
Try using Rules (System) event "Drupal is initializing" (= `init`), which is actually BEFORE a node is being viewed.

Not sure if the Rules condition you're using is OK. But if you still can't get it to work, you may also want to look at my answer to the question "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?". The sample there also includes such "Drupal is initializing".

---
Tags: 7, rules
---


title: Creating a poll inside a content type

text:
# Question
Title: Creating a poll inside a content type
I need a poll inside my content types.

Sometimes the users create an article and like to create a poll directly into the node they created. They don't want to create an extra poll with no connection to the original article.

So how can I get the poll functionality inside a different content type?

# Answer
*Possible solution 1*: The Pollfield module seems to be a good starting point. This should do what you need for Drupal 6. However, it might not be a stable solution for Drupal 7.

*Possible solution 2*: It seems the Poll Improved module might be fit your requirements seeing that provides a field for polls. Though it also doesn't have a stable D7 release.

> They don't want to create an extra poll with no connection to the original article.

You can use references (or entityreference) to have your article nodes reference a poll node. Though that would require another step for your content creators.
> 1 votes

# Answer
Another solution:

1. Add reference field from Article node to Poll node,
2. Use inline entity form to allow users adding Polls when adding/editing Articles
> 1 votes

# Answer
Another way might be to add some fields to content-type comments and use drupal chart to render the aggregated results as a pie chart or whatever...

* pros: rather simple solution, based on stable modules and core;
* cons: poor management.
> 1 votes

# Answer
**Creating a new content type**

Make sure you installed and enabled pollfield module correctly before you try to do the following.

1. Go to Administer-\>Content Management -\> Content types -\> Add Content type (system path: admin/content/types/add)
2. Enter a name: Poll
3. And a type: poll
4. Submission form settings -\> change "Title" field label to “Question”
5. If you like, you can also change the label of the body field
6. The other settings can be left as they are
7. Save!
8. On the next screen (system path: admin/content/types) locate the Poll content type and click on its edit link.
9. Adding the actual pollfield: Locate the “Add” area to find “New field” -\> Label: Poll, fieldname: poll, field type: pollfield, widget: leave as is-\> SAVE
10. Pollfield settings: explained at Pollfield book IMPORTANT: “Global settings”-\> required (so that you cannot accidently create a poll node without an actual poll)
11. SAVE!

You have just created an independent content type for polls. You may customize it by adding other fields. Do not forget that you can control the display settings at system path: admin/content/node-type/poll/display.
> 0 votes

---
Tags: nodes, polls
---


# Question
Title: How to remove "display name" from edit user
I'm building a site that leverages the user email address for the user login instead of a username (via modules Logintoboggan & Email Registration). I'm also using Real Name to display the "first name" field of the user instead of the username.

My solution is working perfectly apart from when the user is on the edit user account page (and some native drupal system notification message), which displays a "Display Name" field instead of the desired "first name" field.

Question: **How can I remove/delete the "Display Name" field from the edit profile page and Drupal system messages/notification fields?**

# Answer
> 3 votes
The first one was easy. To hide any field from the user edit form simply set the `'#access'` to this field to `FALSE` or any other logic you desire. The second one was more difficult. Turned out the display name was still used on the password reset page. That's how we finally solved it:

```
/**
 * Implements hook_form__alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    $form['account']['name']['#access'] = FALSE;
  }

  if ($form_id == 'user_pass_reset') {
    // Here we take the corresponding user ID from the URL, second argument
    $user_id = arg(2);
    // Then we load the user
    $user = user_load($user_id);
    // Now we have the mail
    $user_mail = $user->mail;

    // extracting the date string with a helper function
    $sub_text = getContents($form['message']['#markup'], '<em class="placeholder">', '</em>');
    $expiration_date = $sub_text[1];

    // Now we alter the existing form
    $form['message']['#markup'] = '<p>This is a one-time login for <em class="placeholder">'.$user_mail.'</em> and will expire on <em class="placeholder">'.$expiration_date.'</em>.</p><p>Click on this button to log in to the site and change your password.</p>';
  }
}

/**
 * Helper function to extract a string between two given delimiters
 * Credit: http://stackoverflow.com/a/27078384/2199525
 */
function getContents($str, $startDelimiter, $endDelimiter) {
  $contents = array();
  $startDelimiterLength = strlen($startDelimiter);
  $endDelimiterLength = strlen($endDelimiter);
  $startFrom = $contentStart = $contentEnd = 0;
  while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
    $contentStart += $startDelimiterLength;
    $contentEnd = strpos($str, $endDelimiter, $contentStart);
    if (false === $contentEnd) {
      break;
    }
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;
  }
  return $contents;
}

```

---
Tags: users
---


# Question
Title: How to add an attribute to User reference
I would need to add an attribute to a user\_reference field that "explains" the type of relationship.

Example: My users are music players and the play in different groups. The same user can play guitar in one group and the bass in another group.

Groups are my nodes and I can link them with the players. While I am linking them, I would also like to set the instruments they play in that group.

Group 1 - Player1|guitar Group 2 - Player1|bass Group 3 - Player2|guitar

Probably a way to do that is using "field collection"; is there another way?

# Answer
Alternatives could be Paragraphs, Multifield, Inline Entity Form or Double Field.
> 0 votes

---
Tags: 7, users, entities
---


# Question
Title: How to get menu tree from a node to build a customize breadcrumb?
I would like to build a custom breadcrumb based on node relation from entity reference. For example there is a book node that has menu hierarchy:

```
Book
|-chapter 1
|--sub chapter 1.1
|---sub sub chapter 1.1.1
|----#Node with different content type and not included/displayed on Book
      Navigation

```

The Page Node (sub sub chapter 1.1.1) has entity reference relation with node biblio (for ex)

What I want is when I access biblio then the breadcrumb is displayed like the above tree.

Possible solution: Write a code using nexus theme on template.php on function:

```
function nexus_breadcrumb($variables) {

  //$breadcrumb = $variables['breadcrumb'];
  //$node = $variables['node'];

  if ($node->type == 'biblio'){
   // pseudo code start
   // get 'book' node that point to biblio
   // get menu tree from the book node
   // construct the menu tree and assign it to $breadcrumb

   // this is I still not know how to code the section.
  }

  if (!empty($breadcrumb)) {
  // Use CSS to hide titile .element-invisible.
  $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
   // comment below line to hide current page to breadcrumb

  $output .= '<nav class="breadcrumb">' . implode(' » ', $breadcrumb) .
   '</nav>';
   return $output;
  }
}

```

Any help will do. Thank you.

# Answer
> 0 votes
Menu Breadcrumb

> * Append the page title to the breadcrumb (either as a clickable url or not)
> * Hide the breadcrumb if it only contains the link to the front page.
> * Generate the breadcrumb from the URL structure if content does not belong to a menu (7.x-1.6 and older only)

For more details click here

Custom Breadcrumbs

> Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.
>
> In addition to breadcrumb visibility, this version provides an option permitting PHP code snippets to be used in forming the breadcrumb titles and paths. Multiple languages are also supported.

---
Tags: nodes, breadcrumbs
---


# Question
Title: Paging issue in views when implements node access
I have created a content type called **Details** it is the collection of employees detail. And also I have created a Taxonomy terms called **manager**, **employee**, **lead**. Also I have created a field(as Taxonomy reference) for user profile to indicate whether she/he is **manager** or **lead** or **employee**. Now I want to put the restriction based on the user. I have achieve the restriction using my custom module. The codes are below:

```
    function my_module_node_access($node, $op, $account) {
  global $user;
  $user_obj = user_load($account->uid);
  if (isset($node->type) && ($node->type == 'details') && ($op == 'view')) {
        if (($user->uid == 0) || ($user_obj->field_user_company['und'][0]['tid'] != $node->field_company['und'][0]['tid'])){
            return NODE_ACCESS_DENY;
        }
    }
  return NODE_ACCESS_IGNORE;
}

```

The above code simply do, if the node taxonomy term, and the user field taxonomy term is same then he will perfectly access to the nodes. I got struggle with views. I have created a view to show the node title that can be access by the user. **Manager** has 100 nodes to view, in views settings I have enable the pager, 25 items per page to display. Pager splits into 4 page and shows correctly. But when comes to **employee** user he has access to 1 node only, but in views it still shows the pager in 4 parts.

```
function my_module_views_post_execute(&$view) {
  if (($view->name == 'views1') || ($view->name == 'views2')) {
        $nids = array();
      foreach($view->result as $key=>$result) {
          $nids[$key] = $result->nid;
      }
      $nodes = node_load_multiple($nids);
      foreach ($nodes as $node) {
            if (!node_access('view',$node)) {
                $key = array_search($node->nid, $nids);

                unset($view->result[$key]);
            }
        }
     }
  }

```

The views pager display must be changed dynamically depends on the number of nodes. Is anyone knows kindly show me a right path to achieve this???

# Answer
> 0 votes
hook\_node\_access() doesn't really do any access checks on node listings or views.

To get this to work you should look into implementing hook\_node\_grants() and hook\_node\_access\_records()

That logic will be included in your views query so you could get rid of hook\_views\_post\_execute()

---
Tags: views, paging
---


# Question
Title: Adding "onclick" event to links in text areas
I need some help getting and "onclick" event onto some links in a couple drupal pages.

I've got 2 pages, each with a text entry field set to "full HTML", within which I've added my a tags. the links work great in this format, however when I try to add my onclick event (which contains jquery info for analytics tracking), the only thing I see when I inspect element is the text "onclick" and nothing after it. Not even the " =" ", which would suggest a script error.

When that didn't work I added a class to the A tags and tried to use jquery to append the onclick attribute with these jquery functions: setAttribute attr click

While it sounds simple none of what I've tried has worked (I had used both setAttribute and click successfully on other links), so now I'm looking for a new method. the module Menu attributes doesn't work since it doesn't deal with "onclick" and my links are not menu items, they are just links in text.

I'm using Drupal 6.19 and jquery update.

If anyone has advice or suggestions, please let me know,

Thanks Steph

# Answer
Sorry all, I discovered my question was invalid. I was able to user onclick directly in the "full html" text area, and while the value of the attribute didn't show in the view source, it was working.

I'm not sure if D6 always handles onclick in full html text areas or not. I choose to believe there is something causing this in my theme.

Thanks for your attention!! Steph
> 0 votes

# Answer
An alternative approach is to apply a class to your links, either manually or by adding an option to your WYSIWYG editor (eg. a custom style in CKEditor or a custom button in BUEditor) and then put your onclick javascript in a file in your theme or a custom module.

This approach is preferable to putting the JS code in the text because it means your code is in one place (in the single js file instead of scattered across potentially multiple nodes), the code is not stored in the database (the linked page mentions PHP but most of it also applies to javascript), and you aren't allowing users unrestricted HTML input, which is a potential security risk.

As for the code, Clive's jQuery example from the comments above would work well in this case:

```
$('.selector').click(function() {
  doSomething();
});

```
> 0 votes

---
Tags: 6, javascript, navigation
---


title: Node repeat in a view

text:
# Question
Title: Node repeat in a view
I have a content type called "daily".

I created 7 nodes titled: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. I have a view that shows this content type where it set to show only one node. I need it to show only the node named Monday every Monday and the node Tuesday on Tuesdays, etc. and repeat.

I have been experimenting but can't find an answer since I can't sort this view in a way to show only Saturday on Saturdays and so on.

Note that this was a simplified version of what I want. I really have 366 nodes which I want to repeat every day of the year. Each node must show on the view dependent on today's date.

How to do that?

Here are things I tried: I tried to un-publish content every 360 days and republish (+5) days. This won't work because some years are 366 days. I also tried to use the repeat date where the repeat date is every 1 year. I found out that when I sort by repeat date field, it brings the earliest date first. I can't make it dependent on current date

# Answer
I am not sure what you mean by not a forum. I was able to resolve it. Here is how i did it: I created the following nodes with an unpublish date as follows: Sat to be unpublished next Sat Sun to be unpublished next Sun Mon to be unpublished next Mon, and so on for all 7 nodes of the week

Then I created two rules: 1) schedule unPublish Event. Event: After updating existing content of type Event. Condition: Content is published. Action: rule: Set scheduled unpublishing date 2) Publish unpublished content now. Event: After updating existing content of type Event. Condition: NOT content is published. Action: Publish content
> 1 votes

# Answer
# Part 1: Views between dates filter

Refer to How to filter events between two dates for detailed documentation about how you can make this work, using the Views between dates filter module. Here are some more details about this module (from its project page):

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

This module can be used to filter events on ONE date (and NOT a range of date, as its name suggests!).

To use this approach, it is required that you already have a content type with a date field. It is not necessary to have two fields to adjust an "end date" for the event, only a date field with the "Collect an end date."

# Part 2: Update the dates to next year

With the approach described in "Part 1", you should be able to achieve your goal for the first year already. To make it work after 1 year also, you should create a mechanism to automatically update the date field you're using, to add "1 year" to the date stored in the date field.

There are a few possible approaches to do this. One approach is like so:

* Build a view to list the nodes for which the date in the date field has passed, and use the Views Bulk Operations module to transform that list in something that can be processed by the Rules module.
* Create a Rules component to process the nodes in this list, which updates the date field (to add "1 year" to the date stored in the date field).
> 0 votes

---
Tags: views
---


# Question
Title: How to theme the node edit form to group fields into collapsible containers?
I'd like to tidy up an unwieldy node edit form using collapsible `fieldset` elements.

I can do this by implementing a form\_alter hook but will this affect Drupal/other modules' ability to process/validate the fields? Obviously it will change the `#parents` of several elements, and I'm unclear whether this change will also affect `$form_state['values']`.

Is it safe to do this, or is there another way to achieve the same?

## Example code

```
$form['group1'] = [
  '#type' => 'fieldset',
  '#title' => 'My Grouped Fields',
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  'children' => [
    'body' => $form['body'],
    'field_smallprint' => $form['field_smallprint']
    ],
  ];
unset($form['body'], $form['field_smallprint']);

```

It seems to me that this is probably safe unless `#tree` is `TRUE`, but I don't want to implement something that might lose data, hence the question here.

# Answer
I would recommend you to first try the Field Group module that provides the option to do that kind of grouping and many more options.
> 1 votes

---
Tags: 7, theming, forms
---


# Question
Title: How to save term with term references programmatically?
I've got a list of terms which I need to add or update programmatically based on their name.

To check if the term exists I'm using a combination of `taxonomy_vocabulary_machine_name_load` to get the `vid` and `taxonomy_get_term_by_name` to get the term if exists. Otherwise I'm creating the term as `stdClass` object.

When I save the term normal field (using `taxonomy_term_save`) in format like `$term->field_address[$term->language][]['value'] = 'some address data'` everything works just fine, but when it comes to save relations nothing is begin saved.

I'm saving relations as `$term->field_realization[$term->language][] = array( 'target_type' => 'taxonomy_term', 'value' => $another_term->tid);`.

Where `$term->language = 'und';` and `$another_term` is a term which belongs to right field Vocabulary declared in Administer.

What am I doing wrong?

# Answer
If you're using the built-in term reference field type, the column is named `tid`, e.g.:

```
$term->field_realization[$term->language][]['tid'] = $another_term->tid;

```

If you're using an Entity Reference field type, the column is named `target_id`, e.g.:

```
$term->field_realization[$term->language][]['target_id'] = $another_term->tid;

```
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to add others libraries such as Zenpen to WYSIWYG profiles?
I would like to use an editor for Drupal like Zenpen. Is it possible to add that library (Zenpen) to WYSIWYG profiles?

# Answer
> 1 votes
You'll need to write a WYSIWYG module plugin. Here is an example module you could follow.

Here is a simple `.inc` from the WYSIWYG module itself. Wrap your Zenpen one in a module like Ueditor (above) and you're done.

---
Tags: 7, wysiwyg
---


# Question
Title: How to use the Rules module to attribute a new user role after a product was bought?
I use these modules: Drupal Commerce, Rules, Node option premium.

My question: with Rules, how attribute a new user role, when the product was bought, and when this product is a premium content ? So that, when a user bought the product, that user can have access to full content.

# Answer
> 1 votes
Refer to the tutorial Selling Content with Drupal Commerce using Content Access and Roles for granting access to premium content to users who have a "premium" role.

Here is a summary of the steps required (= quote from that link):

* Enable Content Access and the ACL (optional) module.
* Create a role called "premium".
* Create a content type called "Premium Content" and put some great content in it.
* Verify that users can only access the premium content if they have the premium role.
* Create a product representing the premium role.
* Create a rule that grants the premium role on order completion:
    + After updating an order.
    + If the order state is Completed.
    + And the order contains our premium product.
    + Add a role to the user who is the owner of the order.

---
Tags: 7, commerce, rules, users
---


# Question
Title: Compare Two Select Lists, and Require User to Select Different Values
Use case: I'm presenting the User with two Select Lists populated with the same People names.

The first select list is Primary Person, the second select list is Backup Person.

The User must select a different value from each list. The same Person can't be a primary and backup. If the User attempts to save the page using the same value, Drupal will throw an error.

What's the best approach?

# Answer
For the Drupal form API, this would be handled with your validation handler. Have it check your 2 form values for equality, and throw an error if so.

```
function MYFORMBUILDER_validate($form, $form_state) {
  if($form_state['values']['person_primary'] == $form_state['values']['person_backup']) {
    form_set_error('person_primary', t('The primary and backup person must be different'));
    form_set_error('person_backup', t('The primary and backup person must be different'));
    array_pop($_SESSION['messages']['error']); //Remove duplicate message
  }
}

```
> 2 votes

---
Tags: entities
---


# Question
Title: Get/modify taxonomy term info in node edit form field?
**How do I modify the taxonomy terms that are listed as a field in my Node edit form?**

I need to be able to hide/unpublish/disable my taxonomy terms. Since there is no way to "unpublish" taxonomy terms the way you can unpublish a node, I have created a boolean field in my taxonomy term that holds its status (enabled/disabled).

I would like to use the value of this boolean field to determine whether or not to add a warning text in the taxonomy term name (eg. `Termname [DISABLED]`) so that users choosing that taxonomy term are properly warned.

If it matters, I'm currently using the select list widget.

I know I can look up each term in `hook_field_widget_options_select_form_alter` since the `tids` and term names are available in the `$element`, but I hope there is **a solution which won't require me to re-load/re-fetch the term from the database again**.

# Answer
> 2 votes
> I know I can look up each term in hook\_field\_widget\_options\_select\_form\_alter since the tids and term names are available in the $element, but I hope there is a solution which won't require me to re-load/re-fetch the term from the database again.

Unfortunately I think you will have to load them again and do the hook\_field\_widget\_options\_select\_form\_alter. There are a lot of functions to load taxonomy information which might be helpful and some of those probably have caches and were used in building the node form so the cache is already primed.

Is your concern around performance or code complexity?

# Answer
> 1 votes
A Drupal module called Term Status was created in 2011 (1 year before this answer was posted). It is available at https://www.drupal.org/project/termstatus and will let you publish and un-publish taxonomy terms. A "published" checkbox will appear on each term to let you control whether or not the term should be seen by others. If I recall correctly, it also provides a permission to let privileged users see unpublished terms.

---
Tags: taxonomy-terms, nodes, forms, hooks
---


# Question
Title: How can one add inline JavaScript in the validation function for the Form API?
I found that there is a way to add javascript files in the form validation function as stated in "drupal\_add\_js not work in form validation failed".

However, I would like to know how to add javascript using the `drupal_add_js` function with the inline option. I would just like to execute some javascript code while I am in the validation function of the Drupal Form API.

# Answer
See the docs @https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

> **drupal\_add\_js() example:**
>
> ```
> drupal_add_js(
>   'jQuery(document).ready(function () { alert("Hello!"); });',
>   array(
>     'type' => 'inline',
>     'scope' => 'footer',
>     'group' => JS_THEME,
>     'weight' => 5,
>   )
> );
>
> ```
>
> **#attached example:**
>
> ```
> $element['#attached']['js'][] = array(
>   'type' => 'inline',
>   'data' => 'jQuery(document).ready(function () { alert("Hello!"); });',
>   'scope' => 'footer',
>   'group' => JS_THEME,
>   'weight' => 5,
> );
>
> ```

Just replace `$element` by `$form`.

---

Original source: https://web.archive.org/web/20160502205421/http://www.failover.co/snippets/drupal-7-attaching-css-and-javascript-forms-or-form-elements
> 4 votes

# Answer
Use the `#attached` property to add your JS file instead of `drupal_add_js` function

More info: FAPI #attached
> 0 votes

---
Tags: 7, forms, javascript
---


# Question
Title: Are static html pages required to build a Drupal
Are static html pages required to build a Drupal based social networking site or should I go about creating content (views or modules etc) and assigning regions to them. I have already created a theme based on Zen.

# Answer
> 0 votes
No, of course they aren't.

I encountered approach like "Let's convert this psd to html site and then Drupalize it!", too. But it usually was a failure, and took way too long for the result it gave. Even worse if designers insisted on exactly the same HTML output, not just the same look.

So no, they are not needed, and this approach might even be harmful for the project.

---
Tags: 7, theming, panels, performance
---


# Question
Title: Data export view gives error if 0 records
I have a data export option on a view. however , if the filter has not chosen any records, the excel export gives an error. Is there anyway to disable the data export icon if no records have been chosen, or other wise avoid this error?

thanks

# Answer
> 0 votes
This has been transitioned to https://www.drupal.org/node/2576429 per the request of Mołot.

---
Tags: importing-exporting
---


# Question
Title: Search button with 'lens' icon on the exposed view's filter - Drupal 7
I can't figure out how to make a search button on the view's exposed (as a block) search filter to be styled similarly as in Drupal standard search form, with a 'lens' icon. The examples for hook\_form\_alter() I found using:

```
$form['submit']['#type'] = 'image_button';
$form['submit']['#src'] = base_path() . path_to_theme() . '/images/search-button.png';

```

-don't seem to work correctly, as image on the button just doubles (png file includes both 'active' and 'inactive' images of lens). Could there be a straightforward way for the search button 'lens' styling, not including CSS/templates modifications?

# Answer
> 1 votes
The code you posted is good. The only "problem" is that your lens image is "sprites" image - designed to be shown only partially, depending on the state of your button. There is no standard for this, so Drupal does not support this. You ave two options there:

1. Cut your image, leave only the part you need.
2. Use CSS to implement sprite style your image was created for.

---
Tags: forms, views
---


# Question
Title: Implementing direction of a 1:n relation with entity-reference
Consider two content types A and B which are in a 1:n relation (say any A entity will be referenced by n entities of type B). Implementing such a relation with entity-reference fields can be done in 2 ways:

* content type A holds the relations:
    + CT A has its own fields plus one multi-value entity-reference type filed that will store the references to all the B type entities
    + CT B has only its own fields
* content type B holds the relations:
    + CT A has only its own fields
    + CT B has its own fields plus one single-value entity-reference type field that will store the reference of each B entity to its own parent A type entity.

With the first implementation (A type with a multi-value field) I give the user the possibility to sort the related entities, which is not possible with the second implementation.

Is there anything, on the contrary, that is possible to realize with the second implementation but not possible with the first one?

# Answer
> 0 votes
Your claim that *"With the first implementation (A type with a multi-value field) I give the user the possibility to sort the related entities, which is not possible with the second implementation."* is false.

Some things may be easier one way. Other things may be easier the other way. But ultimately, with Views you should be able to accomplish pretty much anything with both of these approaches. So use the one that's natural for your data.

---
Tags: 7, entities
---


# Question
Title: FTP sites/all and sites/default/files files zipped and unzip on server or FTP as is?
I have cpanel with hostgator, and it's faster to zip the folder sites/all and sites/default/files and then unzip on the server.

Is that the best way to do things or can it get corrupted?

Is it safer to FTP the files as is from the localhost environment?

# Answer
> 1 votes
My first recommendation is for /sites/all that you use a version control system such as Git/Subversion to save then the pull changes. If you *must* FTP them, I've found it's just as easy to copy them all over at once rather than unpack on the server, mostly because shared host SSH capabilities are sporadic and semi-functional at best.

Things to be careful of: if you're literally copying over /sites/default/files make sure that any .htaccess files were also copied. Additionally, you'll for sure have to do a cache clear because any css or js files saved in those directories will be unlinked from the current database.

---
Tags: installation, files
---


# Question
Title: Feeds XPath Parser - Update existing content
I have created a Feed Importer and used XPath Parser for mapping. I have problem with updating a existing content. For example I have this xml structure.

```
<node>
  <nid>1</nid>
  <title>Title 1</title>
</node>
<node>
  <nid>2</nid>
  <title>Title 2</title>
</node>

```

I started importer and everything is OK. I set NID as unique and check "Update existing content" in Node Process settings. So when I run importer again whit the same data this nodes have updated again.

Why have been updated ? The source is the same and don't any difference. Should It display, there is no new content to add if I start importer again and again with the same data ?

Thank you!

# Answer
> 1 votes
it doesn't recognized the nid field as unique,

What is the field associated with the nid value?

If you have a custom field associated with the nid :

You should install https://www.drupal.org/project/field\_validation

and add the validation of the field at http://yourwebsite/admin/structure/field\_validation

and set the validator with the value "Unique values".

Sometimes a space in the value of the feed can cause this in this case you can use tamper for trim spaces : https://www.drupal.org/project/feeds\_tamper

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


# Question
Title: Retrieve contents from a JSON URL using cURL and display them in an HTML table
I am trying to display contents retrieved from an external URL using JSON (the cURL method). So i wrote the below function:

```
function file_get_contents_curl() {
  //JSON URL which should be requested
  $gry_str = "?timezone=" . urlencode(date_default_timezone_get())  . "&dateFrom=" . date('Y-m-d') . "&dateTill=" . date('Y-m-d');

  $json_url = 'https://www.example.com/json/financial-calendar.json' . $gry_str;

  // Initializing curl
  $ch = curl_init();

  //Configuring curl options
  $options=array(CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array('Content-type: application/json'),
    CURLOPT_URL => $json_url);

  //Setting curl options
  curl_setopt_array($ch, $options);

  //Getting resutls
  $results= curl_exec($ch); //Getting json result string
}

```

I want the contents retrieved to be displayed in an HTML table. So i am using this:

```
<script id="calendarContentTemplate" type="text/html">
<![CDATA[
  <tr>
    <td class="calendar-local-time"><%= time %></td>
    <td class="region"><%= region %></td>
    <td class="title"><%= title %></td>
    <td><%= forecast %></td>
    <td><%= previous %></td>
  </tr>
]]>

```

and my constructed table like this:

```
<table class="calendar-table">
  <thead>
    <tr>
      <th class="time">Time</th>
      <th class="region">Region</th>
      <th class="title">Event</th>
      <th class="forecast">Forecast</th>
      <th class="previous">Previous</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="calendar-local-time"></td>
      <td class="region"></td>
      <td class="title"></td>
      <td></td>
    </tr>
  </tbody>
</table>

```

Nothing is being displayed on the table. Am I doing something wrong? Or do I need a Drupal function to make it work? Forgot to mention that its for the front page.

I have read about the `drupal_json_output()` function. But I am not sure if I have to use it. When I tried using it my webpage appeared only HTML.

It is very weird, because when I open Firebug I can see in the Net section. I am receiving **Status** as **200 Ok** for request, but the response is completely empty.

Any help is greatly appreciated.

# Answer
> 0 votes
Have you tried drupal\_json\_decode? drupal\_json\_decode give you back a object that you can use for print the variables.

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_json\_decode/7

---
Tags: 7, services
---


# Question
Title: How to add a submit button in an HTML table?
I need to call the gh\_cart\_prove when the BUTTON is clicked.

```
function gh_view_categories(){
  $a='<table>';
  $a.='<tr>';
  $a.='<td><strong>'.'Categoria:'.'</strong></td>';
  $a.='<td><strong>'.'Soglia minima:'.'</strong></td>';
  $a.='<td><strong>'.'Tot attuale:'.'</strong></td>';
  $a.='<td><strong>'.'Crea ordine'.'</strong></td>';
  $a.='</tr>';
  $query = db_select('uc_product_classes', 'u')
    ->fields('u', array('name','soglia', 'totattuale'));
  $result = $query->execute();
  while ($record = $result->fetchAssoc()) {
    $idUser=gh_get_user_id($record['name']);
    $a.='<tr>';
    $a.='<td>'.$record['name'].'</td>';
    $a.='<td>'.$record['soglia'].'</td>';
    $a.='<td>'.$record['totattuale'].'</td>';
    $a.='<td>'.'<button onClick="gh_cart_prove($idUser)">BUTTON</button>'.'</td>';
    $a.='</tr>';

  }

  $a.='</table>';

  return ($a);
}

```

The button appear but it not works. the function is correctly declared. How can I resolve this problem?

# Answer
> 1 votes
Assign an id to the button and use Jquery, set the $idUser in a data attribute example :

```
 <button id="buddon-id" data-user="<?php echo $idUser;?>" >button</button>
    <script>
    $("#button-id").on("click", function(e){
       userid = $(this).attr("data-user");
    };
    </script>

```

---
Tags: hooks
---


title: Can not login with HybridAuth

text:
# Question
Title: Can not login with HybridAuth
I installed Drupal HybridAuth module on my site for social authentication. I configured this module and it is displaying fine on site block. But when I try to login with any Social Media account details, it is processing correctly, but I cannot login in my site. How can I solve this? Here's a link to the site: example.com

# Answer
> 0 votes
A couple of things I would check.

* Make sure you're using the correct redirect URIs and JavaScript Origins. For example, the redirect URI should be **https://www.example.com/coupon/hybridauth/endpoint?hauth.done=Google** and the app you've registered at Google contain this too. The JavaScript Origins at Google should contain **www.example.com** (and **example.com** if you allow that too).
* Since you're running the site in a subdir, make sure you've set **RewriteBase** in **.htaccess** to **/coupon/**. That might cause a problem with redirecting after auth.

# Answer
> 0 votes
You may need to add the identity to your user account:

1. Go to your user profile at user/.
2. In the "HybridAuth identities", if you don't see the authentication provider listed, you need to go through the authorization process:
3. Click on "HybridAuth" tab.
4. Under "Add more identities", click on one of the social icons provided. This will initiate the authorization process that will allow HybridAuth to log you in using that account.

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


# Question
Title: How do I load the $form_state for a form loaded with drupal_get_form?
Or is drupal\_get\_form not the right way to go about loading node forms where I want to also get the $form\_state?

The reason I am asking is I would like to be able to place multiple node forms on the same page and have them editable (not in a popup) on the same form as the parent form. I have already tried inline\_entity\_form and that would almost work, however that module does not load the entire form inline with the rest of the parent node form. Rather it places the referenced nodes in a table that you then interact with and save separately.

# Answer
> 1 votes
When you do drupal\_get\_form() the form and state is cached, otherwise other Drupal form functions wouldn't be able to get it back later.

The only way I know to get it is like this:

```
// Get the form.
$form = drupal_get_form('my_form_id');
// Get the default form state.
$form_state = form_state_defaults();
// Get the form and form state from the cache for the form you just got.
form_get_cache($form['#build_id'], $form_state);

```

Since form\_get\_cache() returns the form also you could do the last line like this:

```
$form = form_get_cache($form['#build_id'], $form_state);

```

and it would overwrite your form with the cached one and update your form state (since `$form_state` is passed by reference) but in the case of calling it right after drupal\_get\_form() there is no need to do that.

---
Tags: forms
---


# Question
Title: How to get all group content from group?
I am using OG, Flag and Rules module. I would like to do like this.

When a user click **Flag links** in Group (name is `follow_group`) then all group content of that group will be flagged as following.

For now, i'm stuck at getting all group content of specific group. Is there a way to get group content of current group?

# Answer
All the contents are associated in `og_membership` table. If you can get the `gid` (group node id), then it will be easier to get the content associated with that group.

```
$og_contents = db_select('og_membership', 'ogm')
->fields('ogm', array('etid'))
->condition('ogm.gid', $gid, '=')
->condition('ogm.entity_type', 'node', '=')
->execute()
->fetchAll();

```
> 0 votes

---
Tags: organic-groups, flags
---


title: How to filter articles that have image

text:
# Question
Title: How to filter articles that have image
In Views block, how do I display the articles that only have image?

How to filter it?

Update question:

1） Under **Filters**, add **Content: Image (field\_image) - list**.

2) Choose **False** option.

3) Preview of block disappear.

How do I fix it?

# Answer
> 0 votes
You add a filter criteria that checks the image's file id (fid):

```
Content: Image (field_image:fid)

Operator: Is not empty (NOT NULL)

```

# Answer
> 0 votes
1. Add a filter
2. Choose your image field (fid)
3. Set it to 'Is not empty'

# Answer
> 0 votes
> **create view and use these filters ,it will show nodes that only have image not body**

---
Tags: views, 6, media
---


# Question
Title: Mulitple image upload field widget working on custom content nodes but not on user nodes
Using Drupal 7.39 and the MultiUpload FileField Widget module.

It works fine for articles, and custom content types I create, but it doesn't work for user fields. Even if I take the existing field from article, and add it as a field to user, it doesn't work.

You can select multiple images, and they show as "2 images selected", you click upload, and nothing happens.

Any idea why this is happening?

# Answer
It was an administration template problem...

It works in bootstrap, but not with 7 theme, but it does with Stark.

I thought that the Drupal 7 theme would be bullet proof, I guess not...

So always best to test various admin themes to see if that is the problem in the future.
> 0 votes

---
Tags: media
---


title: How to change date field label?

text:
# Question
Title: How to change date field label?
In my content I have one date field label, it is showing all uppercase letters automatically.

*Example* :I have given date field label as *birthday(lower case)* but it's automatically showing *BIRTHDAY(UPPERCASE)*. How can I overcome this.

# Answer
> 1 votes
use Css if nothing is working to show the label in small letters.

```
text-transform: lowercase;

```

# Answer
> 1 votes
According to my understanding you have applied CSS on wrong element, Please apply "text-transform: lowercase" on "label".

```
.from-type-textfield label {
           text-transform: lowercase
     }

```

Please put it on your `.css` file it will work fine.

# Answer
> 0 votes
As you are saying date field label is showing all uppercase letters automatically there might be the case of bad cache. to get rid of it do the following steps:

If you are working with command line try to clear the drupal cache by writing the command as:

```
 `drush cc all`

```

If you are not using the command line then go in the Administer Settings: **Configuration\>\>Development\>\> Performance** or **admin/config/development/performance** and click on clear all cache. It should work fine.

and if not worked this too then apply the CSS code in the style.css file inside your theme folder for that particular element

```
text-transform: lowercase;

```

---
Tags: theming, datetime, entities
---


# Question
Title: where can I find the login block to modify?
I want to modify login block!Where can I see login block ?

I am using danland theme in drupal 7 site. So far I have walked through `sites/all/themes/page.tpl.php` file, `node.tpl.php` and `template.php` file, but I didn't find.

Can anyone help me in this ?

Thanks in advance.

# Answer
> 0 votes
Here are the steps for customizing login block available in Drupal.

1) Go to your template.php file for the theme you're working on. Should be in the root of the theme folder for your theme

2) Now check for the below mentioned function in your template.php file. if its not exist then create it and if its exists then append the below mentioned code in the same.

```
function yourthemenamehere_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }
function yourthemenamehere_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

```

Now save and close!

3) Now in side your theme directory there will be a folder called "template". if its not there please create it there only and then create a php file inside that folder called: "user-login-block.tpl.php" Inside this file, put the following code:

```
<div id="user-login-block-container">
  <div id="user-login-block-form-fields">
    <?php print $name; // Display username ?>
    <?php print $pass; // Display Password ?>
    <?php print $submit; // Display submit ?>
    <?php print $rendered; // Display hidden elements (required for successful login) ?>
  </div>
  <div class="links">
    <a href="/user/register">Singup</a> OR <a href="/user/password">Forgot Password</a>
  </div>
</div>

```

4) IMPORTANT STEP , navigate to "admin/config/development/performance" and click "clear all caches" -- this is critical because only after deleting cache you can able to see the changes in your login block.

Now you can change the stucture of user-login-block.tpl.php as your wish.

I hope this can help you.

---
Tags: 7, users
---


title: Adding a Block Into Region

text:
# Question
Title: Adding a Block Into Region
Using several different themes, I'm looking to add a generic region to the bottom of each "content" section of my webpage. The code I have so far is. . . . with Social Share being the name of the block.

# Answer
> 0 votes
If you have all of these different themes enabled (and you aren't using something like Panels), then you can simple edit this from the Block administration page (admin/structure/block).

If you want this to be completely removed from configurability, then I would recommend either doing a preprocess function for the content region (or hard-coding, ick, your custom HTML into the region itself).

# Answer
> 0 votes
Add a Block Region

1. Modify the Bartik theme directly. Of course, this is not the suggested practice. In the Drupal community, we don't modify Drupal's core unless we are applying a patch.
2. Copy the Bartik theme to the /sites/all/themes directory, rename the theme, and modify it to include the region you desire.

There is a third option, which includes turning Bartik into a base theme and then creating a sub-theme, but that conversation is outside the scope of this tutorial.

In this tutorial, we will make a copy of Bartik and modify it.

OR

Working with Blocks and Regions in Drupal

---
Tags: blocks, theming
---


title: Multiple path alias for a url

text:
# Question
Title: Multiple path alias for a url
I've installed the pathauto module. I have a content type *article*. When I'm trying to create an article, the path is created automatically in the form **content/article-title**, that is fine.

However, I want to pass some dummy values via url like **content/article-title/value1**, **content/article-title/value2**. So now I have multiple aliases for the url. I will create some functionality using this dummy value.

If I try to access **node/10/value1**, I can access the page. But I want to access with path alias like **content/article-title/value1**.

How can I access a page using **content/article-title/value1**, **content/article-title/value1** and **content/article-title**?

I don't need to create multiple path alias for url. But I need to access page using above urls.

Is it possible?

**Answer:**

Eventually, I got the solution for this. Please refer http://www.phponwebsites.com/2016/08/drupal-7-pathauto-multiple-url-alias.html

# Answer
> 2 votes
You need to set path at config \>\> URL aliases \>\> patterns under that article patter you need to set something like.

**content/\[node:title\]/\[node:field\_machine\_name\]**

You can access with pattern url otherwise you can access by default with "node/nid".

# Answer
> 0 votes
You should consider passing the values as parameters instead of arguments.

### Arguments:

* content/article-title/value1
* content/article-title/value2

### Parameters:

* content/article-title?key1=\[value1\]&key2=\[value2\]

---

Parameters will mean you can still have a single path alias for your node.

You pick up parameters in your code by looking in the global `$_GET` variable.

# Answer
> 0 votes
You will need multiple aliases for the same node.

Create a custom module that uses hook\_node\_insert() to trigger a function that uses path\_save() to add a new alias for the node.

path\_save only overwrites paths if you direct it to do so with `$path['pid']`;

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


# Question
Title: Custom url is not working with drealty listing
I am using Drealty module in Drupal 7. I have created custom url for properties.

I am getting path using;

`<a href="<?php print drupal_get_path_alias("drealty_listing/$id"); ?>"><?php print t('More Detail'); ?></a>`

This code is not working for me properly. For some properties it gives *page not found* but *Property* exists.

# Answer
> 0 votes
Using the url() function should give you what you need:

`<a href="<?php print url("drealty_listing/$id"); ?>"><?php print t('More Detail'); ?></a>`

The url will be converted automatically to the alias.

---
Tags: 7
---


# Question
Title: Adding custom field to apache solr drupal 7
I have tried Apache Solr Autocomplete to make autocomplete option in solr search. But it is not work for me. Is there any other alternative to do this?

And also I need to know, how to add custom field to be indexed in solr. I have tried `hook_apachesolr_index_document_build_node` and `my_module_apachesolr_query_prepare` in my custom module. But when I put this the index is not added to solr.\`

Any suggestions?

# Answer
> 2 votes
The apachesolr module defines a hook that allows a search document to be updated before it is sent to the Solr server for indexing. Actually, I lied, there are two.

`hook_apachesolr_index_document_build` and `hook_apachesolr_index_document_build_ENTITY_TYPE` (for specific entity types).

```
<?php
/**
 * Implements hook_apachesolr_index_documents_build_ENTITY_TYPE().
 */
function mymodule_apachesolr_index_document_build_node(ApacheSolrDocument $document, $entity, $env_id) {
  // While indexing article node content
  if ($entity->type == 'article') {
    // Get the field value that needs to be indexed
    if ($fields = field_get_items('node', $entity, 'field_example_field')) {
      // Only need the first value
      $value = field_view_value('node', $entity, 'field_example_field', $fields[0]);
      // Add the value to the document to be indexed. ss_ prefix denotes a string type
      $document->setField('ss_index_field_name', $value);
    }
  }
}

```

The content is added to Solr via the line `$document->setField('index_field_name', $value);` While the example is very simple, this can be used to index values from complex relationships that wouldn’t normally be possible.

Any content that already exists in the index will need to be reindexed.

Now that that new custom field exists, it can be made available for the search results display. Using `hook_apachesolr_query_prepare` the search query can be altered, in this case to add the new field.

```
<?php
/**
 * Implements hook_apachesolr_query_prepare().
 */
function mymodule_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // Make 'index_field_name' available for search results
  $query->addParam('fl', 'ss_index_field_name');
}

```

The new field can also be used to filter search results, again using `hook_apachesolr_query_prepare`.

```
<?php
/**
 * Implements hook_apachesolr_query_prepare().
 */
function mymodule_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // filter where 'index_field_name' = 'indexed_value'
  $query->addFilter('ss_index_field_name', 'indexed_value');
}

```

---
Tags: search
---


# Question
Title: What are the alternatives to the Calendar module?
I have a requirement to add a calendar to my Drupal 7 website. Currently the Calendar module has an alpha version. This is a little subjective, but I was wondering if the Calendar module is stable enough for my needs. Are there alternatives?

# Answer
> 3 votes
Well, in my recent experience is not yet ready to production, but it depends on your needs. Maybe most of this is because the "partner" module, date, has lots of issues now. I suggest you test both: Calendar and FullCalendar. The Calendar module is more powerful and flexible, but if you need a simple calendar, FullCalendar is ready to go now.

# Answer
> 2 votes
The Calendar module is being rewritten from scratch, see Calendar 7.x-3.x. There will be no upgrade path.

# Answer
> 1 votes
There also is Bootstrap Calendar. But it doesn't seem to be ready for production yet. At my first simple test I didn't got it going with the default settings.

---
Tags: datetime
---


# Question
Title: User can self-register unless email is on a blacklist
I want users to be able to register unless their email address is on a blacklist (including wildcards), in which case an administrator has to approve the registration. How do I go about this?

# Answer
No need to add any custom code as your requirement is just to allow visitors to register by themselves but you want to block them for log in till the administer won't approve them, if this the scenario then just go to the following URL:

**/admin/config/people/accounts**

or you can navigate through Admin Menu:

**configuration \>\> People \>\> Account Settings**

Here you can find section "Registration and Cancellation" under which you can find:

**Who can register accounts?** Select: **Visitors, but administrator approval is required**

Note: You can also set "***Require e-mail verification when a visitor creates an account***", if you required e-mail verification too.

For validation whether the email is in your blocked List or not you can validate it by writing your own custom validation function using:

function hook\_form\_alter(&$form, &$form\_state, $form\_id){

if($form\_id == 'user\_register\_form'){

```
  $form['#validate'][] = 'your_validate_func_handler';

```

}

}

function your\_validate\_func\_handler(&$form, &$form\_state){

```
// here is your code to compare

```

}

Note: "hook" will be replaced from your custom module name.

Hope this will help you.
> 1 votes

# Answer
Put the account settings for 'Who can register accounts' on 'Visitors', and write a custom module that uses hook\_user\_presave() to block accounts that match your criteria before they are saved. Or maybe hook\_user\_insert(), then it won't catch profiles that you are manually unblocking.
> 0 votes

# Answer
As per your scenario just go to the following URL:

**/admin/config/people/accounts**

or you can navigate through Admin Menu:

**configuration \>\> People \>\> Account Settings**

Here you can find section "Registration and Cancellation" under which you can find:

**Who can register accounts?** Select: **Visitors**.

Write a custom module that uses hook\_user\_presave() to change the status of accounts that matches your criteria before they are saved.

Let me try to explain:

If a visitor comes with certain email id "xyz@abc.com" so when it's registering in your site it's status would be "1" that is active, but in your hook i.e. "hook\_user\_presave()" you can check whether the email is in your block list or not, if yes, change its account status to "0" i.e. "blocked" in terms of Drupal and can shoot a mail to admin to notify that, one visitor wants to register in our site having mail Id exists in our block list. Ask Admin to approve him or not. **If notifying Admin is required** else the visitor registered as blocked User and only Admin can approve him.

Note: Once Admin approved his account, you can using the same hook i.e. "hook\_user\_presave()" can update the user account status and also the block list of emails, as I think, you should update the block list as once your admin approved a blocked id so that block id won't be a part of that block list anymore.

You can check, whether the account is new or update:

if ($account-\>is\_new){

```
  //Do things

```

}else

{

```
  //Do things

```

}

I am not good in explanation but tried. :)
> 0 votes

---
Tags: users
---


# Question
Title: How can I display a WebForm in a Modal Window
I am using Webform (4.11). I have a 'simple' form with 2 fields that I would like to display in a modal dialog when the 'Apply' button is pressed.

So imagine I have a page with an apply button, and when the user selects this button, I need to know if they are an existing client (they are not logged in), and some other 'meta data' (second field).

Bottom line - I would just like to display the webform that has these questions, in a modal dialog.

I know I can create a custom module, to create a custom form, and use CTools to show the form in a modal window, but then I lose all the functionality that comes with the Webform module.

# Answer
> 1 votes
Use modal form module to load into modal window. Create link using modules custom method after check user is loggedin.

```
$links[] = ctools_modal_text_button(t('webform'), 'modal_forms/nojs/webform-path', t('Webform via modal'),  'ctools-modal-modal-popup-small');

```

---
Tags: ajax, webforms, javascript
---


# Question
Title: How do I access the updated entity after saving with entity wrapper
When using entity wrapper to modify and save an entity, what is the preferred way of accessing the updated entity.

For example, after the following code saves the node:

```
$node = node_load(123);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

```

After that, what is the preferred way to access the updated node object (the full object, not just field values)?
Can it be accessed via the wrapper in some way or do you have to load the node again?

# Answer
> 3 votes
There's no "preferred" way, as such, but I guess if you're using the wrapper to work with the entity, it makes sense to stick with that convention to re-access it.

Don't forget you've just altered an in-memory object, so regardless of the persistence layer, that object will still have the changes in it.

Once you've done this:

```
$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

```

Your changes will immediately be available by inspecting

```
$node_wrapper->field_textfield

```

EMWs use the core entity API under the hood, so persistence is actually done through the default entity controller. As such, everything that would happen in calling `node_save()`, for example, happens when you update the wrapper object.

In practical terms, that means you can save an entity with EMW, and also access the changes on it immediately using an object returned from `entity_load()`. It's the same underlying object in memory.

I think it's safe to say that context, and even surrounding code/conventions, will often dictate the particular method you use.

---
Tags: 7, entities
---


title: Pagination in Panelizer drupal

text:
# Question
Title: Pagination in Panelizer drupal
I'm using panels and panelizer. I created a custom content in panelizer where I can *upload* a file. When I render the results, I have a lot of items. Now I want to paginate them.

How can I add the *pagination* in *panelizer* or use a *view in panelizer*?

# Answer
> 0 votes
Pagerer

> **Features:**
>
> * multi-pane pager
> * Views pager plugin
> * control whether to display links to pages, to items, or to item ranges
> * direct input of the page to go to through an input widget
> * selection of the page to go to through a jQuery UI slider
> * selection of the page to go to through a client-side scrolling pager
> * links to progressively more distant pages (like +10, + 20, +100, +200)
> * adaptive logic links
> * specify text to be used to render page separators (like a vertical bar) and page breakers (like an ellipsis)
> * supports Views' AJAX enabled pager

---
Tags: paging, panels
---


# Question
Title: How to convert Drupal 6 profile taxonomy value to array?
In Drupal 6, Profile module stores taxonomy values for users with this format:

a:3:{s:17:"Local Development";s:17:"Local Development";s:35:"Environmental Policy and Management";s:35:"Environmental Policy and Management";s:22:"Environmental Research";s:22:"Environmental Research";}

Is there a way to programmatically convert that to an array using PHP and/or Drupal 7 functions?

This is the array I would like to obtain:

```
Local Development
Environmental Policy and Management
Environmental Research

```

# Answer
The drupal stores the users data in serialized format to get it in array format you can use
`unserialize ( string $str [, array $options ] )` function in php.
here is the example for you to get better understanding PHP : unserialize() function
> 0 votes

---
Tags: 6, users
---


# Question
Title: How to deal with login attempts coming from 1-127.0.01 and what does it means?
Recently on my drupal 7 site happens that i find the admin account blocked. Looking to the flood table i see a lot of failed login attempts from ip "1-127.0.0.1". It's an external attack or something not working in my site? The fact that the ip the request comes from is 'localhost' is confusing me. In both cases, how to deal with this problem?

# Answer
> 0 votes
After attempt five login drupal block account automatically

1. Install the Flood module flood\_control
2. Enable the Flood module
3. Go to admin/settings/system/Flood control
4. Change the "Failed login (username) window" from 6 hours to None
5. Save

Flood Control

> This project is intended to add an administration interface for hidden flood control variables in Drupal 7, like the login attempt limiters and any future hidden variables.

Flood Unblock

> This module makes it possible for site administrators to remove ip-adresses from the flood table, or to remove all ip-adresses from the table depending on the event type.

Different ways to reset Drupal admin password

Protect site from flooding when user login is attacked...

---
Tags: 7
---


# Question
Title: ASAF module redirects comment form to system/ajax#comment-cid after submission
I use Asaf (ajax submit for any form) module to Ajaxify form submissions in my website. This module works well but in comment form submission, it submits the comment then redirects the page to `system/ajax#comment-cid` which is a blank white page.

How can I solve this or is there any way out to Ajaxify comment form submission?

# Answer
> 1 votes
From This page I found the answer

In the `template.php` add the following code, replace `epic_ajax` with your theme name

```
// Disable the ajax redirect.
function epic_ajax_asaf_form_ajax_commands_alter(&$commands, $form, &$form_state, $form_id) {
    foreach($commands as $key => $command) {
        if ($form['#node']->nid) {
            if ($command['command'] == 'asafRedirect' || 'asafRefresh') {
                unset($commands[$key]);
                break;
            }
        }
    }
}
// These functions allow for subsequent saves without validation errors.
function epic_ajax_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'plan_node_form') {
        // Ensure our own validation is called first to overcome the node changed error node.module: 971
        array_unshift($form['#validate'], "epic_ajax_node_edit_validate");
    }
}
function  epic_ajax_node_edit_validate($form,&$form_state){
    // Update changed value to avoid node changed error node.module: 971
    $form_state['values']['changed'] =  $form_state['node']->changed;
}

```

you need to add this javascript code as well

```
(function ($, Drupal) {
      Drupal.behaviors.epicAjax = {
        attach: function(context, settings) {
    $('input, select').change(function() {
    $('#edit-actions .form-submit').first().trigger('mousedown');
    });
        }
      };
})(jQuery, Drupal);

```

# Answer
> 1 votes
You need to look in to issues of that module I found there one important information which help on this issue. https://www.drupal.org/node/2277137

---
Tags: forms, ajax, comments
---


title: Index custom content in apache solr

text:
# Question
Title: Index custom content in apache solr
I have several custom modules that load and display data from custom tables. I have successfully managed to use the drupal search on these contents, using the drupal search hooks like, hook\_update\_index, hook\_search\_execute, etc. But now we have decided to use solr instead. Now I'm totally confused and don't know how to make solr index my custom data. The closest I've come to solving this is to this:

```
function msearch_apachesolr_index_document_build(&$document, $entity, $entity_type) {
    if ($entity_type == 'people' && isset($entity->description)) {
        $document->addField('s_firstname',
                $entity->field_firstname['und'][0]['value']);
        $document->addField('s_lastname',
                $entity->field_lastname['und'][0]['value']);
        $document->addField('ts_description', $entity->description);
    }
}

```

This code does not work(as in indexing my data) and it really shouldn't. There's no way that the $entity passed to this hook could have my desired data in it. Is there something I should do to manually pass the object to this hook? Do I need to implement hook\_cron and do this there?

Thanks, any help is appreciated

## PS:

I know how solr indexes data, through POST requests to solr/corename/update, but I doubt that's the way to go. If I had to go this way, I would've had to implement the whole mechanisms for indexing rows and making sure no duplicates were sent for indexing. OR SHOULD IT BE EXACTLY LIKE THIS???

# Answer
```
function msearch_group_apachesolr_query_alter($query){
     $query->addParams(array('fl' => array('ss_firstname')));
 //  $query->addParams(array('fl' => array('ss_lastname')));
}

```
> 0 votes

---
Tags: 7, search
---


# Question
Title: Apache Sorl Add Custom Term Indexing with Hierarchy
My project was have 3 content types with taxonomy, i need to combine all the content types term field values and display with hierarchy. My fields are : field\_peoples\_rits\_term, field\_publcation\_rits\_dev, field\_research\_rits\_term I Need combine all these fields as a new field. Thanks in advance

# Answer
> 0 votes
You don't need custom code to achieve this, quoting from here:

> There's a wonderful little checkbox in the Search API workflow tab which enables it.
>
> Head to:
>
> admin/config/search/search\_api/index/*your solr server*/workflow
>
> (You'll need to have created a server to get to this.)
>
> And then tick the box "Index Hierarchy".
>
> In callback options select the taxonomy field where you would like searching for the parent to include the child.

---
Tags: taxonomy-terms, search
---


title: context - url wirh parameter

text:
# Question
Title: context - url wirh parameter
I'm using Drupal 6 and context. It seems that context does not react on path like this **mypath?123** Is there any way to check such path with context?

# Answer
> 0 votes
If you're wanting a module-based solution the Context Query Parameters module adds *Query String* condition that lets you check for multiple query values.

> This module introduces a Context condition that allows you to trigger a Context based on query parameters on a given page request.

---
Tags: 6
---


title: Unable to install modules with Drush

text:
# Question
Title: Unable to install modules with Drush
I've got a fresh install of the Drupal 8 Beta 12. I'm trying to install the REST UI module:

```
$ drush dl restui-8.x-1.x-dev

PHP Fatal error:  Class 'Drupal\Core\Session\AccountInterface' not found in /var/www/html/drup/core/includes/bootstrap.inc on line 64
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Class 'Drupal\Core\Session\AccountInterface' not found in
/var/www/html/drup/core/includes/bootstrap.inc, line 64

```

Does anyone know what's going on here?

# Answer
> 6 votes
Drush 6 does not support Drupal 8 and you need to upgrade to drush 7 (well I just upgraded to drush 8):

```
Drush Version   :  8.0-dev

```

See duplicate issue: Running Drush returns an error

**Edit:** If you are working on Drupal 8 you need the Drupal Console its syntax is a bit long-winded, but it is incredibly powerful.

---
Tags: 8, drush
---


# Question
Title: Predefined field collection items in node edit form
I have a Products taxonomy with all possible product names offered by the organization, Order content type to place an order and ordering form. Order content type includes field collection with term reference field referencing to Product taxonomy. The case is that I need to predefine field collection items with all possible selected Product terms on ordering form. Items number = count(Products terms)

I tried to use *field\_multiple\_value\_form* function to generate items, but in this case I can't predefine default value for field inside field collection item (or can?).

```
$products_taxonomy = taxonomy_vocabulary_machine_name_load('products');
$product_tree = taxonomy_get_tree($products_taxonomy->vid);

if (is_array($product_tree)) {
  $field_instance = field_info_instance('node', 'field_fc_o_position', 'order_request');
  $field_instance['cardinality'] = count($product_tree);
  $field_instance['type'] = 'field_collection_item';
  $field_instance['columns'] = array();

  $form_state['field']['field_fc_o_position'][LANGUAGE_NONE]['items_count'] = count($product_tree);
  $instance = $form_state['field']['field_fc_o_position'][LANGUAGE_NONE]['instance'];

  $form['field_fc_o_position'][LANGUAGE_NONE] = field_multiple_value_form(
    $field_instance,
    $instance,
    LANGUAGE_NONE,
    array(),
    $form,
    $form_state
  );
}

```

Question is how to generate empty field collection items on ordering form and default value for select field inside each new item?

Thank you!

# Answer
I do not think that this will work in the way you wish, since Field Collections are entities rather than normal fields.

It sounds to me like you need to use form\_alter to update your input form.

Checkout this link on Drupal.org for one method that might work: Finally - found a solution... (D7)
> 0 votes

---
Tags: entities
---


# Question
Title: How to get the count on the select list in views?
For example, I have a content type with field. The field is select list. The select list has four default values as well as it is required.

I want the output of a view as:

```
Provincial (2)
Federal (6)
Institutional (3)
...
Value (#)

```

*where # is the number of nodes with this value*

How can I accomplish this?

# Answer
Assuming Drupal 7 and Views 3:

1. Create a view based on your content type with a page or block display
2. Add a contextual filter, based on your select field
3. Under "When the filter value is NOT available" select "Display a summary"
4. Configure the summary as you like, with "Display record count with link" enabled
> 2 votes

# Answer
Use direct database Query, Replace appearance of "field\_select" with your field name in below code

```
SELECT count(*), `field_select_value` FROM `field_data_field_select` GROUP BY `field_select_value`

```

Then get the label of select field from value using below technique replace field\_select with the field name of select list

```
$key = field_select_value; // Or whatever
$field = field_info_field('field_select');
$label = $field['settings']['allowed_values'][$key];

```
> 0 votes

# Answer
Check this answer https://drupal.stackexchange.com/a/81953/12163 for a similar approach. It uses the views\_merge\_rows module. No need for custom coding.

The fields of the views will be the *Select list field* and the nid. The *nid* will be aggrgated with "Count" and excluded from display. The select list will be overwritten with `[select_list] ([nid])`.
> 0 votes

# Answer
You may use Views Aggregator Plus module to display number of nodes.
After installing and enabling the module, In your view

* Select table format as Table With Aggregation Options
* In the settings, under your desired field select Group and Compress as a group aggregation function
* For the number of nodes, select Count as a group aggregation function for the nodes field
* Then render the column and add separator as you like for the display
> 0 votes

# Answer
You could use Views Aggregation feature to attain that result. Check https://drupal.stackexchange.com/a/15875/4915 for a solution similar.
> -1 votes

---
Tags: views
---


# Question
Title: Find out what hooks are implemented in a system
I've been put to work on a very complex Drupal 7 based system with multiple custom written modules for which the developers have gone or been re-assigned. Documentation for the system is very sparse. I think it would help me to get a a better overall picture of the system, as well as to figure out what is happening in particular parts of the system that I have been asked to fix or change, if I could see a listing of all of the hooks that are implemented.

I presume that Drupal scans all of the code in the system and builds itself some sort of structure or associative array in its cache memory so that it can quickly find any hooks that need to be invoked. Is the result stored somewhere that I can read, for example in a database table or a global variable? If I need to figure it out myself, is there a particular function, for example in the system module or bootstrap code that all hooks must pass through once? If so, perhaps I could (temporarily) hack it to get the information I want.

If someone knows how to do this, I'd love to hear how. If you don't know how to do it but have ideas about especially fruitful places to look in the code, database, drush functions, or wherever, that could be useful too.

Thank you very much.

# Answer
> 0 votes
The list of hooks implemented by modules are kept by Drupal in its cache (cache bin: cache\_bootstrap, cache ID: module\_implements); that is why you cannot simply edit an enabled module to add or removed hooks.
Its content is an array whose keys are the name of the hook and the values are array containing couples `$module => $group` (one for each module implementing a hook).
The cache is populated progressively each time a hook is invoked; so, in a fresh Drupal installation it is initially empty.

As reference, these are the relevant parts of code used by `module_implements()`.

```
  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

```

```
foreach ($implementations[$hook] as $module => $group) {
  // If this hook implementation is stored in a lazy-loaded file, so include
  // that file first.
  if ($group) {
    module_load_include('inc', $module, "$module.$group");
  }
  // It is possible that a module removed a hook implementation without the
  // implementations cache being rebuilt yet, so we check whether the
  // function exists on each request to avoid undefined function errors.
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (!function_exists($module . '_' . $hook)) {
    // Clear out the stale implementation from the cache and force a cache
    // refresh to forget about no longer existing hook implementations.
    unset($implementations[$hook][$module]);
    $implementations['#write_cache'] = TRUE;
  }
}

```

As for the functions used to invoke hooks, they are more than one, but in most cases, the modules use `module_implements()` (which is the function populating the hook cache), directly or indirectly. The only case where that function is not used is when a module invokes a hook of a single module, probably getting the module name from a setting or using a literal string for the module name; in this case, `module_invoke()` is used, even if (in the case of settings) I would expect the module to use `module_implements()` to populate the choices the users have.

---
Tags: hooks
---


# Question
Title: How built in functions like theme_field() are called in drupal?
I have function theme\_field() in my `field.module`. But I don't know how it's getting called. I have searched entire drupal project for the function calling statement . But I couldn’t find it. How this function is getting invoked? Please advice.

```
function theme_field($variables) {
//    print_r($variables);
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

# Answer
> 0 votes
Consult hook\_theme($existing, $type, $theme, $path).

It is called via theme() which can be called directly or indirectly on a render array

Each module that introduces a theme element will define a base implementation (what you are looking at in your question) for theme and other modules can override it if they wish.

Look at field.default.inc in Field module, line 212:

```
$info = array(
          '#theme' => 'field',
          '#weight' => $display['weight'],
          '#title' => $instance['label'],
          '#access' => field_access('view', $field, $entity_type, $entity),
          '#label_display' => $display['label'],
          '#view_mode' => $view_mode,
          '#language' => $langcode,
          '#field_name' => $field['field_name'],
          '#field_type' => $field['type'],
          '#field_translatable' => $field['translatable'],
          '#entity_type' => $entity_type,
          '#bundle' => $bundle,
          '#object' => $entity,
          '#items' => $items,
          '#formatter' => $display['type']
        );

```

Theme will then go through this process below to determine whether to render via template file or theme function (screenshot from page 82 of Drupal 7 Module Development).

---
Tags: 7, theming
---


# Question
Title: How to programmatically check a view to test if it has any results?
What's the most lightweight way to test if a view has any results in it or not? I have a system which creates links to various views, but if the view has no results I want the link to be greyed out. I can only think to load the whole view and execute it, but hopefully there is an easier solution?

I should also note that these views contain contextual filters, if it makes any difference.

# Answer
Your options:

* Trim down the "view" to return only 1 row of possible results.
* Attack the problem from the other side. Use a `Rule` or a `Hook` to track the condition of your event (eg, "is there new content of type X") in a site `variable` and check that value instead of your View.

... etc ...
> 0 votes

# Answer
This is the best solution I have found so far:

```
<?php
$view = views_get_view_result($name, $display, $args);
$result = count($view);
if ($result) {
//do something here
}
?>

```

Source: https://www.drupal.org/node/446798#comment-6439726
> 0 votes

---
Tags: views
---


# Question
Title: How to show latest and high price value first using Views?
I am using views to show products in my site. I need to filter my view with high price and latest product . Using expose filter not a sort criteria.

# Answer
To achieve your requirement, you have to expose the sort criteria. Select checkbox **Expose this sort to visitors, to allow them to change it** under sort criterion configuration.

Note: When you add any field into SORT CRITERIA, then under this field configuration you can see this option.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to override path of specific page using views
I have created a page view which contains files listing. On existing Page there are three tabs called 'thumbnails' 'files' and 'thumbnail plus' now I want to override on 'files' tab view with my page view. How do I do that?

# Answer
Just set the path of the view to the same as the path of the page you want to override.

That's all you need to do, paths that Views takes care of "win" over paths provided by core and other modules. The most famous example of this is probably the taxonomy/term/% page View that comes with the module. Once enabled, term pages aren't handled by core any more, the View takes their place.
> 2 votes

---
Tags: views
---