# Question
Title: Glossary mode on View Block disappear once a letter is clicked
I know how to attach Glossary mode into View page, based on setting here. I have tried to attach this mode into one of my block, but it does not seem to work. Is there a solution that work for block with Glossary mode?

--- Update on March 28, 2015 ---

**I fixed by adding a View page(then I disable this) and that Glossary mode just work fine on block, except it will disappear once a letter is clicked. I found a solution about this issue on Drupal 6. Does anyone know how to fix this on Drupal 7?**

# Answer
Found the step by step correct setting from here.

1. Create a view with page to show desired content type (PS: you must create a view page, event you only use the view block)
2. click on CONTEXTUAL FILTERS
3. add content title
4. Select this page override
5. Select Provide default value and type fixed value
6. Enter "a" for default display only "a" word containing content and enter "all" for default display "all" content
7. select Specify validation criteria:Basic
8. Click More AND check Glossary mode option
9. Set Character limit 1
10. save
11. Use Ajax "yes"

**Now add a attachment**

1. click on CONTEXTUAL FILTERS
2. add content title
3. Select this attachment override
4. Click Display a summary
5. Click Unformatted and check Display items inline, under Separator add "-" or "|"
6. Set Attach to: page From ATTACHMENT SETTINGS
7. Set Inherit contextual filters: NO From ATTACHMENT SETTINGS
8. Use Ajax: Yes
9. Now save and run the page
> 0 votes

---
Tags: 7, blocks, views
---


title: simple external variables to hooks

text:
# Question
Title: simple external variables to hooks
Using drupal 7, Views 3, I have a function (present on Leaflet Module) which takes only 2 parameters. I use this hook function to print resulting points from view in different colors

```
//Allow modules to alter the points data while rendering a leaflet views row.
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points)
{
  if (isset($result->number))
 {
  // Add number value to every points data entry, if present.
    array_walk($points, function(&$point, $key, $number) {
     $point['number'] = $number;
   }, $result->number);
 }
}

```

I am trying to use this hook to take variables from outside the function. For example:

```
$data='heeeello';

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points)
 {
  echo $data;
 }

```

Just returns NULL. Tried setting it up as Global (which should already be, but just in case), also variable\_set($data,'hello')... no success.

Executing the function passing the params works neither:

```
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points,$param)
{
  echo $param;
}

```

thanks in advance

**EDIT**

I want to populate an external array based on the data processed by my hook (see below MY\_MODULE\_leaflet\_views\_alter\_points\_data\_alter)

This final array has to contain unique values. On standard PHP I would access the external array and populate recursively it but I have problems accessing this array via my hook.

Using global doesn't work, but it works using variable\_set and variable\_get, but it means that each time the hook access the variable (variable\_get(param)), the array starts empty again.

```
$array = array();

variable_set('my_array', $array);

//testing global, doesnt work
$test=array();

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {

    global $test;
    var_dump($test); //NULL

    $my_array= variable_get('my_array');
    //I will get allways an empty array... even if its later correctly populated

    //fetching results from the hook
    $name=$result->name;

    if (!in_array($name,$my_array))
      {
        array_push($my_array,$name);
      }

    //plots just a value (array is not recursively populated, as allways start empty inside the hook)
    var_dump($my_array);
 }

```

# Answer
> 1 votes
This is a php issue.

```
$data = 'heeeello';

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  echo $data; // $data is NULL, will also throw a notice
}

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  global $data;
  echo $data; // $data is 'heeeello'
}

```

regarding your variable\_set, the params are different:

```
$data = 'heeeello';
variable_set('hello', $data);
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  $data = variable_get('hello');
  echo $data; // $data is 'heeeello'
}

```

**RE edit**: this goes towards your extension: variable\_set() is not designed to do sets on every request, variables should be quiet consistent, every variable\_set will clear your cache (to some extend), abusing this will lead to a lot of performance problems.

If you need a cache use cache\_set and cache\_get, for singletons/ static stuff use drupal\_static. The global variable $test you are using right now in your question, should not return NULL but array(), everything else looks like a different problem.

If you want to build up a storage backend create proper tables using hook\_schema or (advanced) build your own entities.

edit: almost forgot, your code from above, is not working because you are not saving that variable again, so even for the second run it will always be empty.

---
Tags: views, hooks
---


title: Flag: update link to processed via JS

text:
# Question
Title: Flag: update link to processed via JS
I'm using flag module to flags my nodes. Now, in frontpage the list of nodes (html) is get and put in the main DIV via AJAX, so the flag module has not parsed these nodes. How can I say to flag module to re-get and process all flag link ? I know that I need to insert the call in my AJAX .get() function, but which is the correct flag-JS-function to call ?

Thanks.

# Answer
You probably should run `Drupal.attachBehaviors($('.newcontent'));` instead of trying to add this logic manually for each module. But since you asked for flag 3.x it is `Drupal.behaviors.flagLink.attach($('.newcontent'));`
> 1 votes

---
Tags: 7, flags
---


# Question
Title: Solr multi-select facets occurs bad request error
I faced with a weird problem using apache solr faceting search. While selecting two facet constraints, solr respond with 400 error:

> "400" Status: null: null HTTP ERROR 400
>
> Problem accessing /solr/project/select. Reason:
>
> null

Basically I have one index configured and number of fields indexed inside. I'm using facet for "content type" field. There is no problem at all when only one facet constraint is selected.

> http://localhost:8983/solr/project/select?fl=item\_id,score&fq={!tag=facet:type}ss\_type:"system"&start=0&rows=10&sort=ds\_created desc&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field={!ex=facet:type}ss\_type&f.ss\_type.facet.limit=50&wt=json&json.nl=map&q.alt=(ss\_search\_api\_language:"sv") (index\_id:"project\_nodes\_index") (hash:gf1tmd)

Problem starts where two constraints are selected:

> http://localhost:8983/solr/project/select?fl=item\_id,score&start=0&rows=10&sort=ds\_created desc&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field={!ex=facet:type}ss\_type&f.ss\_type.facet.limit=50&wt=json&json.nl=map&q.alt=(ss\_search\_api\_language:"sv") ((({!tag=facet:type}ss\_type:"system") OR ({!tag=facet:type}ss\_type:"product"))) (index\_id:"project\_nodes\_index") (hash:gf1tmd)

Standart modules are used: * search\_api\_solr * search\_api * facetapi

Solr version 3.6.2

# Answer
> 0 votes
I think you can update to the latest dev version.

For more info you could check this issue:

https://www.drupal.org/node/2290601

---
Tags: search
---


title: Export Users with custom fields?

text:
# Question
Title: Export Users with custom fields?
I need to set up a semi-regular export of people who have signed up on our website. We're using Drupal 7. I can do a simple export of the Users table, but that doesn't include the additional custom fields we've added.

Is there a module already available in D7 that handles exporting the user database with the custom fields associated with these records?

If not, is there a simple query I can do to identify the custom fields associated with the registration process at runtime? I'd like the export to still work if my customer decides to add a new field.

# Answer
I can't think of any contrib module that would do this, but I can think of a somewhat simple custom module solution.

Create a custom module that has a hook\_menu call back to a form that you've built with the form api that has a submit button that says "Generate Report".

Make sure to create a corresponding permission with hook\_permission so only users of your choice can access this form.

Then in the submit just run a query ( using db\_query ) on the users table to get all uid's, then iterate thru each uid to load the full user with user\_load and build a CSV row with the fields you want, or all fields. After building the entire csv save it somewhere on the server with a timestamp and link the user to it, or just stream it back to them as a download.
> 1 votes

# Answer
I know that this question has already been answered, but thought I'd point out the Views Data Export module for anyone looking for a contributed solution rather than a bespoke one. This module allows you to define Views that generate CSV files for export. We're using this with Drupal 7 for a client so that they can export all users and their associated custom fields. It's working well.
> 4 votes

# Answer
Another option to consider for addressing these requirements is the Forena module.

You would use its report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file, or XLS, or DOC, or ...

Here is a quote from one of the forena community docu pages, i.e. Reasons for considering Forena:

> Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

The Forena Video demos and tutorials contain quite some links to live demos.
> 0 votes

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


# Question
Title: Can't get hook_field_attach_view_alter to set the value of the field
I'm using some hook code I got from Drupal 7 show empty fields in order to show all of the empty fields on my node when viewing it. I would like to put a simple `-` as the displayed value when the field is empty.

```
function mymodule_field_attach_view_alter(&$output, $context) {
    // other stuff clipped...
    $output[$field_name] = array(
        '#theme' => 'field',
        '#title' => $instance['label'],
        '#label_display' => 'inline',
        '#field_type' => $field['type'],
        '#field_name' => $field_name,
        '#bundle' => $node->type,
        '#object' => $node,
        '#items' => array(),
        '#entity_type' => 'node',
        '#weight' => $display['weight'],
        0 => array('#markup' => '-'),
    );
}

```

I pulled the code from the linked page above and just changed the one line at the end that has `#markup`. As far as I can tell from the api docs, this code should work, but nothing that I put into that `#markup` value shows up.

All of the empty fields DO show up, it's just that the value shown is empty instead of `-` or `blah` or `foo`, because I've tried those as well. :)

How do I set the value to display when I use `hook_field_attach_view_alter`?

# Answer
> 1 votes
Ok, I found the answer: the key "#items" in the output array needs to have an array with an array as the value - not just the array:

```
$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => ' '),
  );

```

becomes

```
$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(array()),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => ' '),
  );

```

---
Tags: 7, entities, hooks
---


# Question
Title: How to allow direct user input links the Facebook way?
Does Drupal offer the possibility to have users input a link the Facebook way? In other words, showing directly a summary kind of view of the linked page? Thanks.

# Answer
> 2 votes
You are looking for oembed, there is a Drupal module for it as well, that offers integration to media and some other modules.

> This module will allow your Drupal site to embed content from oEmbed-providers as well as for the site to become an oEmbed-provider itself so that other oEmbed-enabled websites can easily embed your content.

This won't give you a facebook experience out of the box, you still have to configure quiet a lot, you might want to read up on this: #2108973 Making oEmbed module work with WYSIWYG and CKeditor, which also links #2269433: Support URLs on a line by themselves in ckeditor/WYSIWYG.

---
Tags: social-network, navigation
---


# Question
Title: ajax callback add more on a select field
I am trying to implement a "add x" on a select field but it doesn't seem to work.

I've tried to follow this example but they use a submit for that.

```
$form['myfield'] = array(
    '#type' => 'select',
    '#options' => $optionsServer,
    '#ajax' => array(
        'callback' => 'ajax_select_change',
        'wrapper' => 'names-fieldset-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
    ),
);

$form['#tree'] = TRUE;
if (empty($form_state['num_names'])) {
   $form_state['num_names'] = 1;
}
$form['myfieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('myfieldset'),
        '#prefix' => '<div id="names-fieldset-wrapper">',
        '#suffix' => '</div>',
    );
for ($i = 0; $i < $form_state['num_names']; $i++) {
   $form['myfieldset']['field'.$i] = array(
       '#type' => 'textfield',
       '#title' => t('field'),
       '#size' => 60,
       '#required' => TRUE,
   );
}

function ajax_select_change($form, &$form_state){
    //$form_state['num_names'] is used to create x new textfield
    $form_state['num_names'] = $form_state['values']['myfield'];
    //rebuild this form to get the new count
    $form_state['rebuild'] = TRUE;
    //change the fieldset containing the code to build textfield
    return $form['myfieldset'];
}

```

Is it doable? I can try to create a button then trigger it when I change the select value but this is clearly a crappy hack.

Any idea?

EDIT: I find out some solution:

```
function my_form($form, $form_state){
    $form['container']['myField1'] = array(
        '#type' => 'select',
        '#options' => $optionsField1,
        //don't forget the $form_state['values']['container']['myField1'] as default, it will keep the same value after the rebuild
        '#default_value' => isset($form_state['values']['container']['myField1']) ? $form_state['values']['container']['myField1'] : $form_state['num_names'] ,
        '#ajax' => array(
            'callback' => 'ajax_select_change',
        ),
    );
}

function ajax_select_change($form, $form_state){
    $new_state = array();
    $new_state['build_info'] = $form_state['build_info'];
    $new_state['rebuild'] = TRUE;
    $new_state['values'] = $form_state['values'];
    $new_state += form_state_defaults();

    $new_form_array = drupal_rebuild_form('my_form', $new_state);
    $new_form = drupal_render($new_form_array);

    $commands = array();
    //reload form
    $commands[] = ajax_command_html('#formId', $new_form);
    //change inside Id #price
    $commands[] = ajax_command_replace('#price', drupal_render($form['container']['myField2']));
    return array('#type' => 'ajax', '#commands' => $commands);
}

```

EDIT 2: see the proper solution below (in the comment), much more simple and make more sense!

# Answer
After an AJAX submit by a select or some similar not submit element the Form API rebuilds de form if no validate errors are found. See drupal\_process\_form() where this is stated in the inline comments:

> ```
> // However, for forms that have not been fully executed (e.g., Ajax
> // submissions triggered by non-buttons), there is no submit handler to set
> // $form_state['rebuild']. It would not make sense to redisplay the
> // identical form without an error for the user to correct, so we also
> // rebuild error-free non-executed forms, regardless of
> // $form_state['rebuild'].
>
> ```

Your code is not working because you update your number of elements in the callback function in this line:

```
$form_state['num_names'] = $form_state['values']['myfield'];

```

The callback function is executed after all form processing so your modifications are done too late. In fact, callback function should only return the response, no modifications on the form should be done here.

Try something like this:

```
$form['myfield'] = array(
    '#type' => 'select',
    '#options' => $optionsServer,
    '#ajax' => array(
        'callback' => 'ajax_select_change',
        'wrapper' => 'names-fieldset-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
    ),
);

$form['#tree'] = TRUE;
if (empty($form_state['num_names'])) {
   $form_state['num_names'] = 1;
}
else {
  // If there's is value in myfield update number of available names elems.
  $form_state['num_names'] = $form_state['values']['myfield'];
}

$form['myfieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('myfieldset'),
        '#prefix' => '<div id="names-fieldset-wrapper">',
        '#suffix' => '</div>',
    );
for ($i = 0; $i < $form_state['num_names']; $i++) {
   $form['myfieldset']['field'.$i] = array(
       '#type' => 'textfield',
       '#title' => t('field'),
       '#size' => 60,
       '#required' => TRUE,
   );
}

function ajax_select_change($form, &$form_state){
    return $form['myfieldset'];
}

```
> 2 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Way for Admin to log in as an existing user without password for troubleshooting
I'm the administrator & sysadmin for a Drupal site with a few thousand users. In maintaining the site, sometimes I need to troubleshoot issues reported by users that are difficult for me to reproduce when I'm logged in as me. Discrepancies in our abilities to reproduce the issue could be caused by (for example) roles and permissions or ownership of content. In any case, I'd like an easy way to log in as that particular user to test and troubleshoot the situation. And obviously I don't want to ask the the user tells me their password. Is there an easy way to do this?

# Answer
> 4 votes
Masquerade is what you need:

> The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.

---
Tags: users
---


# Question
Title: Returning all items in Views for Dates with Start dates AFTER Now as well as no date set
I have some items that have dates and some that do not. For items that have dates I do NOT want to show items that are past due (ie. events that are before today's date (or 'now' is fine). However I also want to display items that have no dates set.

In my view if I filter on dates I can choose to display events that are on today or later, and that works fine. But then it doesn't display any items that have no dates.

So, my question is, how can I customize my filter to show items with no value for event date as well as items that start on or after 'now'?

# Answer
> 1 votes
You can use OR conditions with the filters, and have one group of filters checking for the date value, and the other one checking for empty date field.

You would end up with something like:

```
*Some filters group you probably have here*
AND
  Date >= NOW
    OR
  Date IS EMPTY

```

Here is a post for some info on how to work with these - http://www.webomelette.com/drupal-views-filters-and-or-logic

---
Tags: views, datetime
---


# Question
Title: Customize user registration form by adding/modifying fields in the form and handling submit function
I am new to drupal.

I need to customize a registration form by adding fields like id,mobile etc.

Can I accomplish this by creating a custom module?

If yes could anyone please help me with a brief idea on creating and overriding the default user registration submit function. I have to insert these details to another table and also have to pass the data as a service request.

Ive created a custom module with function

```
function module_form_alter(&$form,&$form_state,$form_id){
$form['#submit'] = 'module_form_submit';

if($form_id == 'user_register_form'){
    //print_r($form_id);
    $form['email'] = array(
            '#type' => 'textfield',
          '#title' => t('id'),
          '#default_value' => '',
          '#size' => 60,
          '#maxlength' => 15,
          '#required' => TRUE,
     );
    }
}

function module_form_submit($form, &$form_state){
  echo "test";
 exit();
}

```

module\_form\_alter is being called and I can see the new field on the registration screen but the submit function is still not called. I need to override the default drupal register submit.

I already have the following function in my theme template.php

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

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
     'portal_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'portal_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'portal_preprocess_user_pass'
    ),
  );

  return $items;
}

```

user-register-form.tpl.php

```
    <div class="form-group">
    <?php print drupal_render_children($form); ?>
    </div>

```

And page--user--register.tpl.php with the html

```
<div id="login-page">
    <div class="container">
             <div class="form-login" >
            <h2 class="form-login-heading"><a href="<?php echo $home; ?>"><img src="<?php echo drupal_get_path('theme', 'portal') . '/images/logo.png'; ?>"  width="100"></a><?php echo $createaccount; ?></h2>
            <div class="login-wrap">
            <?php
            $elements = drupal_get_form("user_register_form");
            $form = drupal_render($elements);
            echo  $form ?>

     <?php if ($messages):?>
        <div id="messages-console" class="clearfix">
            <div class="grid_12">
                <div class="mt-grid-fix">
                <?php print $messages; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        </div>
                </div>

    </div>
  </div>

```

Is this approach fine or should I change this approach inorder to make my custom module functional?

One problem, I need to validate this form in client side, Ive added js in module\_form\_user\_register\_form\_alter function as
$form\['#attached'\]\['js'\] = array(drupal\_get\_path('module', 'modulenamne').'/js/myjs.js',);

File is loaded but when clicked on submit the js is not working, instead the page is loading and drupal submit is executing.

# Answer
If it is not crucial for you to have the additional fields in custom code, I would highly recommend you to make use of the fact that user is a fieldable entity and you can add additional fields easily to it via administration at "admin/config/people/accounts/fields" - this way you do not need to handle saving of the data and display of form elements.

When doing so, you can still make use of custom validation or submit handlers or fiddle with the form and fields easily using the same technique you are using - `hook_form_alter` and add your submit handler to do whatever logic you require.

Back to your approach — the reason why your submit function is not being called is that you are assigning a string to it instead of adding an element to the array. Try this:

`$form['#submit'][] = 'module_form_submit';` (notice the empty brackets on the left side).

If you want to completely overwrite the submit functions array use this:

`$form['#submit'] = array('module_form_submit');` \- but this will cause that the user will not be created and data saved (unless you do that by hand in your custom submit handler), this also cancels whatever some contrib modules to with the registration form, so you might have unexpected issues.

**Edit after comments:**

If you do want to keep the default behaviour, but do your logic before everything, you can put your submit handler as first, as they are executed based on their order in the array like this:

`array_unshift($form['#submit'], 'module_form_submit');`
> 3 votes

---
Tags: 7, users
---


# Question
Title: Using Views and adding ALT and TITLE to an image
I've been attempting to add my node Title to the image ALT and TITLE fields during their output in a view.

I am using the Media module to mange my images, and I have included the `image_url_formatter` module to offer up the image URL information in my view.

I attempted the advice in this post How to add alt and title attributes to an image gallery View? and it almost works however this is occurring:

Within the View, If I alter the Image field to output the Image URL this works and I get my option of URL information in both preview and actual view. If I then attempt to Rewrite the results, I suffer from two issues.

1. The `[field_image-fid]` outputs a numerical number only. i.e 1 or 4 etc...
2. The `[field_image-width]` & `[field_image-height]` output the actual image height and width rather then the selected image style, i.e. Thumbnail.

Anyone suffered from these issues, or know the answer?

# Answer
> 1 votes
Is the title-field *before* the Global text-field? Can you provide a screenshot of your field-settings in the View? (the most left column)

# Answer
> 0 votes
Did you try marking all fields Exclude from display? Then, at the end, add another Global text field and write down your code using Views tokens. Every field should be declared above Global text field. From there, you can play with rewriting fields, although they are excluded.

---
Tags: views, media
---


title: Analyzing slow mysql querries

text:
# Question
Title: Analyzing slow mysql querries
Our Drupal site has recently started to get much more traffic and often pegs the CPU and memory when we have 50-100 active connections. We have 8cpus and 16GB of RAM. I notice that when the cpu is pegged mysql is by far the largest consumer so I decided to look at the mysql-slow.log and found that some queries take over 1 second and I am wondering if this is reasonable. Here is one example:

```
# Time: 150330 12:01:34
# User@Host: root[root] @ localhost []
# Query_time: 1.131631  Lock_time: 0.000301 Rows_sent: 4  Rows_examined: 151102
SET timestamp=1427738494;
SELECT
  node.nid AS nid,
  node.title AS node_title,
  users_node.name AS users_node_name,
  users_node.uid AS users_node_uid,
  votingapi_cache_node_points_projects_sum.value AS votingapi_cache_node_points_projects_sum_value,
  node.created AS node_created,
  node.changed AS node_changed,
  node_revision.timestamp AS node_revision_timestamp,
  'node' AS field_data_field_screenshot_node_entity_type
FROM node AS node
INNER JOIN users AS users_node
  ON node.uid = users_node.uid
LEFT JOIN votingapi_cache AS votingapi_cache_node_points_projects_sum
  ON node.nid = votingapi_cache_node_points_projects_sum.entity_id
  AND votingapi_cache_node_points_projects_sum.entity_type = 'node'
  AND votingapi_cache_node_points_projects_sum.value_type = 'points'
  AND votingapi_cache_node_points_projects_sum.tag = 'projects'
  AND votingapi_cache_node_points_projects_sum.function = 'sum'
LEFT JOIN votingapi_vote AS votingapi_vote_node_points_vote
  ON node.nid = votingapi_vote_node_points_vote.entity_id
  AND votingapi_vote_node_points_vote.entity_type = 'node'
  AND votingapi_vote_node_points_vote.value_type = 'points'
  AND votingapi_vote_node_points_vote.tag = 'vote'
LEFT JOIN node_revision AS node_revision
  ON node.vid = node_revision.vid
WHERE node.status = '1'
  AND node.type IN ('arcade_project_container')
  AND EXISTS (
    SELECT na.nid AS nid
    FROM node_access AS na
    WHERE na.gid = '0'
    AND na.realm = 'all'
    AND na.grant_view >= '1'
    AND node.nid = na.nid
  )
ORDER BY
  node_created DESC,
  node_changed DESC,
  node_revision_timestamp DESC
LIMIT 4 OFFSET 5800;

```

This query comes from the front page where I have a view which shows the most recent submissions. Should this query really take 1.13 seconds?

EDIT: Here is a screenshot of the results of running EXPLAIN on this query on phpmyadmin:

Here is the EXPLAIN after switch nid and uid as suggested by mikeytown2:

# Answer
Add a new index of type index on the node table with these 7 columns; I would label it "status\_type\_uid\_nid\_vid\_created\_changed"

```
status, type, uid, nid, vid, created, changed

```

Once you have done that run explain again; odds are the index will need to be re-ordered or another table will need to have an index added to it.

Try #2. Flip nid & uid.

status\_type\_nid\_uid\_vid\_created\_changed

```
status, type, nid, uid, vid, created, changed

```
> 1 votes

---
Tags: views, performance, database
---


# Question
Title: Enabling Views module causing cron to fail
Quite simply, I enable the super common "Views" module, and on Save nothing but a white page happens. On a refresh (Where I agree to the form resubmission) the modules page comes back just fine.

Then I click the "Run cron" link, and that is also blank, and never shows anything else or redirects.

Visiting cron.php by itself, also blank.

I've seen some solutions, such as increasing php's memory\_limit and mysql's max\_allowed\_packet, but neither have done anything.

Everything runs optimally again the moment I disable Views.

**Some info**:

Web server: nginx/1.4.6
PHP: 5.5.9
PHP memory limit: 256M
Drupal: 7.35

I've never had this problem before, especially with Views

# Answer
Sounds like either:

1. You have two copies of the Views module enabled somehow.
2. You have a problem with your server configuration in relation to op-code caching.

Check your "system" table in the database with:

```
SELECT name, filename, status FROM system WHERE name = 'views';

```

Check the results are as expected for your install.

For the op-code cache issue, check this thread:

> Cannot redeclare class view, updating to PHP5.5

https://www.drupal.org/node/2066561

It may be a problem with using multiple op-code caching methods, or xcache conf issue.
> 1 votes

---
Tags: views, 7, cron, users
---


title: Colapse even rows of table

text:
# Question
Title: Colapse even rows of table
I have a table in my site that I build in my own module with theme table. I want to be able to have a sort of link in each even row (the ones with the color buttons) that allows me to collapse those rows. In fact, when loading the page, those rows should be already collapsed and only visible if the user wants.

Is this even possible using theme table? Is there any alternative I should use to do it?

Thanks

# Answer
> 0 votes
Maybe ctools\_collpasbile is a solution? http://timonweb.com/posts/painless-collapsible-divs-in-drupal/#

I just can't apply it to my table.

---
Tags: theming
---


# Question
Title: When using the Batch API should I create an operation per node?
I am using the Batch API in Drupal 7 and I just realized that the reason why my count and totals are not showing correctly is because the initial total is based on a count of the operations given to it.

The thing is I set it up so that each operation processes 100 nodes. I have to update information in nodes that meet certain criteria and there are almost 7,000 nodes that have to be updated. So I thought it would be more efficient to fix multiple nodes per operation call.

Instead it seems like I should put in an operation per node or an operation per 100 nodes (even though my current setup seems to keep calling the same operation with no problems). So what should it be? I guess I could use the context variable to force it to count properly, but I don't like hacking around issues if I don't have to.

Below is the code I am using:

```
/**
 * Load the nodes with the broken language bodies and fix them.
 */
function my_fixes_broken_bodies() {
  $brokenBodyCnt = my_fixes_count_broken_bodies();
  $operations = array();
  $limit = 100;
  $count = ceil($brokenBodyCnt / $limit);

  // Give helpful information about how many nodes are being operated on.
  drupal_set_message(t('There are @brokenBodyCnt nodes to fix. And we are fixing @limit nodes per call. So the operation will require @count HTTP requests.', array('@brokenBodyCnt' => $brokenBodyCnt, '@limit' => $limit, '@count' => $count)));

  //Setup the operations for the fixes
  $operations[] = array('my_fixes_broken_bodies_op', array('broken body fix'));

  $batch = array(
    'operations' => $operations,
    'finished' => 'my_fixes_finished',
    'title' => t('Fixing broken node body language settings.'),
    'init_message' => t('The broken body fix is starting...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('The broken body fix has encountered an error.'),
  );

  return $batch;
}

/**
 * Batch operation for fixing the broken bodies.
 */
function my_fixes_broken_bodies_op($operation_details, &$context) {
  if (empty($context['sandbox'])) {
    $context['sandbox'] = array();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;

    // Save node count for the termination message.
    $context['sandbox']['max'] = my_fixes_count_broken_bodies();
  }

  // Process nodes by groups of 100
  $limit = 100;

  // Retrieve the next group of nids.
  $result = db_query("SELECT n.nid, FROM_UNIXTIME(n.created) AS created, n.title, n.type, n.language AS 'Node Language', b.language AS 'Body Language'
  FROM node n INNER JOIN field_data_body b ON nid = entity_id
  WHERE n.language != b.language AND status = 1
  ORDER BY nid ASC LIMIT $limit");
  $results = $result->fetchAll();

  foreach ($results as $row) {
    $node = node_load($row->nid);

    if (isset($node->body['en']) && !isset($node->body[$node->language])) {
      $node->body[$node->language] = $node->body['en'];
      $node->body['en'] = NULL;
      node_save($node);
    }

    $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;

    // Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $node->nid;
    $context['message'] = check_plain($node->title);
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }

  _my_fixes_update_http_requests();
}

```

# Answer
Ok, so I figured out a better approach. Below I have listed my new code. The gist of it is that I decided to break it out in such a way that I will have one operation per 100 nodes that need to be fixed. I have 6,581 nodes that need to be fixed. So that means I need 66 operations to fix all of the nodes.

I created some calculations that determine how many operations I need to run. Then I set each operation to only process 10 nodes at a time (to save memory). Once an operation has hit it's max of 100 nodes it then tells the Batch API it is finished. This is part of what I was getting hung up on. I thought that max and finished referred to the entire batch process, not the current operation.

Theoretically I could create an operation for every single node that needs to be fixed. But this seems highly excessive, and a bit inefficient. It would increase the db calls quite a bit and the HTTP calls.

Another improvement I made to my code is to only return the node id field in the query instead of all those extra fields that I didn't need. This changed the query run time from about 7.5 seconds to about 0.24 seconds.

All in all I am much happier with the results.

```
function my_fixes_broken_body_nodes() {
  $results = db_query("SELECT n.nid
  FROM node n INNER JOIN field_data_body b ON nid = entity_id
  WHERE n.language != b.language AND status = 1
  ORDER BY created DESC");

  $count = $results->rowCount();
  $results = $results->fetchAll();

  return array('node_ids' => $results, 'count' => $count);
}

/**
 * Load the nodes with the broken language bodies and fix them.
 */
function my_fixes_broken_bodies() {
  $brokenBodies = my_fixes_broken_body_nodes();
  $brokenBodyCnt = $brokenBodies['count'];
  $operations = array();
  $limit = 10;
  $nodesFixedPerOp = 100;
  $count = ceil($brokenBodyCnt / $limit);
  $opCount = ceil($brokenBodyCnt / $nodesFixedPerOp);

  // Give helpful information about how many nodes are being operated on.
  drupal_set_message(t('There are @brokenBodyCnt nodes to fix. And we are fixing @limit nodes per call. So the operation will require @count HTTP requests.', array('@brokenBodyCnt' => $brokenBodyCnt, '@limit' => $limit, '@count' => $count)));

  //Setup the operations for the fixes
  for ($i = 0; $i < $opCount; $i++) {
    $operations[] = array('my_fixes_broken_bodies_op', array(t('(Operation @operation)', array('@operation' => $i))));
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'my_fixes_finished',
    'title' => t('Fixing broken node body language settings.'),
    'init_message' => t('The broken body fix is starting...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('The broken body fix has encountered an error.'),
  );

  return $batch;
}

/**
 * Batch operation for fixing the broken bodies.
 */
function my_fixes_broken_bodies_op($operation_details, &$context) {
  // Process nodes by groups of 10
  $limit = 10;

  if (empty($context['sandbox'])) {
    $context['sandbox'] = array();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;
    $brokenBodies = my_fixes_broken_body_nodes();

    // Save node count for the termination message.
    $context['sandbox']['max'] = 100;
    $context['sandbox']['node_ids'] = $brokenBodies['node_ids'];
  }

  // Retrieve the next group of nids.
  for ($i = 0; $i < $limit; $i++) {
    $row = array_shift($context['sandbox']['node_ids']);
    $node = NULL;

    //Load the node
    if (isset($row->nid) && !empty($row->nid)) {
      $node = node_load($row->nid);
    }

    //Make sure it loaded alright and then run operations on it.
    if (!empty($node) && is_object($node)) {
      if (isset($node->body['en']) && !isset($node->body[$node->language])) {
        $node->body[$node->language] = $node->body['en'];
        $node->body['en'] = NULL;
        node_save($node);
      }

      $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;

      // Update our progress information.
      $context['sandbox']['progress']++;
      $context['sandbox']['current_node'] = $node->nid;
      $context['message'] = check_plain($node->title);
    }
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }

  _my_fixes_update_http_requests();
}

```
> 4 votes

# Answer
* Use `$context['sandbox']` to store the total count to process as well as the current nid.
* Order your SQL by nid ASC
* Select nodes greater than current nid on next pass.

e.g:

```
if (!isset($context['sandbox']['max'])) {
  // Set max for progress count later
  $context['sandbox']['max'] = db_query("SELECT count(nid) FROM {node} WHERE type = 'article'")->fetchField();
  $context['sandbox']['current_nid'] = 0;
  $context['sandbox']['progress'] = 0;
}
// Get current set of nodes to process, based on current nid
$limit = 10; // Number to process on each pass
$query = db_select('node', 'n');
$query->fields('n');
$query->condition('type', 'article');
$query->condition('nid', $sandbox['current_nid'], '>');
$query->orderBy('nid');
$query->range(0, $limit);
$result = $query->execute();
foreach($result as $row){
  // Process nodes...
  // Process nodes...
  // Process nodes...
  $context['message'] = t('Now processing %node', array('%node' => $row->title));
  // Set current node id to start next batch from after this one
  $context['sandbox']['current_nid'] = $row->nid;
  $context['sandbox']['progress']++;
}
// Inform the batch engine that we are not finished,
// and provide an estimation of the completion level we reached.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}

```
> 3 votes

# Answer
I'm looking for same answer and I think array\_chunk() is a good idea for meet this requirement. See this example:http://www.metaltoad.com/blog/using-drupal-batch-api
> 0 votes

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


# Question
Title: Working on Drupal and Drush with teammates
I'm currently working on a website using Drupal 8, with 3 other members in my team.

We use git as a versioning system, and we very often work at the same time on different branches.

Here is the problem :

* If we all use local databases, then it's a mess when we have to merge our code, because we have to isolate the parts of the database that have changed, and create a patch, or re-create the changes ourselves a second time. For example if I have created many static pages, I have to create them again, or export the part of the database containing them.
* If we choose to share a database to avoid that problem, then every time someone runs the `drush cr` command, everyone's website gets synched to their last changes, erasing every other changes from other teammate, which can be very confusing and annoying.

What is the right solution here?

# Answer
Checkout configuration management in Drupal 8. Though there are many modules that can help you out but most of them are in active development and not stable for production use yet.

Two most promising modules are Configuration Update module and Features module.

Checkout What are the alternatives to Features module in Drupal 8 for further notes.
> 0 votes

---
Tags: drush, 8
---


# Question
Title: How to set the default value of remember me in the persistent login module to on?
The persistent login module gives a "Remember me" at login.

How to set this value default on?

# Answer
> 1 votes
It does not look like that module offers such a setting by default, so you'll have to change the option using hook\_form\_alter as well (in a custom module).

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  // I don't check for the specific form here, since we do have a specific element we can look for.
  if (isset($form['persistent_login'])) {
    $form['persistent_login']['#default_value'] = TRUE;
  }
  if (isset($form['account']['persistent_login'])) {
    $form['account']['persistent_login']['#default_value'] = TRUE;
  }
}

```

You will have to make sure that your custom module is run **after** the persistent login module:

---
Tags: users
---


# Question
Title: Is it safe to update a field value direclty on the Database
When updating a field attached to a node, Drupal calls several hooks and add a record on the appropriate field revision. Is there any risk if I by-pass this process and update the field value via a sql query.

# Answer
> 4 votes
It is not recommended, there is a way of doing this using `field_attach_update` which should give you the performance benefit of not saving the whole node while using drupal api. Example:

```
$node = new stdClass();
$node->id = $id_value;          // node id
$node->type = $bundle_value;  // aka content type

$node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
field_attach_update('node', $node);

```

Sources:

updating field value of a content type with query

https://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself

https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field\_attach\_update/7

---
Tags: 7, database
---


# Question
Title: Field values of nodes available as tokens
we would like to habe a node type only for side wide available values. We think we have a title and a 'value' field. When we need one of these values in text areas/fields we would like to type \[title\_of\_the\_node\] and in the output we get the value of the value field displayed.

Does anyone know a solution for this?

# Answer
> 0 votes
Have you looked at the Token API? With the API one can define custom tokens. The functions you should look at are:

With hook\_token\_info() you define new tokens. In your case you could retrieve all nodes of your configureation node type (with an EntityFieldQuery for example), loop over the entries and create a token for each of them.

In hook tokens you define what your tokens are replaced with - just load the node entity for the given token and retrieve the content of your value field.

Here is a tutorial I found useful when writing some custom tokens a while back: http://www.fredparke.com/blog/create-your-own-tokens-drupal-7

---
Tags: nodes, tokens
---


# Question
Title: Image Styles not creating on one custom style only
I've run into this issue where we have created a custom style (emailthumb) which is to be used when sending out email newsletters via simplenews. The thumbnail is based on 'thumbnail' style but is slightly bigger. It works fine when the image is being rendered as thumbnail or any other style but not the one custom style.

The permissions of the folders are all exactly the same (I've even tried 777 for emailthumb-\>public) as in thumbnail but there is no pictures folder being created. I then get a log error of access denied as the URL to the image as the folder doesn't exist.

http://example.com/sites/default/files/styles/emailthumb/public/pictures/image.jpg

I have tried changing the theme as per image style (imagecache) images are not being created but this has not worked.

Does anyone have any suggestions?

Current Permissions sites/default 555

# Answer
> 0 votes
The problem was that the image style was never being called to save the image in the first place. The following code forces the image to save for this use case.

```
function MODULE_node_presave($node){
  // Get some field items from a field called 'field_image.
  if ($image_items = field_get_items('node', $node, 'field_image')) {
    $image_item = array_shift($image_items);

    // Load the associated file.
    $file = file_load($image_item['fid']);

    // An array of image styles to create.
    $image_styles = array('emailthumb');

    foreach ($image_styles as $style_name) {
      // Get the location of the new image.
      $derivative_uri = image_style_path($style_name, $file->uri);
      $style = image_style_load($style_name);
      // Create the image.
      image_style_create_derivative($style, $file->uri, $derivative_uri);
    }
  }
}

```

credit here force image style generation on save node

---
Tags: 7, theming, media, emails
---


# Question
Title: How to edit the Comment Administration Page
I've already edited my comment and comment-wrapper.tpl.php files for public consumption. But I'm finding I'd like to edit the administration page where our staff administers comments that are pending approval. Is it possible to wrap that page in a tag or something so I can apply styles?

I'm talking about the pages at http://mysite/comment/1#comment-1 (for example, and so forth)...

# Answer
> 1 votes
I'm not too familiar with the comment system in Drupal, but you should be able to.

First check that the commment admin page is loading the theme you are using and not a system admin theme (Link to a screenshot if you are not sure).

If it is loading your custom theme then inspect the elements that you want to wrap as you may already have unique classes that you can use to style. Even the body tag should have unique classes for the comment admin section or you could add unique body classes in the template\_preprocess\_page function in template.php

If it is loading an admin/default theme you have 2 safe options:

1. Set drupal to load your custom theme for admin pages (but then you would have to style all the admin pages)
2. Copy & rename the admin theme, and set Drupal to load the copied theme for admin pages and change the styles in the copied theme.

If you know PHP well enough you could add your own template but you would have to override the default Drupal hook - hook\_comment\_admin\_overview() and add a template to the form with the theme() function (if a template file doesn't exist) but that could be quite difficult to get working without breaking.

Finally, if all else fails the quick dirty way would be to add html wrappers with jQuery but this is not recommended.

*EDIT*

Please check in your theme's html.tpl.php you have this code snippet:

```
<body class="<?php print $classes; ?>"

```

There should already be classes that are added to the $classes variable when editing a comment.

---
Tags: theming, comments
---


# Question
Title: Search using external sites Google Search
I am creating a Drupal site for a government agency, and we use Google Search for our websites. The problem I'm running into is the domain the site I'm creating is on is foo.com, and the search is supposed to be run through bar.gov.

My question is is there any way to get either the built in Seach module or the Google CSE module to submit the search query on the other domain? And if there isn't how would I go about creating either a block or content pane with the search box I need?

What I need is when you click Search on foo.com it directs you to bar.gov/gsearch?sitesearch=foo.com&q=terms. Specifically getting a form's action to be the bar.gov/gsearch.

# Answer
It's simple ,, if you know the HTML part so make your form action to the search site and call your GET parameters into the form!

something like this:

```
        <form  action="bar.gov/gsearch" target="_blank" method="GET" id="search-block-form">
        <input type="hidden" value="q" name="terms">
        <input type="hidden" value="foo.com" name="search">
<button type="submit" value="Search">Search</button>
    </form>

```

edit: you need to make sure you have HTML tags enabled and not stripped in anyway so the form and any other HTML tags be available .
> 2 votes

---
Tags: search
---


# Question
Title: How can hook some code before deleting a comment?
How can I add few lines of code before comments get deleted. there must be some hook or something by which we can do this. I am getting nothing relevant by Googling.

Any help appreciated.

# Answer
Strange enough, but there is no `predelete` hook present with Drupal 7 core, or even not provided by the entity module.

However the good news is Drupal 8 has this feature!
> 0 votes

---
Tags: 7, hooks, comments
---


title: User Edit Page for different elements

text:
# Question
Title: User Edit Page for different elements
I want to customize the user edit page. I want to separate the elements (eg. user password, user picture, user email) and put them each on a separate edit page. I tried the panels module, but that only allows me to move the entire form.

Is there a way to separate these form elements on different pages. For instance a change password page, a change user picture page and add the email into an existing user profile edit page?

# Answer
There are basically two main directions you can go if you want to 'expand' user profiles:

* You can either add fields, field groups and eventually group them in tabs or thelike.
* Or you try the module Profile 2 wgich is basically the successor of the core profile module.

Both approaches can be fruitful – both will let you spread user profiles over different 'pages' (or tabs). But I'm not sure how fine-grain you can actually go with these two approaches – and if you can actually 'diconnect' the *change password* ui from the rest. I usually try to keep the core info on one page – and 'the rest' (contact and bio etc.) on sub-pages (tabs).
> 0 votes

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


# Question
Title: How to keep all leading spaces in a text field (Drupal)
I need to allow users to insert leading spaces in their text. It appears that the default text field chopps off all leading spaces. I tried ckeditor and BUEeditor but they appear also to remove leading spaces, and I don't see any way to prevent that.

If possible, I don't want to use any text editor if possible.

Thanks

# Answer
> 0 votes
A very simple solution I found using the class white-space: pre;

---
Tags: entities, wysiwyg
---


title: Drupal 7 or 8 for bilingual site

text:
# Question
Title: Drupal 7 or 8 for bilingual site
I am working on a large project for a bilingual site. I would like to move their site from Wordpress to Drupal and see the multilingual capabilities of Drupal 8. However, the site won't be ready to build until late summer of 2015. Would it be a good idea to build on Drupal 8 or because of lag of modules and such, use Drupal 7. As I'm not using Drupal 7 now and don't need to worry about upgrading modules, I think it would be ok to go right into 8. I would like some feedback as to the best route.

# Answer
> 1 votes
Drupal 8 is great, and has a lot of improvements related to multi language sites. But Drupal 8 isn't ready yet, and it "will be ready when it's ready" (that's what some experienced Drupal-ers say, and I do fully understand that).

Also, after Drupal 8 is released (I've heard dates like somewhere in 2016 only, and it wouldn't surprise me), there are still all the contributed modules that will not be upgraded yet to Drupal 8. Today there are still Drupal 6 modules waiting for their Drupal 7 upgrade) ...

For all these reasons, I will continue to go for Drupal 7 for quite a while (probably at least the rest of 2015). Because of its maturity, and because I would not want to depend on a Drupal 8 release of either core, or any of the contributed modules that I "must have".

There is also that great presentation from David Reid about all those amazing contributed modules in Drupal 7, which are like backports of new Drupal 8 features.

---
Tags: i18n-l10n
---


# Question
Title: How to rename image filename and make same as title field value
Can somebody also help me to rename the image name same as title field?

I have a image content type where we have title and image field and when I submit the form I want to rename the image name same as the title field. This way I can make my image more meaningful by including keyword in the image name. Right now you can write about 'A' in the title field and you can upload images 'B' and that I don't want.

# Answer
It looks like you should be able to do this using the Filefield Paths module. This will allow you to use tokens based on node fields to rename the file on upload.
> 1 votes

---
Tags: hooks
---


# Question
Title: How to hook_views_query_alter arbitrary field and use it in view GUI
For the life of me I can't figure this out.

I have vast and complicated drupal 7 site and among other things I'm using profile2 module. Not sure why, but a few years back I've added field directly to 'profile' table. It is used to store some number and adding it looked like quick fix back then.

Now I need to get some info using views and all is fine except this one field which I absolutely have to take into account, but I am not able to.

What I did so far is:

```
function modulename_views_api(){
    return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'modulename'),
  );
}

```

in my custom module,

```
function modulename_views_query_alter(&$view, &$query){
    if ($view->name == 'viewname') {
        $query->add_field(NULL, 'some_field', array());
    }
}

```

in modulename.views.inc

What I'm trying to do is either add this field to display directly, or add it to the list of fields, or replacement patterns, or anything I could use.

`modulename_views_data()` isn't useful for me, because I would have to recreate whole table structure created (and frequently changed) in GUI.

I tried \_views\_pre\_view, \_views\_pre\_render, relationships, query rewrites, all to no avail. I've run out of ideas...

# Answer
> 0 votes
You could add a normal number field to the user profile in the drupal ui, then translate the rogue column into this normal drupal field by populating the field from the table column with an SQL query (or several queries via a looped php script) on your database.

This would mean that the field would become available in the normal drupal way within views, and would also avoid you having these sorts of issues on another occasion.

I am sure it does not need to be said, but obviously you would backup first and perform this operation in a local development to test.

**Note**: It should even be possible to export the numeric value against uid and use feeds to bring the value into a profile2 field using the uid as unique, if that felt more comfortable than the naked sql population.

---
Tags: views
---


title: Programmatically import a feed

text:
# Question
Title: Programmatically import a feed
I can successfully import remote content using the Feeds module by manually clicking on the *Import* button. I need to execute the import process from code, either from a module or executing PHP code from the Rules module.

I have tried the following code in a custom module.

```
function imports_cron_cron(){
  drupal_set_message('Import-CRON responding to cron execution! ...');
  $importer_id = 'publications_import';
  $url = "http://xml/url";
  $feeds_source = feeds_source($importer_id);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
  $feeds_config['source'] = $url;
  $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
  $feeds_source->save();
  $feeds_source->startImport();

  drupal_set_message(' .... ENDING IMPORTS-CRON CALL!');
}

```

Both the `drupal_set_message()` calls are successfully executed, but no node is imported.

Can anyone help, please?

# Answer
Your code seems to be OK. I use some similar code in one of my projects (this a csv importer, similar concept):

```
function custom_function($importer_id, $csvfile_path) {
  // Load the Feeds Source object.
  $source = feeds_source($importer_id);
  // Load the source fetcher config.
  $fetcher_config = $source->getConfigFor($source->importer->fetcher);
  $fetcher_config['source'] = $csvfile_path;
  $source->setConfigFor($source->importer->fetcher, $fetcher_config);
  $source->save();
  $source->startImport();
}

```

Make sure that you are using the foreground configuration, this way the batch process could be be executed "inside" drupal with showing the progress bar. Or you can force it:

```
// Tweak the importer configuration, to enable "Process in the background".
$config = array(
  'process_in_background' => TRUE,
);
$source->importer->addConfig($config);

// Execute the import.

```

Another approach could be to schedule it

```
// Schedule the import, and make sure importer is scheduled, too.
$source->schedule();
$source->importer->schedule();

```

This is a good article about feeds importer
> 13 votes

# Answer
Ive seen lots about this. Heres my take , I want to be able to do this from the command line, and be able to do it from an install profile.

so taking hints from previous answers, and from the documentation Ive seen / found, Ive come to the realisation that

dont use the batch api for this *unless*

a) you're doing this from the form api (a user clicks)

or

b) you're writing a drush command.

so this is what Ive got working in an module install

```
function load_data(){

// Files to import in specific order.
  $files = array(
    'challenge_importer' => 'data/challenges.csv',
);

$file_location_base = drupal_get_path('module', 'challenge');
foreach ($files as $feed => $file) {

$feedSource = feeds_source($feed);
// Set the file name to import
$filename = $file_location_base.'/' . $file;
if (!file_destination($filename, FILE_EXISTS_ERROR)) {
  $config = $feedSource->getConfig();
  $config['FeedsFileFetcher']['source'] = $filename;
  $feedSource->setConfig($config);
  $feedSource->save();
    while (FEEDS_BATCH_COMPLETE != $feedSource->import());
    }
  }
}

```

where

* challenge\_importer is a feeds importer,
* challenge is the module.
* data is stored in module/data

and with this structure you can have multiple files imported in a defined order.
> 1 votes

# Answer
I believe you need to do something more like

```
$node = new stdClass();
$node->type = 'feed';
$node->title = 'My feed';
$node->feeds['FeedsHTTPFetcher']['source'] = 'http://example.com/rss.xml';
node_save($node);

```

You should take a look at https://drupal.org/node/622700 (Programmatic operations).
> 0 votes

---
Tags: 7, rules, feeds
---


title: Only getting varnish misses

text:
# Question
Title: Only getting varnish misses
Would having the display errors setting turned on in the following admin page admin/config/development/logging cause Varnish to generate cache misses?

# Answer
Messages are stored in the session (errors, warnings and info messages). If anything is in the session, a session cookie is set in the browser. If the session cookie is set in the browser, Varnish is normally bypassed.

Note, the name of the Drupal session cookie is `SESS` followed by a long hexadecimal string.
> 0 votes

---
Tags: performance, proxies
---


# Question
Title: Searching by sku number but some products and new product are not showing using search api drupal 7
Some products are showing by sku number but some products are not showing.please someone help me to solve this problem.

# Answer
This is probably due to indexing by the search module. You need to run cron in order to build the search index.
> 1 votes

---
Tags: search
---


title: Problem with mobile redirection login

text:
# Question
Title: Problem with mobile redirection login
I've implemented this mobile redirection logic but for the past 10 days I've been getting weird behavior(with www version, mobile data is shown sometimes).

**Here is Mobile Theme return logic**

Also I find different behavior if I uncomment "**return 'bartik'** in the last line below.

```
  function mobile_detect_custom_theme() {

        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0)
        {
            return 'mobile_theme';
        }

//return 'bartik'; //IF I uncomment it I find different behavior
    }

```

**In Hook\_book I've setup this redirection logic:**

```
//wantdesktop is set if user has specifically selected Desktop version
if (@$_COOKIE['wantdesktop'] == 'true') {
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0) {

            $url = "http://www.example.com/" . $_SERVER['REQUEST_URI'];

            header('Location: ' . $url, TRUE, 302);
            exit(0);
        }

        return;
    }

//wantmobile is set if user has specifically selected mobile version
      if (@$_COOKIE['wantmobile'] == 'true') {
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") != 0) {

            $url = "http://m.example.com/" . $_SERVER['REQUEST_URI'];

            header('Location: ' . $url, TRUE, 302);

            exit(0);
        }

        return;
    }

//BROWSER DETECTION LOGIC HERE which fills $browser['ismobiledevice'] with true/false

    if ( $browser['ismobiledevice'] == 'true') {
        //check the current domain
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") != 0) { //not a mobile url
            $url = "http://m.example.com/" . $_SERVER['REQUEST_URI'];
            header('Location: ' . $url, TRUE, 302);
            exit(0);

        }
    } else { //desktop
        if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0) { //is a mobile url

            $url = "http://www.example.com/" . $_SERVER['REQUEST_URI'];
            header('Location: ' . $url, TRUE, 302);
            exit(0);

        }
    }

```

**What is wrong with this logic?**

# Answer
May I suggest an alternative approach of using the Themekey module. It was built to solve the exact issue you are facing:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server

The important thing to note about Themekey, is that the module works well with the external caching as well. Do check out its documentation for more.
> 1 votes

# Answer
The first problem I found is

```
$url = "http://www.example.com/" . $_SERVER['REQUEST_URI'];

```

Because, As an example, If the url is `www.example.com/test` the `$_SERVER['REQUEST_URI']` returns `/test` not `test` so your code should be

```
$url = "http://www.example.com" . $_SERVER['REQUEST_URI'];

```

and also replace `example.com` with this:

```
global $base_url;
$url =  $base_url.$_SERVER['REQUEST_URI'];

```

and use `$base_url` to check for the `m.example.com` (whether it is the mobile version or not)
> 0 votes

# Answer
why don't you use simple this module Simple Mobile Redirect ? It has good interface for all of your mobile redirection tasks.
> 0 votes

# Answer
And as a third alternative, Mobile Switch
> 0 votes

# Answer
So in answer to the 'bartik' bit,

> 'HTTP\_HOST' Contents of the Host: header from the current request, if there is one.

http://php.net/manual/en/reserved.variables.server.php

so this code

```
enter code here

function mobile_detect_custom_theme() {

    if (strcasecmp(substr($_SERVER['HTTP_HOST'], 0, 2), "m.") == 0)
    {
        return 'mobile_theme';
    }

   return 'bartik'; //IF I uncomment it I find different behavior
}

```

means that your if must be returning false, and then you get bartik back

HOST headers are mandatory for http 1.1 , but in http 1.0 they are optional .

do you have any proxies - these can often introduce headers, or rewrite headers.

try using the $\_SERVER\['SERVER\_NAME'\] variable, its generally safer (doesnt come from the client, it comes from the virtual host configuration instead).
> 0 votes

---
Tags: 7, theming
---


title: Adding workflow to custom content types

text:
# Question
Title: Adding workflow to custom content types
I am trying to assign a workflow to my custom content type, but i can't find the option to get this working. Is it a bug or maybe just not part of the workflow module?

# Answer
> 0 votes
I would probably suggest to use Workbench Moderation instead of using the Workflow module. I don't know your exact use case, but I've had a lot of luck with the Workbench suite.

# Answer
> 0 votes
The workflow module comes with two other modules **workflow node** and **workflow field**.

> **Workflow Node** *Adds a Workflow to nodes. (Use only if you come from a version below 7.x-2.x. If not, use 'Workfow Field' instead).*
>
> **Workflow Field** Defines a Workflow field, widget and formatter. (Do not enable Workflow Field and Workflow Node together.)

If you're using workflow 7.x-2.0, you should enable **workflow field** module and create a new field (say "State") in the content type and select field as **workflow** with a widget of your choice (defaults to workflow). When you visit after creating content, you can use the field to change the state (workflow state).

You'll get handy options in the field settings like 'allow scheduling', 'adding comment to transition' etc.

---
Tags: 7, nodes, workflows
---


# Question
Title: Forcing file migration after deleting field
I have a situation where I am working on Drupal 6 to Drupal 7 migration. The migration is being done in stages, and stage one is now live.

I am working on stage 2, and have run into a snag file file migrations.

We had a content type 'foo' with field 'field\_bar'. It was originally created as File, but should have been image. We ran migrations, and everything went OK (all files were part of original migration).

'foo.field\_bar' got deleted and recreated as Image. When we re-run migrations, the files aren't being attached.

As far as I can tell, is that the source/destination pair exists in `{migrate_map_files}` but the `fid` doesn't exist in `{file_managed}`, more than likely because it got deleted during garbage collection when cron ran.

What is the best option to force these migrations to run again? Is there a way to do this with the Migration classes, or should I delete the bad rows from `{migrate_map_files}`?

# Answer
> 1 votes
My current solution is to use a query, and manually cleanup the `{migrate_map_files}` table

```
$fids = db_query('
  SELECT mmf.sourceid1 FROM {migrate_map_files} mmf
  LEFT JOIN {file_managed} f ON f.fid = mmf.destid1
  WHERE f.fid IS NULL
')->fetchCol();

db_delete('migrate_map_files')
  ->condition('sourceid1', $fids, 'IN')
  ->execute();

```

reset the watermark in `{migrate_status}` and then re-run my files migrations.

# Answer
> 1 votes
Usually you can set the needs\_update column to 1 for all the known entities that have this issue, if you do this and run the migration with `drush migrate-import MyMigration --needs-update`. The other way would be to force update all items: `drush migrate-import --update MyMigration`

---
Tags: files, migrations
---


# Question
Title: Gmap, Views Draw Lines on Field Collection Locations Map
I have built a website for car tours. There are multiple tours throughout the year, and new ones are added regularly. Here is a quick outline of the website...

Content type: "Tour Page", Fields: Field collection item, allows multiple tour steps to be added. Each field collection item has a Gmap find address on map location field.

On each tour page, I have a view Gmap using a contextual filter to get a default value of Content ID from URL. This displays the tour steps as single icons. This view is in a block, and set to display on all "Tour pages".

I would like to draw a line on the map from point to point. It can be a straight line, going from point to point.

Now, I can edit the view, go to gmap settings, and enter my own lines using the macro for the view, like this...

```
[gmap line=#0000ff/5/45:51.512099,-0.15169000000003052 + 51.20086,3.2629389999999603 + 50.654685,4.833983999999987 + 50.403266,6.240233999999987 + 49.966239,8.18481399999996 + 49.067118,8.10241700000006]

```

...but this will output the same lines for this view on every tour page. But of course, the route is different for every tour. Here is where I am so far...

http://www.dev.ducktoursinternational.com/tour/maranello-monaco-monza-grand-prix-tour-2009

...The line is on the map, following the points. But this same line is in the same place on every tour.

I have all of the latitude and longitude values for all of the points collection in the field collection location fields, is there a way to create a unique macro for every map using these values?

I can probably use a "master" view to assemble all of the lat and long values into the right format for a gmap macro, but how do I get that macro to apply to the different route on each page?

**Some more information...** 1. Here is the tour page with the current macro on it... http://www.dev.ducktoursinternational.com/tour/maranello-monaco-monza-grand-prix-tour-2009

2. Here is a screenshot of the gmap view...
3. Here is a screenshot of the views GMap Settings

So I have a block with a map, and a block with the correct macro for that page. How do I use that macro for that map?

# Answer
> 0 votes
I haven't found a way to do this using gmap. Instead, I will create a view block using all of the fields I need. I will then override the default template, and custom code the map myself using https://developers.google.com/maps/documentation/javascript/overlays I can use the fields from the view along with the Google Map API to create different markers, pop up bubbles with fields, and most importantly draw the lines between the markers.

This is not the answer I was looking for, but in my case is the only option as the deadline for the project is coming to an end.

If I get a chance I will post my code once its done in-case anyone else stumbles into this issue.

# Answer
> 0 votes
off the top of my head a custom module using `hook_views_pre_build` or 1 of the views hooks functions should let you "alter" the Macro value from something you load and compose from the database.

To be of more help we'd need to see your full content type admin page with field collection admin page, and the master layout of the view for example if you wanted coding help ...

# Answer
> 0 votes
1) Make a view which result only the needed points based on contextuel references. So you do not use the gmap extension here. Only plain text output.

2) Put php code in the block which should contain the gmap syntax. You can get the result of the view by using syntax's as mention in : Get a views result using PHP code, and iterate the proper way. Then use this in your block like: gmap line= php views\_get\_view($view\_name);?\> The syntax is not good as I do not understand how to put this correctly in this editor.

# Answer
> 0 votes
Make use of openlayers in combination with views give you much more control.

---
Tags: views, google-maps
---


# Question
Title: Question about adding a field value to a view programmatically
I am having a problem getting a field to print and know it is something I am missing. I am trying to print a product field in a view that is created programmatically. Everything else is working fine, but I cannot pull the item size in to the view. here is the code:

```
 $form['assigned'] = array(
'#type' => 'fieldset',
'#title' => t('Assigned orders'),
'#tree' => TRUE,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$orders = views_get_view('get_drivers_orders');
$orders->set_display('default');
$orders->set_arguments(array('0' => $account->uid));
// change the amount of items to show
$orders->pre_execute();
$orders->execute();
$orders->render();
if ($orders->result) {
foreach ($orders->result as $key => $value) {
  $order = uc_order_load($value->field_driver_id_users_order_id);
  $form['assigned'][$key] = array(
    '#type' => 'fieldset',
    '#title' => t('Order #' . $value->field_driver_id_users_order_id),
    '#tree' => TRUE,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['assigned'][$key]['view'] = array(
    '#markup' => l('View order', 'user/' . $account->uid . '/delivery/' . $order->order_id),
  );
  foreach ($order->products as $product_id => $product) {
    $form['assigned'][$key][$product_id]['attribute'] = array(
      '#type' => 'item',
      '#title' => t($product->title),
      '#markup' => isset($product->data['attributes']['What would you like']) ? $product->data['attributes']['What would you like'][0] : '',
    );
    $form['assigned'][$key][$product_id]['size'] = array(
      '#type' => 'item',
      '#title' => t('Size:'),
      '#markup' => isset($product->data['size']) ? $product->data['size'][und][0]['value'] : '',
    );
  }
  $address = uc_custom_process_get_order_address($order);
  $form['assigned'][$key]['map'] = array(
    '#markup' => l('View map','http://www.google.com/maps?q='.$address.'(tooltip/infowindow title)',array('attributes' => array('target'=>'_blank'))),
  );
  $form['assigned'][$key]['total'] = array(
    '#type' => 'item',
    '#title' => t('Total:'),
    '#markup' => '$' . $order->order_total,
  );
}

```

Here is an image of the krumo of the the view with the products, I do hope someone can help! }

I have looked over the proposed solution and it does not fit my use case. I have a view that shows an individual order, that order has products, and those products have all of there values stored in $product-\>data. I have tried everything to get information from the 'size' field to display in that view and it is not happening. I am not trying to change a value, just display it! I hope this helps everyone help me! :D

# Answer
So the issues was that Krumo pulled that information of its own accord, and the $order object did not have those details. I had to call $product-\>nid first, query the DB for the field values i needed, and insert them. I ended up with this code, in case it can help anyone!

```
    foreach ($order->products as $product_id => $product) {
    $pid = $product->nid;
    $ps = db_query('SELECT field_size_value FROM field_data_field_size WHERE entity_id = :pid', array(':pid'=>$pid))->fetchField();
    $pp = db_query('SELECT field_pack_value FROM field_data_field_pack WHERE entity_id = :pid', array(':pid'=>$pid))->fetchField();
    $form['assigned'][$key][$product_id]['attribute'] = array(
      '#type' => 'item',
      '#title' => t($product->title),
      '#markup' => isset($product->data['attributes']['What would you like']) ? $product->data['attributes']['What would you like'][0] : '',
    );
    if(!empty($ps)){
        $form['assigned'][$key][$product_id]['size'] = array(
      '#type' => 'item',
      '#title' => t('Size:'),
      '#markup' => $ps,
    );
    }
    if(!empty($pp)){
      $form['assigned'][$key][$product_id]['pack'] = array(
        '#type' => 'item',
        '#title' => t('Pack:'),
        '#markup' => $pp,
      );
    }
  }

```
> 0 votes

---
Tags: forms, ubercart
---


title: Problems with EVA generated html

text:
# Question
Title: Problems with EVA generated html
I want to show a list of links to the 5 latest news on my homepage.

I learned that I can install the Views module to make a snapshot of a content type. I also use EVA to create a EVA field from the view and attach it to my homepage content type.

Then I can intercept the value of the view in my homepage\_preprocess\_node but the problem is that the value is a long string containing the whole list wrapped with html.

This is bad...

I want to have full control of the html. I tried different options but couldn't find a clean, basic, barebone option.

I am expecting a value that is an array of 5 objects so I can loop throught them and generate what ever html I see fit. The object would contain the field I asked (title) and a url to get to the news page.

Of course I can remove the html tags and rebuild the array from that long string but I don't want to do that if there is a better solution. I will use that view on the "press room" page also, so I don't want to have to duplicate code in two different preprocess\_node functions

Nothing is simple in Drupal...

I wanted to add "EVA" as a tag for this question but it's not available.

# Answer
> 0 votes
That's because you are doing it the hard way. Why hardcoding everything when views does it out of the box? Views fields are extremely flexible and customizable. You may need to strip the views fields first (style fields and deselect whatever option you have - do that also with your format / html, unformatted etc). Usually, what I do is exclude from display and use views tokens in the last field of type Global text area. This way, the view only displays actually field values, with no html whatsoever.

To escape hard coding even for your content type display, try using display suite. It works smoothly with EVA as well.

I hope I got it right.

And... what is simple when you're trying to achieve complex structures? Is there any other platform delivering something like views OOTB?

There is some research to be done regardless choice of environment. And usually, the shortest, simplest way, is the way you know better.

---
Tags: 7, views, theming
---


title: .htaccess concatenating www + subdomain

text:
# Question
Title: .htaccess concatenating www + subdomain
I'm running a new Drupal 7 site on Ubuntu 14 (so no httpd.conf file), and am trying to make a simple htaccess rule to redirect from no subdomain to www. Basic stuff, the Internet told me what to do, and I used this:

```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

```

Problem is that if I put in a subdomain - something.domain.com - it concatenates the URL to www.something.domain.com

How can I get around this? It's... quite annoying. Perhaps a module would be a better solution than an .htaccess update?

(Also Global Redirect Case Sensitive URL Checking isn't working, but that's another story...)

Thanks.

# Answer
> 0 votes
If I understand you correctly, you want to redirect everyone to the www version of the site. How about this.

```
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

```

It will redirect anything that isn't www.example.com to www.example.com and pass along the url.

http://httpd.apache.org/docs/2.4/rewrite/intro.html has more options you can use.

---
Tags: .htaccess
---


title: Where should I put my entity queries?

text:
# Question
Title: Where should I put my entity queries?
I would like to create a number of entity query methods/functions that I can have easy access to from my entity handlers and controllers.

With Doctrine 2/Symfony 2 you can just attach such methods to the object/entity repository, and then you can call this repository from elsewhere in your code. Should I follow this recipe in D8, and if so, how?

I see 4 options for where to put the queries:

1. Put the methods in my custom entity class. However, out of the box the entity.query service doesn't seem to be available in `Drupal\Core\Entity\ContentEntityBase`, nor is the service container. I can use `\Drupal::entityQuery('myentity')` in a method, but according to the documentation `\Drupal::` should only be used in global functions. I suppose I can override the constructor and inject this class myself, but I would have thought this kind of functionality would be there already.
2. Put the methods in my custom entity storage handler. However, if my understanding is correct, this is the place for special queries that aren't well handled by the entity query services.
3. Inject the querySelector wherever I need it. See \Drupal\node\Form\NodeTypeDeleteConfirm in Beta 9 for an example. This is not an appealing option.
4. Use global functions in my .module file. That way I can just use `\Drupal::entityQuery` and be done with it. See node.module for many sample implementations. However, this goes against the D8 documentation and against the goal of putting as much as possible into classes.

Any thoughts or references to emerging best practice would not go amiss :)

# Answer
> 0 votes
4 is definitely worse than 1. While \Drupal should be avoided to make unit testing and other things easier, it's still possible, but with calling functions, it's definitely not.

I fear there's no clear answer to this. There is no common standard for this in Drupal 8. A few modules have repository services, for example `block.repository`. You still have to manually inject that into your controllers, forms and other places, but you can make interfaces that are much easier to mock/test compared to an entity query.

---
Tags: database, 8
---


# Question
Title: can hook page alter also do all the things that hook form alter can do..?
Since the page alter hook also has information about individual form fields is it correct to say that hook page alter can do everything that hook form alter can do

# Answer
> 1 votes
Not, for sure hook\_page\_alter can't do everything that hook\_form\_alter (or other form alter hooks) can do.

Form alter functions allow to alter the form itself, its structure, values and valid values, submit and validate handlers, etc. This is because they are fired early in the Form API workflow. When Form API ends its work there's a render array that Drupal can render as HTML code.

After all form alter hooks are done (and any other code that generates the page content) comes hook\_page\_alter, but the form is done. Any alterations you make will be unkown for the Form API layer, most of the times resulting in strange validation errors form Form API (for example the 'Illegal Choice has been detected').

What you see in the hook\_page\_alter is not a form but the render array of a form: Here you can't modify submit or validate handlers, options of a select wiidget or add new elements in a multiple element field.

From hook\_page\_alter:

> If you are making changes to entities such as forms, menus, or user profiles, use those objects' native alter hooks instead (hook\_form\_alter(), for example).

# Answer
> 0 votes
in my opinion hook\_page\_alter() is a different thing from hook\_form\_alter() in the page\_alter your alter some result view before it gets rendered but in form\_alter you alter the values that gives you that result in database ,, page\_alter you just alter the page view far from the database ,,

---
Tags: forms, theming
---


title: How to print fields manually

text:
# Question
Title: How to print fields manually
I am using print module. I am also using devel module. In print.tpl.php file, I see a php code that prints the content as `print $content.` I don't want to print the entire content. I think content is an array. How can I print manually some fields from the content variable using the devel module or in php?

Thanks. D

---

1.

> print render($content\['field\_machine\_name'\]);

Get this error: Fatal error: Only variables can be passed by reference in /..sites/all/modules/print/print.tpl.php on line 100

2. > php print $content\['field\_machine\_name'\];

I get left error only (\<)

3.

> print $fields\['field\_vehicle\_options'\]-\>content;

I get completely blank

---

I am using bartik 7.22.

1. themes \> bartik \> template.php

Added the below function.

```
function bartik_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['test'] = field_view_value('node', $node, 'field_price', $node->field_price[$node->language][0]);

}

```
2. themes \> bartik \> template \> print.tpl.php

I added: print render($test);

3. I went to my page http://bettylist.com/ac/node/12 \> clicked printer friendly link \> I did not see the value of variable.

In print.tpl.php, what works:

```
print $content; //I GET CONTENT IN PRINT PAGE
print dsm($title); // I GET VALUE OF TITLE IN PRINT PAGE

```

Please advise. Thanks, D

---

It worked. I have added one more variable as below:

```
function bartik_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['price'] = field_view_value('node', $node, 'field_price', $node->field_price[$node->language][0]);

// Create a var and render using field_view_value
$vars['vehicleOption1'] = field_view_value('node', $node, 'field_vehicle_option_1', $node->field_vehicle_option_1[$node->language][0]);

}

```

In print.tpl.php, I added

```
print render($test);
print render($vehicleOption1);

```

But I am only getting the value of the last variable $vars'vehicleOption1'.

Please advise.

# Answer
> 1 votes
Try with this:

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

```

This should print the field you want.

Change `'your_field_name'` with machine name of the desired field.

You can install and enable Devel module and add this:

```
<?php dsm($node); ?>
<?php dsm($content); ?>

```

in your `print.tpl.php` file. You will see all $node and content fields.

# UPDATE

Also, you can add this function in your **template.php** file:

```
/**
  * Renders the content of the print page using the theme api.
  */
function THEME_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['any_variable'] = field_view_value('node', $node, 'your_field_name', $node->your_field_name[$node->language][0]);

}

```

Replace `THEME` with your theme name, `any_variable` with any name you want for this variable and `your_field_name` with machine name of your field.

After this you can render your field in **print.tpl.php** file like this:

```
<?php print render($any_variable); ?>

```

Again, change `any_variable` with the name you choose for this variable in function from **template.php** file.

---
Tags: debugging
---


# Question
Title: Views Search Returning Unexpected Results
**Problem:** Items are not grouping correctly.

**The Setup:** I'm working in Views and trying to customize it to display items grouped by a taxonomy term field called 'Event Type'. Furthermore I'd like them to be grouped WITHIN each taxonomy term grouping by Category (in a specific order). Each resource has both an event type and category. There are three event types: timely event, quick study, and deep dive. There are 10 categories: webinar, conference, articles, etc. 3 of those categories are also in 'Timely Events'. 4 of them are in 'Quick study'. The other 3 are in 'deep dive'.

My categories are setup to be ordered. The category field is a field list and has key/value pairings to match what I want. So, for example:

```
1|Webinar
2|conference
3|Workshop
4|Articles
etc.

```

Note that webinar, conference, and workshop will the 3 under 'timely events' and that's why they're ordered that way. The next four starting with Articles are under 'Quick Study', etc.

So I have it structured the way I want it to appear in the view already. And I want the view to reflect this by displaying something like this:

```
Timely Events
All webinars listed
All workshops listed
All conferences listed

Quick Study
All Articles listed
All [other 3 categories in order as set in the key/value pair above]

Deep Dive
Same as the others

```

Then in the view itself I have set Format \> Unformatted List \> Settings (Grouping field Nr. 1: Content: All taxonomy terms).

In Fields I have 'all taxonomy terms' set as the first field, with the following settings: 'exclude from display' and 'limit terms by vocabulary' \> set to 'event-type'.

Under 'Content: all taxonomy terms' in 'Fields' I'm displaying icon, price, title, event dates, and body.

My filter criteria is set to published, type=resource, search terms and other exposed filters.

My sort criteria is set to Category (asc), event-dates asc, content: title.

**The Result:**

```
    Timely Events (header)
    All webinars listed in the correct order.

    Deep Dive
    All certificates listed in the correct order.

    Timely Events (again - why?)
    All conferences listed in the correct order.

    Quick Study
    All articles listed in the correct order.

    Timely Events (yet again)
    All workshops listed in the correct order.

```

**My Question for you:** How can I get my results to display so that the headers (event type) display ONLY ONCE followed by each of the categories in that header in the order in which I've set them in the key/value pairing in the field list?

It should be like this:

```
Timely events (header)
all webinars
all conferences
all workshops

Quick Study (header)
all articles
etc.

Deep Dive (header)
all certificates
etc.

```

And that's it.

**Anyone have any idea how to correct my grouping here?**

# Answer
Of course. Since I have 10 sub-categories and I'm ranking them by 'key' number 10 is displaying AFTER number 1 and then 2, 3, 4, 5, 6, 7, 8, 9. That's why it's returning the incorrect results. 10 should be named something else like 99 so it comes after 9.
> 0 votes

---
Tags: views
---


# Question
Title: Gmap Module open info window(bubble) from external link
Not even sure where to start.

Would like to have a menu in the sidebar that when clicking on a link will open an info window (bubble) in the Google map.

Any ideas on a jumping off point?

# Answer
You can create a function that opens an existing infoWindow:

```
function triggerPopup(marker) {
  // Get the map using getMap() which needs the maps ID
  var mapID = $('.gmap').attr('id');
  var map = Drupal.gmap.getMap(mapID);
  map = map.map;
  // Get the map's current markers
  var markers = map.markers;
  // Trigger the popup for the marker passed to triggerPopup()
  google.maps.event.trigger(markers[marker], 'click');
};

```

Then you can use this function with any external link:

```
$('.your-external-link').click( function(e) {
  e.preventDefault();
  triggerPopup(0);
});

```

This gives you the basic idea of how you can trigger the popups, you'd need to figure out a way to associate the sidebar links with the markers - this is completely dependent on how you have everything set up.
> 1 votes

# Answer
Start by trying existing modules.

The Gmap module or the Simple Google Maps module may be a good starting point.
> 0 votes

---
Tags: views, 7, google-maps
---


# Question
Title: How to give access to delete his own comments
I am using Drupal 7 and want user should be able to delete his own comment. I know that is it not supported by drupal 7 due to threading. You can provide edit permission from "admin/people/permissions" but there is no option to provide permission of delete.

Thanks in Advance

Ref : https://www.drupal.org/node/777696

# Answer
> 0 votes
Are you familiar with coding? You can try this tutorial.

edit: and i ran into this site, wich is a patch to the module 'Comment Goodness'. There's also some extra info about flat comments (the default structure is nested, not flat).

# Answer
> 0 votes
Are you building a site with registered users? If not, you could check out https://disqus.com/ , I used that on the site I'm building after I discovered they also have a drupal module. It provides users with the ability to delete their own comments as well. LevelUpTuts (YouTube) made a tutorial about the installation and configuration.

---
Tags: 7, users, comments
---


# Question
Title: Not able to log in to Drupal site as other user
I am a site admin (Drupal 7 - all updates are current) and am able to log in with my own credentials. I'm working an issue and need to log in as another non-admin user. No matter what I try, I'm not able to log in as this particular other user though I have verified their user email address and password. I have copied and pasted their email address directly from their user account. I have also reset their password so I know it is correct. I have tried turning off clean url's (as suggested by another forum), but that didn't help. I have cleared the site cache. I contacted the user and she is able to log in/out and back in with the exact same credentials I'm attempting to use. We have had this problem with another non-admin user on this particular site but it hasn't happened in quite a while and never with this user. I have logged in as this user prior to this happening but it has been a few months.

I saw another post on this site about the same thing but didn't really see a solution (Cannot log in to Drupal site).

Does anyone have any ideas? This is quite an inconvenience.

# Answer
> 0 votes
Once I was able to get in touch with my other site admin and she was able to log in with the same credentials I knew the problem was local. I had tried different browsers. I flushed my DNS and rebooted my computer and was able to log in.

# Answer
> -1 votes
I have got a similar issue because other **users of your Drupal 7 site will have same permissions as the administrator is assigned with**.

See the values stored in **role** and **role\_permission** tables in your Drupal database.

Check if the `rid` value is assigned with similar `permission` values in the **role\_permission** table.\[Also take care of the `module` field if many exist\]

If so, this would be because of the reason that the users' roles are created with extra permissions other than:

```
access content
post comments
skip comment approval
use text format

```

-which are the default permissions assigned to the authenticated user.

All you can do now is either manually edit the table values\[not suggested by the community\] or use a module to update the user permissions for each roles.

Thank you.

---
Tags: users
---


# Question
Title: GTM container in block appears as regular text even though set to be Full-HTML
I have opened a block at the header of my site and have putted the GTM-container code inside while at Full HTML **input-format**.

Yet, the container code appears as regular text (`<p>&<a>`) in this block.

I could solve it by giving "Display:none;" to it's region with CSS, but I would prefer to find the root cause of this problem rather than using CSS.

If there is any module that deals with this service I would prefer not to use it since I'm looking for a none-modular why of doing it.

# Answer
> 1 votes
I've discovered that CKeditor made the code `<p>` so I tried to replace the `<p>` tag of the input to but it didn't help, so as alternative I tried to format the input as with PHP text-foramt, But this also didn't help.

Working solutions would be:

1. Putting the code somewhere (at the first row for example) of you page.tpl.php.
2. Installing the module.

If you plan to change your sites theme and going to change some themes in the near future, better pick option 2 --- It will save you from copying the code time and again to each new page.tpl.php.

---
Tags: theming, input-formats
---