title: Gmap not displaying

text:
# Question
Title: Gmap not displaying
I have Gmap and Location module. I have created a content type and also added a field **location** with term reference(Taxonomy term). I have just added a content and selected one location. But I can't see the *google map* in the content. I have created taxonomy term with location detail.

# Answer
> 0 votes
you can view it go to **content-type\>\>manage display\>\>specific field** change display setting :

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


# Question
Title: How do I add a view with a module when installing a module?
In Drupal 8, I want a view to be created when a module is installed.

I have already used the Features module to export the view, so I have the yml file that creates the view. I can't find what to include in order for this view to be created on installation of my module.

How can I achieve this?

# Answer
> 6 votes
If you have the YAML file, you can put this in: `/modules/your_module/config/install`.

Then the View will be imported, when the module is installed (but there will be no updates, if you change the YAML file, it will only be imported once).

Btw. to export the YAML file you don't need Features, you can do this with core (`admin/config/development/configuration/single/export`).

So you can remove the line `uuid:` from the YAML file, this is only valid for re-importing the YAML to the same or a cloned site.

---
Tags: views, 8, features
---


# Question
Title: Rendering a content of a page using tpl php
Our custom theme has `page.tpl.php` which takes care of the whole site. But I have a page which actually needs to display a collection of nodes. I have written a custom *`page--url.tpl.php`* where the *url* is the path for the page in question. But this way overrides the whole `page.tpl.php`.

What would be best method so that I just need to display my custom content when my `page.tpl.php` calls `<?php print render($page['content']); ?>`? Will modules be the only way? from which I will create my block and add it to the page?

**Note:** We like to have COMPLETE control over our page. And we are getting rid of views from our site.

# Answer
> 4 votes
You can use the same template, add your custom content to a variable in **template\_preprocess\_page** function.

```
function template_preprocess_page(&$vars, $hook) {
  $path = current_path();
  if ($path == 'url') {
    $vars['custom_content'] = "your custom content";
    $vars['theme_hook_suggestions'][] = 'page__url';
  }
}

```

Then print the variable after the content.

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

```

# Answer
> 3 votes
Sure your custom `page--url.tpl.php` overrides `page.tpl.php`. That's Drupal's template hierarchy. The more precised template will overwrite the broader template. That's why you may simply duplicate `page.tpl.php` first, rename it, and then start to change it the way you want.

But honestly that really isn't the ideal approach for this. You absolutely should have a look at Views – maybe the most loved Drupal module so far. With this you can create a views page with a fixed URL that will list specified content in a specified way. Additionally you still can do templating with View's templates if you really need it. But you may be happy already with what Views will let you do through its UI.

Also you are not bounded to the UI. Only enable the parent module and write your views in code when you prefer having everything in custom modules.

# Answer
> 2 votes
If you want to customize your node page then you can write tpl file for that node page. If your node ID is 246 (node/246), then you write `page--node--246.tpl.php`

Otherwise you can display collection of nodes by creating views and render that view in your page.

---
Tags: theming
---


title: Back button in multistep form

text:
# Question
Title: Back button in multistep form
I am facing an issue with the Multistep module in Drupal 7. I used a custom module to build a *session\_store* multistep form with the help of the mforms\_example module. Except for the **session\_store\_example** store key, other forms like *ajax\_forms* and *fs\_store* have the back button implemented.

I tried to compare the form implementation of other storekey forms with the *session\_store* form, but it didn't help.

Is there any way to add the *previous* button along with the *next* button in the *session\_store\_example* form?

# Answer
The first part may seem confusing, but we are just gathering what the user has picked before (in case they went to another portion of the form and came back here). Here we are doing the same thing as the other form, but now with two submit forms. One will bring you to the next form and one to the previous form.

```
/**
 * Form that is called second
 */
function multiform_second_form($form, &$form_state) {
  // Make sure the default values for the checkboxes are set correctly.
  if (!empty($form_state['storage'])) {
    $values = $form_state['storage'];
    if (!empty($form_state['storage']['food'])) {
      foreach ($form_state['storage']['food'] as $value) {
        if (!empty($value)) {
          $default_values[] = $value;
        }
      }
      if(empty($default_values)) {
        // Storage and experience are set, but no values were selected.
        $default_values = array();
      }
    }
    else {
      // Storage was set, but experience wasn't.
      $default_values = array();
    }
  }
  else {
    // Storage is not set.
    $default_values = array();
  }

  // Set options
  $checkboxes = array(
    1 => 'Pizza',
    2 => 'Hot Wings',
    3 => 'Subs',
    4 => 'Salads',
    5 => 'Garlic Bread',
    6 => 'Pasta',
    7 => 'Cake',
    8 => 'Ice Cream',
  );

  $form['additional'] = array(
    '#type' => 'fieldset',
    '#title' => t('Additional Information'),
    '#collapsible' => FALSE,
  );
  $form['additional']['food'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Food you like'),
    '#options' => $checkboxes,
    '#default_value' => $default_values,
  );
  $form['additional']['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company'),
    '#size' => 32,
    '#default_value' => isset($values['company']) ? $values['company'] : NULL,
    '#required' => TRUE,
  );
  $form['additional']['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Additional Information'),
    '#description' => t('Please provide information about your job'),
    '#size' => 32,
    '#default_value' => isset($values['message']) ? $values['message'] : NULL,
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('multiform_second_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
  );
  return $form;
}

```

for more details custom multi step forms
> 0 votes

# Answer
you can use the `hook_form_alter()` Check the form id for your form and add the back button to it
> -1 votes

---
Tags: 7, forms
---


# Question
Title: Smart filter (like webshop) for selection of content possibly using taxonomy
I'm currently working on a website which needs to display paintings. The paintings have certain attributes: the year-of-painting/painter/background color/material. To get the best user experience i want to let them navigate, like one would browse a webshop.

I like the one on http://www.debijenkorf.nl/action/ViewParametricSearch-SimpleOfferSearch?SearchTerm=moleskin very much.

Are there modules in drupal which i can use, that give me such a smart filter functionality (maybe with taxonomy?)

# Answer
> 0 votes
That's usually referred to as a *facetted search*.

Drupal's most oft-used facet solution is probably a combination of:

* Search API
> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc.
* Facet API
> The Facet API module allows site builders to easily create and manage faceted search interfaces.

The module page for each has links to tutorials/examples; you can make some pretty powerful sites with just those two modules, but there are plenty of add-on modules too to augment/improve the basic functionality.

Be prepared for a bit of a learning curve, it takes a little while to get your head around both of the above modules. Diving in and clicking everything on a dev site to see what happens would be the best initial approach IMO.

---
Tags: taxonomy-terms
---


# Question
Title: Node Create/Edit Form - Multistep with dynamic fields
Our site has different type of articles. Based on the type selected, the fields displayed to the user are varied. The ask is to create a *multi-step* form and include type field on step 1. Based on the type, subsequent steps and fields included in those steps need to vary.

An important ask is that they need the ability to change the type of the article after it has been created. So on day 1 they might create an article with type "*single page*" but later change it to "*multi page*" (Multi-page article has all fields in single page plus additional fields).

I looked at Multistep, msnf, webform and webform\_conditional modules etc, but they didn't seem to provide the functionality I need. Is creating this using *Form API* the best approach? Any suggestion?

**UPDATE1**

Another important requirement: An article could have multiple (0 or many) sections and each section could have multiple subsections. What is the best way to model the content type? Create content type *Section* and *Subsection* and then use node references (article will have a nod reference to section; section will have a node reference to subsection)? Using node references, can one to many relationship be implemented?

# Answer
There are three module(may be two in your case), which can together to achieve what you want in D7. I have done this & client use it on daily basis..

Field Group

Multi Step

Then I have used Conditional Field module to have fields dependent on one another & it works great.

If you find any error in setup, please try the issue queue for patch.
> 1 votes

# Answer
You can start from the basic multiple step form using the Examples for Developers module in Drupal.

> The Examples project contains many modules which hopefully illustrate best practices for implementing various Drupal APIs. These modules can be enabled individually, and will typically add menu items to your site, which should guide you through their features. You can then look through the code to see what they are doing.

In the Example module, there is sub-module "form\_example", that is for your need. =\> Tutorial 8: Basic multistep form
> 1 votes

# Answer
You can also try the following modules:

1. Multistep Nodeform
2. Conditional Fields
3. Field Group

I have used these modules in one of my project & it works great. Hope these modules works for you.

**Note**: Multistep Nodeform is module for node forms only but works very efficiently.
> 1 votes

# Answer
You need to use Multistep and Conditional fields modules for the tasks mentioned.

And yes **Node reference supports one to many node reference**, you just need to add a node reference field in your content type and select the option "Number of values" as per your requirement.
> 0 votes

# Answer
You can try the route module

Route module enables the construction of wizard like journeys using Panels. It's mostly useful for developers that require high levels of configurability and flexibility for their multistep forms. Use of Panels gives this flexibility.

To taste an example functionality, please enable route\_example module and navigate to /route-example/step-one.
> 0 votes

---
Tags: forms
---


# Question
Title: How to configure role to edit only specific nodes by field?
I have a content type named "Event". I created a field named "Type" so I may create different kinds of Events (eg. Courses, Lectures, Conferences). The problem is that each type of Event is administered by different people. And one is not allowed to edit other's content. How is the best way to do this? Or is it better to create a content type for each type of event?

# Answer
> 1 votes
This looks like an ideal case for one of the Taxonomy access modules.

There are several to choose from, though I favour Taxonomy Access Control Lite as it also allows you to grant access to individuals (should the need arise) as well as giving access rights based on roles.

The basic setup would be:-

1. Create a Taxonomy of the different kinds of event that you wish to use.
2. Give each "Event" node a Taxonomy reference field, that references the values from the Taxonomy that you setup in step 1.
3. Install and activate Taxonomy Access Control Lite via your preferred method.
4. Configure the access for each role to the Taxonomy from step 1. via the TAC lite configuration screen. There are options to control the viewing, updating, and deletion of nodes, as well as the visibility of the Taxonomy terms in selection lists - which prevents users creating nodes tagged with event types that they don't have access to.

I hope that helps.

# Answer
> 0 votes
Create less number of content types, as too many content type does not a good authoring experience.

But its very important to identify which content types can be merged to one, its better to have a vision before you do this, Why?

* Because content type is like a folder to files, you would like to keep same kind of files in one folder, as an example you would not like to mix your finance files with HR.
* If you see huge difference in types of fields and configuration on your events, its better to have different content types, rather than one.

Again in case it just a difference of few fields you can easily manage them by field permission module. It gives you permission at field level as which field can be accessed by which role.

And as @Jabelpeeps said Event type can be a taxonomy field, field options for which can be configured to use as per user role using Taxonomy simple access module.

# Answer
> 0 votes
I chose to use Taxonomy Access Control Lite. However, I'm also using the Domain Access module which makes the tac\_lite module not work properly. To resolve the issue, I created a custom module to do this: `function trt5_glue_node_access($node, $op, $account) {
 global $user;
 if(!is_string($node)) {
 if (module_exists('tac_lite')) {
 for ($i = 1; $i <= variable_get('tac_lite_schemes', 1); $i++) {
 $config = _tac_lite_config($i);
 if (in_array('grant_' . $op, $config['perms'])) {
 $tids = _tac_lite_get_terms($node);
 foreach($tids as $tid) {
 $user_tids = _tac_lite_user_tids($account, $i);
 if(!in_array($tid, $user_tids))
 return NODE_ACCESS_DENY;
 }
 }
 }
 }
 }
 return NODE_ACCESS_IGNORE;
}`

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


# Question
Title: file_create_url() equivalent in a javascript file?
I am dynamically loading a script using $.getScript() which works fine, but when using the CDN module it comes from the webserver, instead of the CDN. Is there a way to get the correct CDN path in JS, similar to how file\_create\_url() works?

# Answer
CDN has already done its magic by the time the JavaScript file has been prepared for output, and there are no AJAX callbacks allowing it to do its magic from the JS file itself.

If you do know ahead the name of the scripts you might load (or you can iterate from your theme or module) then the trick is to inject those paths as variables directly in your theme using inline JavaScript. For example, from your module or your theme's hook\_html\_head\_alter method in template.php, to add one file (the method would be the same for a list of files, but an array would best be used):

```
drupal_add_js('var my_js_file_1 = "' . file_create_url(drupal_get_path('theme', 'my_theme') . '/js/file_1.js') . '";' , 'inline');

```

then you can call

```
$.getScript(my_js_file_1);

```

in your code.

The magic is done through the file\_create\_url, which is what the CDN module processes.
> 0 votes

---
Tags: javascript, cdn
---


# Question
Title: Drupal installation in nginx subdirectory
I have a new application that will be made of 2 frameworks yii and drupal 7

Yii framework will be in the root (/)

and drupal will be in a sub directory called admin (/admin)

I have a problem how to config it in nginx,drupal doesn't work,it gives me access denied,or just the home page and no link works

This is my configuration file in nginx

```
server {
        listen 80;
        server_name demo.example.com;
        root /home/www/example;
        index /index.php;

        location / {
                if (!-f $request_filename) {
                        rewrite ^(.*)$ /index.php?q=$1 last;
                        break;
                }
        }
        location /admin {
                root /home/www/example/admin;
                index  index.php index.html;
                try_files $uri $uri/ @rewrite;
        }
        location @rewrite {
                rewrite ^/(.*)$ /admin/index.php?q=$2 last;
        }
        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include        fastcgi_params;
                index /index.php;

        }
         location ~ /\.ht {
                deny  all;
        }

}

```

# Answer
> 2 votes
I had a similar scenario, but in my case I didn't need to define again the root folder for the Drupal installation as you do on `location /admin`.

In my case I only needed to add the nginx directives for the Drupal path:

```
location /admin {
    try_files $uri $uri/ @rewrite;
}

location @rewrite {
    rewrite ^ /admin/index.php;
}

```

# Answer
> -2 votes
If Drupal is in a subfolder, probably all you need is:

```
root /home/www/example/admin;

```

as compared to

```
root /home/www/example;

```

Where "example" is the base site and "admin" is the Drupal folder.

---
Tags: 7, installation
---


title: Installing a site on localhost

text:
# Question
Title: Installing a site on localhost
I have read tutorials and drushcommands site, but I'm missing something...

My desired info is as follows:

* Database name: scratch
* Database username: scratch
* Database password: 1
* Account name: scratch (admin login?)
* Account password: 1 (admin password?)
* Site in English

I have the username set up in PHP my admin, desired website URL is localhost/scratch

My Drush command is:

```
drush dl drupal-7.x
drush site-install --db-su:scratch --db-su-pw:1 --account-name:scratch
--account-pass:1 --account-mail:founder@satearn.com --locale:EN

```

Am I missing something? I'm getting these errors:

> e:\xampp-portable\htdocs\>drush site-install --db-su:scratch --db-su-pw:1 --account-name:scratch --account-pass:1 --account-mail:founder@satearn.com --locale:EN
>
> Command site-install needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
>
> The drush command 'site-install' could not be executed. \[error\]

# Answer
> 2 votes
Use this command to install Drupal.

```
drush site-install standard --db-url="mysql://scratch:1@localhost/scratch" --account-name=scratch --account-pass=1 --account-mail="founder@satearn.com"

```

Note: Move to the folder drupal-7.x folder and run this command from there. This command should be run from the place where your drupal files are located. It would be better just to rename it drupal instead of drupal-7.x for easiness. I tested it right now and its working.

# Answer
> 1 votes
Separate your option values with '=' rather than ':'.

---
Tags: drush, installation
---


# Question
Title: Coding a Load and delete Field Collection with Entity API
I'm trying to delete all values of a multivalued field containing a field collection. I want access with Entity API wrappers. I use this in a custom rule with hook\_rules\_action\_info()

I'm using drupal 7.39 and field collection modules 7.x-1.0-beta8 and

I'm testing this code but doesn't work for me, this node has 2 values in field\_collection

```
$node_wrapper = entity_metadata_wrapper('node', $node);
dpm($facWrapper->field_collection,"Field Collection");
//Prints a EntityListWrapper object
dpm($facWrapper->field_collection->count(),"Field Collection count");
//Prints zero, it should be 2
dpm($facWrapper->field_collection->value(),"Field Collection value");
//Prints array() 0 elements, it should be 2 elements
//And obviously doesn't enter into this foreach, it should enter
foreach ($facWrapper->field_collection as $fc) {
  dpm($fc,"Field collection item");
}

```

The questions are:

* How to load or access to the field\_collection in the entity wrapper way ?
* When I have access, How can I delete ? I want to delete the field\_collection\_item and its reference in the node.

# Answer
Please look into this links it will give your answers:

Example: Programmatically create and update field collection with Entity API

How to properly delete a field collection

Delete field content using entity metadata wrapper
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Views joining/relating a custom table entity to users through a field?
Using Drupal 7 and Views 3 - I have created a custom entity and can view it fine through Views using EntityDefaultViewsController. The Table is a view shared to the drupal database and is constructed like:

```
Table A
------------
id_key
data

```

I have a drupal user field - field\_tableA\_data that contains the same data type/items in the Table A data field (they are not linked in any way - two separate systems load this data - in TableA the data is generated by another system and the User field is loaded by the LDAP module)

I want to make it so that I can make a "View" such that when viewing Table A Items I can also make a relationship to the User entities such that: Table A \> field\_tableA\_data \> User

Is this possible in code and if so how?

Here is some code I have tried and to no avail:

```
class TableAEntityViewsController extends EntityDefaultViewsController {

  /**
   * Edit or add extra fields to views_data().
   */
  public function views_data() {
    $data = parent::views_data();
    $data['tableA']['data']['relationship'] = array(
      'handler' => 'views_handler_relationship',
      'base' => 'field_data_field_tablea_data',
      'base field' => 'field_tablea_data_value',
      'title' => t('TableA Data'),
      'label' => t('TableA Data'),
    );
    return $data;
  }
}

```

and in the module (table A entity I have a hook):

```
function (module)_views_data_alter(&$data) {
    $data['tableA']['table']['join'] = array(
    'field_data_field_tablea_data' => array(
      'left_field' => 'field_tableA_data_value',
      'field' => 'data',
    ),
    'user' => array(
      'left_field' => 'uid',
      'field' => 'field_data_tablea_data.entity_id',
    ),
  );
}

```

The best this gives me though is User:field\_tableA data and no other fields from User - I'm trying to get uid and username.

# Answer
I know this is not timely, but if someone else is looking for an answer:

Assumptions: \- Using Entity API \- Joining to another entity where the entity id is a field in your entity's base table \- It's a one-to-one relationship

1. Add the views controller class to your entity info file function my\_entity\_entity\_info() {

$info\['my\_entity'\] = array( 'views controller class' =\> 'MyEntityViewsController', ... );

2 Extend EntityDefaultMetadataController

```
class MyEntityMetadataController extends EntityDefaultMetadataController {

  public function entityPropertyInfo() {

    $info = parent::entityPropertyInfo();

    // This exposes the fields as references to views.
    $info['my_entity_base_table']['properties']['uid']['type'] = 'user';

   ....
  }
}

```
> 1 votes

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


title: Count of nodes by type

text:
# Question
Title: Count of nodes by type
I am looking for a snippet that lets me display the total count for a specific node type, e.g. "Pages = 167" or "Products = 10630."

What code should I use to achieve this?

# Answer
Here is a function that will return the number of nodes for a specific content type:

```
function YOURTHEME_get_node_count($content_type) {
  $query = 'SELECT COUNT(*) ' .
           'FROM {node} n ' .
           'WHERE n.type = :type';
  return db_query($query, array(
      ':type' => $content_type
  ))->fetchField();
}

```

To use this code in your theme, add the function into your `template.php` and then you can call the function like this:

```
echo 'Pages: ' . YOURTHEME_get_node_count('page');
echo 'Products: ' . YOURTHEME_get_node_count('product');

```
> 34 votes

# Answer
You can use the Views module to do this.

1. Create a new view, remove sort options, fields and other default settings
2. Add a field for "Content: Type"
3. Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
4. Add yet another field for "Content: Type"
5. On the second "Content: Type" field, click "Aggregation settings"
6. Set the aggregation type to "count"
7. The second "Content: Type" should now look like "COUNT(Content: Type)"

That should be it! If needed, adjust some more settings like field labels and row style settings.

Here is an export of such a view, so you can easily import it and try it out:

```
$view = new view;
$view->name = 'nodecounts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Node counts';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Node counts';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
$handler->display->display_options['row_options']['hide_empty'] = 0;
$handler->display->display_options['row_options']['default_field_elements'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['external'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['html'] = 0;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type_1']['hide_empty'] = 0;
$handler->display->display_options['fields']['type_1']['empty_zero'] = 0;
$handler->display->display_options['fields']['type_1']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type_1']['link_to_node'] = 0;
$handler->display->display_options['fields']['type_1']['machine_name'] = 0;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type']['alter']['external'] = 0;
$handler->display->display_options['fields']['type']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type']['alter']['html'] = 0;
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type']['hide_empty'] = 0;
$handler->display->display_options['fields']['type']['empty_zero'] = 0;
$handler->display->display_options['fields']['type']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type']['separator'] = '';
$handler->display->display_options['fields']['type']['format_plural'] = 0;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```
> 55 votes

# Answer
The preferred, programmatic way, is to use the EntityFieldQuery class. Learn why EntityFieldQuery is superior to db\_query().

Here's an example of counting Nodes of type Blog.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node') // grab nodes
->entityCondition('bundle', 'blog') // filter by blog type
->propertyCondition('status', 1) // filter by published
->count(); // count

$result = $query->execute();

```

See similar question.
> 11 votes

# Answer
Using Drush is simple and quick.

```
drush sqlq 'select count(node.nid) as node_count, node_type.type from node inner join node_type on node.type = node_type.type group by node_type.type'

```

This gives output similar to:

```
node_count  type
17  category_2012
20  category_2013
19  category_2014
3   competition
19  entry_2012_breakthrough
89  entry_2012_digitalother
50  entry_2012_directdirect
19  entry_2012_filmsecscn
17  entry_2012_insights
12  entry_2012_outdoor
31  entry_2012_promo
19  entry_2013_breakthrough
100 entry_2013_digitalother
40  entry_2013_directdirect

```

And then if you want filter by a specific type, just use grep like this:

```
drush sqlq 'select count(node.nid) as node_count, node_type.type from node inner join node_type on node.type = node_type.type group by node_type.type' | grep 2014

```
> 11 votes

# Answer
I did this using EntityFieldQuery.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    /* this is the content type machine name */
    ->entityCondition('bundle', 'product')
    /* You can set extra properties using fieldCondition and properties with propertyCondition */
    ->fieldCondition('field_product_status', 'tid', key(taxonomy_get_term_by_name('New')))
    ;

$result = $query->execute();
if (isset($result['node'])){
    $count_of_new_product_nodes = count($result['node']);
}

```
> 7 votes

# Answer
For anyone who is interested, another solution is to use the countQuery method of the SelectQuery class (via db\_select).

```
$count = db_select('node')
  ->condition('type', 'some-type')
  ->countQuery()->execute()->fetchField();

```

However, I do prefer the EntityFieldQuery solution posted by timofey. I am only providing this as a reasonably sensible alternative.
> 3 votes

# Answer
```
SELECT
  COUNT({node}.nid) AS node_count,
  {node_type}.type
FROM {node}
  INNER JOIN {node_type} ON {node}.type = {node_type}.type
GROUP BY {node_type}.type;

```

Use this query in your code
> 1 votes

# Answer
The Node Type count module do the same as you require.

> This module is used to Show a count of nodes of a particular content-type and also number of Users of particular role type.
>
> This module will be used for statistical and dev purposes only.
> 0 votes

# Answer
As a variation to the answer about using the Views module, you could "use" the view that comes with the Charts module. Simply install / enable it, no additional configuration, coding, etc needed. Some more details about this view, included in the Out-of-the-box examples (quote from this link):

> ... navigate to `charts/examples/views` in your site. You should then see a column chart and a pie chart, which are followed by a tabular display also. Both charts and the table display contain data about the total number of nodes for each of the available content types.

Notes:

* As a bonus, apart from the tabular format, you also get a chart to visualise the number of nodes by content type.
* If you like the view, and/or it is close to what you want, you might also clone the view, and then just disable the Charts module again.

Disclosure: I'm the maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

---
Tags: 7, nodes
---


title: Redirect with ? in URL - Drupal 7

text:
# Question
Title: Redirect with ? in URL - Drupal 7
I have Domain Access instaled, but not very sure if that is the problem: I have several domains under the same installation. It all works perfectly, but when I try to enter **www.example.com**/?q=user, it only works for some of the domains, for others it redirects to the home, and this causes other problems.

I have revised .htaccess (even installed a fresh copy), I have seen in the database, and cannot trace the problem, which is completely consistent. When using the same config in localhost (home PC), the problem is not found, so there is some incompatibility that came accros the project.

Any suggestion? I have Clean URLs switched on, but because it depends on any domain config, I cannot be sure because don't know where it stores the data, apparently it does work perfectly (don't understand ? in a content node, for example).

# Answer
> 0 votes
I have discovered the problem. It is a malfunction of module or submodule Domain Locale. If you have a domain whose list of languages does not contain your default language (main site), then it doesn't work. All the project to the trash, months of development ruined.

---
Tags: 7, uri, redirection
---


# Question
Title: Adding HTML5 placeholder to all drupal forms
I'm trying to add the placeholder attribute to all textfields across my website, but I'm having no luck.

I've created a module that overrides `hook_form_alter`

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    foreach ($form as $key => $value) {
        if ("textfield" == $value["#type"]){
            $value['#attributes']["placeholder"] = t($value["#title"]);
        }
    }
}

```

I should tell you that I'm also using the webform module.

# Answer
Because I'm using the webform module I could just theme the global webform template (webform-form.tpl.php) and put it in my theme folder. No need to complicate things with a module.

```
foreach ($form["submitted"] as $key => $value) {
    if ("textfield" == $value["#type"]) {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
}

```

I put this at the top of the template file.
> 14 votes

# Answer
Slightly change it to....

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    foreach ($form as $key => $value) {
        if ("textfield" == $value["#type"]){
            $form[$key]['#attributes']["placeholder"] = t($value["#title"]);
        }
    }
}

```

`$value` in foreach scope is value type not a reference.

---

# EDIT:

I just experimented with following code and I succeeded to recursively iterate whole of the form for textfields to edit their attributes.

```
function add_placeholder(&$form){
    foreach($form as $key => $val){
        if(substr($key,0,1) == '#' && $form[$key] == 'textfield'){
            $form['#attributes'] = array('placeholder' => t('some text'));
        }else if(is_array($form[$key])){
            add_placeholder($form[$key]);
        }
    }
}

```
> 10 votes

# Answer
You could probably do that with `hook_form_alter` or `hook_form_FORM_ID_alter` and adding the *"placeholder"* attribute

e.g, untested, but something like:

```
/**
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_webform_client_form_12_alter(&$form, &$form_state) {
  drupal_set_message('<pre>'.print_r($form,1).'</pre>'); // debug form
  $form['submitted']['my_form_component']['#attributes'] = array('placeholder' => 'placeholder 1');
}

```

Find the hidden form element in the webform HTML named `form_id` to get the correct form id for the `form_alter` function name.
> 4 votes

# Answer
A better approach to Josua Pedersen's code:

```
foreach ($form['submitted'] as $key => $value) {
 if (isset($form['submitted'][$key])) {
   $types = array('textfield', 'webform_email', 'textarea');

   if (isset($value['#type']) && in_array($value['#type'], $types)) {
     $form['submitted'][$key]['#attributes']['placeholder'] = t($value['#title']);
   }
 }
}

```
> 4 votes

# Answer
In your code, you change the variable `$value` that never when associate again to the variable `$form`, which one is passed by reference.

In clear, you make some changes but don't send it back to Drupal.

Also, you can do it like that (I've not tested it but in theory it should work).

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $keys = element_children($form);
  foreach ($keys as $key) {
    if (in_array(array('textfield', 'textarea'), $form[$key]['#type'])) {
      if (!empty($form[$key]['#title'])) {
        $placeholder = array('placeholder' => t($form[$key]['#title']));
        if (is_array($form[$key]['#attributes'])) {
          $form[$key]['#attributes'] = array_merge($form[$key]['#attributes'], $placeholder);
        }
        else {
          $form[$key]['#attributes'] = $placeholder;
        }
      }
    }
  }
}

```

I was just lazy to add a check for `fieldset` and add placeholder to the children. But I guess you can change it very easily.
> 3 votes

# Answer
A slight improvement to @Josua's template file solution: This code will also add placeholder text to webform email feilds.

```
foreach ($form["submitted"] as $key => $value) {
    if ("textfield" == $value["#type"]) {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "webform_email") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
}

```
> 3 votes

# Answer
using hook\_form\_alter try this

```
function mymodule_survey_builder_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'form_builder_field_configure') {
        $form['title']['#attributes']=array('placeholder' => t('Please enter the Qustion(English) name here.'));
}
}

```
> 2 votes

# Answer
For anyone using an older or outdated version of Drupal's Webform module, it's worth noting that placeholder support was added in the `7.x-4.x branch` (June 2013).

Thus, HTML5 placeholder functionality is now a native, built-in option along with custom CSS classes for components and several other long-requested features.

Here's a screenshot of how the new functionality appears:
> 1 votes

# Answer
In most cases, I guess, one would only want to add placeholder attributes on some forms.

If you want to add placeholder to all webforms, you can do it like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // If webform, add "placeholder" attributes to all textfields
  // got code here:http://drupal.stackexchange.com/questions/12706/adding-html5-placeholder-to-all-drupal-forms
  if (isset($form['#node']->type) && ($form['#node']->type == 'webform')) {
    foreach ($form["submitted"] as $key => $value) {
      switch ($value["#type"]) {
        case 'textfield':
        case 'textarea':
        case 'webform_email':
          $form["submitted"][$key]['#attributes']["placeholder"] = $value["#title"];
          break;
      }
    }
  }
}

```
> 0 votes

# Answer
Just use the module for it: Webform Hints

Its exactly what you need. Its easy to manage and there is no need to custom code. This module also provides support for legacy browsers that don't support the placeholder attribute.
> 0 votes

---
Tags: forms, webforms
---


title: Removing edit menu link

text:
# Question
Title: Removing edit menu link
How can I remove the "edit" link on this page on the manage menu page (**Structure \> Menus \> My menu \> List links**)?

# Answer
`hook_form_alter()` can take care of this by setting `#access` element on menu item operation links.

```
function MYMODULE_form_menu_overview_form_alter(&$form, $form_state, $form_id) {
  foreach($form as $key => $value) {
    if(strpos($key, 'mlid:') !== FALSE) {
      $form[$key]['operations']['edit']['#access'] = FALSE;
    }
  }
}

```
> 0 votes

---
Tags: routes, hooks
---


# Question
Title: What's the easiest method for migrating content from Drupal 7 to another Drupal 7?
I have two drupal 7 sites and one of them has about 21 content types that does not exists in the other drupal 7 site. It's not a data merge so it's more of a data copy. I know there is the migrate module, but that seems a bit overkill for something like this as I am not merging data into an existing content type. It should just create a new content type on the new site and import all the fresh datas in.

What's the best approach or modules that should be used in this scenario?

I have never used migrate module before, so I'm assuming it's pretty complex as it can deal with many types of data. I remember there was a module which let you copy content from one site into the other.

The only complexity here is that these content types have node references and entity references associated to them. What issues might arise from that?

# Answer
You should use the Features module to export the configuration for your content types (and any related things - taxonomies and the like).

To move content between the sites, I'd recommend looking into the Deploy module, which will allow you to "push" content from one site to another. It requires some configuration to get it all set up, but it works really well, particularly with nodes that have dependencies on other entities (via entity reference or taxonomy term reference or things like that).

If you want to use Migrate (which is probably not a bad idea, depending on your data). You could also look into the migrate\_d2d module, which has a UI that let's you just point at another Drupal site, and then press "Go" and it'll pull in all your content.

tl;dr: There's lot of ways to do it, but the "best" way depends on the data in your sites.
> 4 votes

# Answer
First of all, you should use the Features module in order to migrate content types and fields.

Indeed, the migrate module might be too much for what you're trying to do as your datas are already Drupal formated. Instead, you could use the node export module to export and import the datas of your nodes.

If you use Entity Reference, you might need the Universally Unique IDentifier (UUID) module in order to make sure that your Entity Reference won't get lost during import in your new site (new node id will be affected to your nodes imported).
> 2 votes

---
Tags: 7, migrations
---


# Question
Title: Display random value from multi-value field in Views
I have an image field that allows unlimited values, and I need to use Views to display a random image from a node's image field. The View should display a random image from that node's field each time the page is reloaded. How can this be accomplished?

Example:

* On page load, display image "1" from Node A's multi-image field.
* Reload page, display image "3" from Node A's multi-image field.
* Reload page, display image "2" from Node A's multi-image field.
* Reload page, display image "3" from Node A's multi-image field.

Thanks!

# Answer
Re-querying with Views for information you already have is excessive. I think a better option is to use something like Single Image Formatter which can display a random value from a multivalue image field.
> 4 votes

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


# Question
Title: Creating complex tables in views in Drupal 7
I was trying to make a report via views in Drupal 7. It's quite easy to generate a table with the headers being the labels of the fields, like the following (being very straightforward):

```
:---------:----------:----------:----------:
| Label A | Label B  | Label C  | Label D  |
:---------:----------:----------:----------:
| Value A | Value B  | Value C  | Value D  |
:---------:----------:----------:----------:
|Value A' |Value B'  |Value C'  |Value D'  |
:---------:----------:----------:----------:

```

However, I am getting stumped at creating the following complex table:

```
:---------:----------:----------:----------:
|     Header A       |      Header B       |
:---------:----------:----------:----------:
| Label A | Label B  | Label C  | Label D  |
:---------:----------:----------:----------:
| Value A | Value B  | Value C  | Value D  |
:---------:----------:----------:----------:
|Value A' |Value B'  |Value C'  |Value D'  |
:---------:----------:----------:----------:

```

Any ideas on how to approach this? Thanks :)

# Answer
> 2 votes
The Views UI supports this.

Once you have your View configured, click on the "Settings" link in the Format section. You will then see a table that allow you to choose which column each field should appear in. See screenshot below. In this example, if you wanted the `Author uid` and `Nid` fields to appear in the same column, you would just select `Author uid` from the select list next to `Nid` (or vice versa).

# Answer
> 0 votes
You can also try theme\_table and colspan attribute

```
$header = array( array('data' => 'Header A', 'colspan' => 2), array('data' => 'Header B', 'colspan' => 2));
$rows[] = array('Label A', 'Label B', 'Label C', 'Label D');
$rows[] = array('value A', 'value B', 'value C', 'value D');
$rows[] = array('value A', 'value B', 'value C', 'value D');
$rows[] = array('value A', 'value B', 'value C', 'value D');
$output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' =>  $attributes));

print $output;

```

# Answer
> 0 votes
I know this question is old but I could not find a working answer anywhere and, since this was the best description of the question, I think a working solution here would benefit others.

The Views UI does not yet support two header rows. Thus you need to override the template for styling the views table output.

1. Copy the views/theme/views-view-table.tpl.php template file to your own theme or module directory.
2. Rename it to make it specific to your particular view. To determine what this name should be, click on the "Theme: Information" under the "Other" category in your edit view UI and then find the template name that includes your views machine name and is in the "Style Output" bullet.

3. Ensure your template is detected. To check that it has been detected click the "Rescan Template Files" button at the bottom of the Theme Information opened above. If you template has been detected it will be bolded within the "Style Output" bullet.

a) Custom Theme: If you copied the template file into a theme directory in step 1 then the new template should be automatically detected.

b) Custom Module: Your template will not be automatically detected, therefore you need to use hook\_theme to register your new template. For example,

```
function mymodulename_theme() {
  $items = array();

  // Notice that the key for this array is the name of your template
  // with all dashes replaced by underscores.
  $items['views_view_table__cb_planned_crosses'] = array(
    'arguments' => array(
            'view' => NULL,
            'title' => NULL,
            'header' => NULL,
            'fields' => NULL,
            'class' => NULL,
            'row_classes' => NULL,
            'rows' => NULL
        ),
        // Replace views-view-table--cb-planned-crosses with the
        // name of your template.
        'template' => 'views-view-table--cb-planned-crosses',
        'base hook' => 'views_view_table',
        // Replace cross_manage with the name of your module.
        'path' => drupal_get_path('module', 'cross_manage') . '/theme/templates',
  );

  return $items;
}

```
4. Finally, edit the template file and use HTML/PHP to add an additional header row within `thead`. For simplicity, I am going to show a hardcoded example but I recommend processing the fields in the view and using appropriate criteria to determine programatically which fields should be under which columns.

```
    <thead>
      <!-- Add your custom grouping header -->
      <tr>
        <th colspan="2">Header A</th>
        <th colspan="2">Header B</th>
      </tr>
      <!-- Pre-existing Header code -->
      <tr>
        <?php foreach ($header as $field => $label): ?>
          <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
            <?php print $label; ?>
          </th>
        <?php endforeach; ?>
      </tr>
    </thead>

```

---
Tags: views, theming
---


# Question
Title: Which PHP file would a custom theme_link function go into?
For some Taxonomy term pages I would like to change the "Read More"

link to "More info". Using theme developer, I see it’s using the `theme_link` function and gives a candidate function name.

If I re-write this function, in which `PHP` file would I put this custom function?

# Answer
> 1 votes
`theme_link()` doesn't use a template file. You can override its output by placing your own theme function in your theme's **template.php** file:

```
function MYTHEME_link($variables) {
  //Alter this as you see fit
  return '<a href="' . check_plain(url($variables ['path'], $variables ['options'])) . '"' . drupal_attributes($variables ['options']['attributes']) . '>' . ($variables ['options']['html'] ? $variables ['text'] : check_plain($variables ['text'])) . '</a>';
}

```

---
Tags: theming
---


# Question
Title: Setting error text in Commerce Alter Form Module
I need to validate my form and return a specific error message if the terms of agreement checkbox isn't checked (it's a required field). So I've placed the following code in my CommerceAlter.module. However, it's not working (ie. the error text is still showing the default error text):

```
function CommerceAlter_form_validate(&$form, &$form_state, $form_id) {
  if (form_get_errors()) {
    $form_errors = form_get_errors();
    $drupal_errors = drupal_get_messages('error');

    // Clear form errors
    form_clear_error();

    foreach($drupal_errors['error'] as $key => $error) {
        if (in_array($error, $form_errors)) {
            // Unset form errors
            unset($drupal_errors['error'][$key]);
        }
    }

    // Rebuild drupal errors
    foreach($drupal_errors['error'] as $key => $message) {
        drupal_set_message($message, 'error');
    }

    // Validate form field and set error message
    if ( $form_state['values']['customer_profile_billing']
['field_i_have_read_and_i_agree_to']['und']['0']['value'] === 0 ) {

            form_set_error('value', t('You forgot to check the required
checkbox. Please try again.'));
        }
      }
    }

```

Any idea what I might be doing wrong here?

# Answer
I guess you can obtain the field value using this.

```
if ( $form_state['values']['field_i_have_read_and_i_agree_to'] == 0 ) {
  //or use this in if statement $form_state['values']['customer_profile_billing']['field_i_have_read_and_i_agree_to']

      form_set_error('field_i_have_read_and_i_agree_to', t('You forgot to check the required checkbox.Please try again.'));
    }

```

You shouldn't include `['customer_profile_billing']` unless you have set the `#tree` to TRUE.
> 1 votes

---
Tags: forms, commerce
---


title: How to filter webform results

text:
# Question
Title: How to filter webform results
Can someone kindly tell me how to filter the webform results page? For example how can I show only the submissions where column X has value Y.

I am new to drupal but I am an experienced PHP programmer. If someone kindly points out he right webform hooks I will try to figure out the rest.

Suprisingly, google could not help me. But I'm sure that others have faced the same problem before. Please assist.

# Answer
I am not sure if you still need this information, but for the benefit of others...

1. You might want to look into the webform\_mysql\_views module.
2. If you are using drupal 7+, you can create a simple view of the "Webform Submissions" type. Then, under Fields you should be able to find Webform Submissions: Data Value field. Select that and then add the field you want to show up in your table. Do this for the rest of the fields you want. Finally, add the filters and/or sorts the very same way. NOTE: You might have to add a relationship (the very right drop-down) or two to show you relevant results.

Hope this helps!
> 1 votes

# Answer
There is a Drupal contrib module called **Webform Selectable Filters** that extends views which will help you to create a view with dropdown list exposed filters instead of textfields.
> 1 votes

---
Tags: webforms
---


# Question
Title: Restrict Anonymous Users from accessing/viewing a Customized Form
I have created a form. The codes I used are below:

```
function myid_print_menu()
{
    $items = array();

    $items['user/%user/myid_print'] = array(
        'title' => 'Print an ID',
        'page callback' => 'myid_print_user_page',
        'page arguments' => array(1),
        'access callback' => myid_print_user_access(),
        'file' => 'myid_print.pages.inc',
        'type' => MENU_LOCAL_TASK,
        'weight' => -10,
    );
    return $items;
}

```

The code of the function that allows accessing the form:

```
function myid_print_user_access()
{
   if (user_access('perform_regular_task'))
   {
       return TRUE;
   }else{
       return FALSE;
   }

}

```

I was wondering that even if the user is not log-in the form can be access.

Looking at the module's permission:

I did not assign any permission for the `anonymous` user. Why it is so?

# Answer
The access callback element used in `hook_menu()` takes a string has a value, you're supplying it the output of `myid_print_user_access()` which return a boolean. It should be:

```
'access callback' => 'myid_print_user_access',

```
> 3 votes

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


title: problems with a batch api module

text:
# Question
Title: problems with a batch api module
The function `_calcular_tiempo_usuario` isn't called, and is not saving anything in the `$_SESSION` variable.

```
<?php
function proyecto_estadisticas_menu(){
  $items['admin/settings/proyecto_estadisticas/batchapi'] = array(
    'title' => t('Proceso batchapi para calcular tiempo medio en la página'),
    'page callback' => '_proyecto_estadisticas_tiempo',

    'access arguments' => array('administer site configuration'),
    'file'  => 'proyecto_estadisticas.batch.inc',
    'type'  => MENU_NORMAL_ITEM,
  );
  return $items;
  }

//archivo de php para los procesos de batch.api
/**
 * Esta función es la que empieza montando todo el proceso de batch api.
 *
 * name proyecto_comienzo_batch
 *
 */
function proyecto(){

  //llamamos a la función de batch
  batch_set(_cargar_usuarios());

  batch_process('node');

  /
}

function _cargar_usuarios(){
  //$date = date('Y-m-d',strtotime('yesterday'));
  $date = '2011-09-12';
  $valoresfechas = _get_valores_fechas($date);
  $usuarios = array();
  //se ejecuta correctamente. se ha comprobado.
  $usuarios = _crear_array_usuarios_tiempos( $valoresfechas);

  $operations = array();
  foreach($usuarios as $key => $value){
    $operations[] = array('_calcular_tiempo_usuario', array($key, $value, $valoresfechas));
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'funcion_final',
    'title' => t('Calculando tiempo de usuarios'),
    'init_message' => t('Comienza el cálculo de tiempos.'),
  );
  return $batch;
}

/**
 *
 * Esta función es parte de la batch api que llama a todos los usuarios para recorrer el resultado y hacer el sumatorio.
 * _calcular_tiempo_usuario
 * 151 (Array, 8 elements)
 *   0 (String, 17 characters ) opened 1315836623
 *   1 (String, 17 characters ) closed 1315836924
 *
 * name _calcular_tiempo_usuario
 * @param $usuario es un array con todos los resultados de opened y closed del usuario que se pasas
 * @return el resultado de la suma.
 *
 */

function _calcular_tiempo_usuario($uid, $usuario, $valoresfechas, &$context){
  $_SESSION['metricas'][$uid] = $uid;
  //contamos la cantidad de elementos del array para los for.
  $cantidad = count($usuario);

  //Comprobamos cual es el primer elemento, opened or closed
  if(preg_match("/^opened/", $usuario[0])){
    $si = 0;
  }else {
    $si = 1;
  }
  //si $si == 1, quiere decir que el array empiza con un cloused, y el segundo valor(1) es un opened.
  if($si == 1){
    //calculamos el primer valor que es un cloused
    $suma +=  str_replace('closed','',$usuario[0])- $valoresfechas['antes'] ;
    //recorremos el bucle para sacar todas las relaciones
    for($si; $si <= $cantidad; $si=$si+2){
      if($usuario[$si+1]){
        $suma += str_replace('closed','',$usuario[$si+1])-str_replace('opened','',$usuario[$si]);
      }
      if( !($usuario[$si+1]) && (preg_match("/^opened/", $usuario[$si])) ){
        //el ultimo registro, si es open, quiere decir que la sesión ha permanecido abierta all llegar a la media noche, por lo
        //tanto el close es fecha hasta.
        $suma += $valoresfechas['despues'] -str_replace('opened','',$usuario[$si]);
      }
    }
  }
  //si $si== 0 es que la primera entrada es opened
  if($si == 0){
    //recorremos el bucle para sacar todas las relaciones
    for($si; $si <= $cantidad; $si=$si+2){
      if($usuario[$si+1]){
        $suma += str_replace('closed','',$usuario[$si+1])-str_replace('opened','',$usuario[$si]);
      }
      if( !($usuario[$si+1]) && (preg_match("/^opened/", $usuario[$si])) ){
        //el ultimo registro, si es open, quiere decir que la sesión ha permanecido abierta all llegar a la media noche, por lo
        //tanto el close es fecha hasta.
        $suma += $valoresfechas['despues'] -str_replace('opened','',$usuario[$si]);
      }
    }
  }
    // Store some result for post-processing in the finished callback.
  $context['results'][] = $uid ;

  // Optional message displayed under the progressbar.
  $context['message'] = t('Loading @uid', array('@uid' => $uid));

  $context['results']['metricas'][$uid]= $suma;
}

/**
 * Batch 'finished' callback
 */
function funcion_final($success, $results, $operations) {
  if ($success) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    $message = count($results) . ' processed.';
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = 'An error occurred while processing ' . $error_operation[0] . ' with arguments :' . print_r($error_operation[0], TRUE);
  }
  drupal_set_message($message);

}

/**
 * Esta función crea un gran array con todos los usuarios y sus registros
 * de aperturas y cierres de sesión.
 *
 * name: _crear_array_usuarios_tiempos
 * @param $valoresfechas
 * @return un array con todos los usuarios, menos administradores, y
 * sus aperturas y cierras de sesión
 *
 */

function _crear_array_usuarios_tiempos( $valoresfechas){

    $sql = db_query("
  SELECT DISTINCT(wid), type, message, uid, timestamp
        FROM watchdog
        WHERE type = 'user'
        AND timestamp > %d
        AND timestamp < %d
        AND ( message like '%%Session opened for%%' OR message like '%%Session closed for%%')
        AND uid NOT IN (".db_placeholders(ADMINISTRADORES,'int').")
        ORDER BY timestamp ASC",
        $valoresfechas['antes'],
        $valoresfechas['despues'], ADMINISTRADORES
        );
    while ($result = db_fetch_object($sql)){
      $usuarios[$result->uid][] = limpiar_mensaje($result->message). $result->timestamp;

    }

  return $usuarios;
}
?>

```

# Answer
The reasong of why the `_calcular_tiempo_usuario()` is not being called or why the `$_SESSION` variable is not being saved is following:

On the hook\_menu(), the callback function is `_proyecto_estadisticas_tiempo`, but is the `proyecto()` function which starts the batch process.

Sometimes when you work with batch API you don't see any errors, to confirm that, always check the admin/reports/dblog page.

I couldn't find where do you use the values that should be stored by the $\_SESSION variable, but I suggest you to use:

* `$context['sandbox'][values you need to store]` to store and use those values during batch process.
* `$context['results'][values you need to store]` to use the values after batch process is finished.

You can check it at the Batch API docs
> 0 votes

---
Tags: 7, batch-operations
---


# Question
Title: How to add login form to the Access Denied page?
I'm trying to add a login form to the access denied page, and wonder if this is possible via the UI.

Any suggestions/ideas?

# Answer
> 4 votes
Another solution here is the the LoginToboggan module. It provides a number of different enhancements to login functionality.

> The logintoboggan module offers several modifications of the drupal login system in an external module by offering the following features and usability improvements:
>
> 1. allow users to login using either their username or their e-mail address.
> 2. allow users to login immediately.
> 3. provide a login form on access denied pages for non-logged-in (anonymous) users.
> 4. the module provides two login block options: one uses javascript to display the form within the block immediately upon clicking "log in". the other brings the user to a separate page, but returns the user to their original page upon login.
> 5. customize the registration form with two e-mail fields to ensure accuracy.
> 6. optionally redirect the user to a specific page when using the 'immediate login' feature.
> 7. optionally redirect the user to a specific page upon validation of their e-mail address.
> 8. optionally display a user message indicating a successful login.
> 9. optionally combine both the login and registration form on one page.
> 10. optionally have unvalidated users purged from the system at a pre-defined interval (please read the caveats section of install.txt for important information on configuring this feature!).
> 11. integrates with rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)

The settings configuration form has an option called *Present login form on access denied (403)* that toggles this exact functionality on/off.

# Answer
> 10 votes
# Option 1: Use the CustomError module

The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

You should be interested in the part about "*Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.*".

# Option 2: Redirect to user/login using the Rules module

*"Adding settings for the 'access denied page' and displaying the 'User login' block on that page"* is indeed a solution that should work. However, you could take this a little step further, and enhance the user experience AbitMORE. By using a variation of the approach described in the answer to the question about "How to redirect anonymous users to login page using Rules module?".

To do so, assume the path of the "Default 403" page is set to "no\_access" (via `/admin/config/system/site-information`, near the bottom of that admin page). Then create a rule using the Rules module, with as **Event** something like "After visiting node 'no\_access'". So that the entire rule would look something like so:

* **Events:** After visiting node 'no\_access'
* **Conditions:**

1. *User has role(s)* \- `Parameter: User: [site:current-user], Roles: anonymous user`
    2. *NOT Text comparison* \- `Parameter: Text: [site:current-page:url], Matching text: user/login`
* **Actions:** *Page redirect* \- `Parameter: URL: user/login`

Should you want to do so, you could even add another **Action** to also display some (informational) message in the Drupal message area, with something like "You tried to visit a page for which login is required ...".

True, it might require you to enable an extra contributed module (Rules). But, as indicated by its growing popularity also, that module is probably already enabled in mostly any site (similar to the Views module), because there are dozens of use-cases for this module. Just 1 variation of this question: how about enhancing the user experience for "Page not found" in a similar way?

# Option 3: Show User login block on dedicated page

Another variation, as an alternative to the Rules "Action" (to redirect to `user/login`), is to create some designated node, say with a path like "my\_login\_page\_with\_login\_block". And then combine this with configuring the "User login" block (via `admin/structure/block`) like so:

* Display that block in whatever theme region of your choice.
* Use the "`configure`" link to the right of that User login bloc, to set the "*Visibility settings*" for "*Pages*". I.e. change the option for "*Show block on specific pages*" to "*Only the listed pages*", and specify the path (`my_login_page_with_login_block`) within the text box below it. If for some reason you don't want to use a path, then just specify node/nid (nid = id of the node) as the path instead.

# Answer
> 5 votes
You can add settings for 'Default 403 (access denied) page' in the site configuration (admin/config/system/site-information). And then display 'User login' block (admin/structure/block/manage/user/login/configure) on this page.

# Answer
> 3 votes
Without the LoginToboggan module one can configure the User login block to be visible on designated pages and restricted to anonymous users. In the block Visibility settings for the User login block:

1. In the "pages" tab, set "Show block on specific pages" to "Only the listed pages" and enter the pages.
2. In the "Roles" tab, check "anonymous user" for the Show block for specific roles setting.

# Answer
> 2 votes
In theory, you could set the Default 403 (access denied) page under Site information to user/login at /admin/config/system/site-information.

Never tried it but it's just an idea?

---
Tags: forms, users
---


title: Hook menu item not Showing

text:
# Question
Title: Hook menu item not Showing
I have two hook menu items:

```
function myid_print_menu()
{
    $items = array();
    $items['user/%user/myid_print_settings'] = array(
        'title' => 'ID Print Settings',
        'description' => 'Configuration options for the myid_print module',
        'page callback' => 'myid_print_admin_settings',
        'page arguments' => array(1),
        'access callback ' => 'myid_print_user_access',
        'type' => MENU_LOCAL_TASK,
        'weight' => -9,
    );

    $items['user/%user/myid_print'] = array(
        'title' => 'Print an ID',
        'page callback' => 'myid_print_user_page',
        'page arguments' => array(1),
        'access callback' => 'myid_print_user_access',
        'file' => 'myid_print.pages.inc',
        'type' => MENU_LOCAL_TASK,
        'weight' => -10,
    );
    return $items;
}

function myid_print_admin_settings()
{
     return drupal_get_form('myid_print_settings_form');
}

function myid_print_settings_form()
{
     $form = array();
     $form['summary'] = array(
         '#type' => 'fieldset',
         '#title' => t('ID Summary'),
         '#description' => t('Summary of ID printed, submitted and reset on a specific range of time')
     );
     return $form;
}

```

The `'ID Print Settings'` was not showing, but `Print an ID` was showing. I tried clearing my cache, it was still not visible. Why?

# Answer
I have a feeling with the access callback. Either your function is wrong (which you haven't posted) or something is up with your permission setting for this module.

Try temporarily updating your access callback to true to verify that it is causing the issue:

```
'access callback' => TRUE,

```

and clear your cache.

I think you may be better off creating a permission using hook\_permission and using access arguments instead of access callback.

```
/**
 * Implement hook_permission()
 */
function myid_print_permission(){
  return array(
    'administer myid_print' => array(
      'title' => 'Administer myid_print'
    ),
  );
}

/**
 * Implements hook_menu().
 */
function myid_print_menu() {
  $items = array();
  $items['user/%user/myid_print_settings'] = array(
      'title' => 'ID Print Settings',
      'description' => 'Configuration options for the myid_print module',
      'page callback' => 'myid_print_admin_settings',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -9,
  );

  $items['user/%user/myid_print'] = array(
      'title' => 'Print an ID',
      'page callback' => 'myid_print_user_page',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'file' => 'myid_print.pages.inc',
      'type' => MENU_LOCAL_TASK,
      'weight' => -10,
  );
  return $items;
}

```
> 3 votes

# Answer
Try putting the call to `drupal_get_form` directly in your menu hook like this:

```
$items['user/%user/myid_print_settings'] = array(
    'title' => 'ID Print Settings',
    'description' => 'Configuration options for the myid_print module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myid_print_settings_form', args[1]),
    'access callback ' => 'myid_print_user_access',
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
);

```

Note the `args[1]` in the arguments which will pass the `%user` argument from the path to the form.
> 0 votes

---
Tags: caching, routes
---


title: Get the field value in markup?

text:
# Question
Title: Get the field value in markup?
I have 2 fields in a content type.

**field\_link** and **field\_hoster**

if in the hoster field *youtube* is selected the markup should embed the linked video.

can you guys give me a example of what i have to write in the markup field?

# Answer
> 1 votes
use **hook\_form\_alter()**

```
$form['field_name'] = array(
  '#type' => 'markup',
  '#markup' => $form['field_name'][#value]
);

```

or you can use prefix or suffix

```
$form['field_name']['#prefix'] = '<div class="field-name"><label>'.$form['field_name']['#value'] .'</label>';

```

---
Tags: entities, theming, nodes
---


# Question
Title: How do I get the blog teaser view display on a content type?
I know. I write English language really bad, horrible. I apologize.

I created a blog (with the core's blog module. Also I have a content type called **my-content-type** :). I need the blog teaser view is displayed in my my-content-type.

I installed *Display Suite*. So, my-content-type has the *Display settings* option. With this option I can choose the desired view, in my case the teaser view. OK, very good! Now, but how do I get the blog teaser view is displayed in my-content-type?

Can I do this without *Views*?

Greetings!

# Answer
> 3 votes
## **Short answer:**

Yes, you could do it without views. But, it wouldn't be ideal.

## **Long answer:**

Display suite module will let you control the display of the particular content type and its fields. It won't allow you to control the display of a different content type from the other.
E.g. For your **my-content-type**, it will allow you to change the display settings of the fields of this content type.

If you wish to display teasers of nodes of the **blog** content type, on the node pages of **my-content-type**, you will have to do the follow the steps below:

**Without views:**

1. Create a custom module.
2. Load the **blog** `$node` using `node_load` on **my-content-type** node page.
3. Using `node_view` on the `$node` get the node in the teaser view of the node.
4. Use `drupal_render` to render the loaded teasers in a custom block created using `hook_block_info`.
5. Place this block in an region only on the **my-content-type** node page.

**With views:**

1. Create a view block of content of type **blog**.
2. Select the display method to be **content**, and select **teaser** from the settings.
3. Apply additional settings (filters, relations) as required.
4. Place this block on the node page of **my-content-type**.

In other words you let views build your query for you. And you also get an additional advantage of using other features provided by the views module like caching, etc.

---
Tags: nodes
---


# Question
Title: Disable Panels Preview when adding new Panes in Layout Editor
Some of my pane's are causing the pane's editor to crash (some cause the grears to dissapear, some cause the add new panes element to break). We'd therefore like to disable the preview option in Panels, it looks like Panopoly has the option to do this: https://www.drupal.org/node/2171809. "Enable Previews when adding Panes"

Does anyone know how this could be done on the panels module for Drupal 7? We're not using Panopoly.

The reason behind it not working is that Panels was written against jquery 1.4 and some of my blocks that are being previewed when adding panes to the page manager are panels 1.9+

# Answer
> 1 votes
I had same problem in one of my project. Then what I did, I added a custom code to remove all the js files except drupal core js, Panels js, Token Js, Ctools js and Views Js. And it is only for the panel pages so it solve the issue of jquery version. We also have a drupal module **jqmulti** for this. But in some cases it also do not work well. That is why I removed all the unwanted js files from panel page. Here is the sample code for this.

```
function custom_module_js_alter(&$js){
  if(arg(0) == 'admin' && arg(1) == 'structure' && arg(2) == 'pages'){
    $allow = array('modules/filter/filter.js', 'modules/field/modules/text/text.js', 'modules/file/file.js');
    foreach($js as $key => $value){
      $pos =  strpos($key, 'misc');
      if(strstr($key, 'misc') == '' && $key != 'settings' && strstr($key, 'ctools') == '' && strstr($key, 'panels') == '' && strstr($key, 'views') == '' && strstr($key, 'token') == '' && strstr($key, 'admin_menu') == '' && !in_array($key, $allow)){
        unset($js[$key]);
      }
    }
  }
}

```

---
Tags: panels, javascript
---


# Question
Title: Remove all Div wrapper from comment form
I want to strip all default Drupal form wrappers and have something like below in comment form output

```
                    <form>
                        <input type="text" name="name" placeholder="Your name">
                        <input type="email" name="email" placeholder="Email">
                        <input type="text" name="website" placeholder="Website">
                        <textarea name="comment_body" placeholder="Comment"></textarea>
                        <input type="submit" value="Send">
                    </form>

```

I try

```
    $form['comment_body']['#theme_wrappers'] = array();
    $form['subject']['#theme_wrappers'] = array();
    $form['author']['mail']['#theme_wrappers'] = array();
    $form['author']['name']['#theme_wrappers'] = array();

```

But not worked for `comment_body` field, I also use `Display Suit` I want to know how Can implement comment form like I want without any wrapper.

# Answer
To achieve this you need to create one template page for comment-form.tpl.php. For this you need to specify in template.php that uses template page.

```
<?php
function phptemplate_comment_form($form) {
  return _phptemplate_callback('comment-form', array('form' => $form));
}
?>

```

and in comment-form.tpl.php you can create your own strcution like

```
print drupal_render($form['name']);
print drupal_render($form['comment_body']);
print drupal_render($form['subject']);
print drupal_render($form['author']['mail']);
print drupal_render($form['author']['name']);

```

This works for me with register/login form.
> 2 votes

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


# Question
Title: How to add a CSS class to field label and items div?
I want to add a class in the field label and field items, the HTML I want is the following:

```
<div class="field field-name-field-price field-type-number-integer field-label-above row">
            <div class="field-label col-md-2">Price: </div>
            <div class="field-items col-md-2"><div class="field-item even">100</div></div>
</div>

```

I've tried field\_formatter\_class, the module allow me to add a "row" class into the container, but not in **field-label** and **field-items**. I want to add col-md-2 class for such two divs

How to do that without writing a module to do that?

# Answer
have you try `hook_preprocess_field()`.

please check this link everything is given in this blog may be it help you http://atendesigngroup.com/blog/adding-css-classes-fields-drupal
> 1 votes

# Answer
Are you using views? If so, you can easily add the class by using the **Style settings** available in **Configure field** options

Hope this helps!
> 0 votes

---
Tags: entities, theming
---


# Question
Title: Organic groups content propagation direction
where can I set content propagation direction in Organic groups (7.x-2.x). Post https://drupal.stackexchange.com/questions/40835/need-groups-within-a-group/175000 shows screen which I can not find even though I have installed modules Organic groups and Subgroups for organic groups.

Do you have any advice where can I find this screen or any other way I could set proparation of content from parent to children groups?

# Answer
> 2 votes
That screenshot is from Drupal 6.

In Drupal 7 the organic groups module works much differently in that it now uses fields to store its settings.

With Drupal 7 organic groups you need to go the the "OG field settings" administration page (admin/config/group/fields) and configure which fields appear on which content types.

The way that admin page works can be a little confusing but it's fairly straight forward once you get used to it.

The fields provided by the Subgroups for Organic groups module are:

* Group user inheritance
* Group user permission inheritance

On that admin page add those fields to your sub-group content types, then you can go to the content type field settings for those content types (in the admin/structure/types section) and you can configure default for those fields that will be used whenever sub-groups are created.

If you want to stop content administrators from being able to change the value of that field you can then use the field permissions module to restrict access to those 2 fields.

This is the same way you have to manage the fields from the base OG module (Group and Groups audience) and the fields in the OG access sub-module (Group visibility and Group content visibility).

# Answer
> 0 votes
rooby, I tried to set up user membership inheritance using fields Group user inheritance and Group user permission inheritance, but user membership is not inherited.

I've read other posts describing how to set up subgroups with user inheritance, but it doesn't work for me.

I want to create different products P1, P2,... and assign content to them. Then create several groups G1, G2,... for user management. I would like to subscribe group G to product P (as a subgroup), so that users in group G would be able to see content from group P.

I tried two solutions: (A) Set up content inheritance from parent group P to subgroup G, but I couldn't make it work with Subgroups for D7 (subgroups 7.x-2.x has only user inheritance) (B) use reverse approach:

group P has parents G1, G2 on G1 and G2 have set user inheritance to children groups (so when I add user U to group G1, it will also become member of P- this user will see content from groups P and G1, but not the content from G2) This is current situation: I have 2 groups (Content types): Product and Group.

Product: has fields

"Group audience" (to set parent group Group), "Group visibility" (Private - accessible only to group members), Group roles and permission (Use default roles and permissions) Group content visibility (tried public and private) Group: has fields

Group visibility (Private - accessible only to group members) Groups views (none set) Group roles and permissions (Private (only author and administrators can edit and view)) Group user inheritance (Yes - subgroups of this group will inherit its users.) Group user permission inheritance (Inherit Permissions - inherited users in this group's subgroups will have the permissions as they do in this group and not the permissions of generic members of that subgroup.) Group content visibility (Private- accessible only to group members) Expected behaviour: When I add user to group G1, it should also become member of group P, but it does not.

Am I missing something? Are my settings wrong?

---
Tags: organic-groups
---


# Question
Title: Commerce Kickstart Product: URI links to admin
When I try to use a Commerce Product Reference field in any view with a link to content, it links to the -admin- for the product, not the content.

This was discussed for the images here: https://www.drupal.org/node/1970482

But I'm finding that this will happen if you try to create a link wrapper to -any- Commerce Product field. (SKU, Title, etc.)

So.. can someone point me to the place in the Commerce code where that URI is generated so I can override it?

I thought it was in commerce\_product\_reference.module but I can't figure it out.

# Answer
I was facing this problem also in the latest Kickstart 2 version, so after hours of investigating I was able to prepare those detailed steps how to solve it:

1. In Views under 'Advanced' and the 'Relationship' heading choose 'Add', and find and select 'Content: Referenced Product' (if adjusting a cart form view, then select 'Commerce Line item: Product'). Check the 'Require this relationship' checkbox.
2. Now, under 'Fields' heading add a field 'Content: Path' (in case of the cart form view, add 'Commerce Line item: Display path'). 'Exclude from display' this field and arrange it to be the first field (it is important to have this field above the image field in order to be able to use its \[path\] token (see point 3)). If you have a multilingual page, check 'Use absolute link' under 'Rewrite results' (matters for the 'Content: Path field' only).
3. Finally, add the 'Product: Images' field. Link it to Nothing. Under 'Rewrite results' choose 'Output this field as a link' and use the token \[path\]. If you are facing the problem also with other fields, apply this solution also to them.

Source: Me and https://drupalcommerce.org/discussions/556/product-image-views-link-product-admin-rather-product-display-page
> 1 votes

# Answer
Please see my answer at https://www.drupal.org/node/1970482#comment-9252269 and try to avoid posting the same support request in multiple support forums.
> 1 votes

# Answer
You can add the path alias of the products display to your view, check the box to hide the field. Then rewrite your product reference field to link to path.
> 0 votes

---
Tags: commerce
---


# Question
Title: Show menu only when user ticks the checkbox
I have a menu for user to enter user details which should visible only to logged in user, it works fine. Now I want to add another restriction where I want menu to be displayed only to the user who ticked the checkbox during registration (i.e.,) In registration form there will be a checkbox when user tick the checkbox the menu should be visible otherwise menu should not be accessed by use. I tried following code but not working.

```
 function my_module_form_alter(&$form, &$form_state, $form_id) {
   if($form_id = 'user_register_form'
   $form['checkbox1'] = array (
      '#title' => 'XYZ',
      '#type' => 'checkboxes',
      '#options' => array('Sell themes'),

   );
 }
 function my_module_user_register_form_submit_handler($form, &$form_state) {
   $check = $form_state['complete form']['checkbox1'][0]['#checked'];
 }
 function check() {
   if($check !== 1) {
   return TRUE;
   }
   return FALSE;
 }
 function my_module_menu_alter(&$items){
   $items['node/add/detail']['access callback'] = 'check';
   $items['node/add/detail']['access arguments'] = array(1);
 }

```

**$check** return 1 if checkbox is ticked. But it is not working. Please Correct my mistake. Thank You

# Answer
> 1 votes
1. Go to `admin/config/people/accounts/fields` and add a boolean field.
2. In your `MYMODULE_form_alter()` add a `'#type' => 'checkbox'` form field and a custom submit handler.
3. Inside that custom submit handler save the checkbox value into the user's boolean field from step 1.
4. Inside your `MYMODULE_menu_alter()` call `global $user` and check that field's value `$user->field_sell_themes` and build the access control accordingly.

---
Tags: forms
---


# Question
Title: How to reduce HTML output on Drupal forms
How to let Drupal **print only necessary HTML in *forms***. I want to override fields input.

This is the current code for `node add form`:

```
<form ...>
...
    <div class="field-type-text field-name-field-price-ad field-widget-text-textfield form-wrapper" id="edit-field-price-ad">
      <div id="field-price-ad-add-more-wrapper">
        <div class="form-item form-type-textfield form-item-field-price-ad-und-0-value">
          <label for="edit-field-price-ad-und-0-value">Price</label>
          <input class="text-full form-text required" type="text" id="edit-field-price-ad-und-0-value" name="field_price_ad[und][0][value]" value="" size="60" maxlength="55" />
          <div class="description">Text</div>
        </div>
      </div>
    </div>
    <div class="field-type-youtube field-name-field-video-ad field-widget-youtube form-wrapper" id="edit-field-video-ad">
      <div id="field-video-ad-add-more-wrapper">
        <div class="form-item form-type-textfield form-item-field-video-ad-und-0-input">
          <label for="edit-field-video-ad-und-0-input">Video</label>
          <input type="text" id="edit-field-video-ad-und-0-input" name="field_video_ad[und][0][input]" value="" size="60" maxlength="1024" class="form-text" />
          <div class="description">Text</div>
        </div>
      </div>
    </div>
...
</form>

```

I want something like this:

```
<form ...>
...
    <div id="edit-field-price-ad">
          <label for="edit-field-price-ad-und-0-value">Price</label>
          <input class="text-full form-text required" type="text" id="edit-field-price-ad-und-0-value" name="field_price_ad[und][0][value]" value="" size="60" maxlength="55" />
          <div class="description">Text</div>
    </div>
    <div id="edit-field-video-ad">
          <label for="edit-field-video-ad-und-0-input">Video</label>
          <input type="text" id="edit-field-video-ad-und-0-input" name="field_video_ad[und][0][input]" value="" size="60" maxlength="1024" class="form-text" />
          <div class="description">Text</div>
    </div>
...
</form>

```

Using `theme_form_element` I was able to remove third div (form-item). I cannot figure out how to edit first 2 div wraps.

# Answer
> 1 votes
With Display Suite and sub module Display Suite Extras you can remove unnecessary wrappers.

# Answer
> 0 votes
Try Fences module - you can override any templates with your own.

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


# Question
Title: Custom redirect specific page after edit
With my Drupal website ( which is much more custom than drupal ) I've got node referenced in another ( ex. an article in a custom page ).

I want the ability to easily edit the referenced content. To do that I've put a button with the link:

```
<?php print $base_url; ?>/node/<?php print $article->nid; ?>/edit?destination=<?php print urlencode('node/'.$node->nid); ?>

```

Sadly Drupal doesn't care about the destination and redirects me to the article node and not the current node it was into.

# Answer
> 1 votes
It is always a good habit to use **l()** to create links in Drupal. In your case, you can use the below code to create link.

```
l(t('Title'), 'node/' . $article->nid . '/edit', array('query' => array('destination' => 'node/' . $node->nid)));

```

# Answer
> 0 votes
Destination should work. If it doesn't then you could try this way using `hook_form_alter` to make it work.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'your_form_id') {
                $destination = $_GET['destination'];
                $form_state['redirect'] = $destination;
        }
}

```

---
Tags: redirection
---


# Question
Title: Remove drag table in field collection module drupal 7
Hihi. Hi all. I have a content type and in which I created a collection field using field collection module. I set the value for the field collection that is unlimited. In field collection including some certain fields. Then I proceeded to create content for this content type. I discovered that the field collection module enables drag row and show weight of the current row. Now I want to remove drag and drop function and the weight of that row without knowing how processing. Expect people to help me handle this problem. Thank all.

# Answer
> 0 votes
To removing ajax dag and drop table widget for multiple value field you need use "hook\_theme\_registry\_alter" to override theme registry function. Here you can find all information regarding your question.

---
Tags: nodes, entities
---


# Question
Title: how can i change new password/confirm password by using services module in drupal
I am using services module to consume users account details.

Enabled **user** in `admin->services->resources`.

**URL**: `https://drupal.com/service/user/23`

**method** : `post`

**request body:**
`{
"current_pass":"xyz"
"email":"xyz@gmail.com"
}`

I have updated these two values are successfully, but how can I change new password and confirm password values.

How to take these values in request body and I have tried like this(new\_pass) but failed to update.

Please help me.

# Answer
> 3 votes
https://drupal.com/servics/user/9

where 9 is User ID

**Method** : PUT

Pass 'X-CSRF-Token' paramerter with user token value in header.

**Example Call** :

{"uid":"9","current\_pass":"guessusername1","pass":"guessusername1xxx","pass1":"guessusername1xxx"}

---
Tags: services
---


# Question
Title: How do I use it only in the frontend theme?
Using the jQuery Update module, I set version 1.8. This version "broke" the views UI in the Admin theme; it seems that the AJAX calls in the Views UI work only with jquery 1.5.

How can I fix it?

# Answer
> 1 votes
With jQuery Update 7.x-3.0-alpha2 and later, there is a setting that allows to change the jQuery used for a specific theme; you can select:

* The site default version (set with the jQuery Update module)
* The version that comes with Drupal
* Any version supported by the jQuery Update module

>

# Answer
> 0 votes
try this

```
/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'library_alter') {
    if(isset($implementations['jquery_update'])) {
      // Move jquery update to the end. This will make sure our hook_library_alter
      // is always called before the jquery_update.
      $jquery_update = $implementations['jquery_update'];
      unset($implementations['jquery_update']);
      $implementations['jquery_update'] = $jquery_update;
    }
  }
}

/**
 * Implements hook_library_alter().
 */
function mymodule_library_alter(&$libraries, $module) {
  // If it is the admin theme all we want to do is change the global $conf
  // variable so when jquery_update runs right after us it will use 1.5.
  // We are not using path_is_admin(current_path()) because some admin path can use
  // the frontend theme like node edit page
  global $theme_key;
  if (variable_get('admin_theme') == $theme_key) {
    // Modifying global $conf variable, can be dangerous. Be carefull.
    global $conf;
    $conf['jquery_update_jquery_version'] = '1.5';
  }
}

```

from http://antistatique.net/blog/2013/01/04/drupal-use-a-different-jquerys-version-for-the-frontend-and-backend/

# Answer
> 0 votes
You can use my patch from this issue. It will add per path settings, like on the following mockup:

Patch code here, and also below:

```
*** jquery_update.module    Fri Sep 28 01:53:48 2012
--- jquery_update.module    Tue Oct 08 11:12:58 2013
***************
*** 68,77 ****
--- 68,83 ----
    // We are updating just the system module. For all other cases we return.
    if ($module != 'system') {
      return;
    }

+   // We don't want to alter if we are on one of the excluded paths
+   if(drupal_match_path(current_path(), variable_get('jquery_update_exclude_paths', ''))) {
+     return;
+   }
+
+
    $path = drupal_get_path('module', 'jquery_update');

    // Make sure we inject either the minified or uncompressed version as desired.
    $min = variable_get('jquery_update_compression_type', 'min') == 'none' ? '' : '.min';
    $cdn = variable_get('jquery_update_jquery_cdn', 'none');
***************
*** 146,155 ****
--- 152,167 ----
        'microsoft' => t('Microsoft'),
        'jquery' => t('jQuery'),
      ),
      '#default_value' => variable_get('jquery_update_jquery_cdn', 'none'),
      '#description' => t('Use jQuery and jQuery UI from a CDN. If the CDN is not available the local version of jQuery and jQuery UI will be used.'),
+   );
+   $form['jquery_update_exclude_paths'] = array(
+     '#type' => 'textarea',
+     '#title' => t('Disable jQuery update on the following paths'),
+     '#description' => t('You are allowed to use wildcards, for example admin/*'),
+     '#default_value' => variable_get('jquery_update_exclude_paths', ''),
    );

    return system_settings_form($form);
  }

```

# Answer
> 0 votes
Use dev version, that has already commited patch allowing to set different version for administrative pages: https://drupal.org/node/1524944

---
Tags: javascript
---


# Question
Title: Obfuscating email addresses displayed by Views?
I'm working on a View that displays a user's email field as a mailto. Given this is a recipe for spam, I'm wanting some way of obfuscating it.

I thought I'd go with Invisimail, but it (and seemingly ever other similar project) relies on a text filter. Given that the User email field doesn't use input formats, this makes it useless for my particular application.

I suppose I could create a separate email field, but I'd really like to not have to.

In short -- **How do I obfuscate a user email field displayed via Views?**

Thanks!

# Answer
Spamspan module will help you. It can obfuscate email addresses from email fields along with emails provided inline in text.

For email field - chooses Spamspan formatter in display settings.
> 1 votes

# Answer
To obfuscate the default users email field in a view you need to combine answers from Eugene and Eva.

* install spamspan module
* use the users email field in a view
* copy the file views-view-field.tpl.php from \[path\_to\_modules\]/views/theme folder to your theme folder
* change file name from views-view-field.tpl.php to views-view-field--mail.tpl.php
* replace the default output in that file for the code snippet from Eva
* clear theme cache
> 1 votes

# Answer
We use custom tpl.php file for the user account email field. In this field we have the following code:

```
<?php
if (function_exists('spamspan')) {
  print spamspan($output);
} else {
  print $output;
}
?>

```
> -1 votes

---
Tags: views, users, emails
---


# Question
Title: How to apply pagination on checkbox options of form elements in Drupal?
How to apply pagination on checkbox options of form elements in Drupal?

for example:

```
$form['display'] = array(
        '#title' => t('Type'),
        '#type' => 'checkboxes',
        '#description' => t('Please Select Type'),
        '#options' => theme('xyz',array($disclaimer_term)).theme('pager'),
    );

```

Is this possible to limit the number of options of checkbox?

# Answer
Best option you can do it without checkbox in pagination you can enable module like multiselect widget which work like dropdown with checkbox field.
> 0 votes

---
Tags: forms
---


title: How do you add the 'Edit View' Links?

text:
# Question
Title: How do you add the 'Edit View' Links?
How do you add the 'Edit View' Links in the gear icon that appears when you hover the mouse over a block. I can see "Configure Block" but I want also "Edit View" option. I know these icons are the output from the Contextual links module that comes with Drupal core so I'm not sure how to merge the two to be used on 1 block.

# Answer
> 1 votes
Can you Please Check this, Hope its help you. https://www.drupal.org/documentation/modules/contextual

---
Tags: views, navigation, blocks
---