# Question
Title: Limit the results returned by 'published'
I am new to the Database API and SQL queries in general. I needed to create a custom module that could be given a list of fields and would output the average value of each of these fields. I am pleased to have got my module to do this.

Unfortunately it includes all of the values for my fields, irregardless of whether they belong to a published node or not. To get it to exclude results from unpublished nodes I'm guessing that my query needs to draw in information from the node table. Could someone please point me in the right direction of how to exclude results from unpublished nodes?

Please find my module code below.

```
    function custom_aggregate_data_block_info() {
  // This example comes from node.module.

   $blocks['custom_data'] = array(
    'info' => t('Custom Data'),
// DRUPAL_CACHE_PER_ROLE will be assumed.
  );

  return $blocks;

}

/**
* Implements hook_block_view().
*
* Prepares the contents of the block.
*/

function custom_aggregate_data_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {

      case 'custom_data':

    // initial output for block
        $block['subject'] = t('feild test');
        $blockoutput = "<div id='results'>";

    // searches the database and displays the results in a block

      /* database table name, table cell name */
      /* ie DRUPAL_MACH_NAME_value, field_data_DRUPAL_MACH_NAME */
      $feilds_to_query = array ("field_test_2004","field_test_2005");

      foreach ($feilds_to_query as $dbfeild) {
          // Do something with each $record
          $dbfeild_tablename = $dbfeild + "_value";
          $dbfeild_cellname = "field_data_" + $dbfeild;
          $querystring = "SELECT " + $dbfeild_tablename + " FROM " + $dbfeild_cellname;
          $query =  db_query($querystring);

          $total_field_value = 0;
          $total_records_field_value = 0;
          $average_records_field_value = 0;

          foreach ($query as $record) {
              // Do something with each $record
              $total_field_value = $total_field_value + $record->$dbfeild_tablename;
              $total_records_field_value = $total_records_field_value + 1;
          }

          // when looping through the results is finished then average the total by the number of records returned.
        $average_records_field_value = $total_field_value/$total_records_field_value ;

        // add the averaged data to the values stored ready to be returned
        $blockoutput .= "<div>Average results: " . $dbfeild . ": " . $average_records_field_value . "</div>";

       }

       // when finished looping through all the queries then close the html div, then return the results as a block
       $blockoutput .= "</div> <!--end #results -->";
       $block['content'] = $blockoutput ;

    break;
  }
  return $block;
}

```

Note that I have the case statement included as I plan to make use of several blocks in the completed module.

# Answer
Whether a node is published is stored in the node table, in the 'status' column. You can do an innerJoin with that table and add a condition. I'd do it something like this, using db\_select (haven't tested this...):

```
$fields_to_query = array ("field_test_2004","field_test_2005");

foreach ($fields_to_query as $dbfield) {
  // Do something with each $record
  $dbfield_tablename = $dbfield . "_value";
  $dbfield_cellname = "field_data_" . $dbfield;

  $query = db_select($dbfield_cellname, 'c');
  $query->addField('c', $db_field_tablename, 'value');
  $query->condition('n.status', 1);
  $query->innerJoin('node', 'n', 'n.nid=c.entity_id');
  $result = $query->execute();

  foreach($result as $r) {
  //fetch field value by calling $r->value
  ...
  }
  ...
}

```
> 0 votes

# Answer
The node table has a field called **status** \- 1 is published, 0 is unpublished.

Are field\_test\_2004 and field\_test\_2005 Drupal generated tables?

Normally table names take the form of field\_data\_field\_test\_2004...

Anyway, assuming they are Drupal generated tables they will have a field called entity\_id which you can join to the node table with.

If you are building queries like this I would suggest you look into using Drupal Dynamic Queries as opposed to string concatenation - it is much easier to add bits to and manipulate the query.

Also feilds is spelt fields (sorry, couldn't help myself)
> 1 votes

# Answer
olyN's answer is correct and helped me greatly. For anyone trying to do something similar here is my code:

```
case 'custom_data':

    // searches the database and outputs the results as a block

    // initial output for block
        $block['subject'] = t('field test');
        $blockoutput = "<div id='results'>";

      /* database table name, table cell name */
      /* ie DRUPAL_MACH_NAME_value, field_data_DRUPAL_MACH_NAME  */
      $fields_to_query = array ("field_test_2004","field_test_2005");

      foreach ($fields_to_query as $dbfield) {
          // Do something with each $record
          $dbfield_cellname = $dbfield . "_value";
          $dbfield_tablename = "field_data_" . $dbfield;

            $query = db_select($dbfield_tablename, 'c');
            // Add extra detail to this query object: a condition, fields and a range

            $query->addField('c', $dbfield_cellname, 'value');
            $query->innerJoin('node', 'n', 'n.nid=c.entity_id');
            $query->condition('n.status', 1);

            $result = $query->execute();

              $number_of_rows = $result->rowCount();
              $myresults = $result->fetchAll();

               $total = 0;

                for ($x=0; $x<$number_of_rows; $x++) // loop for each of the number of results returned
                  {
                   $total = $total + $myresults[$x]->value;
                  }

                  // add to the output block for each table returned
                  $blockoutput .= "<div>RESULTS: " . $dbfield_tablename. " averaged total: " . $total . "</div>";

      } // end for foreach ($fields_to_query as $dbfield)

       // when finished looping through all the queries then close the html div, then return the results as a block
       $blockoutput .= "</div> <!--end #results -->";
       $block['content'] = $blockoutput ;

    break;

```
> 0 votes

---
Tags: database
---


# Question
Title: How to build a url path from raw path and arguments?
In Drupal 7, from within a module,

My goal is having a **menu path** (e.g. "`/path/to/page/%/%/view/%`") and an **array of arguments** (e.g. `array('foo1', 'foo2', 'foo3')`), be able to **build the resulting path** (e.g. "`/path/to/page/foo1/foo2/view/foo3`").

After looking all over in the Drupal API, I cannot find a function that would do that.

Does such function exist?

**EDIT:**

The placeholders can be different as well. e.g. "`/path/to/page/%user/%blah/view/%`". The original raw path is dynamic and is only known during runtime.

I thought that `format_string` may work for `%user` and `%blah`, but what about the `%` in the end, does `format_string` work to replace that one too?

# Answer
I ended up building a simple version based on `_menu_router_build`.

```
function build_path($raw_path, $parameters)
{
  $new_path = '';
  $parts = explode('/', $raw_path);

  foreach($parts as $part)
  {
    // Look for wildcards in the form allowed to be used in PHP functions,
    // and if we do find one, then replace it with the next variable
    if(preg_match('/^%(|' . DRUPAL_PHP_FUNCTION_PATTERN . ')$/', $part))
    {
      $part = array_shift($parameters);
    }

    if(!empty($new_path))
      $new_path .= '/';
    $new_path .= $part;
  }

  // add remaining parameters at the end
  foreach($parameters as $parameter)
    $new_path .= '/'.$parameter;

  return $new_path;
}

echo build_path('category/%cat/view/%', array('cat1','id123','extravar1','extravar2'));

```

Prints `category/cat1/view/id123/extravar1/extravar2`
> 0 votes

# Answer
I don't think core has a function like that but it's easy enough to write a simple version:

```
$path = '/path/to/page/%foo/%bar/view/%';
$args = array('foo1', 'foo2', 'foo3');

$wildcards = array();
foreach (explode('/', $path) as $part) {
  if (strpos($part, '%') === 0) {
    $wildcards[] = $part;
  }
}

if (count($args) != count($wildcards)) {
  // Handle it
}

foreach ($args as $key => $arg) {
  $wildcard = $wildcards[$key];
  $pos = strpos($path, $wildcard);
  if ($pos === FALSE) {
    break;
  }

  $path = substr_replace($path, $arg, $pos, strlen($wildcard));
}
print $path;

```

Result is: `/path/to/page/foo1/foo2/view/foo3`
> 2 votes

# Answer
You can use hook\_menu function for creating url path from arguments, Drupal 7 doesn't support any direct function for creating menu :

Example :

```
function hook_menu() {
  $items['path/to/page/%/%/view/%'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'page arguments' => array(3,4,6),
    'access arguments' => array('access content'),
  );

function example_page($foo1,$foo2,$foo3) {
 // Things  to  do.....

}

```
> 1 votes

# Answer
If creating the path filled in with all the dynamic arguments is what you are after, not creating the Drupal menu callback to it, then certainly a quick php string manipulation can be done, eg, something along the lines of:

```
$path = 'path/to/page/%/%/view/%';
$args = array('foo1', 'foo2', 'foo3');
$wildcard = '%';

$path = str_replace($wildcard, '%s', $path);

$vpath=vsprintf($path, $args);

print $vpath; // path/to/page/foo1/foo2/view/foo3

```

Note: this quick and dull ax approach offers *no* error checking, and thus fails quite gracelessly when the number of arguments is less than what is expected.
> 1 votes

---
Tags: 7, routes, uri
---


title: Views sorting with list item text

text:
# Question
Title: Views sorting with list item text
I have a list field (category) associated with content type

Fruit|Good Fruit Meal|Fantastic meal Thai Coffee|Coffee

In views, I used sorting as category ascending. Now, I expected result to be sorted as: Coffee, Fantastic meal and Good Fruit. BUT it is sorting using value of list item as: Fruit, Meal and Thai Coffee.

Is there any way I can sort it using list item text but not with list item value?

Thank you.

# Answer
> 1 votes
The best way to accomplish this is to use a term reference field rather than a list field, for a number of reasons:

* The taxonomy module is made specifically for categorizing things, so it's a natural fit for a "Category" field.
* You don't have to edit your Category field every time you want to add options; you can simply add more taxonomy terms. This is better for Features-driven development (assuming you've exported your fields to code).
* You can sort by the taxonomy terms' titles in Views by using a Views relationship between the node and the term via the term reference field.

AFAIK, there is no way to sort by value labels in a list field like you're trying to do. I'd definitely recommend going with a term reference field instead.

---
Tags: 7, views
---


title: Adding a unique key to Drupal column

text:
# Question
Title: Adding a unique key to Drupal column
I'm just doing a one-off script, but I'm wondering if there's a correct "Drupal way" to alter a table and a unique key.

For example, this is essentially the query I want to do:

```
ALTER IGNORE TABLE `node_revision` ADD UNIQUE(`hash`);

```

And then if I later wanted to remove the unique index on hash, how would I also do that?

Does it have something to do with updating the database schema? or possibly `db_change_field()`?

# Answer
db\_add\_unique\_key() is the function you're looking for.
> 2 votes

# Answer
You can use hook\_schema\_alter and db\_add\_field in the hook\_install of your module to modify exists tables.

This question is on on that exact subject.
> 0 votes

---
Tags: database
---


# Question
Title: Drupal 7: Database select query FROM cache_bootstrap brings server down
The below query occasionally takes up to 24 sec and consumes the complete server resources.

```
SELECT cid, data, created, expire, serialized
FROM cache_bootstrap
WHERE cid IN ('variables');

```

I was informed today by my web hoster (I am on a shared server) that above select query brings down the whole node.

I have caching enable (with block caching disabled). JS- and CSS files are aggregated and cached pages are compressed. The site is running ok with no issues.

Any ideas how to track down the problem?

# Answer
If you can get memcache properly installed, that will help the most as it will shift queries from the cache tables in the db to your memcache server.

Try these 3 things (in order of importance):
Set the transaction isolation level to Read Committed - https://drupal.org/comment/8437127#comment-8437127 (look in your settings.php for the insertion point; it will be after the $databases variable has been set with the database credentials). This is helpful even if using memcache.

```
$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

```

Change your semaphore table to memory - https://drupal.org/comment/8469889#comment-8469889 (use the first code block "Have the name value be a primary key"). Note that this might not work if you are using MySQL 5.0 or lower due to BTREE indexes not working in Memory tables. Also noted that if you are using the memcache version of lock.inc this will not help.

```
ALTER TABLE semaphore ENGINE = MEMORY;
ALTER TABLE semaphore DROP PRIMARY KEY;
ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE;
ALTER TABLE semaphore ADD UNIQUE name (name) USING BTREE;
ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;
ALTER TABLE semaphore DROP INDEX expire;
ALTER TABLE semaphore ADD INDEX expire (expire) USING BTREE;

```

Apply this core patch - https://drupal.org/node/2193149 This will help to reduce database deadlocks from occurring only after the above 2 have been done. If using memcache this core patch will not help as this fixes an issue when using the database as a cache backend.
> 5 votes

---
Tags: caching, bootstrapping
---


# Question
Title: Tracking isotope clicks with Google Analytics?
Is there a way to track the clicks of the views isotope header through Google Analytics?

If so how would I set that up? Where would I put the file or code and in what type of file and how would that code be set up?

I'm using: Drupal 7 Views module Views isotope module Google analytics module

# Answer
> 1 votes
You can use Google Event Tracking. There is a great module for that already Google Analytics Event Tracking

Just enable both the main and the example module included so you can try it out. In the selectors array you can define wich element you want to track (e.g. a#logo) By setting `'label' => '!test'` you can test if the click works (will show an alert box)

```
$selectors = array(
array(
  'event' => 'mousedown',
  'selector' => 'a#logo',
  'category' => 'Home Link',
  'action' => 'click',
  'label' => 'Logo',
  'value' => 0,
  'noninteraction' => TRUE,
),

```

---
Tags: views, google-analytics
---


# Question
Title: Building a view programmatically fails when filtering specific nids but not others
I am quite stuck with this, so I hope you can help me out…

I have a view which filters (contextual filter) by 'nid'. I have two 'filter criteria's (view ui):

* Published
* Node type

I want to embed that view in a page programmatically through an Ajax call. I have discovered it sometimes returns the correct node and sometimes not. It depends on the specific node so for example it always retrieves the node nid = '4' and it never does for nid = '35'

Trying to figure out where the problem comes from I have tried few things. For example: I have tried to embed the view using panels, just for testing, using arguments for the contextual filter. It always work (always retrieve the correct node) this way. But when I call the view programmatically from a form building function (the one I use inside 'drupal\_get\_form()'), it just work with some nodes (some values of nid).

I am using devel for debugging and, when the view doesn't returns results,

```
$view->build_info['fail'] = TRUE

```

Here is the way I call the view:

```
$view = views_get_view('proyecto_en_arquitecto');
$view->init();
$view->set_display('block_1');
$view->set_arguments('35');
$view->execute();
dpm($view);  //Here is where I can see the building process fails

```

I am lost as I don't have a clue of why it just works with some nodes…

I hope you can point me to the right direction.

Thanks in advance for your help and let me know if you need further information.

# Answer
> 2 votes
The argument to the `$views->set_arguments()` function should be an array containing the arguments, even if only one, so, try:

```
$view->set_arguments(array(35));

```

or

```
$view->set_arguments(array($nid));

```

instead of passing the value in directly.

As to why it was working before sometimes, I am betting it was working with nids 1 thru 9 only, because there, for example, if `$nid='4'`, `$nid[0]=='4'` is also true, but if `$nid='35'`, `$nid[0]=='35'` is false (it is `'3'`) but I leave this to another discussion, but look up "php strings as arrays" if you want to delve into it further. This Strings as Arrays Q&A gives a brief description/introduction.

---
Tags: 7, views
---


# Question
Title: Creating node with multiple custom blocks, best method
What is the best method to create a node that includes multiple custom blocks with content related to only this node? The main concern is having a method that content editors will be able to understand with all the blocks related to this node editable from the node edit page for example. Having multiple custom blocks with each having an edit page is really confusing.

# Answer
You could try the context module https://drupal.org/project/context. With context you can specify that certain blocks only appear on a path specified so if you only wanted them to appear on the page with the url applepoluza you could do so.

As for being able to edit the blocks from the node edit page, perhaps you could set a context with a path to the edit page of the specific node to display a new custom block and in that custom block put in a list of links to each of the desire custom block edit pages. That would a be a pretty simple way to be able to accessibly access all of the custom blocks edit pages from the node edit page.

To directly edit the blocks on a node edit page would get pretty messy but could probably be done with something like Entity Fields and a bit of hard coding if you REALLY wanted to.
> 0 votes

# Answer
Sounds like views is something you could use here - Youre bascially creating a list of related content on the same page - you could also set it so that each piece of content could be editable from that page

views:

> You need Views if
>
> * You like the default front page view, but you find you want to sort it differently.
> * You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
> * You use /tracker, but you want to restrict it to posts of a certain type.
> * You like the idea of the 'article' module, but it doesn't display articles the way you like.
> * You want a way to display a block with the 5 most recent posts of some particular type.
> * You want to provide 'unread forum posts'.
> * You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
> "Month, YYYY (X)" where X is the number of posts that month, and
> displays them in a block. The links lead to a simple list of posts
> for that month.
>
> Views can do a lot more than that, but those are some of the obvious uses of Views.
> 0 votes

---
Tags: nodes, blocks, theming
---


# Question
Title: I am unable to get 'file' #type to appear in my form
I am building a custom module where the user needs to upload an image. Here is the code for my form:

```
function floor_map_form($form, &$form_state) {
        $form['file'] = array(
            '#type '        => 'file',
            '#title'        => t('Choose a file'),
        );
        $form['center'] = array(
            '#type'     => 'textfield',
            '#title'        => t('Center'),
            );
        $form['country'] = array(
            '#type'     => 'textfield',
            '#title'        => t('Country'),
            );
        $form['region'] = array(
            '#type'     => 'textfield',
            '#title'        => t('Region'),
            );
        $form['submit'] = array(
            '#type'     => 'submit',
            '#value'    => t('Submit'),
            );

        return $form;
    }

```

The only thing that shows in the browser are the text fields and submit button, the file upload field is nowhere in the page or html for the page.

# Answer
> 1 votes
Does this look wrong to you:

> '#type ' =\> 'file',

it's not `'#type'`

---
Tags: forms
---


# Question
Title: I am unable to login using linkedin integration module drupal 7?
I have installed Drupal linkedin Integration 7.x-1.x-dev and Oauth module .

I have entered the details like api key and secret key and all other settings properly

Now when I login using linkedin using the option as shown in the image I am redirected to the page as shown in the image

but after I enter linkedin credentials I am redirected to following page with no drupal user created

what is the reason for that?

# Answer
The LinkedIn Integration module won't automatically create a new user account for you. From step 5 of the directions in the module's README:

> Usage : Users will have to associate their LinkedIn account with their local Drupal account (at user/%user/edit/linkedin) to use any functionality provided by submodules.

So if you log in via LinkedIn with a LinkedIn account that isn't yet associated with a Drupal user account, you still need to create the new Drupal user account, and then the module will automatically associate the LinkedIn account with the new Drupal account in a submit handler that it attaches to the user register form.
> 3 votes

---
Tags: 7, authentication-authorization, social-network
---


title: How to set up OpenSearch in Drupal?

text:
# Question
Title: How to set up OpenSearch in Drupal?
I would like to set up OpenSearch so it works in Drupal 7 so the search experience can be integrated with the user browser the way it is done on drupal.stackexchange.com.

I found the following contrib modules (none ported for D7):

What is the current solution for this for D7 ?

# Answer
From looking at these three modules closer, I see that only the opensearch module has a 7.x branch: https://drupal.org/node/74142/release. You could try using that branch, but it probably not ready for a production system.

It looks like Kiam is the module author you may be able to contact him to find out if he is planning to complete the Drupal 7 version.
> 2 votes

---
Tags: 7, search
---


title: Drupal Feature pushed to staging site

text:
# Question
Title: Drupal Feature pushed to staging site
I am just getting into drupal features and wanted to make sure I understood something.

I updated my drupal features. Used Git Flow to finish the branches and create a release. I pulled the new release branch to the staging server.

My question is after I checkout the release branch and run drush fl - I see the features I worked on and committed as overwritten.

I know on my local if I want the changes I run drush fu to update them. However I thought I remembered that it is the opposite on the staging server. I did run drush fd to get the diff but still learning to read that better.

Thanks!

# Answer
> 1 votes
When you have an existing feature and you are changing some configurations which are stored in the feature, you have to update your features

```
drush fua

```

does an update on all enabled features. After that you deploy your features (propably using git) an then you have to accept the changes done to your feature on the production side.

```
drush fra

```

(feature revert all) does the trick.

A better explanation is here: https://drupal.org/node/582680

---
Tags: drush, features
---


# Question
Title: Remove a content type from search results
How do I go about removing a content type such as webforms from the site search results?

# Answer
You need Search configuration module.

It will allow you to exclude a content type from search results and even particular nodes.
> 5 votes

# Answer
Drupal's contrib module Search Restrict is a lightweight module that just does the basics - it allows administrators to restrict by role who can search for each content type. It may be a better option than Search configuration in that it only does what you're asking for - restrict content types from search results based on a user's permissions. If you're looking for something more configurable, Search configuration may be the way to go.

From the module's page:

> Approach of this module is to re-write the search query, so that content is indexed and available as search results to users in role(s) that have permissions to view it, but not displayed to other roles. Integrates with Apache Solr to exclude results based on the role of the person searching.

Simply download, install, and enable the module. Then to restrict (by role) which users can search which content types, edit each Content Type individually and there will now be a 'Search Restrict' section option (below the Display Settings). It allows you to specific, for each content type, which roles can search nodes of that content type.
> 6 votes

---
Tags: 7, search
---


# Question
Title: How to show directions on a map when using the Geolocation Field module
I installed the Get Directions and the Geolocation Field modules.

The Geolocation Field module displays a map, but I also want directions.

How do I get the directions shown on a map? Do I need another module?

# Answer
> 1 votes
When you download the Get Directions module, it has a `README.txt` that explains how to set up the module. Make sure to:

Make sure both modules are enabled, then configure the Get Directions module at: **`Administer > Site configuration > Get directions`**.

Go to **`Administer > User management > Permissions`** and set up permissions according to your needs.

Configure up a Geolocation field on a content type, then create a node of that type and fill in the field. You should then be able to use this URL pattern to see Get Directions module work with that node by going to

> http://{hostname}/getdirections/location/to/{node\_id}

or

> http://{hostname}/getdirections/location/from/{node\_id}

where {hostname} and {node\_id} are filled in with correct values.

Here is the full section on all the options from the README.txt:

> For instance, if you want to "preload" the getdirections form with information about the destination use a URL in this format:
>
> getdirections/location/to/99
>
> Where '99' is the node id (nid) of the location. The user will only have to fill in the starting point.
>
> To do it the other way around use getdirections/location/from/99
>
> You can also get a map with waypoints getdirections/locations\_via/1,2,3,99
>
> If you have both the starting point and destination node ids then you can use getdirections/locations/1/99
>
> Where '1' is the starting point node id and 99 is the destination node id (note the 's' in locations)

---
Tags: location, google-maps
---


title: Character limit on body Summary field

text:
# Question
Title: Character limit on body Summary field
I am trying to make the summary field on the body field have a limit of 40 words.
I have searched on the net so far, and I haven't found any solution.

Do you have any idea on the best approach for this?
The website is live and already has content with summaries, so I can't use a new field to do this.
am working with drupal 7

# Answer
> 1 votes
after little bit of more research i was able to solve this i used the hook\_form form\_id() and some custom javascript in a custom module to do this and it works great for me am open to suggestion on how to improve the code. here is how my module looks like. in the module file i have this function

```
     function summary_limiter_form_blog_node_form_alter(&$form, $form_id)
{
 drupal_add_js(array('summary_limiter' => array('blog_node_form' => TRUE)), 'setting');
}

```

My Java script file looks like this

```
var maxwords = 40;
var max_words_val;
(function ($) {
    Drupal.behaviors.summary_limiter =
    {
         init: function()
         {
                          var summary_field =$('.text-summary');
                          $('.description').append(" <b id='summary_limiter_rem_counts'>"+maxwords +"</b> word(s) remaining")

           summary_field.keyup(function()
           {summary_limiter.check_length(summary_field, $('#summary_limiter_rem_counts'))});

        },
       check_length: function(obj, rem,cnt)
          {
               var ary = obj.val().split(" ");
                var len = ary.length;
                rem.html(maxwords - len);
                if (len > maxwords)
                {
                rem.html(0);
                obj.val(max_words_val);
                }
                max_words_val =obj.val();

          },
        attach: function (context, settings) {
            try{
               if(settings.summary_limiter.blog_node_form){
                    this.init();
                }
            } catch(ex){}
        }
    };

})(jQuery);

```

# Answer
> 3 votes
The answers on this question might help you.

You override maxlength in a `hook_form_alter()`.

```
function hook_form_[content-type]_node_form_alter(&$form, &$form_state, $form_id) {
    $form['summary']['#maxlength'] = 40;
}

```

The above is not tested but should get you started. You can inspect the `$form` object with `dpm()` if you have Devel installed to check the exact name and place in the `$form` array of the summary field.

# Answer
> 0 votes
There's some work going on in the Maxlength project to implement this: https://drupal.org/node/1496570. It might be worth checking out/contributing to.

---
Tags: 7, entities
---


title: Taxonomy Term Permissions

text:
# Question
Title: Taxonomy Term Permissions
i tried to use Taxonomy Term Permissions module to set permissions on terms, but this module does not work.

After selecting the roles that i want to allow them selecting the specific term and saving the changes, nothing get saved, i tried also to search for a solution i found a version that worked in drupal 7, i replaced it with the first module.

this version has corrected to allow us to select the roles with saving the changes, but when i requested to create a node(go to create node page) the page did not open and show up a message that tell me an error happen in my site,

There is another module like that one above? or is there another way to set permission on a terms?
thanks.

# Answer
> 3 votes
There are some other modules you can try:

Taxonomy Access Control

Taxonomy Access Control Lite

A short but good tutorial for `Taxonomy Access Control` is available at Control Who Can View Drupal Nodes: Taxonomy Access Control

---
Tags: 7, users, taxonomy-terms
---


title: How force to rebuilds all block list?

text:
# Question
Title: How force to rebuilds all block list?
When I change some block info, in my custom module, sometimes the block doesn't change in my page, even if I clear all cache.

Is there anything I can do for force change?

# Answer
Visit the blocks admin page `admin/build/block`, that will fix it 99% of the time. Function in question for the rebuilding task: \_block\_rehash(). Also see block\_flush\_caches().
> 1 votes

# Answer
Sometimes clearing the cache twice in a row helps, for whatever reason.
> 1 votes

# Answer
If you are editing the code of an enabled module, you should disabled it from the modules' page, and then re-enable it. This forces Drupal to clear its cache, which includes also a cache containing the list of hooks implemented by all the modules.

Still better, you should disable the module before editing it, and re-enable it after you edited the code.
> 1 votes

# Answer
You could do that in page scope via hook\_preprocess\_page() as following

```
function MODULE-NAME_preprocess_page(&$vars){
         //make changes in the blocks

         //rebuild the blocks managed via Block module
         block_page_build($vars['page']);
         //rebuild the blocks managed via Context module
         context_page_build($vars['page']);

          //set the new changes in cache
         drupal_set_page_content($vars['page']);
}

```
> 0 votes

---
Tags: 6, blocks, caching
---


# Question
Title: I am trying to pull ldap server information from the ldap_servers table in drupal
I have a user search module in drupal that creates contact cards base on LDAP user information. Everything works fine, I just need to make it more flexible, so that if the same module is used in a different drupal install, it can just set the same ldap server that is set in drupal. Currently it is hard-coded.

first, I tried using this to get the server info:

```
  $ldapServer = db_query("SELECT address FROM ldap_servers WHERE `binddn` = 'cn=Directory Manager'");
  print_r( $ldapServer);

```

This is what the query returned:

> DatabaseStatementBase Object ( \[dbh\] =\> DatabaseConnection\_mysql Object ( \[needsCleanup:protected\] =\> \[target:protected\] =\> default \[key:protected\] =\> default \[logger:protected\] =\> \[transactionLayers:protected\] =\> Array ( ) \[driverClasses:protected\] =\> Array ( \[MergeQuery\] =\> MergeQuery \[SelectQuery\] =\> SelectQuery \[UpdateQuery\] =\> UpdateQuery \[InsertQuery\] =\> InsertQuery\_mysql ) \[statementClass:protected\] =\> DatabaseStatementBase \[transactionSupport:protected\] =\> 1 \[transactionalDDLSupport:protected\] =\> \[temporaryNameIndex:protected\] =\> 0 \[connectionOptions:protected\] =\> Array ( \[database\] =\> tlsconnectapp \[username\] =\> drupal \[password\] =\> drupal \[host\] =\> localhost \[port\] =\> \[driver\] =\> mysql \[prefix\] =\> Array ( \[default\] =\> ) ) \[schema:protected\] =\> \[prefixes:protected\] =\> Array ( \[default\] =\> ) \[prefixSearch:protected\] =\> Array ( \[0\] =\> { \[1\] =\> } ) \[prefixReplace:protected\] =\> Array ( \[0\] =\> \[1\] =\> ) ) \[queryString\] =\> SELECT address FROM ldap\_servers WHERE `binddn` = 'cn=Directory Manager' )

I'm sure I did something wrong, but I'm not sure what this means, and the server isn't in there.

# Answer
> 0 votes
Please read on Working with Result Sets documentation. You have not issued the query yet to your database, you've only built a SELECT statement.

I also recommend installing the Devel module as you can get much more readable debug information from dpq() for queries or dpm() for Objects you want to inspect.

---
Tags: database
---


# Question
Title: Is there a reference by url widget type for term reference field as we have it for node reference field?
Is there a module for term reference as we have "Node reference url widget" module for node reference field. So that I can auto-populates a term reference field with a value from the URL.

# Answer
Closest thing is RSpliet's sandbox module:

https://drupal.org/sandbox/RSpliet/1416486
> 0 votes

---
Tags: nodes, entities, users, taxonomy-terms
---


title: D7 equivalent to AutoMenu module

text:
# Question
Title: D7 equivalent to AutoMenu module
In the past I always ensured that I had AutoMenu module installed on any Drupal 6 site I created. This module afforded me the following:

* The ability to auto-create the menu item entry (per content type) when a new node is created (instead of manually clicking `Provide a menu link`), and
* (optionally) Automatically set the newly created menu item to `disabled`.

These 2 features with D6 sites have always allowed me to not worry about another content-editor users messing up the hierarchy of the site. Plus it played well with my menus and breadcrumbs.

I have been desperately trying to get similar functionality working in D7, but haven't had much luck so far. There was an unofficial port of the said module to D7 but after trying it, it gave some errors.

Please can you suggest a way in Drupal 7 for me to achieve the same? Thanks!

# Answer
> 1 votes
That module has a drupal 7 version in the issue queue at https://drupal.org/node/1138946

Comment #25 has a link to a sandbox of the drupal 7 port: https://drupal.org/sandbox/wojtha/1331132

There is another version in a zip file at comment #46 but it seems that one is inferior.

It seems that it has been reviewed by a few people and works but the module doesn't seem to have an active maintainer so it has not been committed to the repository and made available on the project page.

I would try those versions of the module and see if either of them work.

---
Tags: 7, routes
---


# Question
Title: How do I recover a deleted Views display?
I installed a module (FAQ) which provides multiple Views displays, which are based in code. I accidentally removed the master display, and am left with the various block and page displays also created by the module.

Is there any way to retrieve/recover the master display, short of removing/reinstalling the module?

# Answer
> 3 votes
To revert the whole view back to what the faq module provides by default:

1. Go to the views listing (admin/structure/views).
2. Click the little arrow next to "Edit" in the operations column.
3. Click the "Revert" link.
4. Click the "Revert" button.

---
Tags: 7, views
---


# Question
Title: How do I remove a menu item on a module?
So there's the course module for Drupal, and I want to remove one of the form items, `$form['course']['duration']`.

It's setup like this.

```
$form['course']['duration'] = array(
    '#title' => t('Duration'),
    '#type' => 'textfield',
    '#description' => t('Length of time in seconds that a user can remain in the course. Leave blank for unlimited.<br/>For a better experience, install the !link module.', array('!link' => l('Time period', 'http://drupal.org/project/timeperiod'))),
  );

  if (module_exists('timeperiod')) {
    $form['course']['duration']['#type'] = 'timeperiod_select';
    $form['course']['duration']['#units'] = array(
      '86400' => array('max' => 30, 'step size' => 1),
      '3600' => array('max' => 24, 'step size' => 1),
      '60' => array('max' => 60, 'step size' => 1),
    );
    $form['course']['duration']['#description'] = t('Length of time that a user can remain in the course.');
  }

```

How could I remove this from the module? I don't want non-admin users to be able to modify this. I obviously don't want to hack the core of the module.

Would I just rewrite the function? Is there anyway to do this?

# Answer
> 1 votes
This is an option in a form. You can use hook form alter in your custom module to hide it. For example

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'SOME_FORM_ID') {
    // you need to find out the form id . You can do so by adding a
    // print line or (dpm($form_id)) in the ..._form function in the Course module.
    $form['course']['duration']['#access'] = FALSE;
   }
 }

```

---
Tags: forms
---


# Question
Title: how to modify drupal 7 mysite/user/login and mysite/user/registration pages "in-place"?
I am trying to find out a way to add fields/modify existing fields/theme the default Drupal 7 login/registration pages in-place.

What I mean "in-place" is to find a way to not create new login/registration pages through creating "page--user--register.tpl.php" files.

I am looking for a way to add/modify/theme the mysite/user/login and mysite/user/registration pages without having to create page--user--register.

However, if overriding the `hook_theme()` in "template.php" and creating "page--user--register.tpl.php" file is the only way, then is there a way to have it use the same theme as the rest of the pages? I can make the custom registration page have the same theme through coyping code from "page.tpl.php" and pasting it in my "page--user--register.tpl.php" file, but this seems wrong to me.

Any help or comments are appreciated.

# Answer
If you want add form fields to either the login or registration form(s) you will have to write custom PHP code in a module file to make any use of the fields.

The forms are just blocks on the page, and should inherit or reuse block.tpl.php pretty much everywhere. Since they are just blocks, sitewide css can target them specifically once you've made them.

The drupal login and registration system is fairly pluggable, you can "inject" your own validation code (to handle your own custom fields) and authentication pretty much however you wish.

A useful tutorial/blog post might be: http://omegadelta.net/2011/03/23/custom-authentication-with-drupal-7/

It doesn't add custom fields, but does modify the existing drupal login behavior which is what you're trying to do as well.

In your case you probably want to do something like:

1. create a custom login/registration block in a module, it simply loads the default login or registration block as an object. Implement hook\_block family of functions.
2. hook\_form\_alter() the block and inject your fields and override the default user authentication validator with your own to consume your fields (similar to the linked blog posts' \_geospike\_user\_login\_form\_alter() function).
3. define a hook\_menu path which outputs a page that loads/outputs your custom defined block to login or register.

Drupal can do what you want with basically a custom module and like a few hook functions. Your not creating your own user login or registration form, and your not writing your login login validators from scratch -- you are just overriding the pre-existing ones for new ones your basically telling drupal exist now via your module.
> 2 votes

# Answer
Add this to you template.php file, where your\_themename is the machine name of theme you are using

```
function your_themename_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'your_themename') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
      'your_themename_preprocess_user_login'
    ),
  );
  return $items;
}

```

Create a user-login.tpl.php file and add this

```
<?php
    print drupal_render($form['name']);
    print drupal_render($form['pass']);
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);
?>

```

This is a summary of what I found on this blog post
> 2 votes

# Answer
If you just want to change the theme for each page alot install Devel Themer and it can tell you a specific way to name a tpl file for your site theme to change its look/HTML/CSS specifically.
> 0 votes

# Answer
Drupal 7

Add this code to your template.php in your theme directory.

```
    function yourtheme_theme() {
      return array(
        'user_login' => array(
          'template' => 'user-login',
          'arguments' => array('form' => NULL),
        ),
      );
    }

    function yourtheme_theme() {
      $items = array();
      $items['user_login'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
        'template' => 'user-login',
        'preprocess functions' => array(
           'yourtheme_preprocess_user_login'
        ),
      );
      return $items;
    }

    function yourtheme_preprocess_user_login(&$vars) {
      $vars['intro_text'] = t('This is my awesome login form');
    }

```

Create a file in your theme's "templates" folder called user-login.tpl.php.

Add this code and change "yourtheme" to your theme name.

```
 <?php print drupal_render_children($form) ?>

```

Clear you cache.

Source (Where you can find details on how to do this for user-register-form, user-password-form, and Drupal 6) https://drupal.org/node/350634
> 0 votes

---
Tags: users
---


title: Disabling core block system in Drupal 7

text:
# Question
Title: Disabling core block system in Drupal 7
We are using Drupal 7 with context. I have understood that in Drupal 6 the core block system is inefficient in terms of performance. According to this article http://treehouseagency.com/blog/neil-hastings/2010/10/14/context-everywhere in context module (Drupal 6 version) there is a setting to disable the core block system. But in Drupal 7 context module configuration I cannot find this setting.

How can I make sure the core block system doesn't take part in the showing of the blocks? Ideally I would like to block access to admin/structure/block (since I don't want anybody to set blocks via that interface) but allow to access to admin/structure/block/add (since I want to be able to create blocks but show them with context).

# Answer
> 2 votes
The block module is not required by core; just go to mysite.com/admin/modules and disable it, if you don't want to use it in your site.

**EDIT** to address your updated question. This code should do the trick. It will deny access directly to the blocks admin overview page, but will still allow access to the add block page.

```
function mymodule_menu_alter(&$items) {
  // Deny access to the blocks overview page.
  $items['admin/structure/block']['access callback'] = FALSE;

  // Explicitly allow access to the block add page
  $items['admin/structure/block/add']['access callback'] = 'user_access';
  $items['admin/structure/block/add']['access arguments'] = array('required permissions');
}

```

# Answer
> 1 votes
Disabling the core block module would also disable all blocks. The context module also uses the block module to render blocks. You can see this by looking at the block reaction plugin in the context module.

There are a few methods. I recommend using use hook\_menu\_alter() to change the access arguments.

```
/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  $items['admin/structure/block']['access arguments'] = array('my new powerful permission');
}

```

Then you can declare the permission in hook\_permission if you want. But yo dont' have to. If you set the access arguments to a permission that doesn't exist, the page will render.

```
/**
 * Implements hook_permission().
 */
function mymodule_permission() {
  return array(
    'my new powerful permission' => array(
      'title' => t('Power Permission'),
      'description' => t('Very powerful stuff here'),
      'restrict access' => TRUE,
      'warning' => t('Do no give this to anyone'),
     ),
  ),
}

```

# Answer
> 0 votes
You can disable block and enable bean. At present, this patch is required.

# Answer
> 0 votes
For the more advanced:

If you are defining a callback via hook\_menu and wish to not display any blocks when that callback is ran, add the following to the top of your menu callback function.

```
<?php
  // Disable all blocks.
  $blocks = &drupal_static('block_list');
  $blocks = array();
?>

```

If some extra content is still getting through then using hook\_page\_alter can do the trick. In my case the admin\_menu module was still showing up.

```
<?php
/**
 * Implements hook_page_alter()
 */
function mymodule_page_alter(&$page) {
  // Bail out if not on the my-awesome-page page and not on the
  // my-other-awesome-page page.
  // This code will vary quite a bit depending on your setup.
  $args = arg();
  if (   $args[0] !== 'my-awesome-page'
      && $args[0] !== 'my-other-awesome-page'
      ) {
    return;
  }

  // This code should stay the same.
  // Get page children.
  $children = element_children($page);
  // Kill all but content.
  foreach ($children as $value) {
    if ($value != 'content') {
      $page[$value] = '';
    }
  }
}
?>

```

Also noted that you might have to hide the footer with CSS due to the way drupal renders it. You can add this to your menu callback function as well.

```
<?php
  // Use CSS to hide the footer.
  drupal_add_css('#footer {display:none;}', array('type' => 'inline'));
?>

```

---
Tags: blocks, 7
---


# Question
Title: Menu that conditionally shows webform, or edit previous submission
How can I have a menu item "RSVP" that shows a webform, but after an authenticated user has submitted that webform, clicking on "RSVP" would now bring them back to their submission in edit mode?

rsvpdirect.info:

```
name = rsvpdirect
description = "Redirects webform nodes to edit if the user has already submitted it once before."
package = Custom
core = 7.x
files[] = rsvpdirect.module

```

rsvpdirect.module:

```
<?php

/**
* @file
* Forces redirect of webform node to edit the user's previous submission.
*
*/

/**
* Implementation of hook_node_view()
*/
function rsvpdirect_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($node->type == 'webform' && $view_mode == 'full' && arg(0) == 'node') {
    $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid));
    $submission_count = webform_get_submission_count($node->nid, $user->uid);

 if ($submission_count >= 1) {
      // Get first submission
      $submission = reset($submissions);
      drupal_goto('node/' . $node->nid . '/submission/' . $submission->sid . '/edit');
    }
  }
}

```

# Answer
You can do it using hook\_node\_view and redirect functionality to redirect if webform is submitted. Your menu link always point to webform page.

```
function YOURMODULENAME_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($node->type == 'webform' && $view_mode == 'full' && arg(0) == 'node') {
    $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid));
    $submission_count = webform_get_submission_count($node->nid, $user->uid);
    if ($submission_count >= 1) {
      // Get first submission
      $submission = reset($submissions);
      drupal_goto('node/' . $node->nid . '/submission/' . $submission->sid . '/edit');
    }
  }
}

```
> 1 votes

---
Tags: routes, webforms, redirection
---


# Question
Title: Views sorting by number of values in field
I have a content type with an text field with unlimited number of values.

I have a view for that content type and I want to sort it by number of values in that field.

How can I do that in Views?

# Answer
1. Enable Aggregation in View settings.
2. Add Your Multiple Field in Sort Criteria
3. Select Count as Aggregation Settings
4. Select Sort Criteria - Asc , Desc

PS: Do not add same field to field list , it will lead to multiple results in the view
> 2 votes

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


# Question
Title: Create a real taxonomy with drupal taxonomy and pathauto
I'm creating a taxonomy for reptiles in drupal and wish to use pathauto for the term url's. The problem is to find the right tokens (I do have entity token installed). Lets look at an example of the taxonomy-tree for the vocabulary Reptiles:

```
Lizards
--Family
----Genus
------Species

```

So far so good:

```
[term:vocabulary]/[term:parent:parent:parent]/[term:parent:parent]/[term:parent]-[term:name]

```

result: /reptiles/lizards/family/genus-species

However sometimes there is also a subspecies, thus:

```
Lizards
--Family
----Genus
------Species
--------Subspecies

```

then starting at the lowest level and using \[term:parent\] doesn't work anymore.

Been looking for \[term:child\] and to generate the path from the opposite direction but I find nothing similar. Another way would be if I could define the term patters with levels in the hierarchy?

something like this:

```
    [term:vocabulary]/[term:level:1]/[term:level:2]/[term:level:3]-[term:level:4]-[term:level:5]

```

Maybe someone else knows how to crack this nut?

A better example on the outcome I seek:

```
/reptiles/lizards/gekkonidae/phelsuma-klemmeri

```

or as with a subspecies:

```
/reptiles/lizards/gekkonidae/phelsuma-klemmeri-subsp

```

# Answer
> 0 votes
@hitesh's solution using \[term:parents:join-path\] is good, but it won't create the hyphenated sub-path that you're after. To generate that you could add something like the following to a custom module (not tested):

```
  //move your module's execution of hook_taxonomy_term_presave to the end of the list,
    //so that it won't be overridden by the pathauto module.
    function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
      if ($hook == 'taxonomy_term_presave') {
        // Move hook to the end of the list.
        $group = $implementations['your_module'];
        unset($implementations['your_module']);
        $implementations['your_module'] = $group;
      }
    }

 // invoke hook_taxonomy_term_presave().
function YOUR_MODULE_taxonomy_term_presave($term) {
  switch ($term->vocabulary_machine_name) {
    case 'reptiles':
      //create the alias
      module_load_include('inc','pathauto','pathauto');
      $vocab = taxonomy_vocabulary_load($term->vid);
      $path = pathauto_cleanstring($vocab->name) . '/';
      $parents = array_reverse(taxonomy_get_parents_all($term->tid));
      foreach ($parents as $key => $parent) {
        // use '-' as glue for the second level down and '/' elsewhere
        $glue = ($key >= 1) ? '-' : '/';
        $path .= pathauto_cleanstring($parent->name) . $glue;
      }
      $path = rtrim($path, "-");
      $path_save('taxonomy/term/'.$term->tid, $path);
  }
}

```

# Answer
> 5 votes
You can configure URL pathauto alias for taxonomy terms as :

**\[term:vocabulary\]/\[term:parents:join-path\]/\[term:name\]**
for creating url aliases for taxonomy taxonomy hierarchy.

Explore more using replacement patterns for specific taxonomy terms.

Please refer this image for url aliases configuration page

# Answer
> 0 votes
@olyN Big thank you for the code, it works like wonders. I'll post the finished code for future reference below if someone else seeks a php solution when tokens is not enough.

```
<!-- language: lang-php -->

 //move your module's execution of hook_taxonomy_term_presave to the end of the list,
    //so that it won't be overridden by the pathauto module.

function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'taxonomy_term_insert') {
        // Move hook to the end of the list.
        $group = $implementations['YOUR_MODULE'];
        unset($implementations['YOUR_MODULE']);
        $implementations['YOUR_MODULE'] = $group;
    }
}

function YOUR_MODULE_taxonomy_term_insert($term) {
  switch ($term->vocabulary_machine_name) {
    case 'VOCABULARY_MACHINENAME':
      //create the alias
      module_load_include('inc','pathauto','pathauto');
      $vocab = taxonomy_vocabulary_load($term->vid);
      $path['alias'] = pathauto_cleanstring($vocab->name) . '/';
      $parents = array_reverse(taxonomy_get_parents_all($term->tid));
      foreach ($parents as $key => $parent) {
        // use '-' as glue for the second level down and '/' elsewhere
        $glue = ($key > 1) ? '-' : '/';
        $path['alias'] .= pathauto_cleanstring($parent->name) . $glue;
      }
      $path['alias'] = rtrim($path['alias'], "-");
      $path['source'] = 'taxonomy/term/'.$term->tid;
      path_save($path);
  }
}

function YOUR_MODULE_taxonomy_term_update($term) {
  switch ($term->vocabulary_machine_name) {
    case 'VOCABULARY_MACHINENAME':
      //create the alias
      module_load_include('inc','pathauto','pathauto');
      $vocab = taxonomy_vocabulary_load($term->vid);
      $path['alias'] = pathauto_cleanstring($vocab->name) . '/';
      $parents = array_reverse(taxonomy_get_parents_all($term->tid));
      foreach ($parents as $key => $parent) {
        // use '-' as glue for the second level down and '/' elsewhere
        $glue = ($key > 1) ? '-' : '/';
        $path['alias'] .= pathauto_cleanstring($parent->name) . $glue;
      }
      $path['alias'] = rtrim($path['alias'], "-");
      $path['source'] = 'taxonomy/term/'.$term->tid;
      path_save($path);
  }
}
<!-- language: lang-none -->

```

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


# Question
Title: Add user's role as a class to all user links
My goal is to attach a users role as a class to their user name anywhere it is displayed so I can color the link based on role.

I can get roles of every displayed user link using `MYTHEME_username_alter`:

```
function MYTHEME_username_alter(&$name, $account) {
  $user = user_load($account->uid);
  // I can get the roles of each user link through $user
}

```
1. Is this the most efficient way to get the role for each user link?
2. What is the best way to go about adding the role as a class to every user link?
3. Am I way off track and overlooking an easier way to complete my goal?

# Answer
> 1 votes
I don't think you can do it with username\_alter. You can only modify the user name string in there. Its probably better to use preprocess. In your theme `template.php`. Do something like this:

```
function YOUR_THEME_NAME_preprocess_username(&$variables) {
  // Username is linked, use the link_attributes to inject the class or any other attribute
  if (isset($variables['link_path'])) {
    $variables['link_attributes']['class'][] = 'SOME_CLASS';
  }
  // Username is NOT linked, maybe do something else or nothing
  else {
    $variables['attributes_array']['class'][] = 'SOME_CLASS';
  }
}

```

# Answer
> 1 votes
To add roles as a class to all user links I used the following:

```
function MYTHEME_preprocess_username(&$variables) {
  $user = user_load($variables['account']->uid);

  foreach ($user->roles as $role) {
    if (isset($variables['name'])) {
      $variables['attributes_array']['class'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
    }
  }
}

```

---
Tags: 7, users
---


# Question
Title: Why is hook_form_alter() not setting default values in _after_build function on /node/add/myct?
I've got a validation form (`id="mymodule-myct-verify-form"`) that retrieves data from `temp_node` to populate it's hidden fields. On submit, the form sends its data to /node/add/myct. (currently via `$form['#method' = 'get';`, which I'm planning on changing to 'post') What I want to do is this: in `mymodule_hook_form_alter`, get the data from `$_REQUEST` (later `$_POST`) and use that to set the default values of my CCK fields. Currently, jQuery is the approach I'm going for, being unable to get `mymodule_form_alter()` and `mymodule_after_build_convert()` to work. Here's what I've got:

```
 function mymodule_form_alter(&$form, &$form_state, $form_id) {
     if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'].'' == "myct") {
        // if converting, set default values through an after_build function
        if (isset($_REQUEST['conv']) && (strip_tags($_REQUEST['conv']) == 'app') &&
            isset($_REQUEST['taid']) && (intval($_REQUEST['taid']) > 0)
            && ($form['type']['#value'] . '_node_form' == $form_id &&
            (strpos($form['#action'], '/node/add/myct') !== FALSE))
        ) { // on the /node/add/myct/?conv=app&taid=1 page, this is true
            $form['#after_build'][] = 'mymodule_after_build_convert';
        }
  }
}

function mymodule_after_build_convert ($form, &$form_state) {
    //TODO: Set default values for CCK fields
    /*dsm($form);
    dsm($form_state);
    dsm($_REQUEST);*/
    // set receiving date and time
    dsm($form['#field_info']['field_status_10']); // date popup
    $form['#field_info']['field_status_10']['widget']['default_value'] = time();     //date("j F, Y - H:i");
    dsm($form['#field_info']['field_status_10']);
    // set deal type (select list)
    $form['#field_info']['field_deal_type']['widget']['default_value'][0]['value'] = intval($_REQUEST['ta_type']);

    return $form;
}

```

Why is my date\_popup field empty instead of containing today's date? Why does the select list not change?

# Answer
After doing some research, it turns out that taking a JavaScript/jQuery approach is the wrong way to do this. Rather, the code should use `hook_form_alter()` to retrieve POSTed data (`$form['#method'] = 'post';`) and set the default values of the node form (including CCK fields) via a function specified with `$form['#after_build']`.

So, if you want to dig in here and start monkeying with the "real" properties, you need to come in after the point that the CCK form elements are processed. Luckily, the form API has a phase designed for exactly this purpose: #after\_build.

```
/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  // Check for a particular content type's node form.
  if ($form_id == 'example_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'example_after_build';
  }
}

/**
 * Modifies CCK form elements on the example node form.
 */
function example_after_build($form, &$form_state) {
  // Your code here.
  return $form;
}

```
> 1 votes

---
Tags: nodes, 6
---


title: Problems with Clean URLs

text:
# Question
Title: Problems with Clean URLs
I've got a problem with Clean URLs. I had a look around and my problem doesn't look like any thing else on this site or anywhere on the internet.

I have a *.htaccess* file. It's there and it's working. I know because I've set it to remove www. and it is.

I go to *Configuration-\>Search and Meta-\>Clean URLs* (some people don't pass the clean URLs test but I do, it doesn't even come up) I have the option to turn on Clean URLS:

---

---

I tick the box and click Save configuration. But this happens:

---

---

NO! I ticked you!

So if I go to a clean URL (/contact) it works. But in the menu it comes up as (/?q=contact).

I thought I'd hack the database and turn it on.

But it was on the whole time... \<hold flashlight under chin and look scary\>

Does anyone know how to remedy this situation so it stays ticked and comes up clean in the menu?

# Answer
> 2 votes
Ok, alright. I'm not going to kill anyone.

Turns out there was a line in my *settings.php* file:

> $GLOBALS\['conf'\]\['clean\_url'\] = 0;

Commented it and everything worked just fine.

That was 2 hours of my life wasted...

---
Tags: 7, .htaccess, uri
---


# Question
Title: How to save uploaded image in an content type to picasa?
I am uploading an image in a content type and I want that image to saved in picasa web albums.

While showing that node, I want the image to be displayed from picasa. Is there any module available for that or how do I achieve this?

# Answer
> Picasa Node Album module provides gallery support in the form of associating Picasa albums with nodes.

Features

* Link any public Picasa album to a node
* Thumbnail view with a template you can override
* Lightbox2 support already in the default template
* Select albums of the current Picasa account with autocomplete
* Supported node types configured via admin settings
* Define if thumbs should show on teasers and/or page views
* Define how many images in the gallery should be displayed on teasers/page views
* Define the sizes of thumbnails and images to request from Picasa
* Define whether you want an Albums tab on the node or not
* Image data results cache with a defined expiration
* Restrict what picasa accounts content can come from
* Restrict how many albums a user can upload per node
> 0 votes

---
Tags: 7, nodes, media
---


title: Admin menu duplicate errors

text:
# Question
Title: Admin menu duplicate errors
I'm having a problem with duplicate administration menu bars, is there a way to remove it? I'm using commerce kickstart 2 and I've uninstalled the commerce kickstart menus and installed Administration menu. The problem was present whenever I don't have commerce kickstart menu enabled.

# Answer
Disable the "Commerce Kickstart menus", the "Toolbar Megamenu" and the "Toolbar" modules.

Later, go to the admin/structure/menu/management and reorder the menu links as shown in the video.

Found the solution with detailed steps here: http://www.youtube.com/watch?v=BMoTuHf5WX0
> -1 votes

---
Tags: commerce
---


title: Enter OG audience to a node with Rules

text:
# Question
Title: Enter OG audience to a node with Rules
How to add a specific Organic Group to a node in the action-step with rules (7.2)?

I can't figure out which action and which options i should use. Now i've something like

```
**action**
Set a data value
Parameter: Data: [node:og-group-ref:0]

```

But this isn't correct. How can i give the og-group-ref the correct value (the OG is in this case nid 180).

# Answer
This is not the correct answer, but i found a different way. If the og\_group\_ref is **set to checkboxes** (these checkboxes are essential) (look at admin/structure/types/manage/\[YOURCONTENTTYPE\]/fields/og\_group\_ref), you can set the default audience. Now i just hide the field 'audience' for certain roles and new nodes are saved to the right OG.

Again, this isn't the way i asked to do it with rules. When someone knows the right answer how to do it, i'm eager to hear it.
> 0 votes

---
Tags: rules, organic-groups
---


# Question
Title: How to add wrapping elements & classes to a table in a view?
I'm building a custom theme using bootstrap 3, I need responsive tables. Yes, I'm aware of responsive\_tables but I didn't like it. I want to use bootstrap's native `.table-responsive`. for that I need to wrap table like this:

```
<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

```

I need to add couple more classes to the `<table>` element.

How to do that?

# Answer
You can add css class to the whole view (go to your view edit page -\> Advanced -\> Other -\> Css Class). It will print something like this:

```
<div class="view view-test view-id-test view-display-id-page table-responsive view-dom-id-47b9f610df77a3f6181e64ca36b9881e">
  <div class="view-content">
    <table class="views-table cols-2">
       ...
    </table>
  </div>
</div>

```

In views UI there is no option to add class to `<table>` element, but you can create/copy a template file (e.g. views-view-table.tpl.php, you can copy it from views module, look in "Theme information" in your view for more specific details) in your theme, clear caches and edit it as you wish.
> 1 votes

---
Tags: 7, theming
---


title: Filter RelationQuery by relation_type

text:
# Question
Title: Filter RelationQuery by relation_type
I have some 2-point-relations called 'is\_member\_of' where the source endpoint is a person and the target endpoint is a group.

I like to list all of the members (without using a view).

In the code I build a relation query with the nid 1234 as target (last option = 1)

```
$query = relation_query('node',1234,1);
$results = $query->execute();
dpm($results);

```

This lists ALL relations to the nid 1234. I only want to have relations of the

```
relation_type='is_member_of'

```

Is there a fieldCondition which can do that?

Thanks.

# Answer
A `RelationQuery` is just an `EntityFieldQuery` under the hood, and since `relation_type` is the bundle key of the `relation` entity type, both

```
$query = relation_query('node',1234,1);
$results = $query->entityCondition('bundle', 'is_member_of')->execute();

```

and

```
$query = relation_query('node',1234,1);
$results = $query->propertyCondition('relation_type', 'is_member_of')->execute();

```

should work.
> 3 votes

---
Tags: entities
---


# Question
Title: Taxonomy filters don't display results - Drupal 7
I've updated the taxonomy module to the last version, so after doing this I've noticed that clicking on one category or on one tag of my blocks inside the blog area will produce a page without results.

I've already checked if it was a pathauto fault, and it seems work fine and the settings inside there are right. The field in my blog content type concerning tags and categories are already there, and they are linked to the taxonomy vocabularies.

So at the moment I'm alone in the dark, does anyone knows how to help me in order to sort out this problem?

Many thanks.

# Answer
So far I've found the right solution to this issue. I will write down it as who will have the same problem can sort it out.

To solve this problem I was just needing to create again the panel-page that I've used to create the taxonomy pages.

Why I was needing to do it? - It's simple, because when there's a new update if you have any entity that is pointing to a module's variable or whatever about that module and something is obviously changed in its implementation after the update, then this entity is pointing to the old representation of that variable/whatever of that module, so obviously drupal will show you an empty set as a result of a normal query.

I hope that this can help someone on the way in the future.

Have a good day drupalers!! See ya next time ;)
> 0 votes

---
Tags: taxonomy-terms
---


title: How to translate country names

text:
# Question
Title: How to translate country names
I need to translate the names of countries in drupal. I am using `countries_get_list`, looping through the array and saving it in another array but wrapping the country names in `t()`. I'm not so so sure but it seems this isn't working. I was doing something like

```
$new_array = array();
foreach(countries_get_list() as $key => name) {
    $new_array[$key] = t($name);
}
return $new_array;

```

# Answer
You should never use t() to translate variables, unless the text that the variable holds has been passed through t() elsewhere:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/73#sec\_translating\_vars

In this case country\_get\_list() calls \_country\_get\_predefined\_list(), and inside this function country names are passed through t():

https://api.drupal.org/api/drupal/includes%21iso.inc/function/\_country\_get\_predefined\_list/7

So, if you have country strings translated in your database (as Molot says) translation should work.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Unable to create new user from Admin "New User" page ... Drupal 7
```
function MODULE_NAME_form_user_register_form_alter(&$form, $form_state, $form_id) {
 $form['actions']['submit']['#value'] = t('Submit');
}

```

I override the name of the submit button using customs module.

User registrations works fine, but when I'm trying to create a user through admin interface, fill out the form and click "Submit", I get redirected to "user/list" page, user doesn't get created, and the text on the top of the page is actually from "create user":

Any idea why this problem occurs?

# Answer
> 0 votes
This is a core bug. You can read about it here. What you can do is to translate "Create new account" string or use String Overrides module.

---
Tags: users
---


# Question
Title: General Content Search of Content type Exposed form
Is there a method of giving a user the ability to search any term within all content of a particular node through an exposed form. For example you have the content type of, say - Business, with the fields of - CEO and Base of Operations. Could you give them a simple search that looks for a match in both those fields?

# Answer
> 1 votes
This is certainly possible and there can be many approaches to this, but it would require some effort in any case.

Taxonomy terms are not indexed by core search, therefore you would need to rely on a third party module. Such popular modules are Search API and Apache Solr.

My preferred method, in short, is to use the Search API in combination with Views:

* Install the modules Search API, Search API DB, Views, Ctools.
* Create server and index, add the taxonomy fields in the index.
* Create a view for the search page based on the index
* Filter by eg. "Search: Fulltext search", exposed
* Add any fields to view, such as "Rendered entity" (for teasers etc.)
* Sort by any field, such as "Search: Relevance".

---
Tags: nodes, views
---


# Question
Title: Drush Error: no database record could be found after failed attempt of sql-sync
I was pushing our latest version of the site from our development environment to our live site (located on the same server). But unfortunately our web server ran into memory issues which prevented the move. We opened up access to more space but now SQL-sync refuse to function.

I assumed that we had issues with the database being corrupt so I replaced the database with our backup. But this did not help.

The development environment seem to work really well but I am very poor with Drush/SQL so I got a hard time understanding the error messages I get when testing the alias and site config. The Dev site work well while the live site is down and I would appreciate any advice on likely sources of the error.

**The Dev alias that work well**

```
sigvard@server1:~$ drush @mysite.dev status
 Drupal version                :  7.26
 Site URI                      :  dev.mysite.org
 Database driver               :  mysql
 Database hostname             :  localhost
 Database username             :  mysite_dev
 Database name                 :  website_mysite_dev
 Database                      :  Connected
 Drupal bootstrap              :  Successful
 Drupal user                   :  Anonymous
 Default theme                 :  mysite
 Administration theme          :  seven
 PHP configuration             :  /etc/php5/cli/php.ini
 Drush version                 :  4.5
 Drush configuration           :
 Drush alias files             :  /usr/share/drush/includes/../aliases/mysite.
                                  aliases.drushrc.php
                                  /home/sigvard/.drush/aliases.drushrc.php
 Drupal root                   :  /var/www/mysite_dev
 Site path                     :  sites/default
 File directory path           :  sites/default/files
 Private file directory path   :

```

**Alias of the live site**

```
sigvard@server1:~$ drush @mysite.live status
include_once(/var/www/mysite/sites/default/settings.php): failed to [warning]
open stream: Permission denied in drupal_settings_initialize() (line
717 of /var/www/mysite/includes/bootstrap.inc).
include_once(): Failed opening                                       [warning]
'/var/www/mysite/sites/default/settings.php' for inclusion
(include_path='.:/usr/share/php:/usr/share/pear') in
drupal_settings_initialize() (line 717 of
/var/www/mysite/includes/bootstrap.inc).
 Drupal version         :  7.26
 Site URI               :  mysite.org
 Default theme          :  garland
 Administration theme   :  garland
 PHP configuration      :  /etc/php5/cli/php.ini
 Drush version          :  4.5
 Drush configuration    :
 Drush alias files      :  /usr/share/drush/includes/../aliases/mysite.aliases
                           .drushrc.php /home/sigvard/.drush/aliases.drushrc.php
 Drupal root            :  /var/www/mysite
 Site path              :  sites/default
 File directory path    :  sites/default/files

```

**sql-conf of the dev site**

```
sigvard@server1:~$ drush @mysite.dev sql-conf
Array
(
    [database] => website_mysite_dev
    [username] => mysite_dev
    [host] => localhost
    [port] =>
    [driver] => mysql
    [prefix] =>
)

```

**sql-conf attempt on the live site**

```
sigvard@server1:~$ drush @mysite.live sql-conf
include_once(/var/www/mysite/sites/default/settings.php): failed to [warning]
open stream: Permission denied in drupal_settings_initialize() (line
717 of /var/www/mysite/includes/bootstrap.inc).
include_once(): Failed opening                                       [warning]
'/var/www/mysite/sites/default/settings.php' for inclusion
(include_path='.:/usr/share/php:/usr/share/pear') in
drupal_settings_initialize() (line 717 of
/var/www/mysite/includes/bootstrap.inc).

```

# Answer
The initial error was caused by a server error filling the allocated memory and crashing the sync.

The corrupt server was a nightmare so in the end I just wiped the database and recreated the site from a backup using Drush.
> 0 votes

# Answer
I wonder if it's a file system permission on your live site. Are you sure /var/www/mysite/sites/default/settings.php on the live site is readable by your web server?

(Also, unrelated to this but Drush 4.5 is getting pretty old so if possible you might want to update it.)
> 1 votes

---
Tags: drush
---


# Question
Title: Drupal 7, MySQL, InnoDB, and transactions
I was reading default.settings.php for Drupal 7.x this afternoon, and came across this comment:

```
/*
 * Some database engines support transactions.  In order to enable
 * transaction support for a given database, set the 'transactions' key
 * to TRUE.  To disable it, set it to FALSE.  Note that the default value
 * varies by driver.  For MySQL, the default is FALSE since MyISAM tables
 * do not support transactions.
 */

```

This is different in Drupal 8:

```
/*
 * Transaction support is enabled by default for all drivers that support it,
 * including MySQL. To explicitly disable it, set the 'transactions' key to
 * FALSE.
 * Note that some configurations of MySQL, such as the MyISAM engine, don't
 * support it and will proceed silently even if enabled. If you experience
 * transaction related crashes with such configuration, set the 'transactions'
 * key to FALSE.
 */

```

So, how does `db_transaction()` work then on MySQL in Drupal 7?

Is this comment outdated, or should I explicitly set

```
$databases['default']['default']['transactions'] = TRUE;

```

if I know everything is InnoDB (which is the default for Drupal 7.

# Answer
The constructor for the `DatabaseConnection_mysql` class, has this code and comment:

```
public function __construct(array $connection_options = array()) {
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) ||
    ($connection_options['transactions'] !== FALSE);

```

In addition, there is support and workaround for the MySQL implementation of transactions (including no proper support for DDL transactions).

This suggests that the documentation in the settings file is incorrect.
> 1 votes

---
Tags: 7, database
---


# Question
Title: I want to save data using ajax. But AJAX callback function replace method not working ? why?
**THIS MY CODE:**

```
function form_test_permission() {
    return array(
        'submit_form_test' => array(
            'title' => t('Submit_form_test'),
            'description' => t('Submit the form_test form'),
        ),
    );
}

function form_test_menu() {
    $items = array();
    $items['production'] = array(
        'title' => 'Production',
        'type' => MENU_NORMAL_ITEM,
        'access arguments' => array('submit_form_test'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_test_form'),
    );

    return $items;
}

function form_test_form($form, &$form_state) {
    $form['production'] = array(
        '#title' => t('production'),
        '#type' => 'hidden',
        '#value' => '1',
    );
    $form['production1'] = array(
        '#title' => t('production1'),
        '#type' => 'hidden',
    );

    $form['production_date'] = array(
        '#title' => t('production_date'),
        '#type' => 'hidden',
        '#value' => date('Y-m-d'),
    );
    $form['production_time'] = array(
        '#title' => t('production_time'),
        '#type' => 'hidden',
        '#value' => date('H:i:s'),
    );
    $form['production23'] = array(
        '#title' => t('production23'),
        '#type' => 'hidden',
        '#value' => '1',
    );

    $form['button2'] = array(
        '#value' => 'UNDO',
        '#type' => 'submit',
        '#prefix' => '<div  class="test">',
        '#suffix' => '</div>',
        '#submit' => array('form_test_form_button2'),
    );

    $form['button1'] = array(
    '#value' => '  ADD  ',
    '#type' => 'submit',
    '#prefix' => '<div  class="test1">',
    '#suffix' => '</div>',
    '#submit' => array('form_test_form_button1'),
    '#ajax' => array(
        'callback' => 'ajax_example_submit_driven_callback',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'click',
        'wrapper' => 'countvalue',
        )
    );
    return $form;
}

function ajax_example_submit_driven_callback($form, $form_state) {
    $result = db_query("SELECT * FROM  form_test WHERE production_date='2014-02-10' and production_time between '01:00:00' and '02:00:00'");
    $prod_1 = $result->rowcount();
    $form['#tree'] = TRUE;
    $form_state['rebuild'] = TRUE;
    return 'count value is:' . $prod_1 . '';
}

function form_test_form_button1($form, &$form_state) {

    $ft_id = db_insert('form_test')
        ->fields(array(
            'production' => $form_state['values']['production'],
            'production_date' => $form_state['values']['production_date'],
            'production_time' => $form_state['values']['production_time'],
            'production1' => $form_state['values']['production1'],
        ))
        ->execute();
    $form_state['rebuild'] = true;
}

```

I have to mentioned in wrapper id in page.tpl.php file.

i want to save data using ajax. But i wrote query in AJAX callback function. AJAX Append method is worked fine. But AJAX replace function not working ? why?

# Answer
> 3 votes
Fun issue here. I pulled your code out and stuffed it into a test module and the ajax appeared to work once, eg, on first click of the ADD button, it replaced the `<div id="countvalue">foo</foo>` I had also stuffed into my `page.tpl.php`. But then each successive click put up the throbber without any further apparent change. Throwing a `watchdog()` into the callback showed it was indeed being called upon each click and then the `voila` moment:

```
return '<div id="countvalue">count value is:' . $prod_1 . '</div>';

```

is needed because it was replacing the original `<div id="countvalue">` with just the `count value is....` text, and then when clicked again, the DOM no longer contained a `#countvalue` for it to replace again :)

---
Tags: ajax, forms
---


# Question
Title: Caption Filter works in Preview, but not in regular view of node
I am using the caption filter module, which is working fine on a couple sites I manage, but on one specific site, when I use the markup and click on preview, it works perfectly, but if I save the node and then view it normally, it is clear that filter is not processing as it outputs the filter markup as plain text.

I am mystified as to why an input filter would work in preview, but not after its is saved. I keep thinking it might be a permissions issue, but I can't identify anything that would seem to trigger this.

Any suggestions to narrowing down this issue would be greatly appreciated. And I do have the caption filter as the last one, per the instructions and same with a similar site that I do not have this issue.

# Answer
> 1 votes
OK, I figured this issue out. This particular content type was using a custom template and I forgot to push the body content through check\_markup(..) before outputting it.

---
Tags: media, entities
---


# Question
Title: Restricting node access for nodes that are associated with other nodes which have user reference
I have one content type Jobs. These include a user reference field which is the contact.

I have another content type called Job Applications. The include a node reference field that links to Jobs.

How can I make so that public if someone attempts to read a URL for a job application, they won't be able to access that node unless they are contained in the user reference in the job node associated with that job application node.

I know that nodeaccess modules offers restrictions for content types containing user reference. I could add a contact user reference field in the job application content type BUT how do I keep it hidden (I think there is a module for hidding fields) AND more importantly how do I automate things so that when a job is selected (or used through node reference auto url) the hidden contact user reference field will automatically adjust based on that job node's user reference field.

Note: I don't want to restrict access by roles.

Update:

Job Contact (user reference)

Job Applications Job (node reference) Contact (user reference) \<-------- I need this to be copied automatically from the job (that is referenced in the node reference) contact user reference

# Answer
> 0 votes
To add on, you can also consider the Access by Term module:

> Provides very flexible, hierarchical node access control (content access control), for D7.
>
> Supports following flags: View, Update, Delete
>
> Grants are based on the relationship between the user-\>term\<-node.

# Answer
> 0 votes
I don't have enough rep to comment, however, if you are referring to an authenticated user (logged in). You can set the Access Control rules for the logged in user per node. If the user is not logged in, then it is not possible as anybody with a valid URL can view the node.

If you want to hide fields in a content type node. Go to Structure-\>Pages-\>View Node (you will have to enable this first in case it isn't). Then create a new variant for that content type and then manually add fields you want the authenticated/anonymous user to see. Make sure you have Context and Selection rules enabled and that admin roles are excepted from viewing that variant. In other words, admin will see everything.

---
Tags: entities, nodes, users
---


# Question
Title: How to make product attributes appear as checkbox on the add-to-cart form?
In Drupal Commerce how to make product attributes appear as checkboxes on the add-to-cart form? I want to see the sum of the prices of all checked products and add them all to the cart, when the add-to-cart submit button is pressed.

I wonder if there is tutorial, or - even better a module - for that?

# Answer
> 1 votes
The closest thing to what you're asking for is Commerce Add to Cart Extras.

---
Tags: 7, commerce
---


title: Add field into other field with Views

text:
# Question
Title: Add field into other field with Views
I have a view with td grid style and two fields: views-field-field-foo-image and views-field-field-foo-title.

The image is linked with colorbox load and the structure of the HTML is like this:

```
<div class="views-field views-field-field-foo-image">
  <div class="field-content">
    <a class="colorbox views-ajax-processed-processed"....
       <img width="230" height="150" title="" alt="" src="...>
    </a>
  </div>
</div>

<div class="views-field views-field-field-foo-title">
</div>

```

How can I put the foo-title into the foo-image field, so the structure to become like this?

```
<div class="views-field views-field-field-foo-image">
      <div class="field-content">
        <a class="colorbox views-ajax-processed-processed"....
           <img width="230" height="150" title="" alt="" src="...>
            <div class="views-field views-field-field-foo-title">
            </div>
        </a>
      </div>
</div>

```

With views module by changing the order of fields, so the title become on top and with Rewrite results/Rewrite the output on the image field will be possible to change the structure, but I cannot understand the building process with tokens.

EDIT: Unfortunately the answers didn't helped me.

Here's an example http://www.mtv.co.uk/the-valleys when you hover on any latest video, you'll see the title. This is their structure:

```
<a href="/the-valleys/videos/the-valleys-season-3-angle-grinding-0">
<div class="carousel-item-image">
<h2>
<span class="videos-list-tag">Exclusive</span>
</h2>
</a>

```

I want to add that `<h2>` inside the link, or in my case the title field. That's what I want to achieve.

I can see they don't use views. If someone knows how to create that even without Views module, please let me know.

# Answer
> 1 votes
One possibility is to use the Views Field View module:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.

Also, there is the 'Rewrite results' options in Views definition.

Alternatively by code, you can use use a field--\[type|name\[--content-type\]|content-type\].tpl.php file to override the rendering of the field. You would then have to access the `$element['#object']` to get access to the other field that you would need to render manually. Reference: https://api.drupal.org/api/drupal/modules%21field%21theme%21field.tpl.php/7

# Answer
> 0 votes
Easier way is applying separate anchor tags to both fields and manage the style setting through CSS.

# Answer
> 0 votes
To have fine control over the html of a view field, we're going to use the field rewrite functionality built into the fields interface. This tool allows us to hide the default field mark up and produce modified mark up using tokens to place our field data without html. To completely replace field mark up you can also use a global custom text field.

To modify the image field mark up to contain the title:

* Click the title field and check "Exclude from display".
* Click Apply.
* Click the image field and open "Rewrite Results" for the image field.
* Check "Rewrite the output of this field".

Now enter:

```
<div class="views-field views-field-field-foo-image">
  <div class="field-content">
   <a class="colorbox views-ajax-processed-processed" href="#">
       [image]
       [title]
    </a>
  </div>
</div>

```
* Click Apply.
* Click "Save" in the top right.

---
Tags: views
---


# Question
Title: How to target non admin pages (front end) from a module?
From my custom module I'd like to target essentially all front end pages on my site whether it be a node, front page, a views page or taxonomy page. I started out thinking it would be better to use logic that said *if not admin or node edit / add* but did not seem to have much luck. I came up with this and it seems to work fine but I don't know if accounts for every possible front end type of page that I have mentioned.

```
function mymodule_page_build(&$vars) {

  // Global node.
  $node = menu_get_object ();

  // Target front end pages
      if ((!empty($node) && arg(2) === null) || (drupal_is_front_page())) {

// do stuff

  }
}

```

I have a feeling the code does not account for all possible conditions I have mentioned so I am looking for some suggestions. I was thinking to exclude by path would be good except that node edit and node add don't have /admin in the url.

**Note**: By Target, I simply mean to focus or act upon. Example: If you want to add javascript or css to a specific page or pages from a module, you are "targeting" those pages.

# Answer
> 4 votes
You can use the `path_is_admin()` function to determine whether or not a path is an admin page, so you can just use the reverse to determine if it's a non-admin page:

```
if (!path_is_admin(current_path())) {

}

```

# Answer
> 1 votes
Are you using the same theme for admin pages and publicly viewable ones?

I've done this by using a separate admin theme - only the publicly viewable pages use my 'public' theme, so I can just show my 'public' stuff on all of them.

---
Tags: 7
---


# Question
Title: Why does my D7 User view only display 6 results in Block View, but all results in Page view?
I have a simple D7 view that lists all usernames and a couple of associated fields (business name, contact name) in table format. It has exposed filters on those fields, and about 200 users to list, sorted by creation date.

In Page View, this works perfectly as expected : I can page through a list of active users, and filter them.

However, when I try to embed the same view as a block, it displays only 6 results and no pager or exposed fields.

I've changed the pager ID - didn't help. I changed the pager ID on the other block shown with this one, too. I have no contextual filters or relationships set up. I tried changing to 'show all results' without a pager - still just those six results.

Any thoughts on where to start looking to fix this?

**ETA** I checked the queries being run, and as suggested, they turn out to be different in page view to block view.

This is my page view query:

```
SELECT users.name AS users_name, users.uid AS uid, users.status AS users_status,
 users.created AS users_created, 'user'
AS field_data_field_business_name_user_entity_type
FROM
{users} users
WHERE (( (users.status <> '0') ))
ORDER BY users_created DESC
LIMIT 30 OFFSET 0

```

But my block view query is different, all the exposed filters are applied, and I can't change them:

```
SELECT users.name AS users_name, users.uid AS uid, users.status AS users_status,
users.created AS users_created, 'user'
AS field_data_field_business_name_user_entity_type
FROM
{users} users
LEFT JOIN {field_data_field_business_name} field_data_field_business_name
ON users.uid = field_data_field_business_name.entity_id AND
(field_data_field_business_name.entity_type = 'user' AND
 field_data_field_business_name.deleted = '0')
LEFT JOIN {field_data_field_contact_name} field_data_field_contact_name
ON users.uid = field_data_field_contact_name.entity_id
AND (field_data_field_contact_name.entity_type = 'user'
AND field_data_field_contact_name.deleted = '0')
WHERE (( (users.status <> '0') AND
(field_data_field_business_name.field_business_name_value LIKE '%%' ESCAPE '\\')
AND (field_data_field_contact_name.field_contact_name_value LIKE '%%' ESCAPE '\\') ))
ORDER BY users_created DESC
LIMIT 30 OFFSET 0

```

# Answer
A good way to start understanding what happens is to turn on the `Show the SQL query` option in the basic view settings under `admin/structure/views/settings`. You can then copy-paste the generated query into your database application and check if the query catches all expected results. If yes, then the problem most probably happens during the rendering of the results, maybe a custom views block template (check the theme overrides for the views display)? If no, then there is probably something wrong with the query itself, which could be either some kind of filtering, or maybe a contrib module that alters the query from code.
> 0 votes

# Answer
AHA! Thanks to berliner kindly pointing out that I should check whether the two queries were different, I've got it.

In block view, my exposed filters were being applied with no option to enter a value.

I hadn't realised that the exposed filters are hidden in block view **unless Ajax is turned on**, but that now makes total sense. To fix this, I just had to turn on AJAX in the view, (Other-\> Use Ajax -\> Yes)

Just leaving this as an answer in case someone else needs it.
> 0 votes

---
Tags: views, blocks, paging
---


title: form api ajax stops javascript loading

text:
# Question
Title: form api ajax stops javascript loading
I have set an ajax callback to a form using the form api #ajax. I also have custom jquery in a file which styles part of the page and sets click handlers. I found something funny - my custom javascript only begins working AFTER the ajax has been called on the drupal form. Before I that form api ajax is called, it doesn't work.

Why would this be?

EDIT:

I am attaching my behaviors like this:

```
(function($) {
  Drupal.behaviors.updateCart =  {
    'attach': function(context) {
    $(document).ready(function () {...
```

This file is being included inside of my modules hook form alter:

```
if($form_id == 'commerce_checkout_form_checkout') {
  drupal_add_js('sites/all/modules/my_subscription/js/updateCart.js');
}

```

# Answer
> 1 votes
Even with the extraneous jQuery ready function within the behavior, it *should* still work. I guess it depends on what code resides within the javascript function and if all the jQuery selectors actually exist at that point. I would change two things to make it more "drupal"

1. Per my earlier comment, remove the jQuery ready function from within the attached behavior function
2. Attach the form javascript using the Form APIs #attached property. See here for more info.

# Answer
> 0 votes
The reason the extra ready function fails is because you're defining a callback to the event (page ready), in the processing of a callback to that same event... eg. the callback definition is added, to an already fired event.

---
Tags: forms, javascript
---


# Question
Title: Fetch a view into hook_preprcess_node and then put it in a block
I want to fetch a view in my template\_preprocess\_node function and then put in in a block, so I can diplay it in the sidebars of my page. I have the view (the code below) but don't know how to put it in a block. Thank you for your help in advance!

```
    $view = views_get_view('playlist');
    $view->set_display('block');
    $view->set_arguments(array($course));
    $view->pre_execute();
    $view->execute();
    $variables['content']['playlist'] = $view->render();

```

# Answer
> 1 votes
If you want to draw a view of content based on a node, then you should build a module that declared hook\_block(), and that hook\_block gets the current node with menu\_get\_object(), and form the desired view.

At the theming layer, when your node is preprocessed for theming, it's not a good place to construct any blocks. Hope this helps.

---
Tags: views, blocks, theming
---