# Question
Title: Why won't this update in hook_update_n() run in batches correctly?
I am working on this issue in the Feeds issue queue: https://www.drupal.org/node/2341407

I am trying to make the updates to the importers run in batches. I can't figure out why this won't run in multiple batches when there are multiple importers. What happens is instead of seeing a progress bar reload a few times when running update.php, it loads once and processes all importers in a single batch.

The code works well except for batching. Below is the code. Thanks in advance!

```
<?php

/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['total'])) {
    // Load all importers.
    $importers = feeds_importer_load_all(TRUE);
    $sandbox['total'] = count($importers);
    $sandbox['current'] = 0;
  }

  foreach ($importers as $importer) {
    $processor = $importer->processor;
    $config = $processor->getConfig();
    foreach ($config['mappings'] as $id=>$mapping) {
      // Act on mappings that do not contain a colon.
      if (!strpos($mapping['target'], ':')) {
        // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
        $info = field_info_field($mapping['target']);
        if (!empty($info)) {
          // Act on file or image fields.
          if (in_array($info['type'], array('file', 'image'))) {
            // Add ':uri' to fix the mapping.
            $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
          }
        }
      }
    }
    // Add the updated config and save the importer.
    $processor->addConfig(array('mappings' => $config['mappings']));
    $importer->save();

    drupal_set_message(t('@importer fields have been updated.', array('@importer' => $importer->id)));
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('@importers importers processed.', array('@importers' => $sandbox['total'])));
  }
}

```

# Answer
> 5 votes
Why are you expecting it to work as a batch, it's doing exactly what you're asking it to do and processing all the importers in the foreach loop! `foreach ($importers as $importer)` It's not magic, it can't assume that's what you want to batch :o)

Try this instead (obviously I haven't tested it, I've just typed it straight into the text editor here - but it's essentially your code so it should be fine);

```
/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['progress'])) {
    $sandbox['importers'] = feeds_importer_load_all(TRUE);
    $sandbox['progress'] = 0;
    $sandbox['max'] = count($sandbox['importers']);
  }

  $importer = array_pop($sandbox['importers']);
  $processor = $importer->processor;
  $config = $processor->getConfig();
  foreach ($config['mappings'] as $id => $mapping) {
    // Act on mappings that do not contain a colon.
    if (!strpos($mapping['target'], ':')) {
      // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
      $info = field_info_field($mapping['target']);
      if (!empty($info)) {
        // Act on file or image fields.
        if (in_array($info['type'], array('file', 'image'))) {
          // Add ':uri' to fix the mapping.
          $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
        }
      }
    }
  }
  // Add the updated config and save the importer.
  $processor->addConfig(array('mappings' => $config['mappings']));
  $importer->save();

  $sandbox['progress']++;

  // Set the value for finished. If progress == max then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['progress'] / $sandbox['max']);

  if (empty($sandbox['importers'])) {
    return t('@importers importers processed.', array('@importers' => $sandbox['max']));
  }
}

```

For hints about my alterations see the API documentation \- note that the naming convention changes don't alter anything, I just made them for Drupal core consistency. The most important thing to note is that all I've really done, is to remove the `foreach` loop so one importer gets used at a time.

**NOTE:** For clarification (as it's really not obvious) the percentage shown relates to the number of batch *operations* run - not the amount of *passes* through one batch operation. See `_batch_process()`:

```
// Total progress is the number of operations that have fully run plus the
// completion level of the current operation.
$current    = $total - $remaining + $finished;
$percentage = _batch_api_percentage($total, $current);

```

On a normal batch operation you'd pass in several separate operations like this;

```
$batch = array(
  'operations' => array(
    array('batch_example_one_process', array($options1, $options2)),
    array('batch_example_two_process', array($options3, $options4)),
  ),

```

And you'd see 50% completion only after `batch_example_one_process` has completed. I guess you can see that your code is working correctly though, as it clearly only processes one processor per pass - as long as they all get processed, you can confirm that batch api is working correctly.

---
Tags: feeds, batch-operations, updating
---


title: Touch of Flex Slider is not working

text:
# Question
Title: Touch of Flex Slider is not working
I am using Flexsilder in Drupal7, and i also enabled touch FROM Admin .

But Flexslider is not working for pad using touch

Here is my link, where i am facing issue this is my link where flex slider is implemented

Anybody can help please

# Answer
> 0 votes
Maybe you should try with different images. It works perfectly on my tablet and phone (both w8.1) you just can't drag it with your mouse, maybe thats why you tought it didn't work?

---
Tags: views, 7
---


# Question
Title: Drush aliases and Permission denied (publickey,password) problem
Im trying to use Drush Aliases but getting Permission denied (publickey,password) error. I can login to server using publickey without password but Drush can not. I've read the solution mentioned here and made the change but no success. Is there anything I'm missing here?

# Answer
> 0 votes
A possible cause is that you are not specifying your remote user in the drush alias file.

For example, if the ssh command that works to allow you to login is:

```
ssh myuser@example.com

```

Then an alias might look like this:

```
$aliases['dev'] = array(
  'uri' => 'http://www.example.com',
  'root' => '/var/www/vhosts/example.com/docroot/',
  'remote-host' => 'example.com',
  'remote-user' => 'myuser'
);

```

---
Tags: drush, ssh
---


# Question
Title: How do I have points and polygons in the same Leaflet map?
I have two content types

1. Location that geocodes an addressfield to place markers on the map
2. Boundary that uses a geojson field to create complex shapes on the map

I need to use views to show both content types on the same map. It appears that I can only do one or the other.

For an example, think about a map that shows constituency boundaries and voting stations.

# Answer
> 5 votes
Nigel Waters has it correct. Here are the details. I did this for cities and states. I used points for cities and polygons for states. Here are the steps.

Requirements:

* Geofield module
* Leaflet module
* Leaflet Views module (a submodule of Leaflet)

Steps:

* Create the two content types: City and State.
* Create a field of type Geofield, call it "Location"
* Choose GeoJSON as the field widget
* Add the Location field to both content types
* Create a city. For location enter GeoJSON Point data
* Create a state. For location enter a GeoJSON Polygon data
* Create a view with a Page display
* Add the Location field to the view
* Filter the view by State and City content types
* Set the Format of the view to Leaflet Map
* Your view should now look like pic 1
* Click on View Page
* You should see a map like pic 2

# Answer
> 2 votes
To answer my own question is to use the same field on both content types. I used a geojson (geofield) field which accepts both points and polygons to merge into a single leaflet map in views.

# Answer
> 0 votes
To show multiple content types in the same View:

* Edit your view
* Under "**Filter Criteria**" click "**Content: Type**"
* Select both content types under the "Content types" section
* Click Apply

---
Tags: location, javascript
---


title: Append a Drupal form table

text:
# Question
Title: Append a Drupal form table
For the past few days I have been trying to update a rather simple table with ajax. The table cannot be rebuilt. This is of my own accord, if the table is rebuilt all of the colors data that was already put in is ruined. The table must remain unchanged, only appended on.

Drupal's append does not seem to give me this functionality. Even if I set up the form and theming properly the big issue is that on submit the node will not recognize the new data. It only accepts that which was built on start and my appends although showing up on the screen do not show up at all on submit. Each input is not named either despite being put in. I cannot figure out what is going on here. This is just a mess... Please help.

IN HOOK\_FORM

```
$form['recipe_ingredients']['recipe_more_ingredients'] = array(
    '#type' => 'submit',
    '#value' => t('More ingredients'),
    '#description' => t("If the amount of boxes above isn't enough, click here to add more ingredients."),
    '#weight' => 1,
    '#submit' => array('recipe_more_ingredients_submit'),
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'recipe_more_ingredients_js',
      'wrapper' => 'thistobe',
      'effect' => 'fade',
      'method' => 'append'
),
);

function recipe_more_ingredients_js($form, &$form_state) {

    $form['recipe_ingredients']['ing'][$id] = array(
        '#theme' => 'ingredients_row',
    );

    $form['recipe_ingredients']['ing'][$id]['quantity'] = array(
        '#type' => 'textfield',
        '#title' => t('Quantity'),
        '#size' => 8,
        '#maxlength' => 8,
        '#attributes' => array('class' => array('form-item-recipe-ingredients-quantity')),
);

  return $form['recipe_ingredients']['ing'][$id];
 }

```

# Answer
> 0 votes
All changes to form must be done through hook\_form. Adding a new form in a js callback function will not be accepted as new elements to a form in Drupal.

---
Tags: forms, ajax
---


# Question
Title: show amount of results for exposed filter
I have a couple of exposed filters to filter the content in my view. Most of them are taxonomy terms, now i would like to show how many nodes are tagged with that term behind the taxonomy term.

example:

```
London (5)
Paris (3)
Madrid (2)
...

```

Any idea how i can do this?

# Answer
i created a module with a `hook_form_alter()`.

In that function i created a query that counted the nodes attached to a certain taxonomy term and added this number at the end of every term.
> 1 votes

# Answer
Here is some sample code to do this:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'views_exposed_form':

            $allowed_categories = db_query("SELECT 1 as tid, "Term Name (2)" as `name`")->fetchAllKeyed();
            $allowed_categories = array_reverse($allowed_categories, TRUE);
            $allowed_categories['All'] = '- Any -';
            $allowed_categories = array_reverse($allowed_categories, TRUE);

            $form['field_category_tid']['#options'] = $allowed_categories;

            break;
    }
}

```

Just change the query to return 2 columns - the tid and the name with a count.
> 4 votes

# Answer
```
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id){
    case 'views_exposed_form':
      if ($form_state['view']->name == 'viewname') {
    //must add some bool so this doesn't get into infinite loop
    if(!isset($form_state['view']->gg)){
      $form_state['view']->gg = TRUE;
      $form_state['view']->execute();
    }

    $form['results_count'] = array(
      '#markup' => t('!count results match your criteria', array('!count' => '<b>'.$form_state['view']->total_rows.'</b>')),
      '#weight' => -99,
    );
      }

      break;
  }
}

```
> 1 votes

# Answer
Couple of links (may be useful)

1. Module Taxonomy Menu, that has count option.
2. Question about these things, but without trusted answer.
> 0 votes

# Answer
This is an example from my real site. field\_marka\_prochnosti is a field of a node represented by a taxonomy vocabulary. I used phpMyAdmin to learn the name of a table and the name of the field of that table to make a query. bricksale\_omega is the name of my theme.

```
function bricksale_omega_form_alter(&$form, &$form_state, $form_id) {
switch($form_id){
case 'views_exposed_form':

  foreach ($form['field_marka_prochnosti_tid']['#options'] as $tid => &$value) {
    $query = db_select('field_data_field_marka_prochnosti', 'f')
            ->condition('f.field_marka_prochnosti_tid', $tid);
    $query->addExpression('COUNT(*)');
    $count = $query->execute()->fetchField();
    $value = $value . ' (' . $count . ')';
  }

  break;
  }
}

```
> 0 votes

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


# Question
Title: How do I add a Commerce product type to a feature?
I have a custom product type that I created in my local dev environment and I'm trying to export it into a feature.

However, I can't seem to find where the product type is stored in the Features module UI. I found the permissions (Product: View Own *Custom* Products) and the field instances (commerce\_product-*custom*-commerce\_license\_role) but I don't see the product type itself.

Instead, when I enable the feature on production, I get the following error message:

> Warning in features rebuild of custom\_module. No module defines permission "view any commerce\_product entity of bundle custom\_product\_type\_machinename".

When I export to production, the product type is not created. Where are the Commerce product types in the Features UI?

# Answer
As it turns out, product type export is not supported in the core Commerce module. Instead, you need to install the Commerce Features module.
> 2 votes

---
Tags: commerce, features
---


# Question
Title: How do I include a custom JavaScript file in a module?
I want to include a custom JavaScript file in a module using the following code.

```
function profile2_form_user_register_form_alter(&$form, &$form_state) {
  drupal_add_js('http://localhost/prf2.js', 'external');
}

```

I then add `scripts[] = js/prf2.js` in the .info file, but it throws this error.

> Warning: file\_get\_contents(js/prf2.js): failed to open stream: No such file or directory in drupal\_build\_js\_cache()

# Answer
This is the right & simple way to include any JS file in Drupal 7.

1. Create a folder named i.e. `js`, inside your module folder.
2. Inside that folder place `(modulename).js` file.

Note: Drupal JS code has a specific format as follows:

```
(function ($) {
  $(document).ready(function(){
    alert("Hello world!");  //here we can add our JS code
  });
})(jQuery);

```
3. Open `(modulename).info` file & add:

`scripts[] = js/(modulename).js`
4. Clear Cache & Run.
> 19 votes

# Answer
There is a lot of documentation about how to include a JS file into a custom module or into your theme in general. Here is the official article: https://www.drupal.org/node/304255

There are plenty of examples and you can inspire yourself with it.

PS: Don't hardcode the path of your JS file as you did in your code. Use the drupal\_get\_path function.
> 1 votes

# Answer
Here is two place where you can add JavaScript: In a theme or in a module.

### 1. Theme

If you want to add JavaScript in theme simply go in `your_theme.info` file and add your file path for example if your theme directory is:

```
mytheme\
 \js\my_theme.js
 \my_theme.info

```

So write down:

```
scripts[] = js/my_theme.js

```

Under your `my_theme.info` clear cache from admin and that should be work

### 2. Module

I you want to add js in module then

```
my_module
my_module\js\my_module.js
my_module.module

```

In my\_module.module call hook:

```
function my_module_init(){
    drupal_add_js(drupal_get_path('module', 'my_module').'/js/my_module.js');
}

```

Above code add JavaScript once module enable.
> 0 votes

---
Tags: javascript
---


# Question
Title: How to get the current user id in the path
I'm using the Workspace module and when the user goes on their '`SITENAME/user`', there's a link which leads them to all the nodes they have added.

The path of the link is '`workspace/<UID>`' for example '`workspace/1`' for admin. I'm trying to create another tab to do the same function but I can't figure out what path should I put. I tried '`workspace/%`', '`workspace/user`'. But nothing seems to work.

# Answer
> 2 votes
I found the answer for this myself. Used the me aliases module. And used the path '`SITENAME/me`'. Works perfectly

> Provides shortcut paths to current user's pages, eg user/me, blog/me, user/me/edit, tracker/me etc.
>
> This means logged in users no longer have to know/remember their uid, and it makes it easier to link to user-specific pages from a site help page (without resorting to using php to put $user-\>uid in the link).

# Answer
> 0 votes
Have a peek at what workspace is doing itself: http://cgit.drupalcode.org/workspace/tree/workspace.module

You probably want 'workspace/%user/foo' as the menu link, as it will autoload the user by the id that's provided in the call (see https://www.drupal.org/node/224170)

---
Tags: users, uri
---


# Question
Title: Is it possible to change the layout of the registration form using display suite?
My registration form contains the following fields -Name -City -Mobile -Email -Password -Confirm Password -Terms and Conditions (using legal module)

Is there some way to change the layout? I want it to appear something like this

```
************** ***************
*   TERMS    * *   Name      *
*     &      * *   City      *
*   COND.    * *   Mobile    *
* ************ *   Email     *
*   Submit   * *   Password  *
************** ***************

```

# Answer
> 1 votes
Sorry, I don't think it is possible with display suite on its own but you may find this link helpful Changing the layout of user profile edit page. Display suite appears to only get you some of the way there.

---
Tags: users, display-suite
---


# Question
Title: How to create different Panels for Add and Edit node?
There is a default "add/edit node" panel inside the Pages content.

When I use it, it utilize the its variant for both add and edit forms.

I would need to differentiate between both of these two instead of having a common panel for both of them.

Do you have any solutions?

(My Drupal version is 7.x)

# Answer
> 2 votes
On the *node/edit* panel, create two variants, "add" and "edit."

Make sure the add variant is first. Then add a selection rule for the add variant:

**String: URL path** node/add/\*

All paths not meeting this condition will be sent to the edit variant, which should give you the effect you want.

---
Tags: nodes, panels, chaos-tool-suite
---


title: Error Message are not coming

text:
# Question
Title: Error Message are not coming
I have create a template for user-register page

I have created a module under hook\_form\_alter as

```
if($form_id == 'user_register_form') {

            $form['account']['pass']['#type'] = 'password';
            $form['account']['pass']['#title'] = 'Password';
            $form['account']['mail']['#title'] = 'Email';
            $form['actions']['submit']['#value'] = 'Request Access';
             $form['#theme'] = 'user_register';

    }

```

**Edited:**

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

        if($form_state['input']['field_first_name']['und'][0]['value'] == ''){
            form_set_error('field_first_name', t('Email can not be empty'));
        }
          drupal_set_message($message, 'error');

     if($form_state['input']['field_last_name']['und'][0]['value'] == ''){
        form_set_error('field_last_name', 'Title cannot be "test"');
         drupal_set_message($message, 'error');
     }

                return $form;
    }

```

And i have created a user-regiter.tpl.php file

under this i have code like this

```
 <?php print drupal_render($form['field_first_name']); ?>
<?php print drupal_render_children($form); ?>

```

Which is working fine

Now when i submit form. it doesnt display error message . **But it is showing red border** in input box.

Why it is not showing error message . Please help

Thanks

# Answer
It's probably because you're not showing the Drupal messages in your theme. Take a look to ensure you have the following (somewhere, probably in your page.tpl.php file);

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

```

Note that you've made some other mistakes though (not related to your issue) - First, you should use `$form_state['values']` to gain the values when using `_validate()`; second, you can lose the two `drupal_set_message($message, 'error');` lines as they aren't doing anything?
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to attach a single node multiple times to an entity (e.g. badges)?
For an experimental Drupal 7 site, I would like attach a single node to another entity (this might be users, other nodes or even organic groups). The reasoning is fairly simple, say I have several users active and they can gain badges for activity just like in any stackexchange platform. Each badge is represented by a single node. Now, how could a user get the *same* badge multiple times?

Using entityreference, I can attach the same reference multiple times, but I am struggling with the output, it will show the same badge multiple times instead of only badge name and a counter. **Is there already a module for that I haven't found yet? Can you think of a better way to do it?**

Badges might not be the best example as you normally wouldn't lose any. Think of a trading card game might be better, as you can have the same card multiple times and trade it with another user. So, in the end I would need a way to add and remove the references. But this will be custom code, I guess.

**EDIT (in answer to Webdrips' comment):** As said in the very beginning, it's just an experiment so far, we are trying to use Drupal in unconventional ways in order to explore the full capacity of Drupal as a framework.

So, I came up with a better example to illustrate what I would like to achieve: let's say I am building a browser game. Game users will be normal Drupal user entities. An user may have several normal fields like health (number), name (text) and gender (list). Additionally, this user can collect items where each individual item type can be found multiple times.

Several players can be in a clan (organic group). This group has a central storage. So, each individual player of that group can place an item in the central storage.

Technically, I need a relation between user and item (for each item type) which also holds the number of items (e.g. Player1 has 5 nails). If he places 2 nails in the central storage, I need to change the relation between user and item (e.g. Player1 now has 3 nails) as well as the relation between organic group and item (e.g. Group1 has 2 nails).

So I am actually looking for a way to connect an item node (e.g. nails) to other entities (users, organic groups, ...) along with an additional value (item count).

I hope this renders my problem/question in an easier-to-understand way.

I've come across the User Points module and for keeping track of game points in my example this might be the right way to go, but imho it's not suited for the item thing.

# Answer
> 1 votes
Somehow it kept slipping my attention, I was probably focussed too much on specific ideas, but as it turns out, there is already a module for that, it's simply called Relation.

It's not that straight forward to use (imho), but it essentially creates relations between entities. The created relations are also entities and thus fieldable. By creating a relation type (A \[owns\] B / B \[is owned by\] A), I can add a custom field "amount" which holds the information how many Bs are owned by A.

The result (one custom view block added plus a single line of CSS) looks like this.

# Answer
> 1 votes
**Note**: The following approach would work but is very custom. Some contributed modules for badges functionality exist and may work for your case, but I have not tried them.

You could still use Entity Reference module and create a custom field formatter for the reference field.

You need to group and count the references that have the same node id, and then pass it to a theme function or template, alongside the fields you want to display of that content type.

For how to create a field formatter for entity reference fields, see both Entity Reference and Examples modules source code. The source code of Entity reference multiple display and Field Extractor contributed modules may help as well.

---
Tags: 7, entities
---


# Question
Title: time mismatch after convert with format_date
In my custom module, I converted time from database like ('17:00:00') with `format_date()`. After I converted this I got a wrong time (17:10). Please check my code, I am also naive drupal develper.

```
$form['departure_time'] = array(
  '#type' => 'textfield',
  '#maxlength' => 10,
  '#title' => t('Departure Time'),
  '#default_value' => format_date(strtotime($data -> departure_time),'custom', 'H:m'),
  '#description' => t("You Need To Add Departure Time.<< 00:00"),
  '#required' => TRUE,
);

```

# Answer
As listed in the documentation http://php.net/manual/en/function.date.php lowercase m is for month. For minutes you should use i.

```
$dep= format_date(strtotime($data -> departure_time),'custom', 'H:i');

```
> 0 votes

# Answer
Just of note, you don't need to pass the date through `t()` as `format_date()` handles this itself through `_format_date_callback()` for reference. You just have to pass in the langcode yourself.
> 0 votes

---
Tags: datetime
---


# Question
Title: How to add and render a region in omega 3.x subtheme?
Can anyone let me know as how to render a region in omega 3.x subtheme ?

I have tried creating a region using this command in .info file as regions\[region name\] = region name and used render command in page--front.tpl.php , ,but regions are not getting rendered !

Can anyone please help me with this issue

# Answer
Clear the cache first.

Go to the subtheme appearance settings, click the "Zone and region configuration" tab, and scroll down to the bottom to find your "unassigned regions". Simply assign it to a zone, configure the options above, and save.

Go to Structure and check "Demonstrate block regions".
> 0 votes

---
Tags: theming
---


title: drupal_static and XHProf

text:
# Question
Title: drupal_static and XHProf
I'm using D6 but stole drupal\_static() from D7 for a high demand site I'm currently working on.

I'm currently optimising some of the slower pages with XHProf which has been fine, but I'm getting a strange result with drupal\_static().

It doesn't matter whether I use:

```
$registry = &drupal_static(__FUNCTION__, array());

```

Or the fast static method:

```
static $registry;
if (!isset($registry)) {
  $registry = &drupal_static(__FUNCTION__, array());
}

```

The number of calls to `drupal_static()` is given as the same in XHProf.

Am I missing something?

# Answer
You should use either `static` declaration or `drupal_static()`, but not both for the same variable. The issue here is that the reference is lost because references are not stored statically.

From https://www.drupal.org/node/619666#comment-2211696

> So unfortunately this is not possible (declarations of static variables don't accept expressions):

```
static $implementations = &drupal_static(__FUNCTION__, array());

```

> An this neither (it'll lose the reference):

```
static $implementations;
if (!isset($implementations)) {
  $implementations = &drupal_static(__FUNCTION__, array());
}

```

> But this is:

```
static $cache = array();
if (!isset($cache['implementations'])) {
  $cache['implementations'] = &drupal_static(__FUNCTION__, array());
}
$implementations = &$cache['implementations'];

```

So you should do this:

```
static $cache;
if (!isset($cache)) {
  $cache['registry'] = &drupal_static(__FUNCTION__, array());
}
$registry = &$cache['registry'];

```
> 2 votes

---
Tags: 6, debugging
---


# Question
Title: How can I make a view showing all users who have not created any nodes or made comments?
I am trying to fix a site that has had more than 10,000 spam user registrations. However, some legitimate user registrations have also been made, so I cannot simply delete all the accounts.

Manually sorting through all of this would take a very long time. However, it appears to be the case that no spam users made any comments or created any nodes. So, I thought I might be able to create a view that shows all the users that have not created content or made any comments, and then use VBO to delete all such users.

But, although I can make a view that shows users who have created content, I haven't been able to figure out a way that shows users who have not created any content/comments. How might I go about this?

# Answer
Before some days I was also work on some thing like this. In my registration page there is a field named looking-for. I was created a view to show all the members as per there looking-for field. It mean that if user selected male in looking for then only male is shown. I have added below code in the view. You can change condition as per your condition & add relationship & filter criteria.

```
global $user;
  $profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
        if ($items = field_get_items('profile2', $profile, 'field_sex')) {
        break;
      }
    }
    $i_am=$items[0]['value'];
 if($i_am=='sdmale' || $i_am=='sbmale'){

  $looking='smfemale+sbfemale';

}

if($i_am=='smfemale' || $i_am=='sbfemale'){

  $looking='sdmale+sbmale';

}

   return $looking;

```
> 0 votes

---
Tags: views, advertising
---


title: is my menu-block not properly inserted?

text:
# Question
Title: is my menu-block not properly inserted?
quite new to drupal and having a small issue i can't seem to solve. it's quite a lot to start to explain so i think it's best to just send you the link and explain the problem.

take a look at www.contribute.be i have inserted a new menu block called 'News' + a menu link to that block. Now i have 2 issues with this:

1) when i click on a job (in the section underneath), the job description should slide out in the same place (what it does when the News block is not enabled) but what happens is it jumps to the news block first 2) similar problem: when i click on a customer case (in the second section of customers), it should link to another content type with the customer case in full, but what happens is the menublock 'News' is displayed as well.

It seems to be getting in the way of the other blocks and content types. I have looked but cannot find the solution.

Can somebody assist?

Thx B

# Answer
From what I can see, the News block is NOT on the main page (#block-block-9 is not in source code). When clicking a job title, the visitor is taken to /jobs and there IS a News block. Since it's just before the Jobs block and the page seems to remember the scroll offset, the visitor sees the news block instead of the jobs block (which is then right below).
> 0 votes

---
Tags: routes, blocks
---


title: display node inside colorbox

text:
# Question
Title: display node inside colorbox
Is it possible to display a node content (without sidebar etc.) inside colorbox in Drupal 6. I know there is module for that in drupal 7 - colorbox-node. But I could not find any thread bout same functionality for drupal 6. Can anybody help? Thank you

# Answer
Try the Popup module. There is a version for Drupal 6.

> The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: Term taxonomy child from first and second level menu
I have a drupal commerce with taxonomy which have child.The menu was generate automatically. Exemple:

```
Vehicle
      |-->4 wheel
                |-->car
                |-->bus
      |-->2 wheel
                |-->motorbike
                |-->bicycle

```

I want to display a link "4 wheel" and a "link 2 wheel" when we are on the "Vehicle" page (which don't have product inside) And I want to display "motorbike" and "bicycle" when we are on the "2 wheel" page (which don't have product inside).

I have a drupal commerce default content display and the default views product\_category. I found this video which make me make a new view call catalog which does exactly what I want (video at 15:18). https://www.youtube.com/watch?v=y1jqu8JnLbU But the main menu (automatically generated) still going to product\_category. So now if I want a can make a menu and add every link by my hands but I don't like bad work.

So my question is how can I say to drupal commerce: "Hey now stop using the default view which is call product\_category and use my view which is call catalog. Or
How can I configure the product\_category view to display all the child taxonomy like I explain.

I found many stuff but nothing very helpful https://drupal.stackexchange.com/questions/5732/is-there-a-good-tutorial-for-entity-views-attach-module The path module The PHP filter with code Try to make a block this context filter and display it ...

If someone can help It will be nice !

# Answer
I've found a way to do it. It's not the best way but it's a way which is enough clean for me for now . It's with Menu block module. I made 2 blocks with this module and I configure it on a specific page. http://www.youtube.com/watch?v=1rku2vHqZP4

If you want you can also use Pathauto module to generate nice url so you don't need to configure on evry specific page but on every page with a specific URL like www.yoursite/Vehicle/\*.

To configure that go to admin/config/search/path/settings and set the Slash (/) option to "Do not Replace" under "Punctuation" then go to the taxonomy path which you need and put `[term:parents:join:/]/[term:name]` the URL will be like www.yoursite/Vehicle/4-wheel/car.

Hope that help.
> 0 votes

---
Tags: taxonomy-terms, routes
---


# Question
Title: Page caching with multiple versions of the cache
My site is very much faster with page caching on. However, I have a custom module that serves 5 different slightly different versions of my content. In other words, people in New York see East Coast stories, but not California stories, but everyone sees national stories. This is mostly done through a custom Views filter that checks for a cookie.

Each node is tagged with an internal taxonomy that determines which areas to show that content in lists generated by views. The actual content isn't hidden or different based on the cookie, just the lists of events, local stories, etc.

Is there a way of serving cache A to people with cookie A, cache B to people with Cookie B, etc?

Code from the custom Views filter-

```
function query(){

  $this->query->set_distinct(TRUE);
  $invert = $this->options['invert'];
  //Get the taxonomy id corresponding to the user's location from a cookie.
  $office_tid = MCC_location_get_cookie("tid");

  //Get the taxonomy id of the country- code used on 2 sites
  $country_name = variable_get('MCC_location_site')?"U.S.":"Canada";
  $country_tid = taxonomy_get_term_by_name($country_name,'regions');
  $country_tid = current($country_tid)->tid;

  if($office_tid == $country_tid){
    // An area without an office was selected, such as Yukon, filter should act as if no province has been selected
    $case = $this->options['office_not_set'];
  }

  $join = new views_join();

  $join->definition = array(
    'table' => 'taxonomy_index',
    'field' => 'nid',
    'left_table' => 'node',
    'left_field' => 'nid',
  );
  $join->construct();
  $this->query->add_table("taxonomy_index", NULL, $join);
  $this->query->add_table("taxonomy_index", NULL, $join, "taxonomy_index_for_office");

  $this->query->add_where_expression($this->options['group'], "taxonomy_index_for_office.tid = ".$office_tid." AND taxonomy_index_for_office.nid NOT IN (SELECT taxonomy_index_for_office.nid FROM taxonomy_index AS taxonomy_index_for_office WHERE taxonomy_index_for_office.tid = ".$country_tid.")");
}

```

# Answer
> 1 votes
If you're using Varnish, you can simply add the cookie as a hash key - there's lots of information about how to do this.

One example and one based on mobile devices.

If you mean Drupals internal page cache then maybe look to this module.

---
Tags: views, caching
---


# Question
Title: Unable to set the data property xxx as the parent data structure is not set
I currently use geofield to set latitude and longitude but rules gives me this error:

> 0 ms Unable to modify data "user:field-coordonnees:lon": Unable to set the data property lon as the parent data structure is not set.

So values are not set and I do not understand why, it's just a set data. The value exists because I can see it in a "Show a message on the site". I've also tried to cast the value as Integer, nothing has changed.

Any idea ?

Configuration:

> Geofield Map 7.x-2.3
>
> Geofield 7.x-2.3
>
> geoPHP 7.x-1.7

# Answer
I've found the issue. In fact insted of set a lat and a lon value, I had to use "Create geofield values from lat/lon".
> 0 votes

# Answer
If you see this error it's most likely that the developer forgot to add a proper check (or try/catch block) for his entity\_metadata\_wrapper() call. Better report this to the module you were using on the drupal.org/geofield page.
> 0 votes

---
Tags: location
---


title: Entity reference, save only value

text:
# Question
Title: Entity reference, save only value
I am looking for the best approach to do the following:

I have a content type Product and a content type Invoice, where i can reference products.

I would like to be able to save the referenced products AT THAT TIME (with their price info). So when the product is changed in the future, the invoice will not be updated with it.

Any suggestions on how to approach this best?

Thanks in advance!

# Answer
> 0 votes
as far as i can see there are 2 options, and both would involve writing some custom code.

1st, provided that you have enabled product revisions, when saving the invoice, save that particular revision number and then load your product based on that revision.

2nd, would be to add product fields that you are interested in, to you invoice (price, desc etc.) and based on the product attached save those in form validation handler

---
Tags: entities
---


# Question
Title: drupal_form_submit() does not update(edit) the node?
$fs has following data

```
 $fs = Array
(
    [values] => Array
        (
            [field_1] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [target_id] => val_1
                                )

                        )

                )

            [field_download_1] => Array
                (
                    [und] => 1
                )

            [field_download_nid_1] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [target_id] => Downloaded_48840
                                )

                        )

                )

            [field_status_1] => Array
                (
                    [und] => 7
                )

            [field_view_1] => Array
                (
                    [und] => 1
                )

            [field_view_nid_1] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [target_id] => Viewed_48840
                                )

                        )

                )

            [field_rt] => Array
                (
                    [und] => 0
                )

            [field_date_1] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Array
                                        (
                                            [date] => 11/19/1927
                                        )

                                )

                        )

                )

            [field_date_2] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Array
                                        (
                                            [date] => 17/08/2011
                                            [time] => 20:04
                                        )

                                )

                        )

                )

            [field_date_2] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Array
                                        (
                                            [date] => 18/08/2011
                                            [time] => 08:49
                                        )

                                )

                        )

                )

            [field_text_field_1] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] =>
text is displayed here
                                )

                        )

                )
            [nid] => 48840
            [vid] => 48840
            [uid] => 1
            [op] => Report stamp
        )

    [triggering_element] => Array
        (
            [#parents] => Array
                (
                )

        )

)

```

The drupal\_form\_submit() is called when submit button is clicked on a form(which is not abc\_node\_form).
`drupal_form_submit('abc_node_form', $fs, $node );`
**abc\_node\_form** : form\_id of content type abc .
**$fs** : has all the values extracted from the $node.
**$node** : form\_state of the form which has all the values for which the content\_type abc needs to be updated.
Also I have checked for form\_get\_errors(), I dont get any errors but the form node does not get updated.;

# Answer
> 1 votes
As said by @znerol

Additionally one needs to ensure that $fs\['values'\]\['op'\] is set to the value of the **submit button on the target form**. In this example I think it should be
`$fs['values']['op'] = t('Save');`

this solved the problem and node is being updated

# Answer
> 1 votes
Make sure about the parameters you are using

```
 drupal_form_submit('abc_node_form', $fs, $node );

```
* '`abc_node_form`'- is the appropriate form id.
* `$fs` \- current state of the form. Most important is the $form\_state\['values'\] collection .
* `$node` \- is the old node object, that you will find in $form\_state\['node'\],if using default node creation form.

I am not sure how you are getting $node value,here is small snippet which can be helpful to build $node

```
  // Before drupal_form_submit()
  $node = node_load($fs['nid']);
  $fs['node'] = $node;
  drupal_form_submit('abc_node_form', $fs, $node );

```

# Answer
> 1 votes
this was how i submitted an existing node using drupal\_form\_submit:

```
$node = node_load($nid);
$fs['build_info']['args'] = array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('mytype_node_form', $fs);
$fs['node'] = $node;
$fs['values']['op'] = t('Save');
drupal_form_submit('mytype_node_form', $fs, $node);

```

---
Tags: 7, forms
---


# Question
Title: Can we use panels for header and footer?
I have a few different top menus which I want to display in certain contexts, and ideally this should go in the header region. However, I have found that Panels can only take over the content region, and the right and left sidebars.

Is there a way to make panels for the header (and footer) regions?

EDIT: I am using the Bootstrap theme, so I'm not sure if this plays well with the Panels Everywhere theme.

# Answer
Panels takes over the "Content" region.

Panels everywhere takes over the entire page, and is the module that does what you want.

Some themes are listed on the PE page as "compatible", but all that means is that they ship with appropriate templates, which makes it easier to get started.

You can use any theme you want with PE, but you will likely want to provide your own `site-template` as alternative to the regular `page.tpl.php` which PE will disregard. Look at one or two of the themes that are listed on the PE page and their use of template to get started.
> 1 votes

---
Tags: panels
---


title: Omega 4 without Drush

text:
# Question
Title: Omega 4 without Drush
Hi \[still new to Drupal\]

Due to certain constraints I can't install drush. Am I able to work on Omega 4 without Drush? The organisation I work for has strict online security and firewall. I have a lot if issues installing drush. So I have decided not to install it and would like ti work on omega 4 without drush.

Does anyone have a good place to start, or can anyone point me in the right direction?

I'm look for tutorials, forums anything that can help. This has cost me time and now i need to hit the theme.

Please can you assist?

# Answer
You can user Omega without Drush but I do recommend to try to install the Drush. Even if you do not want to use Omega you need to have Drush for serious Drupal projects. It makes your life easy.
> 0 votes

---
Tags: drush, theming
---


# Question
Title: Ajax request: 500 (Internal Server Error)
I am using this jQuery plugin to render a toggle button in a block. When the button is toggled off/on I want to write to a databse table (with `entity_save`). Here's the relevant code I'm using to try to acheive this:

```
// hook_menu item
$items['product-status-update'] = array(
  'title'=>'Status update',
  'page callback' => 'my_module_status_update',
  'access callback' => 'product_entity_access',
  'type'=> MENU_CALLBACK,
);

// jQuery
drupal_add_js('
  (function($) {
    $(function() {
      $(".toggle-button").toggles({' . $status . $state . '});
      $(".toggle-button").on("toggle", function (e, status) {
        status = status == true ? 1 : 0
        $.ajax({
          type: "POST",
          url: "?q=product-status-update",
          data: "pid="+' . $pid . '&"status="+status,
        });
      });
    });
  })(jQuery);
', 'inline');

// Callback
function my_module_status_update() {
  $pid = $_POST['pid'];
  $status = $_POST['status'];
  $product = entity_load_single('product', $pid);
  $product->status = $status;
  entity_save('product', $product);
}

// Console log output when toggling
POST http://example.com/?q=product-status-update 500 (Internal Server Error) jquery-1.10.2.js:8706
1 ?q=home:98
0 ?q=home:99
POST http://example.com/?q=product-status-update 500 (Internal Server Error) jquery-1.10.2.js:8706
1 ?q=home:98
1 ?q=home:99
POST http://example.com/?q=product-status-update 500 (Internal Server Error) jquery-1.10.2.js:8706
1 ?q=home:98
0 ?q=home:99

```

As you can see from the console log output I am receiving: 500 (Internal Server Error).

Any ideas why or what might be the culprit? Thanks.

# Answer
> 0 votes
My mistake was:

```
data: "pid="+' . $pid . '&"status="+status,

```

should be

```
data: "&pid=" + ' . $pid . ' + "&status=" + status,

```

Seems obvious now.

Anyway, the above is the basics of how to update a value in the database by sliding a jQuery toggle button back and forth.

# Answer
> 0 votes
At a glance, there's some issues with the code, however, the main error may be:

```
$product = entity_load_single('product', $pid);

```

where you don't have a `$pid` value, you're setting `$fid` instead.

```
$fid = $_POST['pid'];

```

---
Tags: ajax
---


# Question
Title: Trouble displaying different info for same role/node type
In D7 I am trying to display different information to different users with the same role. The 2 types of roles are 'Renter' and 'Landlord'. I've tried creating different views, but currently all renters and all landlords can see all renter info and all landlord info. I've tried Display Suite, Views, References, Entity References, all with no luck. :(

Ideally Larry Landlord would be able to see a list of all of his tenants (renters) with their addresses, rent amount, date of last rent payment, if the payment was processed, and if the rent is overdue. But currently he can see his info, and the info for the other landlords and renters.

Any thoughts?

Thanks!

After creating views and setting up an Entity Reference field, I am still having difficulty displaying the views I need. I'm trying to tie a renter (tenant) to a landlord, which would be a 1:1 relationship, and allow that one renter to see their history with their landlord. I am able to display all landlords and all renters, but when I try to create the 1:1 relationship that's where it falls apart. I may need another view, but I'm not sure how to connect the various views.

Any thoughts?

# Answer
If you don't already have one, create a View of Users to filter on.

In the Displays section of that view, add a new Display of type "Entity Reference" (where you would add one of Block, Page, etc.).

Now, you'll see in this new View Display the Format is called "Entity Reference List". Go to the settings for this formatter and add a field to search by (in this case, you'll want to use 'User: Name', most likely). Add a Filter Criteria here to only include Users of a specific Role (Tenants).

Now, go to Admin \> Configuration \> People \> Account settings \> Manage fields

Add an EntityReference field called "Tenants".

On the Field Settings page, change the Target type to User. Then change the Mode to "Views: filter by an EntityReference View". You'll see your list of "Tenants" here.

Still with me?

You'll want to make this field widget a Checkbox, probably, so that multiple values can be selected.

Okay, save on that screen and then on Field Edit page, change the number of accepted values to Unlimited. (it defaults to one).

Now, logged in as a Landlord, go to that Landlord's profile and select the Tenants off the checklist now visible on their profile.

You probably created a 'Page' by default with your Tenants (User) View, so now go to that page's View Display settings.

Add a Contextual Filter of User: UID. Set this to a 'Provide a Default Value' with type of "User ID of logged in User".

Now you can Utilize Fields on this Page View--Display content of "Field Tenants" and it will show whoever is selected in that field for the currently logged in user. You can tweak the settings here--if you want to show more information you can display them as "Rendered Entities" and then use any of the View modes for that user you've set up, you'll need to mess with "Multiple Field Settings as well to get it how you want, probably.
> 0 votes

---
Tags: views
---


title: Disqus not showing

text:
# Question
Title: Disqus not showing
I have been trying to set up Disqus commenting system on my website. For some reason it does not show on my website.

I have follow many YouTube tutorials, the module documentation and the documentation from Disqus, on how to implementing Disqus in my website and for some reason I still no able to see it.

I found some that have a solution in this post. By adding this piece of code.

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

```

And even with this I'm not able to show my disqus comments.

I enable the module and give permission to anonymous, authenticated and administrator to see Disqus comments. The current location view is on the content.

Can someone help me troubleshoot this problem ?

# Answer
> 2 votes
If you don't have to, don't add Disqus via templates. It depends on how you're implementing it and what tools you're using, but I suggest using Display Suite.

1. In the Disqus settings under the Visibility tab (admin/config/services/disqus), enable the content types using Disqus and change the location to Block.
2. In Display Suite, add a new Block field (admin/structure/ds/fields/manage\_block) and select the Disqus Comments block.
3. In your Default or Full display, add the block to the appropriate region.
4. Under Disqus permissions, add anonymous and authenticated users to View Disqus comments. (probably your specific issue)

---
Tags: comments
---


title: Alter keywords searched in solr

text:
# Question
Title: Alter keywords searched in solr
I want to search phrase entered by user as

```
q="phrase"^21.0 OR phrase

```

On `localhost:8983/solr/admin/form.jsp` it parses `"phrase"^21.0 OR phrase` perfectly! and return correct results

How can i do it in PHP. I am using Drupal 6. Please help!!

If more information is required please let me know.

# Answer
> 0 votes
In solrconfig.xml

```
<requestHandler name="drupal" class="solr.SearchHandler" default="true">
<str name="defType">dismax</str>

```

so the request handler was "default" hence query was parsed with deftype:dismax and dismax does not parse BOOLEAN operators in the query string.

I created a new HANDLER in solrconfig.xml

```
<requestHandler name="sohail" class="solr.SearchHandler" >
    <lst name="defaults">
     <str name="echoParams">explicit</str>
     <bool name="omitHeader">true</bool>

```

Set `$params[qt] = "sohail";` in the MYMODULE\_apachesolr\_modify\_query()

Now it works perfectly!

---
Tags: search
---


# Question
Title: Drupal 7 with front-end in Spanish/English; Back-end in English only
I installed Drupal in English and also installed the i18n and Locale modules for translation. I then enabled Spanish as a language and set it as default. My aim is to have the site default to Spanish (www.mysite.com/spanish-page), and to allow users to choose English if they wish (www.mysite.com/en/english-page).

My site is still defaulting to English... for example, in "admin/config/system/site-information", my Default front page setting is defaulting the the "en" (English) url prefix. I cannot delete that prefix on that page; it is listed in the non-editable text just in front of that field. Likewise, when I click the "Home" button on my admin menu, it takes me to "www.mysite.com/en" (the English home page) instead of "www.mysite.com" (which would be the Spanish home page). I'm sure it must be a default setting somewhere, but I cannot find it. Can anyone provide guidance on how to properly set up this type of language scenario?

Thanks!

# Answer
> 0 votes
I just found what I suppose is my "fix"... in "admin/config/regional/language/configure", I unchecked "Session", "User", and "Browser" in the "User interface text language detection" section, leaving only "URL" and "Default" checked. This seems to have fixed my issue.

---
Tags: 7, i18n-l10n
---


# Question
Title: Remove tags from dependent term ref field when dependee is deactivated
I have a check box acting as the dependee. When it is checked, it opens up a free-tagging term-reference field. So when `A` is checked, `B` appears and users can add tags:

`A (checkbox): []
 B (tags): [________]`

In the settings I have the following selected:

> "Reset the dependent to its default values when the form is submitted if the dependency is not triggered."

The default value for the term-ref field is blank. When the checkbox (dependee) is unchecked and the content saved, it should revert to the default value. However, all added terms remain.

Is there a way to remove all taxonomy terms in this scenario? I have multiple dependee/dependent fields in the content type, so it would have to act independently of other fields.

# Answer
Fixed...

In the conditional fields settings I had used the following:

> * The dependent field is: visible
> * When the dependee: is checked

For some reason this does not revert the dependent to its default value if the dependee is deactivated on saving. Instead, I used these settings and it works:

> * The dependent field is: visible
> * When the dependee: is has value
> * (select the name of the checkbox)

This might be because I have used the label as the value for the checkboxes (instead of the default 0 & 1).
> 0 votes

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


# Question
Title: Zurb vs. Bootstrap themes: About performance
I'm trying to decide to use Foundation or Bootstrap as a base theme for a redesign, but even if Foundation have a lot of strengths (native sass support as I've read), it seems that it is waaay bigger than Bootstrap.

**Zurb compressed file is about 585.16 KB while Bootstrap is 103.27 KB.**

Bootstrap is being used by way more people, but that doesn't necessarily mean that it's better. Any insight about their performance?

I've read several articles about their performance, **but none about their "Drupal versions" of each theme.**

**So, my question is: Does a much, much bigger base theme impacts into performance?**

**It seems that it does, but** I've read somewhere that Bootstrap and Foundation are almost equal in terms of performance. How can that be?

# Answer
> 3 votes
The Drupal Bootstrap is just a wrapper for the Bootstrap Framework. When you download that, the compressed size increases by about 200 Kb. However, I don't think size is a good metric for theme performance.

Foundation has a very limited number of UI elements, it just gives you the foundation to build your own theme upon. Bootstrap provides almost every UI element you can think of. If you want to design your own CSS carefully, to give your site a personal design, go with Foundation. If you just want to do rapid prototyping or to have a responsive site up quickly and with little effort, go with Bootstrap.

As for performance, I haven't spotted any clear differences between these in the context of Drupal. Btw.: I don't think the Drupal versions should differ from those on other platforms, as most of the code is the same for all platforms. The Drupal versions are just wrapped to fit into Drupal's theme system.

---
Tags: theming, performance
---


title: How to send password in email body

text:
# Question
Title: How to send password in email body
```
function lawyer_register_menu() {
  $items['lawyer_register'] = array(
    'title' => 'Lawyer Registration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'lawyer_register_form'
    ),
    'access callback' => TRUE
  );

  $items['lawyer_register-autocomplete-engine'] = array(
    'page callback' => 'lawyer_register_autocomplete',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE
  );

  return $items;
}
function lawyer_register_form($form, &$form_submit) {
  $form         = array();
  $form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE
  );

  $form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE
  );

  $form['fname'] = array(
    '#title' => t('Full Name'),
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 20
  );

  $form['phone_no'] = array(
    '#title' => t('phone_no'),
    '#type' => 'textfield',
    '#description' => t(''),
    '#size' => 20,
    '#maxlength' => 20
  );

  $form['street_address'] = array(
    '#title' => t('Street Address'),
    '#type' => 'textfield',
    '#size' => 50,
    '#maxlength' => 100
  );

  $form['county'] = array(
    '#title' => t('County'),
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 20
  );

  $form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1
  );

  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit'
  );
  return $form;
}

function lawyer_register_form_submit($form, &$form_submit) {
  $edit    = array(
    'name' => $form_submit['values']['name'],
    'pass' => user_password(),
    'mail' => $form_submit['values']['mail'],
    'init' => $form_submit['values']['mail'],
    'status' => 1,
    'access' => REQUEST_TIME,
    'fname' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['fname']
        )
      )
    ),
    'street_address' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['street_address']
        )
      )
    ),
    'phone_no' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['phone_no']
        )
      )
    ),
    'county' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['county']
        )
      )
    )
  );
  $to      = $form_submit['values']['mail'];
  $subject = 'New account created';
  $headers = "From: something@somewhere.org\nContent-type: text/html";
  $body    = 'A new user account has been created for you at <a  href="http://something.org/">Something.org</a>.<br /> Your login details are as follows:<br />Username: <b>' . $form_submit['values']['name'] . '</b><br /> Password: <b>\'???????\'</b> <br /><br /> Please login to <a  href="http://us.lawandmoney.info">Lawandmoney.org</a> and change your password.<br />';
  if ($form_submit['values']['send_message'] == 1) {
    mail($to, $subject, $body, $headers);
  }
  user_save(drupal_anonymous_user(), $edit);
  drupal_set_message("Successfully Register. Please check your Email for login    details.");

}

```

here I'm creating customized login registration page working properly. Now I want to send password to user via email so what i can write in message body like for username I write Username: '.$form\_submit\['values'\]\['name'\].' So what can I write for password?

# Answer
> 3 votes
Store user\_password() in a variable. Change your code to this

```
    function lawyer_register_form_submit($form, &$form_submit)
    {
     $new_password = user_password();
     $edit = array(
      'name' => $form_submit['values']['name'],
      'pass' => $new_password,
      'mail' => $form_submit['values']['mail'],
      'init' => $form_submit['values']['mail'],
      'status' => 1,
      'access' => REQUEST_TIME,
      'fname' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values']   ['fname']))),
      'street_address' => array(LANGUAGE_NONE => array(array('value' =>  $form_submit['values']['street_address']))),
      'phone_no' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values'] ['phone_no']))),
      'county' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values'] ['county']))),
      );
      $to = $form_submit['values']['mail'];
      $subject = 'New account created';
      $headers = "From: something@somewhere.org\nContent-type: text/html";
      $body = 'A new user account has been created for you at <a  href="http://something.org/">Something.org</a>.<br /> Your login details are as follows:<br />Username: <b>'.$form_submit['values']['name'].'</b><br /> Password: <b>'$new_password'</b> <br /><br /> Please login to <a  href="http://us.lawandmoney.info">Lawandmoney.org</a> and change your password.<br />';
       if($form_submit['values']['send_message'] == 1){
         mail($to,$subject,$body,$headers);
         }
       user_save(drupal_anonymous_user(), $edit);
       drupal_set_message("Successfully Register. Please check your Email for login    deatils.");

     }

```

---
Tags: users
---


# Question
Title: how view count number vote fivestar on comment?
it like this. examp:

* 5 star \***** (15)
* 4 star \**** (150)
* 3 star \*** (2)
* 2 star \** (0)
* 1 star * (12)

now.

* 15 is number comment vote 5star for node this
* 150 is number comment vote 4star for node this
* 2 is number comment vote 3star for node this ....

This examp other:

# Answer
You can check this page at Drupal.org: Fivestar 7.x: Creating a User Comment/Rating and Average Rating for a Content type.

If you use the Fivestar voting module, your content will have own rating and reviews, and each contents each comment will have its own rating and review.
> 0 votes

---
Tags: views, comments, nodes, rating
---


# Question
Title: Views3 date field (filter) treated as string
I am used to getting int operators(like less then) in views when using date api fields but now I'm getting string operators so I can't filter on dates(like now). When creating a filter on 'post date' for ex. it works just as usual. It actually just looks like when you turn off date views.

It's a drupal 7 installation with views3 and the latest date api.

I don't know what went wrong or this is a bug but I can't seem to fix it.

# Answer
> 0 votes
In the Date project there is submodule called "Date Views". Enable this and the operators you're looking for will appear.

---
Tags: views, datetime
---


title: Assign user survey created by webform

text:
# Question
Title: Assign user survey created by webform
I've created a survey using the webform module. I now want to assign a set of users to take the survey. Does anyone have any recommendation on how I should go about doing this.

# Answer
Create a Role and assign set of users to that Role. Now go to your Webform configuration settings (Form Settings) \>\> Submission Access and assign newly created role to it.

For example in the following example I've created a 'moderator' rule and assigned users (those I want to assign users to take survey).

That's it. Now users under "Moderator" role only can access the form.
> 1 votes

---
Tags: users, nodes, webforms, quiz
---


# Question
Title: How can i add our own field in Ubercart billing address?
I have used Ubercart in my project. I would like to add my own one field in Ubercart Address field.

How can I?

Does any one had same experience?

# Answer
> 1 votes
Entire order is an object, so having some extra fields for order object from checkout level will solve this.

Extra Fields Checkout Pane module will help to add additional fields.

---
Tags: ubercart, entities
---


title: How to reinstall Drupal?

text:
# Question
Title: How to reinstall Drupal?
Can anyone tell me the best possible way of how to reinstall Drupal 7 from ubuntu 13.04? After googling came through many options that is making me confused!

# Answer
> 4 votes
You can do it with the following steps too :

1. Go to `http://localhost/phpmyadmin`
2. Select your database and drop all the tables
3. Go to `http://yoursite.com/install.php`

Or you can use : `drush si`

And done.. :)

# Answer
> 0 votes
Drupal Community Documentation - Installation Guide

or if you want to install it from the Ubuntu packaging system, you can execute this to remove Drupal:

```
sudo apt-get --purge remove

```

Then execute this to install it again.

```
sudo apt-get install drupal

```

---
Tags: 7, installation
---


# Question
Title: Form with Site Content that Creates an Entity with User Created Content and Site Content Combined
Webform and EntityForm do not seem to have the ability to create entities.

Please help me find modules that can be used to build a Planning Form that creates User Created Planning Entities for the use case below. Any further tips or modules for the bonus features would also be greatly appreciated.

**Minimally Viable Product:**

At its core this is a way for Authenticated Users to plan for a conference. The user views videos, pictures and text then saves notes about the videos, pictures and text, and later accesses an entity they created with the original videos, pictures and text grouped with their user created content. So a video about networking at a conference has a form below it for the user to make notes they can see later and know it’s notes for that particular video.

**Parameters:**

* Three Entity Types:
    1. Conference Node Content Type (that provides access to the Conference Planning Form)
    2. Conference Planning Form (for viewing standard Drupal Fields and saving user created content)
    3. User Created Conference Planning Entity (for future viewing and editing of Conference Planning Form site admin and user created content)
* The user does not need to actually book the event through this feature. This feature is to help them stay organized.
* If there is a way to have the user save their User Created Conference Planning Entity on the front end that would be great but not required.

**Use Case:**

1. User finds a Conference Node they are interested in.
    1. User selects a button to plan for the conference and they are taken to a standard site wide Conference Planning Form.
2. The Conference Planning Form (hopefully an entity) contains instructions and tips created by the site admin (such as videos, pictures, links or text), and a form field the authenticated user can use to create notes (links and text) grouped with the field or a group of fields the site admin created that display on the Conference Planning Form to generate a User Created Conference Planning Entity.
    1. The authenticated user fills out the form fields they would like to use and saves the Conference Planning Form to create a User Created Conference Planning Entity which is added to their list of User Created Conference Planning Entities.
3. Later the user can access the User Created Conference Planning Entity they created to add content to the form entry fields
4. The user can access the User Created Conference Planning Entity they have created to view notes they created.

**Bonus Features:**

* After saving the Conference Planning Form and when viewing the User Created Conference Planning Entity the user created, the original content from the Conference Planning Form is displayed and grouped with each form field of content the user created the first time they saved Conference Planning Form and created the User Created Conference Planning Entity.
* The ability to for the sited admin to provide site wide generic Conference Planning Form or a custom Conference Planning Form for any Conference Node.
* The ability to automatically displays fields on the Conference Planning Form referencing the Conference Node the user came from with the referenced fields (possibly with Entity Reference module) grouped (possibly using Field Group module) with a form field the user could add notes to.
* A site admin created task list that can be on the Conference Planning Form that would also show on the User Created Conference Planning Entity that could be checked off (possibly using the Flag Module.
* The authenticated user can create a custom task lists on the User Created Conference Planning Entity that they can checked off.

# Answer
check out Flexiform module. This can be used for adding/editing entities using custom form. It has its own drawbacks though. So far I couldn't find a way to create multi-step form using the Flexiform. The documentation says it is WIP. Not sure if it is available now.

Here is the article with the comparison on multiple form modules.
> 0 votes

---
Tags: entities
---


# Question
Title: display submitted variable - where does it originate
The following code appears in node.tpl.php and file\_entity.tpl.php, but strangely enough not in comment.tpl.php.

```
  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

```

In node.tpl.php $display\_submitted it true, but in file\_entity.tpl.php it is false. I am using Zen 5.x theme.

Why is it different? I would assume it is some theme setting but I can't find it.

Where is this variable initialized? And do I just set it to true in preprocess\_file\_entity?

# Answer
> 1 votes
$display\_submitted is the author and date information of a node / file entity.

If you go to the node type page (e.g. admin/structure/types/manage/article) you can manage the display of it in the 'Display settings' vertical tab (see First Step in this blog post)

# Answer
> 1 votes
For completeness, I have added a patch to File Admin's issue queue. Patch adds the vertical tab to file entity's GUI edit page and sets the variable: `'file_submitted_' . $file_type`, which is read by `template_preprocess_file_entity` in `file_entity.module`.

---
Tags: nodes
---


# Question
Title: Updates: keep panels pages, views, etc.. updated via hook_update_n?
im having a little trouble keeping a project update.

I track the code via a private git repo, and for each update I follow those steps (first on stagin, then on production):

* update all the 3rd pars modules (from drupal.org)
* Update database (via drush updb)

Then if everything is ok:

* update my modules (via git repo)
* update database (drush again)

All works perfectly, except for pages/views exported via Features module: in my module i hav a function like this:

```
/**
 * Implements hook_default_page_manager_pages().
 */
function mymodule_default_page_manager_pages() {
    // Second page...
    $page = new stdClass();
    // page definition, display, etc..
    $pages['page_machine_name'] = $page;

    // Second page...
    $page = new stdClass();
    // page definition, display, etc..
    $pages['page_machine_name'] = $page;

    return $pages;
}

```

The structure is the same for views.

I noticed that if i update that function changing something in a previous declared (and imported) page (add a pane, change a configuration on a content, etc..), this one wont get updated! (yeah, i flushed the cache different times both via UI and via drush)

Am I doing something wrong? There is a specific way to update those elements?

# Answer
> 1 votes
Well, this can not be the best solution but it works:

```
function mymodule_update_7001(&$sandbox) {
  // Views.
  if (is_callable('views_save_view')) {
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_delete_view($view_object);
    }
    // Rebuild it.
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_save_view($view_object);
    }
  }

  // Pages
  module_load_include('inc', 'page_manager', 'plugins/tasks/page');
  if (is_callable('page_manager_page_save')) {
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_delete($page_object);
    }
    // Rebuild it
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_save($page_object);
    }
  }
}

```

Basically just keep updated the views and pages definitions (`views_default_views` and `default_page_manager_pages`), the delete and rebuild them.

Obviously, this remove all customizations done via the Drupal's UI, so only do it for the views and pages you need to update!

---
Tags: 7, chaos-tool-suite, updating
---


# Question
Title: Give permission to translate a specific language
I want to give an editor the permission to translate only (a) specific language(s). By default a user can translate content to all available languages.

Any ideas?

# Answer
There is an awesome module for it... Translation Management

> You can specify that a user can only translate from English to Spanish and another user can translate from English to French and you can also have a translation administrator to maintain translation jobs.. And it provides a beautiful interface for it.. There is a Guide for it too..
> 1 votes

# Answer
Download the patch from HERE.

This patch changes all `hook_perm()` .

```
<?php

  $perms = array(
    'permission internal name' => array(
      'title' => t('Permission title'),
      'description' => t('The permissions does this and that.'),
    ),
}

```

?\>

Read the comments for better understanding. Read Here.
> 0 votes

---
Tags: users, i18n-l10n
---


# Question
Title: Primary menu not showing when lanugage is changed?
I have installed following modules :

1.Locale 2.Content Translation 3.Internationalization 4.Block translation 5.CCK translation
6.Content type translation 7.Menu translation

I added Arabic language .po file using admin/build/translate/import. I added one menu item for English and another menu item for Arabic in primary links. The menu items added for English are displayed on a node view page (when English is selected from language switcher) but the menu items added for Arabic are not displayed on a node view page (when Arabic is selected from language switcher).

# Answer
> 1 votes
Since Menu items are user created the Locale module cannot translate them all.. You have to manually create translation for each menu item for both the languages and it maps according to the language.

---
Tags: 6, i18n-l10n
---


title: Drupal user registration form

text:
# Question
Title: Drupal user registration form
I just want to do somthing without using module like profile2, so here is my requirement.

=\> theme user registration form for e.g. I already have a beautiful user registration form as static html template which use bootstrap classes for css so how can I implement this html template in my drupal registration form..

=\> In login form I want to remove tabs LIKE create new account and request new password and enstand of these tab I want to give like just before login button.

let me know if anything not clear.

# Answer
> 1 votes
**1. theme user registration form**

implement hook\_theme:

```
function MYMODULE_theme()
{
  $return = array(
    'my_custom_registration_form' => array(
      'render element' => 'form',
      'template' => 'my_custom_registration_form'
    ),
  );

  return $return;
}

```

implement hook\_form\_alter:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{
  //dpm($form_id);
  if ('user_register_form' == $form_id) {
    $form['#theme'] = 'my_custom_registration_form';
  }
}

```

create `my_custom_registration_form.tpl.php` file in MYMODULE directory, clear the cache, check if it works;

```
<?php dpm($form) ?>

```

copy html from your static file (just form part), put it into `my_custom_registration_form.tpl.php`, example (this will be different in your case):

```
<div class="col-md-4">
  <div class=""><?php print render($form['DESIRED_FIELD']) ?></div>
</div>
...

//render other fields (hidden fields), without them submit won't work
<?php print drupal_render_children($form) ?>

// or you can render them manually

// <?php print render($form['form_build_id']) ?>
// <?php print render($form['form_token']) ?>
// <?php print render($form['form_id']) ?>

```

**2. In login form i want to remove tabs LIKE create new account and request new password** \- you can do it with CSS, or by removing `$tabs` variable from page template (you can create specific page template just for login page),

**3. enstand of these tab i want to give like just before login button** \- with hook\_form\_alter fnction you can add other fields (manage theme) to the form

P\>S: `dpm()` \- is from Devel module

# Answer
> 0 votes
For theming of your form :

1. Impletement `hook_form_alter`
2. Add the classes you want to any of form element like `$form['element_name']['#attributes'] = array('class' => 'your_class');`

To Hide Tabs :

1. You can do this with css.
2. or by creating a `page.tpl.php` for user register page.

# Answer
> 0 votes
You can use LoginToboggan module for your requirements. `Optionally combine both the login and registration form on one page.`

Elseif you wants to remove create new account tabs.

Go to admin/config/people/accounts and change " Who can register accounts? " to admin only.

---
Tags: theming
---


# Question
Title: Scald : How to add several medias to a node using entity metadata wrapper?
I'm looking for a solution to my problem that is pretty simple in fact. I'm on an importing task in which I have to create programmatically a node and then populate all its fields.

As we're using the Scald module, we can add several medias to a node. But I can't figure out how to associate several medias to a node ?

I tried the following :

```
foreach ($file_atoms as $i => $atom) {
    $node_wrapper->field_atom[$i] = $atom->sid;
}

```

or :

```
foreach ($file_atoms as $i => $atom) {
    $node_wrapper->field_atom[$i]->set($atom->sid);
}

```

But I get the following error :

> Error: Cannot use object of type EntityDrupalWrapper as array

I followed the doc on this page but it does not seems to work..

Can somebody help me ?

I'm encountering the same problem with taxonomies : I'm not able to set multiple values to the node wrapper.

# Answer
> 0 votes
Your issue is that your `field_atom` field is not configured as multiple.

When it's not, an `EntityDrupalWrapper` object will give you direct access to the field, instead of having to go through the `0` delta.

Just fix the `field_atom` options to accept multiple medias, and your code will work fine.

---
Tags: entities, media, scald
---


title: How to create a simple vote button

text:
# Question
Title: How to create a simple vote button
I'm trying to create a voting option for the nodes in my website. I want the voting to look like this

The users click on the vote button and the number increases.

I have tried using the Rate module but it's not working with views or display suite. Is there any other module that I can use which will help me achieve this.

# Answer
> 1 votes
you can use Rate module, and since you are using display suite, you can integrate it with it for nodes like so:

1. Create a rate widget at `admin/structure/rate`
2. Using Display Suite module, at the bottom of page, click on `Custom fields`
3. Click on `Add a code field`
4. Fill all the fields and check `Nodes` and on Code field copy and paste this:

$widget\_id = '1'; print rate\_generate\_widget($widget\_id, 'node', $entity-\>nid);

**remember to open and close PHP tag before and after the code, I can't paste that here.**

5. Hit save and now you can see there's a new field added to the list of fields you previously had on your `Manage Display` Page.
6. Re-Arrange the field to where you want it to be displayed and you are good to go.

# Answer
> 1 votes
The Plus One Module (in conjunction with the Voting API) should do what you're looking for.

> \[This module provides\] a simple digg-like voting widget for content that uses Ajax.

Here is a demo I put together for another question.

---
Tags: 7, rating
---


# Question
Title: How to get all rows from a database table?
I have the table where I store uid column. I want to get all the values from that table, but I only get the frist element.

My query:

```
$sql = db_select('voting_nomination_counter', 'v')
->fields('v', array('uid'))
->execute()
->fetchAssoc();

```

Where is my problem?

# Answer
DatabaseStatementBase::fetchAssoc fetches the next row and returns it as an associative array.

```
$query = db_select('voting_nomination_counter', 'v');
$query->fields('v',array('uid'));
$result = $query->execute();
while($record = $result->fetchAssoc()) {
  print_r($record);
}

```
> 9 votes

# Answer
check with this

```
 $query = db_select('voting_nomination_counter','v');
 $query->fields('v');
 $results=$query->execute()->fetchAll();
 print_r($results);

```
> 6 votes

# Answer
You may use this for fetching all records. Remove condition if you don't want to add.

```
<?php
    $query = db_select('data');
    $query->fields('data', array('LivingArea', 'Postalcode', 'Street'));
    $query->condition('Postalcode', $postalcode);
    $result = $query->execute()->fetch();
    drupal_set_message($result->street);
    drupal_set_message($result->livingarea);
?>

```
> 0 votes

---
Tags: database
---


# Question
Title: How to examine existing field values and modify other field in hook_form_alter?
I have a content type with a bunch of fields attached. When displaying the node edit form I want to hide or display one field ( using $form\['some\_field'\]\['#access'\] = FALSE; ) if another field has a specific value.

I am using hook\_form\_alter() and would expect to find existing field values within $form\_state\['values'\] but this key isn't present even though the form fields do contain existing previously saved field values.

What am I missing ?

Thanks

# Answer
In node edit form `$form_state['node']` contains full node object , from which will get the existing field values.
> 2 votes

# Answer
As far as I know `$form_state['values']` is for the submitted data, I'm not completely sure if it'll be present if some invalid data is submitted.

Check the `$form` array instead for the default value of the desired field, then use the states to add some behavior.
> 0 votes

# Answer
Instead of trying with new code you can try with Conditional Fields module

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

or

if you still want try with code then you can **use ajax wrappers with change events** in this way

```
  $form['some_field']=array(
                '#type' => 'select',
                '#title' => 'location',
                '#options' => array(1,2,3),
                '#default_value' => 1,
                '#description' => t('select your news location.'),
                '#ajax' => array(
                        'event' => 'change',
                        'callback' => 'some_call_back_function',
                        'wrapper' => 'city-term',
                        'method' => 'replace',
                        'effect' => 'fade',
                ),
                );

```

and with callback function you can rebuild form with **form rebuild**.
> 0 votes

---
Tags: forms
---


# Question
Title: How to redirect from node view to node edit page in a view?
I need on of the views in my Drupal design, which is using node title linked to the node content view, just redirect form **node content view page** to that **node edit page**.

How would it be possible? If it needs coding please write the code. Thanks

(My Drupal version is 7.x)

# Answer
Steps to achieve:

Add new field: **'nid'**

* Add nid field to view above the title field.
* Exclude nid from display.
* Goto arrangement and put it above the title field, so that it can fetch it.

Change to existing field: **'title'**

* Open title field settings.
* Uncheck Link this field to the original piece of content.
* Expand `REWRITE RESULTS` section.
* Check `Output this field as a link checkbox`.
* Put `node/[nid]/edit` to the `Link path` input.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: How to alter search query to include custom fields?
How can I alter the query for user search (using normal Drupal search) so that instead of searching only email and username, it will also search custom user fields (from fields module)?

# Answer
For the normal Drupal search you can do so by defining a **custom search type** in a module.

Use hook\_search\_info() to define your custom search type & hook\_search\_execute($keys = NULL, $conditions = NULL) to create or extend your search query.

More available hooks can be found at the Drupal's Search interface or by looking up the **search** contrib module under **yourdrupal\modules\search\search.api.php**
> 1 votes

# Answer
What you need to do is install the Search api module

And upon enabling the module, go to **admin/config/search/search\_api**, and click add index. Add an index of item type user. Once that is done all custom user fields will be listed with a checkbox in front of them. Select the fields you want indexed and this would then make custom user fields searchable.
> 0 votes

---
Tags: users, search, database
---


title: How to alter view query

text:
# Question
Title: How to alter view query
I am just looking for altering select query, created by any view just before its execute. For e.g. I want to add some manual filter which I can't add from Views' UI.

# Answer
You are likely looking to use `hook_view_query_alter`, additionally you might want to look into some related questions on Drupal answers How do I use hook\_views\_query\_alter()?.
> 1 votes

---
Tags: views, 7, hooks
---


# Question
Title: How to show the contents of view page from template?
I'm trying to theme a view page on Drupal 7, I used views-view--name-of-page.tpl.php

So now it's blank right? I invoked some blocks on the view page and added some divs to style but I can't seem to show the contents of the view page.

I have tried

```
print render ($content);
print $content;
print $page;

```

etc.

Like what we do for node. but it's not working on views template.

Can anyone suggest me?

# Answer
In this type of template file you can not use
print render ($content);
print $content;
print $page;

Instead of you can use In **page template** file you can only use **$rows** variable for display output. print $rows; for display result.
> 0 votes

# Answer
In view Advanced Section `Theming information` click `Rescan template Files` for your theme.
> 0 votes

# Answer
In the Views-\> Advanced -\> Other -\> Theme: Information -\> You need to rescan template files.

Then in your tpl

```
foreach ($view->style_plugin->rendered_fields as $key => $value) {

print_r($value);

}

```

$value will render the required values.

Hope this helps.
> 0 votes

# Answer
Neither `$content` nor `$page` won't work for Views templates, these variables initialized by other theme system functions (for ex. `template_preprocess_page`); Views provides own (different) variables, you can find them here. If you want to see what variables are available for you to use, you can open `Advanced - Theme:Information - Display output` and look at its comments..
> 0 votes

---
Tags: views, theming
---


# Question
Title: Drag & drop upload plugin, how to make it multiple
I am trying to use this module to upload multiple files into a schemma that I created (in a separated module),

https://www.drupal.org/project/dragndrop\_upload

```
$form['file'] = array (
'#type' => 'dragndrop_upload',
'#title' => 'Test',
'#description' => 'Test',
// This settings allows to drop multiple files at once.
'#attributes' => array (
        'multiupload' => '1',
'cardinality' => '10')
);

```

Seems to work great but it seems to ignore the 'multiupload' and the 'cardinality' arguments,

Any idea what am I missing?

# Answer
It suggests you need this module; from the README file and project page;

> Multi-upload support will be enabled if Multiupload Filefield Widget module exists.
> 1 votes

---
Tags: 7, entities, files
---


# Question
Title: How do you add information text to a Drupal 7 form?
I have this:

```
$form['rate_the_room']['room_rating'] = array(
  '#type' => 'radios',
  '#title' => 'How would you rate the room you stayed in?',
  '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5),
  '#default_value' => isset($values['room_rating']) ? $values['room_rating'] : NULL,
);

$form['next'] = array(
  '#type' => 'submit',
  '#value' => t('Next')
);
return $form;

```

This will produce a radio button block where you can select the rating for a room and then a submit button right after it. I want to be able to add a block of text inbetween these two elements. That block should be:

```
<div id="test">Hello</div>

```

Is this possible or would I have to somehow make it part of the actual fields?

# Answer
To add plain text to forms, you use `#markup`\- see the Form API.

```
$form['rate_the_room']['hello'] = array(
  '#markup' => '<div id="test">Hello</div>',
);

```
> 4 votes

---
Tags: forms
---


# Question
Title: Create entities when user account created
I am looking for a hook to fire off an Entity creation method (for an unrelated item that pertains to the user) when a user registers for the site. I'm divided between hook\_form\_user\_register\_form\_alter and hook\_user\_insert. What's the best approach here, and i'm wondering which one is the best to use here.

# Answer
> 0 votes
After doing my due diligence, I chose to use the hook\_user\_insert() to extend my logic for the entity creation. It fires when a new user is verified and added to the users table/entity.

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


title: Implementing Google CSE Results Code

text:
# Question
Title: Implementing Google CSE Results Code
I'm trying to implement the Google CSE Search Results code on a page that I created called search-results. When I implement the code using CKEditor (PHP mode) and save the page, the code does not show up when the page is rendered?

I was able to enter the Search box code no problem but I cannot seem to get the search results code to load on a page? I created a static html page and it works fine but will not work when I create the page in CKEditor. I also tried creating a block but this did not work?

How can I get the Google CSE Search results code snippet in a Drupal page? I'm not interested in using any of the Drupal modules for CSE as I don't like the way they render the results.

# Answer
You should be using Google Custom Search Engine Module instead of embedding the code. Using this module would give you better integration option.

Additional Info: Avoid using PHP Filter as its creates security risk.
> -1 votes

---
Tags: search
---


title: How to rebuild registry table?

text:
# Question
Title: How to rebuild registry table?
I've truncated `registry` table, because of the other problems, but now I have problem rebuilding the `registry` table based on the files listed in the database.

I'm calling `registry_update()`, `_registry_update()` or `registry_rebuild()` to do it:

```
drush eval "registry_rebuild();"

```

But then I've the following error which appears:

> Fatal error: Class 'SelectQueryExtender' not found in includes/pager.inc on line 15

By default (on `system` module install) `registry` table is empty, so how Drupal fills that table with the proper default data?

# Answer
> 15 votes
The absolutely easiest way to do it, is to enable any module, as that will do it for you. Of course, if you need to rebuild the registry, generally speaking the UI might be unavailable, but `drush en [modulename]` might be all you need.

If that's not enough, Registry rebuild makes it trivially easy to rebuild the registry. The easiest way to do it, is to install it as a drush extension.

Install the extension, and run `drush rr`.

The module page has detailed installation instructions and also shows how to run it without drush if necessary.

# Answer
> 10 votes
This can be fixed either by reinstalling Drupal or by copying the table from an ideally fresh installation of Drupal into your broken instance.

Or you can try the following workaround (only do it when your Drupal instance is already broken):

1. Backup the old registry table first (just in case):

```
drush sqlq "CREATE TABLE registry_bak LIKE registry; INSERT INTO registry_bak SELECT * FROM registry;"
drush sqlq "CREATE TABLE system_bak LIKE system; INSERT INTO system_bak SELECT * FROM system;"

```
2. Clear the bootstrap cache and registry table.

```
drush sqlq "TRUNCATE cache_bootstrap; TRUNCATE registry"

```
3. Insert the basic data into registry table:

```
drush sqlq 'INSERT INTO registry (name, type, filename) VALUES ("SelectQueryExtender", "class", "includes/database/select.inc"), ("DrupalDefaultEntityController", "class", "includes/entity.inc");'
drush eval "registry_update();"

```
4. Clear the caches:

```
drush -y cc all

```
5. If clear caches in 4. failed, because of some other missing classes, you can either:

a) Add the missing classes manually, in example:

```
$ drush -y cc all
Fatal error: Class 'Entity' not found in profile2.module on line 593
$ grep -Rwl "^class Entity" .
./sites/all/modules/entity/includes/entity.inc
$ drush sqlq 'INSERT INTO registry (name, type, filename) VALUES ("Entity", "class", "sites/all/modules/entity/includes/entity.inc");'
$ drush -y cc all # testing...
# If Fatal error:, repeat 5a. again.

```

or:

b) Try to disable these failing contrib modules (e.g. profile2, rules) by:

```
drush sqlq 'UPDATE system SET status = 0 WHERE name = "failing_module"'

```

and repeat the steps starting from 4.
6. If something is more broken than it was, you can restore your tables to the original point (which was done in 1. step) by:

```
drush sqlq "TRUNCATE registry; INSERT INTO registry SELECT * FROM registry_bak;"
drush sqlq "TRUNCATE system; INSERT INTO system SELECT * FROM system_bak;"

```

and try again.

See also: How to move installed modules from /sites/all/modules/\* to /sites/all/contrib/modules/\*

---

Rebuilding `registry` table can be also achieved by the following script ran in Drupal webroot:

```
grep -ERo "^(\s+)?(abstract )?class (\S+)" . | tr ':' ' ' | sed "s/abstract //g" | awk '{print "INSERT INTO registry (filename, type, name) VALUES (\x27"$1"\x27,\x27"$2"\x27,\x27"$3"\x27);"}' | $(drush sql-connect) -f

```

Thanks to Mike's help with regex.

---
Tags: 7
---


# Question
Title: how rename series legend in chart created by views
I created a chart page by using Views. But the legend is always Series 1, Series 2. Not using the label data.

I tried to find the option to replace the label "Series" with the label from the data, but I could not find it. Anyone can help me how to use the label of the data instead of "Series"

# Answer
Finally I can find the answer, after keep on trying: I have to switch to custom label. Just change to custom label in the field.
> 2 votes

---
Tags: views, charts
---


# Question
Title: Lightbox2 doesn't open html content and links
I installed Lightbox2 module and I tried to link an image to a webpage, say `google.com`, this is my code

```
<a href="https://www.google.com/" rel="lightframe[][This is Google]"><img  src="<?php print $base_url;?>/sites/all/themes/MY-THEME/image/fp/map.jpg"></a>

```

but it displays nothing in Lightbhox. This is the print screen of the Lightbox using Firebug

as you can see there is nothing in body.

# Answer
> 1 votes
This link works to get google search in the ligtbox:

```
<a href="http://www.google.com/custom?q=&btnG=Search"rel="lightframe">Search</a>

```

I got it from this post: How to show google.com in an iframe?

---
Tags: navigation, javascript
---