# Question
Title: Changing the key/value pair of a field list in Drupal 7 once content has been added to the site
I have a field list on my content type that I need to edit. Specifically I just need to change one of the key/value pairs. Unfortunately there's already content in the site so I can't just change it in the admin interface (it gives me an error that there are already records that use this).

I'm looking through my database (mysql) and I can't even find where the key/value pairings are stored. I can see the keys being attached to my nodes and can manually change them there, but that doesn't solve my underlying problem.

So my question is two-fold:

1) where is the table to edit field lists for a content type?

and

2) what's the preferred way to change a field list key/value pairing once content has been added to the site (too much to delete and start from scratch)?

Thanks!

# Answer
> 2 votes
In future use taxonomy for the list. That way you can add/edit to the list without any problems. Lists should be used for things that are constant, like the seasons of the year etc.

Use MySQL Workbench (assuming you are using MySQL). Open the table 'field\_config' and do a select on it.

Look for your field in question. It's data is a blob. Right click on the blob and select 'Open Value in editor'. Select text.

You will see something like this:

> a:7:{s:12:"translatable";s:1:"0";s:12:"entity\_types";a:0:{}s:8:"settings";a:2:{s:14:"allowed\_values";a:2:{i:1;s:3:"one";i:2;s:3:"two";}s:23:"allowed\_values\_function";s:0:"";}s:7:"storage";a:5:{s:4:"type";s:17:"field\_sql\_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field\_sql\_storage";s:6:"active";s:1:"1";s:7:"details";a:1:{s:3:"sql";a:2:{s:18:"FIELD\_LOAD\_CURRENT";a:1:{s:21:"field\_data\_field\_list";a:1:{s:5:"value";s:16:"field\_list\_value";}}s:19:"FIELD\_LOAD\_REVISION";a:1:{s:25:"field\_revision\_field\_list";a:1:{s:5:"value";s:16:"field\_list\_value";}}}}}s:12:"foreign keys";a:0:{}s:7:"indexes";a:1:{s:5:"value";a:1:{i:0;s:5:"value";}}s:2:"id";s:1:"6";}

You can see under allowed values I have two list entries:

1 =\> one

2 =\> two

**To add** 3 =\> three I change this bit:

"allowed\_values";a:2:{i:1;s:3:"one";i:2;s:3:"two";}

To this:

"allowed\_values";a:3:{i:1;s:3:"one";i:2;s:3:"two";i:3;s:5:"three";}

a:2 changed to a:3 as it is the count of values in the list

i:3 indicates the new key

s:5 is the string length of the word three

Then hit apply in the edit box, and hit apply in the SQL window and you are done.

So you don't want to add a new value, but edit an existing one. Use same process as above, but just edit the allowed\_values, then run an SQL update on your two tables for the field : 'field\_data\_XXX', 'field\_revision\_XX' to update old key to new key.

---
Tags: nodes
---


title: Real-time node form

text:
# Question
Title: Real-time node form
Is there a way for users to see the choices he/she already made on the form on real-time? For example a user clicked a checkbox or radio button and on the bottom part of the form it shows all the choices he/she made without saving it yet. Basically its like a summary of all the choices the user made on the bottom part of the form without actually saving the form.

I've been trying this for a while now, any help or suggestions would be really appreciated.

Thank you

# Answer
> 0 votes
Use Jquery. For example, at bottom of your form you can append new container:

`$('.your_form').append('<div class="summary"></div>');`

and then by adding to your input elements click/change listeners add their values to your new container:

`$( "#name input" ).change(function() {
 $('.summary').html($( this ).val());
});`

---
Tags: forms, nodes
---


title: Views Secondary Group

text:
# Question
Title: Views Secondary Group
I have a View which is a list of stores and for each store I have a list of products. This is a sample as it looks now:

```
Ken's Store

Products: Doodles
Products: Daddles

Joe's Store

Products: Acme Hammer
Products: Acme Nails

```

Stores are a content type and products are a content type. Products has an entity reference to stores. The view is set to Unformatted list and grouping by Content title(store). I'd like the view to group products like this:

```
Ken's Store

Products:
Doodles
Daddles

Joe's Store

Products:
Acme Hammer
Acme Nails

```

Setting Content Title (products) as the second grouping field only causes a repetitive title without grouping. **How do I get the products to group under the store grouping?**

# Answer
> 0 votes
You can set grouping after any field in the view at the format settings. This should work for this.

---
Tags: views, entities
---


title: Make field editable in comment form

text:
# Question
Title: Make field editable in comment form
Could you please help me with the following task? I need to make the existing field (name Clarify, type select - "clarification required/clarification isn't required") to be editable from display view (not on the Edit tab) and I need to place this field next to Comment field (see the screenshot).

I'm trying to use hook\_alter\_form in the following way, but with no luck. I know the below code is wrong and I need a little help to know which way to go.

```
function custom_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'comment_node_support_ticket_form') {
    $form['field_clarify'] = array(
      '#type' => 'select',
      '#title' => 'Clarify',
    );

    $form['#validate'][] = 'custom_support_comment_submit';
  }
}

function custom_support_comment_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $node_wrapper->field_clarify->set($form_state['values']['field_clarify']);
  $node_wrapper->save();
}

```

# Answer
First, you need `'options' => array('clarification required', 'clarification isn\'t required')` for select because you need options. Then you need to make sure your module name is `custom` (unless you don't want to expose your module name). Also, you pass your function name to `$form['#validate'][]` but it ends with \_submit (it should be \_validate).

There are what I found at the first glance. I didn't check the code.
> 0 votes

---
Tags: forms
---


# Question
Title: How to remove Upload picture lable from registration page?
how to remove Upload picture lable from avatar image field.

# Answer
> 0 votes
Something similar to this should work. Use form id alter hook to remove the label from image field.

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

 // Search for the field you want to alter

 // unset the label using $form['search_image_field_name'] or remove the label using empty string for that form field.
}

```

---
Tags: users, media
---


# Question
Title: What is the best approach to write hooks?
I had to use some hook functions on almost every project I worked, right now I am working on a project ( basically to collect donations and maintain organizations list ) where I need to write lots of custom code, at first I started to write all the code in theme i am developing, later I realized that its not going good with all the functions in theme because **some hooks need to be written in modules** so now some of the code is written in module and some is in theme which breaks the functionality when switch theme or with admin theme.

So I am thinking to write all the code again but not sure what is the best approach to write custom code in a drupal project.

if all code goes in custom module some of the theme sections needs to be rebuild and I didnt find any proper article on net on this

# Answer
> -1 votes
I think your question is more of in-general type . Please specify for what all purpose you need to use hooks . I think this might be helpful for you : http://www.stephanemartinw.com/articles/25-theme-drupal-hooks-templates-functions

Thanks

---
Tags: 7, theming, hooks
---


title: add captch to registration modal box

text:
# Question
Title: add captch to registration modal box
I have a modal box for login and registration for my site.

example.com I want to add the captcha with the registration process.I added the captcha module in my site. But the captcha only work with the drupal's default registration page but not work with the modal box's registration.

How can I add the captcha with the modal box.

# Answer
> 0 votes
Try something like the following:

```
$form['my_captcha_element'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);

```

More info here :https://www.drupal.org/node/743056

---
Tags: users, javascript, captcha
---


# Question
Title: User password Reset without sending an email
I know by default Drupal provides '*Forgot password*' option which allows user to enter their username/Email. If that's valid, sends a password reset link to their Email.

But I would like to do the same process without involving an email, which allows users to logged in immediately in one or two steps (by validating some checks).

How can I achieve that in Drupal?

# Answer
> 4 votes
I found a module called Password Reset. This is what I was looking for. I've tested this module and working great!.

> The password\_reset module allows for passwords to be reset without involving e-mail addresses through the use of security questions. This module would typically be used on sites that do not require users to enter their e-mail addresses or prefer not having to deal with spam folder issues etc.

---
Tags: 7
---


# Question
Title: Do not create new nodes, only update existing
I have a CSV feed that contains only prices and stock levels. The feed has to update only stock and price of existing products. What is the easiest way to block (just "in case") creating new products for the given feed?

# Answer
> 1 votes
First you need to ensure that each created node has a unique id associated with it that Feeds can use to identify it (eg as an existing node that needs updating).

You can set one (or more) of the fields to be unique in the node processor mapping section (admin/structure/feeds//mapping):

My example takes the generic 'Item GUID', I would suggest that you might instead map **SKU** to **GUID** and then set that to unique (make sure to click both update **and** save).

You then change the node processor settings to Update/Replace:

# Answer
> 0 votes
Put empty columns for other fields and fill data for prices and stock levels. E.g:

```
column1,column2,prices,column3,stock levels
---------------------------------------------
       ,       ,231   ,       ,Available 24/7

```

# Answer
> 0 votes
I am sure In feeds importer theres setting option that says update existing node, which will as it sounds will update the product irrespective of other fields.

# Answer
> 0 votes
I think this issue coverage your case https://www.drupal.org/node/1286298

Issue status still in state "Need works", but patch https://www.drupal.org/node/1286298#comment-8459327 can help you.

---
Tags: 7, feeds
---


# Question
Title: Ckeditor can not create new profile with input format
I've already a profile with input types but I can not create another, even when I am cloning the profile with input types.

These are my text format, and I using administrator user.

This is the list of ckeditor profiles

In Test profile, the only text format allowed is PHP code.

What could it be?

# Answer
It seems to be a problem when creating or cloning a ckeditor profile, the module doesn't insert registers into the table **ckeditor\_input\_format**, so we can do that by the following SQL queries

```
INSERT INTO `ckeditor_input_format` (name, format) VALUES ('<profile_name>','filtered_html')
INSERT INTO `ckeditor_input_format` (name, format) VALUES ('<profile_name>','full_html')
INSERT INTO `ckeditor_input_format` (name, format) VALUES ('<profile_name>','plain_text')

```

The name must be replaced with the name of the profile you created with ckeditor.
> 0 votes

---
Tags: 7, wysiwyg, input-formats
---


title: Publish or Un publish any comment

text:
# Question
Title: Publish or Un publish any comment
How to give moderator a right to publish or unpublish/edit any comment , not just own comment or comment on own content without giving "Administer comments and comment settings" Permission, by giving just a tab for publish and unpublish for appropriate role ?

# Answer
> 0 votes
Go to /admin/people/permissions and check assign the appropriate permission("Administer comments and comment settings") you'd like to the that role. Check https://www.drupal.org/node/777696

---
Tags: comments
---


title: Get rid of absolut links / redirects

text:
# Question
Title: Get rid of absolut links / redirects
I just got a project from a friend:
D6, 6.34, 3 languages.
Theme: Sharp Sales (via Fusion via Topnotch)
So quite an ancient project and I first installed a local copy, but I can't login - it keeps on forwarding me to the live server.
I deleted the rewrites in .htacces, deleted cache, watchdog, access\_log tables and I searched for redirects in the database, but it seems to come from the theme somehow:

```
INSERT INTO `cache` VALUES ('theme_registry:tnt_sharpsales_6',
...
:\"skinr_preprocess\";}}s:23:\"link_formatter_absolute\";a:8:{s:9:\"arguments\";a:1:{s:7:\"element\";N;}s:4:\"file\";s:14:\"link.theme.inc\";s:4:\"type\";s:6:\"module\";s:10:\"theme path\";s:22

```

and I found sth in the template.php as well:

```
* @param $options
 *   An associative array that contains the following other arrays and values
 *     @param $attributes
 *       An associative array of HTML attributes to apply to the anchor tag.
 *     @param $query
 *       A query string to append to the link.
 *     @param $fragment
 *       A fragment identifier (named anchor) to append to the link.
 *     @param $absolute
 *       Whether to force the output to be an absolute link (beginning with     http:).
 *       Useful for links that will be displayed outside the site, such as     in an RSS
 *       feed.
 *     @param $html
 *       Whether the title is HTML or not (plain text)
 * @return
 *   an HTML string containing a link to the given path.
 */
function tnt_sharpsales_6_themesettings_link($prefix, $suffix, $text,         $path, $options) {
  return $prefix . (($text) ? l($text, $path, $options) : '') . $suffix;
}

```

So I installed a fresh D6 and copied the theme over, but I can't find a setting there for absolut links. Anybody any idea how I could get rid of the absolut links?

# Answer
Finally figured it out:
Issue derived from the language negotiation settings. Under: admin/settings/language/configure Domain name only was configured and I switched it in the database (manually updated the variables table):

```
UPDATE `dinilu6`.`variable` SET `value` = 's:1:"2";' WHERE `variable`.`name` = 'language_negotiation';

```

Afterwards I needed to clear the cach with **drush cc** and then it finally worked.
> 0 votes

---
Tags: 6, theming, navigation
---


# Question
Title: (solved) How to hook into ajax results (server side)?
I'm looking for a way to make changes in rendered HTML parts, when they are the result of an AJAX request, just before they are returned to the user.

Currently it concerns Views, but its own hooks don't meet my need since the changes I want to make don't regard Views results but Views admin responses.
Anyway I'd like to be as generic as possible, so I could intervene upon any AJAX return.

Thanks in advance for any idea.

---

## Issue when using the interesting solution proposed by Andre-B

It seemed to perfectly meet my need so I introduced it gradually into my module in order to test successively each of its aspects.

First I added only a simple trace to my module, using FirePHP:

```
<?php
function mymodule_init() {
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $buffered_output = &drupal_static('mymodule_output_buffered', true);
    // AJAX request
    fb($buffered_output,'init');
  }
}

function mymodule_exit() {
  $buffered_output = &drupal_static('mymodule_output_buffered', false);
  if ($buffered_output) {
    fb($buffered_output,'exit');
  }
}

```

The results were:

1. no trace when AJAX not involved
2. for an AJAX request, the trace was:

* init: 1
    * exit: 1

In other words, it worked as expected, without any error message and normally delivering the HTML output.

Then, in order to now control what was uncertain about the warning stated in the hook\_exit page:

> This hook MUST NOT print anything because by the time it runs the response is already sent to the browser.

I simply changed for the following:

```
<?php
function mymodule_init() {
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $buffered_output = &drupal_static('mymodule_output_buffered', true);
    // AJAX request
    ob_start();
  }
}

function mymodule_exit() {
  $buffered_output = &drupal_static('mymodule_output_buffered', false);
  if ($buffered_output) {
    print ob_get_clean();
  }
}

```

What I expected was, either:

* if there was a real issue regarding the warning, it should merely NOT return the expected HTML output
* otherwise all should have worked as usual

But in fact I got the error message:

> Call to undefined function MYFUNCTION (which belongs to MYMODULE, see below)...

At the opposite of what was expected, this relies to the OTHER warning stated by the hook\_exit page:

> If you implement this hook and see an error like 'Call to undefined function', it is likely that you are depending on the presence of a module which has not been loaded yet. It is not loaded because Drupal is still in bootstrap mode.

At this stage, I don't understand what happens:

1. At a first view, seems that introducing `ob_start()` and `ob_get_clean()` should not change anything to which modules are already loaded or not. In other words, if it fails here, it should have failed with the previous test too
2. Secondly, the allegedly undefined function (say `undef_func()`) belongs to my module: it resides in an additional file, which is loaded by mymodule.module (using `module_load_include()`), while the `hook_exit()` function is also located in mymodule.module, so `undef_func()` should have already been loaded when `hook_exit()` is called

To be more clear, here is (part of) the mymodule schema:

**file: mymodule.module**

```
<?php

module_load_include('inc', 'mymodule', 'mymodule.data');
module_load_include('inc', 'mymodule', 'mymodule.core');

function mymodule_init() {
# ...
}

function mymodule_exit() {
# ...
}

# other mymodule hooks...

```

**file: mymodule.core**

```
<?php

function undef_func() {
# ...
}

# other mymodule core funcs...

```

For now I don't see how to understand what is happening...

---

## Issue solved, but a mistery remains

I tested more, adding a lot of trace points to identify how and when the files were loaded.

Then I first realized that, since I was connected with administration menu active, every call to a mysite url caused successively:

1. the entire page to be returned as expected
2. then an AJAX request to be sent by admin\_menu

And I discovered that, for some reason, **this** AJAX request only invokes `hook_init()`, while any non-AJAX call and all other AJAX requests invoke both `hook_init()` and `hook_exit()`.
It was apparently the reason why I got the error mentioned above.

Another strange thing is that, systematically, after an error had been fired:

1. flushing class registry caused a normal page to be rendered without any error
2. then F5 fired the error again

And so on, cyclically, without any change in the code! I can't figure out how this can be explained.

In the other hand, once this behaviour known, I could act to avoid this case, and do the job where I need it.

**So definitely, this solution works!**

# Answer
> 0 votes
This is all dev stuff and belongs in a custom module. Basic idea behind this: buffer any output, modify it before it get's send out, send it out.

```
<?php
/**
 * Implements hook_init();
 */
function mymodule_init() {
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $buffered_output = &drupal_static('mymodule_output_buffered', true);
    // AJAX request
    ob_start();
  }
}

// see https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_exit/7
// it states that this module must not print anything, but it should be possible
// by looking at the code, you'll just have to make sure that you don't break the
// request and be aware that headers area already sent, and you have to catch the
// output in the first place if you intend to modify it.

/**
 * Implements hook_exit();
 */
function mymodule_exit() {
  $buffered_output = &drupal_static('mymodule_output_buffered', false);
  if ($buffered_output) {
    $ajax_response = ob_get_contents();
    ob_end_clean();
    // do your string manipulations here.
    $ajax_response = str_replace('something', 'intosomethingelse', $ajax_response);
    print $ajax_response;
  }
}

```

You can implement any other logic in your hook\_init implementation to start buffering the output, even define additional options in other static variables that can be acted on in your hook\_exit().

Be aware to keep the logic in your hook\_init and hook\_exit as lean as possible, since it is run on each request.

---
Tags: hooks, ajax
---


# Question
Title: What are "Text format" option in standard Drupal?
I would like to know if in Standard Drupal, the comment form allows you to select a text format such as "Full HTML", "Plain Text" and "Filtered HTML" when commenting or even posting an article?

I have installed some module like WYSIWYG, CKEDITOR,IMCE, .., so now I am confused and do not know if the reason I have the option to select format text when commenting is because of the modules that I have installed or not?

# Answer
"Full HTML", "Plain Text" and "Filtered HTML" are default Textformats in Drupal, they determine which elements are allowed in the input and what gets filtered.

The wysiwyg editors only add UI controls to the field so user don't need to know HTML to style their output. If you don't want anonymous users to use formats like 'full html' you can turn it off in the permissions and give access to full html only to administrators or roles you trust.
> 0 votes

---
Tags: comments
---


title: ckeditor.styles.js caching issue

text:
# Question
Title: ckeditor.styles.js caching issue
I have a new drupal install. The only modules installed so far are devel and ckeditor.

I've added the 'styles' dropdown button and successfully directed it to the ckeditor.styles.js in my theme directory. At the moment, I'm using a path without tokens.

Initially, I had it at the root of the theme: */sites/mysite.org/themes/mytheme/ckeditor.styles.js*

but, when I updated the file in that location, the styles dropdown did not change. I tried resaving the ckeditor and I tried clearing all caches (from the performance section), I tried re-editing and saving the .js file (and I tried several permutations of the order); but, the dropdown would not update. I have browsed directly to the .js file after changing to confirm that it has updated

Eventually, I discovered that the only way to get the styles dropdown to update was to place the ckeditor.styles.js file in a brand new location (each time I want it to update).

So, if I change it I need to move it to:
*/sites/mysite.org/themes/mytheme/includes/ckeditor.styles.js*

and if I change it again, I need to move it to:
*/sites/mysite.org/themes/mytheme/includes/ck/ckeditor.styles.js* etcetera

This seems inefficient and I'm sure there must be another way. Please let me know if you have insight into this issue. Thanks

---

## EDIT

I was originally experiencing this issue while using the 'ckeditor' module. I've switched to the 'wysiwyg' module and I am not experiencing the problem any more.

# Answer
I believe this is due to your browser cache, not drupal cache. If you clear your browser cache or go incognito in chrome you should see your changes.
> 6 votes

# Answer
I wrote a small module to set `CKEditor.timestamp = +new Date` which then is queried to the JS so only the freshest JS is loaded on browser reload during development. For me this works super fine.
> 1 votes

# Answer
I believe that in addition to clearing the cache of Drupal (and potentially the browser), you should also manually run CRON, which might otherwise take hours to be triggered automatically.

To do that, go to `/admin/config/system/cron` and press `Run Cron`.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Block defined in code not appearing in admin interface
I have implemented hook\_block\_info() to define a block inside a custom module 'x'. I have followed the documentation and believe the values in my array are correct. I have cleared all caches multiple times. I have disabled and re-enabled my module. I have tried setting status to both 0 and 1.

What is strange is that if I place a DPM() inside the x\_block\_info\_alter(), I can see the block as an array when I visit the admin page. However, in the actual block list, it's not there!

Is there something wrong with my code that I can't see?

```
function x_block_info() {
  $blocks['mname'] = array(
    'info' => t('Admin title'),
    'cache' => DRUPAL_NO_CACHE,
    'status' => 1,
  );
  return $blocks;
}

```

# Answer
The only thing that ended up working for me was removing the cache setting from the array. If anybody else runs into problems, I suggest stripping the array down to only the required values and seeing if it appears. Then, set the rest of the values you need in the UI. Sad, but it was the only solution which worked for me.
> 0 votes

# Answer
I had exactly the same thing: dpm() showing me my block on admin/structure/block, but no block actually appearing in the admin. Disabling, uninstalling and re-enabling the module where I defined my block then clearing cache worked for me.
> 1 votes

# Answer
Do you have something like this in your module in addition to the function above?

```
function x_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'mname':
      $block['subject'] = t('MName');
      $block['content'] = x_function_to_generate_block_content();
      break;
  }
  return $block;
}

```
> 0 votes

---
Tags: blocks, hooks
---


# Question
Title: How to create a chart for tracking Product stock over some period of time using Ubercart?
Does anybody know about a good solution for tracking Product stock in a certain timespan?

It is nice to see the stock numbers of products, but I find quite handy to see product performance **over time**.

**My Questions**: Is there any module for this? Or is it more appropriate to create such Product stock tracking using views?

*Edit*: Maybe it's possible to record some "Product stock"-field into some database?

# Answer
You should try views charts for creating graph

> About the Project
>
> Provides a "charts" style output for Views module so you can render result-set not just as text (list, tabular) but as pie-chart, bar-chart, scatter-plot etc.
>
> DC DrupalCon '09 Presentation
>
> http://vimeo.com/5306364
>
> Dependencies
>
> Views Charts and Graphs Suggested modules
>
> For Drupal 6 you will need the Views GroupBy: if you want to chart anything actually useful. Views 3 for Drupal 7 has grouping built in. Documentation
>
> Views Charts has basic usage instructions available as Advanced Help pages. Please install and enable it to see the available help.
> 0 votes

# Answer
Folks,

From My Professional experience you can use Highcharts in drupal. Usually highcharts also have its own significances with views but I will suggest you guys to use highcharts libraries with visualization module. You have much flexibility to use CHARTS IN VIEW As per required + Filters and all other stuff also works quite Smoothly with highcharts. You also have lot of other options also to use with visulization API.

It also allows you to create custom charts serving the data from database or wherever you want.

Important Links : Visualisation : https://www.drupal.org/project/visualization

References : Screencast : https://www.youtube.com/watch?v=ot2cFQVgzfA
> 0 votes

---
Tags: 6, ubercart, charts
---


# Question
Title: Clean URLs work*, but not when I submit forms?
I have a local dev site configured (Ubuntu 14.04.1 LTS), and I copied a production website to play with there. Everything appears to work great. Clean URLs seem to work and I can navigate the site. It's all wonderful... until I try to login.

When I login at /user, submitting the form returns me to the login as if nothing happened. I was able to login by visiting /?q=user .

After that, if I attempt to clear the cache under performance settings, I get a similar result where the performance page loads as if nothing happened (clearing cache manually via mysql doesn't help). If I disable clean URLs altogether, all is well.

I tried replacing the .htaccess file with Drupal's default to prevent special config issues (no effect). I didn't see anything set as $base\_url in settings.php (I'll try setting that to see what happens next).

Any thoughts on why a site with clean URLs enabled seems fine until POST data is involved? Thanks for the feedback in advance!

# Answer
> 1 votes
I think you need to enable Apache's rewrite module using `a2enmod rewrite` or with sudo if you get permission errors and added the Apache directive `AllowOverride All` for VirtualHost.

# Answer
> 0 votes
Try to uncomment `RewriteBase /` (remove #) in `.htaccess` file and make sure that `$base_url` in `settings.php` file is commented.

---
Tags: users, forms, uri
---


# Question
Title: Can you customize the User Edit page without editing the theme?
Is there a way to customize what appears on the user profile edit page without editing the theme? I'd much rather use blocks or hooks to accomplish this task.

Is this possible?

# Answer
You can use panels. It has a panel page for the 'user edit page' that you can edit, put blocks, views, etc.
> 1 votes

---
Tags: hooks, users
---


title: Get next node in nodequeue

text:
# Question
Title: Get next node in nodequeue
I have a nodequeue named `work_order`.

If I am in a page which belongs to this queue, is there a way I can get the next node that will be there in the nodequeue?

I looked at most of their API functions, but I did not find one that does this.

I am using drupal 7

# Answer
Should be something like getting the nid of the current node and then being $nid the node id of the current node and $sqid the queue id:

```
$pos = nodequeue_queue_position('work_order', $nid);
$nodes = nodequeue_load_nodes($sqid, FALSE, $pos+1, 1, TRUE);

```

It's untested so maybe you need to tweak the position and so.
> 2 votes

# Answer
My solution is bit different from pcambra's. Actually I implement looking for previous and next node like this:

```
$pos = (int)nodequeue_get_subqueue_position($sqid, $node->nid);
$node_prev = nodequeue_load_nodes($sqid, FALSE, $pos - 2, 1);
$node_next = nodequeue_load_nodes($sqid, FALSE, $pos, 1);

```

Note: The previous is $pos-2, not $pos-1. The reason is that the returned position of nodequeue\_get\_subqueue\_position is starting from 1, and the argument of position in nodequeue\_load\_nodes is from 0! The same reason for the next node.

Finally, the node you got is stored in the returned array. For example you can retrieve its nid like this:

```
$next_node_nid = $node_next[0]->nid;

```
> 0 votes

# Answer
I got it working using custom\_pagers module.

https://www.drupal.org/project/custom\_pagers

It actually quite simple once you apply the needed patches as the module is not well maintained.

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

apply these patches -

https://www.drupal.org/node/1288368#comment-6429832 https://www.drupal.org/node/1346194#comment-5881226

Now, just enable the module, create a new custom pager
pager position : sideblock
pager node list : view \>\> nodequeue\_#

to get the correct nodequeue - admin/structure/nodequeue
just hover over the edit link to get the machine id
> 0 votes

---
Tags: paging, navigation, nodes
---


# Question
Title: How do I reroute a logged-in user after page access denied at user/login?
My Drupal 6 site has the login form at /user/login. If I'm logged in already and I click it, I'm sent to the Access Denied page (though the login URL stays the same).

I'd like to send such users somewhere else. Anywhere else. /user would be fine. Is there anything I can hook into to achieve this?

# Answer
> 0 votes
That sounds like a familiar question ... Here is how I was able to solve it so far (not sure if there are better ways to do so ...):

* within /admin/settings/error-reporting I entered a relative URL like **no\_access**
* then I created a no\_access page, in which I described what might be causing the problem.

For a sample of such no\_access page, visit http://www.inpetto.be/no\_access (access allowed by anybody ...). Note bullet nr 2 there ...

Makes sense?

---
Tags: 6, users
---


# Question
Title: IMCE 6.27 Missing Buttons to Upload to Editor
I'm attempting to correct my IMCE file browser issue where the images don't appear. I cannot click on the file names to select them, I am, however, able to move around the left hand navigation sitemap and choose different roots and folders.

I'm running on Drupal 6, and using IMCE 6.27 (non-dev). CKEditor is not installed, and TINYMCE is turned off. Turning it on didn't seem to solve any issues. There are no SSL pages, so that fix didn't resolve my issue by letting it ignore the IMCE files.

Any thoughts?

# Answer
> 0 votes
The issue in this instance laid with Google Analytics and it's Event Tracking. A quick test is to turn on the Google Analytics Module, then try to use the IMCE upload buttons again. If they return, do the following:

* Re-enable Google Analytics Modules you'd previously turned off to test.
* Goto /admin/settings/googleanalytics
* Open the collapsible menu option "Page Specific Tracking Settings"
* Add *imce* to that list Click Save
* Configuration and test again.

Your IMCE should be working again without issue should the Google Analytics have caused your issue in the first place.

---
Tags: 6, files, media
---


# Question
Title: How to add Variables in Drupal (and how to visualize them)?
I'm new to Drupal Answers, but I've been programming for a few years now.

I'm looking to create something simple (at least I think) within the Drupal CMS to use throughout the site. I want to create a variable, let's call it **$phonenumber** and store the value of this variable, like **(789) 456-7894** (not a real number). That way I may use the value of this variable on my site without hardcoding the number.

I have installed the Variable module, which has little to no documentation, and poor usability all around.

I build in PHP, I know this is basic, Drupal is built on PHP. But for some reason I cannot get a **printr** or **echo** of the variable on any page to work.

# Answer
> 0 votes
Are you aware of the devel module? It is typically used in dev versions of a site only, and is not recommended for production status sites.

After you enable that module, you'll get many features, such as **dprint\_r()**, **dpm()** (I like the last one for debugging). For more details, refer to https://www.drupal.org/node/174575 ...

---
Tags: configuration
---


title: Need to center images in wyswyg block

text:
# Question
Title: Need to center images in wyswyg block
I am trying to center 3 images in a block I have created in my footer but the images just won't center. I tried the wysiwyg editor's center button, but that did not work. I then tried to put in manual css which failed. I can't seem to get these images to center. I would appreciate any help.

Using: CKEditor 7.x-1.13

I tried adding a Bootstrap 3 "center-block" css class, but this does not work either.

```
<p>© 2014 Environmental Law Alliance Worldwide (ELAW)<br />
U.S. Office: 1877 Garden Avenue, Eugene, OR 97403 USA<br />
Phone: +1 541 687 8454<br />
Fax: +1 541 687 0535</p>

    <div class="center-block">
    <a href="/projects/edigest/user"><img class="float-left img-responsive" src="http://localhost/projects/edigest/sites/all/themes/bootstrap-business/images/facebook.png" /></a> <a href="/projects/edigest/manage-translate"><img class="float-left img-responsive" src="http://localhost/projects/edigest/sites/all/themes/bootstrap-business/images/blog.png" /></a> <a href="/projects/edigest/translate"><img class="float-left img-responsive" src="http://localhost/projects/edigest/sites/all/themes/bootstrap-business/images/twitter.png" /></a>
    </div>

```

Here is what displays:

# Answer
> 0 votes
Add the "center-block" class to the **img** tag.

---
Tags: 7, media, wysiwyg
---


# Question
Title: How to change the author of a node after payment using the rules module?
I would like to use the rules module to change the author of a node after payment.

Even though I have limited experience with the rules module, I am sure it is possible to do.

This is what I'm looking for:

1. Client pays for existing node.
2. Ownership of the node is transferred to that client.

Any help would be greatly appreciated!

# Answer
This seems like a variation of the question "Change node author on node save with rules". And the accepted answer there (with the comment added to it) seems the answer to it.

Does this answer your question?
> 1 votes

---
Tags: commerce, rules
---


title: How do I change the front page?

text:
# Question
Title: How do I change the front page?
In commerce guys demos store I toggled off the main menu in commerce kickstart template and have enabled the main menu block to stay on sidebar first block. I want to get a vertical main menu instead of a horizontal one like the demo store default installation.

Besides, I disabled the slide show content. I want to get the products of a specific collection to be displayed in front page. So I went to Site settings \> configuration \> System information and changed the default front page URL to collection/my-collection.

But the page doesn't display the main menu on sidebar first. The my-collection colletion is displayed but lose that tiny margins that wrap the products.

I follow this drupal.stackexchange post and tried to comment out the lines

```
function omega_kickstart_alpha_preprocess_page(&$vars) {
  if ($vars['is_front']) {
    unset($vars['page']['content']['content']['content']['system_main']['default_message']);
  }
}

```

in both profiles/omega\_kickstart/preprocess/preprocess-page.inc and profiles/commerce\_kickstart/preprocess/preprocess-page.inc, but didn't work.

Could somebody please help me?

# Answer
> 0 votes
Check the block configuration for the menu, might be set to only on the default front page, changing the default home page changes the url, so your block needs to be configure to display on the url for your "new" front page. At least I think this is what's going on.

---
Tags: commerce
---


# Question
Title: Procedure For Cloning Commerce Collection Taxonomy View Page?
We are creating a store with Commerce Kickstart2. We need to duplicate the functionality of the Collection taxonomy. Essentially, we need -exactly- what the collection field does, but we need another one to organise products in a different way.

I've created a new Taxonomy term called 'Specialty'. I've successfully added that field to the Products. They can be searched and displayed and if I type in

/specialty/whatever-term

...I get a basic taxonomy term page of the correct products.

What I want to do is clone the View called 'collection-products' to a new view 'specialty-products' which does -exactly- the same thing, but for the new vocabulary 'Specialty'. I took a wild stab at it:

1. I copied/renamed the PHP file for the view into my theme folder

views-view--specialty-products--page.tpl.php

1. Edited that php replacing 'specialty' for all the vars 'collection'.
2. I cloned the collection-products view and replaced the 'collection' field with 'specialty' where necessary.

So (naturally) this does nothing.

Can someone provide guideance on where I went wrong or how to proceed from here?

# Answer
I think you need a view based on your products filtered to your taxonomy term. You should be able to do this with the views UI more easily than the way you're attempting to programatically.

I think you're misunderstand the theme folder altogether and how drupal presents the page that is rendered in the browser. The theme folder has mark up, images, and CSS that defines how your whole site is displayed, the views are generated, not stored as discrete files in your theme folder.

If you're on the kickstart demo store. Go to Product Categories, delete the defaults, add your own 'categories', and that should change the demo store to reflect your own set up. You should play with a default drupal set up to get familiar
> 1 votes

---
Tags: taxonomy-terms, commerce
---


# Question
Title: Will changing the value of $drupal_hash_salt in settings.php file break site
I was looking through a list of steps to take when there is a risk that your site has been hacked. It recommends changing the value of `$drupal_hash_salt` in settings.php.

According to the inline comments in settings.php:

> Salt for one-time login links and cancel links, form tokens, etc.
>
> This variable will be set to a random value by the installer. All one-time login links will be invalidated if the value is changed. Note that if your site is deployed on a cluster of web servers, you must ensure that this variable has the same value on each server. If this variable is empty, a hash of the serialized database credentials will be used as a fallback salt.

Can I simply replace the existing value with random string? I am worried that changing this string may adversely effect some other aspect of site functionality.

# Answer
> 4 votes
Disruption should be minimal -- the salt value was designed to be changeable. As it says, it will invalidate one-time login links when the salt is changed. But if you suspect that you've been hacked, this is precisely what you want to happen.

---
Tags: security, users, configuration
---


title: HTML table to Drupal table

text:
# Question
Title: HTML table to Drupal table
How can I translate this to drupal table?

http://www.bootply.com/sXmuAJQjO4

I know how to do simple tables and the header and first row I can do also with this code:

```
$title = '<div class="panel panel-default">
<div class="panel-heading"><h3>Table Title</h3></div>
<div class="panel-body">';

    $header = array(
        array('data' => ' '),
        array('data' => 'Job Name'),
        array('data' => 'Description'),
        array('data' => 'Provider Name'),
        array('data' => 'Region',),
        array('data' => 'Status'),
    );

    #'data-toggle' => 'collapse'
    $row = array(
        'data' => array(
            array('data' => '<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-info-sign"></span></button>'),
            array('data' => 'OBS Name',),
            array('data' => 'OBS Description'),
            array('data' => 'hpcloud'),
            array('data' => 'nova'),
            array('data' => 'created'),
        ),
        'class' => array('accordion-toggle'),
        'data-toggle' => 'collapse',
        'data-target' => '#demo1',
    );
    $rows[] = $row;

```

But I can't add the hidden row. Can anyone help me?

Thanks!

# Answer
For the hidden row, you need a second table which would look like:

```
// This is the hidden table
$table_hidden = '<div class="accordian-body collapse" id="demo1">';
$table_hidden .= theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));
$table_hidden .= '</div>';

$row2 = array(
  'data' => array(
    array(
      'data' => $table_hidden,
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

```

Option 2, a more module-clean way would be to use hook\_theme function and create a simple template file where additional markup is placed like so.

```
function YOURMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'any_name_you_like' => array(
      'template' => 'hiddentable', // This called hiddentable.tpl.php
      'arguments' => array('table' => null),
    ),
  );
}

```

Then in your page callback or wherever, you would just need to use your declared theme function like so.

```
$table_hidden = theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));

$row2 = array(
  'data' => array(
    array(
      'data' => theme('any_name_you_like', array('table' => $table_hidden)),
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

```

Now in your hiddentable.tpl.php

```
<div class="accordian-body collapse" id="demo1">
  <?php print $variables['table']; ?>
</div>

```
> 1 votes

---
Tags: javascript, theming
---


# Question
Title: How do I re-queue a test that has been postponed on Drupal.org?
I'm trying to run the tests on a patch on Drupal.org. The relevant issue is here. The status is marked as **Test request sent** but more than a week has passed and the test hasn't been run.

I tried changing the issue status from *Needs review* to *Needs work* and then back to *Needs review* but that didn't re-queue the test. If the test has been run, whether it succeeded or failed, there is usually a **Re-test** link, but since the test is marked as "test request sent" then the link does not appear.

How can I re-queue such a test?

# Answer
> 4 votes
You can post an issue to the drupal.org testbots project issue queue and get someone to look into it.

---
Tags: testing
---


# Question
Title: How can I format the date like this in search-result.tpl?
In node.tpl I have

```
<div class="imported-text">

Created on <?php print date('l', $node->created); ?>, the <?php print date('jS', $node->created); ?> of <?php print date('F Y', $node->created); ?>.

</div>

```

But when I place this in search-result.tpl I get an error. `<?php print $info_split['date'] ?>` can only use the short format AFAIK.

# Answer
> 3 votes
I find it is generally best to do things in a consistent way and since the drupal template\_preprocess\_search\_result() function uses Drupal's format\_date() function I recommend also using that when overriding things.

So to leave the date in the default info variable but change the format I would do this, in my template.php file of my theme (or a custom module, depending on my requirements):

```
/**
 * Variable preprocessor for the search result template.
 *
 * @see search-result.tpl.php
 */
function MODULE_OR_THEME_NAME_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Override the date format.
  if (!empty($result['date'])) {
    $variables['info_split']['date'] = format_date($result['date'], 'custom', 'l, \t\h\e jS \o\f F Y');
  }
  // Reset the info variable based on the new date.
  $variables['info'] = implode(' - ', $variables['info_split']);
}

```

If I wanted a date variable available in my template that was separate from the info variable I would do this:

```
/**
 * Variable preprocessor for the search result template.
 *
 * @see search-result.tpl.php
 */
function MODULE_OR_THEME_NAME_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Add a custom date variable for use in the template.
  $variables['custom_date'] = '';
  if (!empty($result['date'])) {
    $variables['custom_date'] = format_date($result['date'], 'custom', 'l, \t\h\e jS \o\f F Y');
  }
}

```

Then to use that variable in the template file you would do something like this:

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

```

Something I recommend to make things even a bit better again is instead of using the 'custom' date formatter, make a preset for "l, \t\h\e jS \o\f F Y" in the Drupal UI at admin/config/regional/date-time, then use that preset like this:

```
format_date($result['date'], 'preset_name');

```

Then you can easily change the format in future via the UI.

In this case I would recommend calling the preset "Search result date" or something along those lines so that you know what it is used for when looking the the UI and you know what will be affected if you change it.

---
Tags: search
---


title: Question about part of Comment.module

text:
# Question
Title: Question about part of Comment.module
The following is part of the comment.module file (line 950):

```
// Add indentation div or close open divs as needed.
if ($is_threaded) {
  $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n"     . '<div class="indented">';
}

```

Can someone explain that what is it doing?

# Answer
> 4 votes
For reference, this is in the comment\_view() function.

It is equivalent to this, which makes it a little easier to understand:

```
if ($is_threaded) {
  if ($comment->divs <= 0) {
    $prefix .= str_repeat('</div>', abs($comment->divs));
  }
  else {
    $prefix .= "\n" . '<div class="indented">';
  }
}

```

`$is_threaded` is a boolean value for whether or not threading has been enabledfor comments in the settings for this content type.

$comment-\>divs is set in comment\_prepare\_thread() and is a count of the indentation divs required to have this comment in the right place in terms of the comment's depth. So this value will either be 1 if a new indentation div needs to be added to make sure the comment is at the correct depth, or a negative number, which is how many indentation divs need to be closed to have the comment at the correct depth.

So if comment threading is enabled, then if `$comment->divs` is less than or equal to zero then close zero or more indentation divs by appending `str_repeat('</div>', abs($comment->divs))` to the markup otherwise, if `$comment->divs` is 1 then open a new indentation div by adding `'<div class="indented">'` to the markup.

For example if you had these comments:

```
Comment 1
-Comment 2
--Comment 3
---Comment 4
--Comment 5
---Comment 6
----Comment 7
-----Comment 8
-----Comment 9
Comment 10
Comment 11
-Comment 12
Comment 13
Comment 14

```

Then for each comment, $comment-\>divs would be:

* Comment 1: 0
* Comment 2: 1
* Comment 3: 1
* Comment 4: 1
* Comment 5: -1
* Comment 6: 1
* Comment 7: 1
* Comment 8: 1
* Comment 9: 0
* Comment 10: -5
* Comment 11: 0
* Comment 12: 1
* Comment 13: -1
* Comment 14: 0

---
Tags: comments
---


title: Theme_hook_suggestions not working

text:
# Question
Title: Theme_hook_suggestions not working
I'm using hook\_preprocess\_node in a module. In that, I check whether the node type, and on satisfying the condition I'm doing a theme\_hook\_suggestions. My tpl.php files are inside my modules template folder, It is not taking the tpl file I have suggested. I have searched a lot, but didn't find any solutions

Any solution would be apprecaited Here is my code

```
/**
 * Implements hook_preprocess_node().
 */
function mymodule_preprocess_node(&$varaiables) {
  if (isset($varaiables['node'])) {
    $node = $varaiables['node'];
    $field_template_list = $node->field_template_list[$node->language][0]['value'];
      if ($node->type == 'event') {
        $varaiables['theme_hook_suggestions'][] = 'module_name_' . $field_template_list;
      }
   }
}

```

# Answer
> 2 votes
Drupal will not look for template overrides in custom modules, only themes.

If you really want to put a template override in a custom module see the answer to this question.

Extra notes are:

* Make sure to handle punctuation and any other undesirable characters in your field value.
* field\_get\_items() is a better way to get the value of a field from a node.
* It is generally best to keep your template suggestions in line with what is already there. For example starting this suggestion with 'node\__' followed by your custom stuff, like maybe `'node__event__' . $field_template_list` or something like that. It makes it easier in future to know what kind of template it is.

---
Tags: theming
---


title: Play or Download an Audio file

text:
# Question
Title: Play or Download an Audio file
I'm running a radio website on Drupal 7 http://punkrockradio.net/ We have podcast that user can listen with Pushtape Player using Soundmanager2 API. I have installed DownloadFile.

I would like to give my user the option to listen to the file or to download it.

Any idea? Thanks in advance

# Answer
> 2 votes
There are a number of ways you could accomplish this. Some might be better than others depending on your specific requirements.

Since soundmanager2 and downloadfile both provide field formatters the easiest way is probably just to print the field twice, each with a different formatter.

A couple of ways you might do that (this is not an exhaustive list) are:

* Create a node view with a contextual filter that takes a node ID. Set the filter to use a default value if no value is present and set the default to be the node ID from URL. Then put the field in question in the view twice with the different formatters. Then either manually print the view in your node template or use the EVA module to show the view on the node.
* Set the field up to display as one of the formatters via the node display settings UI and print it manually in the node template like you would any other field. Then also add a node preprocess function to render the field a second time with the other formatter into a custom variable using field\_view\_field(). Then print that custom field rendering alongside the other field rendering.

I can possibly provide more detail on those solutions if you have further questions.

---
Tags: files
---


# Question
Title: Group by parent terms from indexed node in views
Based on this question, I've obtained an "Indexed Node: Taxonomy Name" field in my view.

How can I group the results by parent terms? When I group by the term field (Format \> Settings \> Grouping field Nr.1), no parent terms are displayed.

# Answer
You can also add the parent term to the index.

So if you have field\_category as your term field you will be able to index field\_product\_category:parent.

Note that you may have to use the "Add related fields" section at the bottom of the fields admin page for your index to add the parent term relation before you can add the parent term tid or term name etc.

Then in your view also add the parent term name field and exclude it from display and then group by it.
> 2 votes

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


# Question
Title: Comments and Testimonials on Profile 2 Profiles
Is there a way of enabling either comments or a guestbook/testimonial functionality on Profile 2 Profiles?

I've read discussions on here about implementing on User Account Pages but not for the Profile 2 Profiles module.

Any ideas?

# Answer
There is a module called reply, that is intended as a solution for fieldable comments on non-node entities and should work with any entities created via the Entity API module, which includes profile2 entities.
> 0 votes

---
Tags: theming, comments, users
---


# Question
Title: Show menu link descriptions for a custom navigation menu
I have the following navigation, displayed in `page.tpl.php`:

```
theme('links', array('links' => menu_navigation_links('menu-site-navigation')));

```

There are four navigation elements that show up. I would like to display the description that goes along with these elements as well, how do I go about that?

In my `template.php` file I have the following code, but I can't figure out how to only apply this change to `menu-site-navigation`

```
function MYTHEME_link($variables) {
   // if there is a description for the menu item, show it
  if(!empty($variables['options']['attributes']['title'])){
      return '<a href="' .
      check_plain(url($variables['path'], $variables['options'])) .
      '"' . drupal_attributes($variables['options']['attributes']) . '>' .
      ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) .
      '</a><div class="description_nav">' . $variables['options']['attributes']['title'].'</div>';
  }
  else{
    return '<a href="' .
    check_plain(url($variables['path'], $variables['options'])) . '"' .
    drupal_attributes($variables['options']['attributes']) . '>' .
    ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) .
    '</a>';
  }

```

}

# Answer
> 0 votes
Here are two things that may help you get this going:

1. It looks like you're calling the theme\_links() rather than the theme\_link() function in your page.tpl.php file, so make sure that the call and theme function implementation match.
2. You could add additional information to your links when you theme them to distinguish them from other links. For example, notice how I'm **adding an id** in the 'attributes' section below, so I can check for it later, in my theme\_links implementation

Does that help?

```
 print theme('links', array(
  'links' => $secondary_menu,
  'attributes' => array(
    'id' => 'secondary-menu',
    'class' => array('links', 'inline', 'clearfix'),
  ),
  'heading' => array(
    'text' => $secondary_menu_heading,
    'level' => 'h2',
    'class' => array('element-invisible'),
  ),
));

```

# Answer
> 0 votes
An alternative solution to what you are doing that requires no coding is the menu descriptions module, which allows you to create menu descriptions blocks for your menus via the Drupal admin UI and then position those block where you like.

The blocks will display your menus along with descriptions that have been set for those menu items.

---
Tags: 7, routes, navigation
---


# Question
Title: Add custom styles for printing taxonomy terms
I'm using print module for generating a PDF file. Here, the node that I'm printing has a field that lists all the `taxonomy terms` for that specific node.

When the page is printed, the taxonomy terms are displayed in an `unordered list` with bullets, leaving an empty line between field name and taxonomy terms as:

```
Field name:

 - term1
 - term2

```

But, I wish to display the terms next to field name in the generated pdf. I tried using taxonomy menu module, but i anticipate it doesn't work with print module. Is there any way to get this done.

# Answer
> 0 votes
If you go to the display settings for your node (eg. admin/structure/types/manage/article/display) and in the "Custom display settings" fieldset check the box for "Print" and the save. Then click the tab for the "Print" display settings.

Then configure your field with an inline label.

If this is not sufficient for your requirements you could also then override node or field templates specifically for that print display mode.

I can provide more information on that if you require it.

For node and field templates you can either use an if statement in the template to specify a specific view mode or you can add specific template suggestions so that you can have specific templates, like node--print.tpl.php

For the if statement method there are variables already available in those tempaltes:

**node.tpl.php**

```
<?php if ($view_mode == 'print'): ?>
  Your code goes here.
<?php endif; ?>

```

**field.tpl.php**

```
<?php if ($element['#view_mode'] == 'print'): ?>
  Your code goes here.
<?php endif; ?>

```

Or you can add template suggestions like this in your template.php file:

**node.tpl.php**

```
/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_node(&$vars) {
  // Template suggestions for node--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['view_mode'];
  // Template suggestions for node--NODE-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' . $vars['view_mode'];
}

```

**field.tpl.php**

```
/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_field(&$vars) {
  $element = $vars['element'];

  // Template suggestions for field--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_type'] . '__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-NAME--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_name'] . '__' . $element['#view_mode'];
}

```

Those are examples. You can make other suggestions based on pretty much anything you want.
You can also just do a specific template suggestion for the print view mode instead of doing dynamic ones for all view modes like the above examples.
If using the above examples be careful that you don't have conflicts, for example if you have a node type that is the same as a view mode.

---
Tags: taxonomy-terms, files
---


title: Get the user theme

text:
# Question
Title: Get the user theme
In my admin page, I have a text field, for which I want to set the default\_value as the active theme. I am getting the admin theme. But my requirement is to get the user theme.

Is there some how I could get theuser active theme.

# Answer
The user default theme could be obtained by

```
variable_get('theme_default');

```
> 1 votes

---
Tags: theming
---


# Question
Title: Exposed filter (by terms), only to show terms related to this content type
I'm using the Vocabulary 'Tags' in multiple content types.

I have a view showing 'Content Type A', and I want to have an exposed filter showing only the 'Tags' used in 'Content Type A', not every content type.

Any ideas on how this can be achieved would be greatly appreciated, thanks!

# Answer
> 2 votes
You can use hook\_form\_alter to alter the exposed form:

```
<?php
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'form_views_exposed_form') {
    drupal_set_message("Form ID is : " . $form_id);
  }
}
?>

```

Just write some code that fetches all the used categories in content type A and compare those with the categories in the dropdown. Then, unset the categories that aren't used.

You can do this by building an array that has the same structure as the options in the drop down and then use array\_intersect to get all the values that are shared over your custom build array and the options in the dropdown.

# Answer
> 0 votes
Here is why iLoveDrupal :)

There is a module for this functionality.

https://www.drupal.org/project/views\_selective\_filters

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


title: call specific name of views from module

text:
# Question
Title: call specific name of views from module
Below code changes the all quantity label to none. i am trying to change quantity field label for specific views block for ubercart3. (so in product node, quantity labeled as quantity and in product views block, quantity field is not labeled.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if(strpos($form_id, 'uc_product_add_to_cart') !== FALSE){
    $form['qty']['#title'] = t('');
  }
}

```

How to call specific views from module? or is this something i should do in views template? i tried the below code and qty label doesn't change.

```
if(strpos($form_id, 'uc_product_add_to_cart') !== FALSE){
  $view = $form_state['view'];
  if ($view->name == 'my_view_machine_name') {
    $form['qty']['#title'] = t('');
  }
}

```

# Answer
> 0 votes
So you want to get a name of current view in form alter function, which is not related to this view - this form is just located on the same page.

Use views\_get\_current\_view() to get current view is currently in use: `$view = views_get_current_view();`

If there is no view is currently is use, views\_get\_current\_view() will return NULL, so we need to add additional condition: `if ($view)`

```
if (strpos($form_id, 'uc_product_add_to_cart') !== FALSE) {
  $view = views_get_current_view();
  if ($view && $view->name == 'my_view_machine_name') {
    $form['qty']['#title'] = t('');
  }
}

```

# Answer
> 1 votes
You need to replace 'my\_view\_machine\_name' with your actual view machine name.

To get view machine name, you can edit your view, and in the URL you will see it: *admin/structure/views/view/**machine\_name**/edit*

---
Tags: 7, forms
---


# Question
Title: Set entity reference field to 'autocreate' directly in the entity field definitions
I'm having trouble with the two ways of defining forms for entities in Drupal (the first one being in the entity field definitions and the second one being by defining a custom form class).

Now, in a classic form, all I have to do is add an element with the `entity_autocomplete` type and set `#autocreate` to `array('bundle' => 'foo')`. I tried replicating this in various ways in my entity, none of which worked out (I tried via `BaseFieldDefinition`'s `setSetting` or in the display options for the form).

What I don't understand is why the two ways of defining forms are so different? Why can't it just be the same syntax in both places?

I'm aware of the Inline Entity Form module, but there doesn't seem to be a proper port for Drupal 8 yet, and what I'm trying to do works perfectly fine when I define the form manually as explained. I just want to be able to define all this in my entity directly to avoid unnecessary code.

# Answer
> 3 votes
I finally found a way to get it to work after digging through the code for the `EntityReferenceAutocompleteWidget`. To enable automatic creation, I needed to edit the handler settings. Here's my code:

```
$fields['client'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Client'))
  ->setSettings(array(
    'target_type'      => 'client',
    'handler'          => 'default',
    'handler_settings' => array(            // Added
      'auto_create'    => TRUE              // Added
    )
  ))
  ->setDisplayOptions('form', array(
    'type'     => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size'           => 60,
      'placeholder'    => ''
    ),
    'weight'   => 0
  ))
  ->setRequired(TRUE);

```

---
Tags: forms, entities, 8
---


# Question
Title: How can my eCommerce site only showcase products without an Add to cart option?
I want my Drupal eCommerce site to only show products which contain only product name, description, PDF file.

I don't want price & Add to cart options. Is there any possibility in Drupal?

# Answer
Yes, there is a possibility. You can achieve that by using the Views module.

Create a content type for Products (say products) or you can also use default content types Basic Page or Article .

Add fields whatever you want to show for products (say description, file for PDF).

Create a *View* for to display the Product content type nodes (products)

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

---
Tags: 7
---


title: Removing link from slideshow images

text:
# Question
Title: Removing link from slideshow images
Hello I Have Created A Slideshow Using Views but in slideshow if anyone is clicking The link was opening node/8 I Don't Want To Show Link In When Anyone Clicks on slideshow here is my website link Windowhelpdesk.com

# Answer
> 0 votes
Without knowing how your view looks like (or what slideshow module you use, if any) it is hard to give a definite answer - but check the image field in your view. If you edit the field there should be an dropdown titled 'link this image with' and right now it is probably set to 'content'. Set it to 'nothing' to remove the link.

Note: I am not sure about the exact labels as I work with a german drupal instance right now, but they should come close. The dropdown is right above the Design Settings fieldset.

---
Tags: views
---


# Question
Title: How to get a patch for the Views module reviewed and committed to the project?
Recently I found an issue with the Drupal Views module. I have submitted a patch to fix it.

Does anyone know what the process is to:

1. get this issue (and related patch) reviewed?
2. ultimately get the patch committed to the project?

Due to the amount of open issues (like over 3.700 ...) it appears the maintainers for Views are possibly dealing with more complex issues, or there might be a views project specific process to get a patch committed?

Does anyone know the answer to my questions?

**Note**: The specific issue I have fixed can be found at https://www.drupal.org/node/2428065, so if anyone could check this any confirm on the issue if this is fixed that would be appreciated.

# Answer
> 5 votes
A pitty that nobody has reviewed your patch so far. I think you should consider posting a question in one of the Drupal.org forums, with some kind of friendly reminder about it. Something like "can anybody help me on this specific issue to get it in status Reviewed & Tested by the Community (RTBC) please?".

By the way: RTBC is not to be considered as a synonym of "Patch to be ported". Though as a maintainer of a few Drupal modules, I often treat an issue in such status as "Ready To Be Committed".

RTBC is, in my opinion, the next status that your issue should be changed to (assuming your patch is tested by somebody else, and confirm to indeed solve the issue).

After the issue receives RTBC status, it's up to any of the (co-) maintainers of that project to actually **apply** the submitted patch to the most current dev version (make sure your patch was created as compared to that, if not there is a risk the patch needs to be re-rolled, which in turn will cause more delays until that gets done). It is perceived as a good practice in Drupal to also "give credit" to the submitter of the patch, by indicating your drupal userid as part of the commit message.

And from then on, it's a matter of waiting for a new release that includes the corresponding commit of course.

A great illustration of this workflow can be found in the issue at https://www.drupal.org/node/1947876 ... Even though that specific issue has taken really long (over 2 years ...) before it made it to the finish, i.e. status fixed and closed. What I find so amazing about this issue is that it is a perfect illustration of "the community at work", where each of the players did their part of the work ...

FYI: I'm a (co-) maintainer of a few Drupal modules (refer to my SE profile for details), sometimes it's hard to find sufficient time to process such RTBC-patches (waiting to be committed). But whenever I have time, I always give those RTBC-issues the highest priority, out of respect for the contributors of such patches (and the people who reviewed them) ...

PS: even if your patch doesn't get committed as fast as you'd like it to be, you should still continue submitting patches. Because that way you have them available for any sites where you believe this patch is required. This may require however that occasionally you need to update / rework your patches.

# Answer
> 3 votes
There is nothing wrong with Pierre.Vriens answer, but I just want to add a few points to what he says:

1. If the module has a huge backlog of uncommited patches, and you feel like helping out with getting things done in a more timely fashion, you should consider offering to co-maintain the module. Just post an offer to co-maintain in the project's issue queue, with a copy to the project owner as a PM using his/hers Drupal.org contact form, point out your patches (that helps the owner evaluate your skills as a developer), and wait at most two weeks for a reply. The maintainer is not obliged to accept your offer (some owners insist on being in total control), but most owners will appreciate a helping hand. Btw. if you're made co-maintainer, it is not considered good form to commit your *own patch* until it has received at least one positive review from another user - but I know that not all co-maintainers respect this rule.
2. If your offer to co-maintain is not answered in two weeks, and the maintainer also appears to be missing in action (patches are no longer committed or rejected, the maintainer no longer responds to issues being raised in the issue queue), you may consider initiating the unsupported (abandoned) project process. You may enter this process to take over the project yourself to make it properly maintained, or just to get it flagged "Unsupported". The latter status signifies that the project is "put up for adoption".

The Views project is my no means abandoned, but its team is very busy with the D8 port (Views is in core for D8) - so the D7 version could probably use some extra love.

---
Tags: 7, views, community-official-site, version-control
---


# Question
Title: use drupal's hashing in an external php fil
we are making a few web services for a Drupal 7 based websites. in that webservice, one task is to sign up new users on that website.

the only main issue at the moment for this task is to access the drupal hash function in a php code file that is not inside the drupal's installation directory.

any guidance on how to achieve this will be highly appreciated.

# Answer
> 0 votes
What you'll need is Drupal's password.inc file, located at: /includes/password.inc

Just copy this file to your project and include it in your custom php file. This way you can use the user\_check\_password() function (and many others).

here is a good example of something like you are trying to do in Laravel 4. http://www.goodbytes.be/blog/article/create-a-custom-drupal-7-authentication-driver-provider-in-laravel-4

---
Tags: 7
---


title: how to create regions on zen

text:
# Question
Title: how to create regions on zen
I would create regions on my zen theme, reflecting the narrow columns side by side.

I want a layout that does not provide the content by default, but it plans to create 3 sidebar facing the same width.How can I do?

EDIT

Also, I want the page layout different from the initial layout of other pages, so I can have different layout templates with different regions?

# Answer
In the file your\_theme.info you should add

```
regions[new_region] = New Region

```

regions\[new\_region\] this is the machine name so the variable will be $new\_region

Then on page.tpl.php you should add the html and the php like

```
<?php
if ($new_region) :?>
<div id="new-region">
<?php print $new_region; ?>
</div>
<?php endif; ?>

```

Remember to flush the cache and do the performance after you modify page.tpl.php
> 3 votes

# Answer
I just created a region on my Zen 7.x-5.5 subtheme like this:

1. Added: `regions[new_region] = New Region` to my\_theme.info
2. Added (*differs slightly from Tyler Durden's code which haven't worked for me*):

`<?php if ($page['new_region']) :?>
 <div id="new_region">
 <?php print render($page['new_region']); ?>
 </div>
 <?php endif; ?>`

to page.tpl.php.

3. Cleared the cashe.
> 0 votes

---
Tags: theming, 7
---


title: Search API ItemType missing Node

text:
# Question
Title: Search API ItemType missing Node
I am using Search API and search views to add facet blocks into my views page. It works perfect on my test site with only search/facet/views related modules.

But on my working site, when I add Search Index, the ItemType is missing "Node" selection, instead, it is showing "Content". I have updated all modules, but can't figure out why "Node" option is missing.

Anyone has ideas on this?

# Answer
> 0 votes
You do not need the "**Node**" Item type. Using the "**Content**" is going to index all your nodes.

---
Tags: views, search
---


title: Webform for each item in a view

text:
# Question
Title: Webform for each item in a view
I have a view of events and I want each event to have a "Register" button that brings up a webform form for the event. Obviously the filled out form should be saved so that I can tell who signed up for which event. I'm pretty new to Drupal so I'm not sure what the best approach is to associate each event with a webform.

# Answer
I think first you have to attach the webform to the content type(under webform settings) and then you can use this module https://www.drupal.org/project/webform\_default\_fields to add fields to the web form. cheers
> 0 votes

---
Tags: views, webforms
---


# Question
Title: Is the views module a viable options for creating reports with calculated totals?
I have an application built in Drupal 7 that records properties as nodes and relates property nodes to charge nodes and payment nodes.

I would like to add the ability to view a report by selecting a property and specifying two dates, a start date and an end date for the report, that shows a total of payments, a total of charges and then a balance total for a particular property.

However, the charges content type is only used to record additional charges to a property. There is a monthly service charge which is stored as an amount in a field of the property node. So when generating the report, I simply add one service charge payment for each month the report spans.

A summary of the report:

Select a property and give a date range. Produce a list of charges by :

1. Adding one service charge for each month between the two dates. (Note: The service charge amount is given in a field of the property node)
2. Adding amount from all charge nodes related to this property.
3. Give a total field for all the charges.
4. Show all payments from payment nodes related to this property.
5. Total the payments.
6. Give a balance total(charge total - payment total)

What I can't figure out is if views can build the report I need.

Can this be done by adding calculated fields to views, in particular the service charge payments, or do I have to do this in a template file (views-view--foobar--page.tpl.php for example)?

I know how to get all payments and charges related to a property into a view, but I am not sure where to go from there. Maybe this comes down to personal preference, but this is my first venture into views and I would appreciate some advice on where I should be concentrating my efforts!

# Answer
> 5 votes
Another Module you can consider is the views summarize

> Enables an extra display style which displays summaries of a column on the last row.

You can also use the views calc mentioned by @Felix together with the views aggregator module

# Answer
> 4 votes
Would this be a suitable case for using the Views Calc module?

Example image from module page:

# Answer
> 2 votes
It seems that views is not a good way to go when trying to build reports that require more than one query of the database. Problems I found were:

-- 1) I could not bring in all payment nodes to the view using a property node id and then call in all charge nodes for the same property. The query returned the same information into the view multiple times, once for each payment and once for each charge. I wanted separate tables and then I wanted to make total fields from the data in each table. It seems a solution to this is to use hook\_views\_pre\_execute() to edit the query to create a union query as described here but this was honestly mostly over my head!

-- 2) I could not calculate fields base on a value from a field in the property node and add them to the view (the service charge I talk about in the question).

The help offered in the previous two answers (if ordered by oldest date) solved the problem of creating a sum of a column in a views table, but didn't allow me to add a computed field of my own based on data from the view. For example, take two summed fields, subtract one from the other and put the result into a custom field. Views' custom field would be the way to do this as it allows you to use php snippets to build the field value, although again I am not sure it would allow you access to other custom fields in the view (just the view results).

Furthermore, I would then have to format the results by a call to some template hook function (sorry, I haven't figure out which one yet!).

So instead my solution was to use `hook_menu()` to add a path to create my own report

```
  $items['property_account_summary'] = array(
    'title' => 'Property account summary',
    'page callback' => 'MYmodule_property_account_summary_view',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('List Charge by Prop'),

```

and in `MYmodule_property_account_summary_view` it was pretty straight forward to construct the two queries I needed to collect the payment and charge nodes I needed. For example, for payments (where `$prop_nid` contains the node id of the property node I am working from:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'payment');
  $query->fieldCondition('field_payment_property', 'target_id', $prop_nid, '=');
  $result = $query->execute();
  $node_list = $result['node'];

```

and for charges:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'charge');
  $query->fieldCondition('field_charge_property_id', 'target_id', $prop_nid, '=');
  $result = $query->execute();
  $node_list = $result['node'];

```

and from there build the html and add the totals.

Now I just need to format the values and add links to the term values in the Type column.

It just seems like a lot less work than trying to force views into doing what I needed. I must reiterate that this is my first attempt at using views (other than the straight forward grab and show data) and maybe I missed something amongst the views hooks that would have made my life a lot easier. But for now, I will use a solution within my module.

# Answer
> 1 votes
Another module to consider for addressing these requirements is forena. Here is a quote from one of its community docu pages, i.e. Reasons for considering Forena:

> "Why not use views instead of forena?" ... The answer is generally something along the lines of "Most forena users love views, views is great! If you want to report against external data though, or you want to do **aggregation or analytics**, Forena is much more suited to address these requirements."

# Answer
> 1 votes
About Views Calc, mentioned in a prior answer: because of the "entity reference" comment in that prior answer, I assume this question is about D7 (consider refining your question to clarify that).

For anybody still in D6 (there are over +8K sites of them these days while for D7 there are only about 6K): be aware that the D6 version **WAS** unsupported until just a few days ago. Refer to issue 2198015 for more details on that, which also includes some details about renewed D6 support that happened recently.

---
Tags: views, entities
---


title: Removing Baground Link From Slideshow

text:
# Question
Title: Removing Baground Link From Slideshow
Hello i Am Using Drupal 7 and created a slideshow using views and views slideshow so in slideshow when a user is clicking the image url is opening you can also check my slideshow at Windowhelpdesk.com When Anyone Clicks on image a url is opening i want to remove that url plz anyone help me to do this

# Answer
> 0 votes
When you add the image field to views, make sure to set it to 'Link image to: Nothing'

---
Tags: views
---


# Question
Title: What are best practices for supporting and upgrading a list of contributed and custom Drupal module?
My organization has made the decision to build the next version of our website on Drupal 7 with the assistance of a consultant. The consultant will be responsible for the initial build and supporting the modules required by their functionality.

We will be responsible for supporting and upgrading the contributed and custom modules we install.

We anticipate the module list will be fairly long and management of module responsibilities will become an issue. We’re trying to come up with an easy way to track the modules installed on the site and whether they are the responsibility of the consultant or us. In a perfect world we would also be able to add notes as to why a particular module is needed.

Anyone know of anything already out there that would allow us to do this? We've looked but came up empty.

# Answer
Using an Install Profile can really help with these situations. Have the consultant create a profile and manage the modules they are responsible for in profiles/\[PROFILE NAME\]/modules. You will be responsible for everything that is in sites/all.

You can use https://www.drupal.org/project/profiler\_builder to easily generate an install profile from an existing site. https://www.drupal.org/project/profile\_switcher can be used to convert a site started with a standard install to use a profile.

https://www.drupal.org/project/profile\_status\_check is also useful to visually see which modules are being loaded from profiles/\[PROFILE NAME\]/modules vs. sites all as well as break out custom modules (regardless of location) vs. contrib.

Install profiles are as easy as developing a custom module. Most people are only familiar with the Install Profiles that are included in Popular Drupal Distributions like OpenAtrium and Acquia Commons. Distributions are more difficult to manage. They require drush make and/or .make files to manage contrib modules as well as 3rd party libraries.

While going to a full blown Distribution makes sense in some use cases, just using an Install Profile could be an elegant solution to defining who is responsible for different modules in your use case.
> 2 votes

---
Tags: 7, configuration
---


title: Unix time stamp to date

text:
# Question
Title: Unix time stamp to date
I'm displaying a custom table in a view with Data & Schema module.
One of my field in that table is created\_date, int of unix timestamp.
The view's page shown as table, how can I display it in a readble format?

# Answer
> 4 votes
You need to describe the table for views to know which handler to use. For that you have to implement hook\_views\_data\_alter. It looks complicated at first, but its definitely worth it :).

EDIT : Data & Schema should allow you to set the handler, somewhere in the properties of the table. I haven't used it for a while but am quite sure its there :).

# Answer
> 2 votes
Normally you define the handler type in `hook_views_data`

The Data module presumably allows something similar

e.g:

```
  // Expose the created and changed timestamps.
  $data['my_table']['created'] = array(
    'title' => t('Created date'),
    'help' => t('The date the record was created.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

```

Note the "\_date" type handlers there. That's all Views needs.

# Answer
> 1 votes
You can add your own custom date in the Date Format Settings:

1. Navigate to /admin/config/regional/date-time.
2. Click on "Formats" tab.
3. Click "Add Format".
4. Add a single "U" character to the text field. Using PHP's Date syntax this is Unix timestamp.
5. Save, and go back to Types.
6. Add Date Type.
7. Call it whatever you want. I recommend "Unix Time", attach your format to it. (Will display something like "1427999400".
8. Save and go back to your View. Format your date as "Unix Timestamp" wherever you need to, without mucking with nasty template files or hacking around to make simple changes.

# Answer
> 0 votes
Install views\_php module module,
add your field and exclude form display,
add another field ,global php field in output write someting like below

```
<?php   print format_date($rown->timestamp); ?>

```

for more details read format\_date api

# Answer
> 0 votes
The simplest way to achieve this is by formatting the date in a views field template. The ideal way to do it is as @mojzis mentions.

To do it in a views field template:

1. Include the field in the view as normal.
2. In the view go to Advanced \> Theme: Information and find the field you need, copy the last template suggestion, something like views-view-field-date--view-name--view-display-id--view-node.tpl.php
3. Copy the file from modules/views/theme/views-view-field.tpl.php to your theme directory and rename it to the name from step 2.
4. Edit this file to be using the date format you require.

I believe that should do it, the only problem might be that $output isn't the raw timestamp, in that case you should be able to manipulate it before outputting.

I know it's not 'pure' to do this at the theme level, but it's arguably related to content display rather than functionality.

---
Tags: views
---


title: Parameter page=0 gives problem in rules

text:
# Question
Title: Parameter page=0 gives problem in rules
I have a rule which is activated with the following url

redirect/startcoursewithpage?course=502&page=1&module=471

The condition of the rule is: \- Check if URL argument exist for course \- Check if URL argument exist for page \- Check if URL argument exist for module.

The parameter values of course and module will never be 0. The page can be of a value of zero.

If the parameter page=0 is given in the url the condition is not true and the redirect is not done. If I remove the condition Check if URL argument exist for page it is working.

The value zero is directly from the database from another view. I think I should uuencode this zero value but I do’n know how. Other suggestions?

# Answer
> 1 votes
Having a look through the code of the module, the function that checks if the url parameter exists is this:

```
/**
 * Rules condition callback.
 *
 * Checks if the specified URL argument is set.
 */
function rules_url_argument_argument_exists($argument) {
  return !empty($_GET[$argument]);
}

```

This will return false if the argument is 0.

I think it should really be this:

```
/**
 * Rules condition callback.
 *
 * Checks if the specified URL argument is set.
 */
function rules_url_argument_argument_exists($argument) {
  return isset($_GET[$argument]);
}

```

Might be a good idea to submit an issue (and maybe a patch) in the modules issue queue.
**I'm not exactly sure why the function gets the argument argument and doesn't use it**
I have never used this module BTW.

**EDIT:**
There is also `if (!empty($_GET[$argument_name])) {` on line 71 of the module file that might need changing to `isset`.

---
Tags: rules
---


# Question
Title: Is there a drupal hook that I can use to redirect a user to an interstitial page for the first page view? If not then how can I accomplish this?
I am currently in the process of developing a custom module that will redirect a user on entry to an interstitial landing page. This page will closely replicate how forbes.com functions. The landing page itself is a page template within the custom module that displays a view, an ad, and links back to the originally requested page. All of the pieces are in place and function as intended except for the hook when caching is enabled. After researching hook\_boot, hook\_init, and hook\_page\_alter, I have found that none of these are working when caching is turned on or in the case of hook\_boot because drupal functions were not loaded when the hook was called. I feel hook\_boot is the closest solution at this point but after reading the comments in the api it was said that you shouldn't invoke any drupal modules inside of that hook. Is there a way I can detect if the user is anon without user\_is\_anonymous()? Should I write this hook without any drupal functions? Should I bootstrap drupal in hook\_boot similar to how its done in the core module file statistics/staticstics.php?

Here is my code for hook\_boot:

```
function my_module_boot() {
  // If anon proceed
  if(user_is_anonymous()){
    if(isset($_COOKIE['welcome_page'])){
      // do nothing
    } else {
      $cookie = filter_xss($_COOKIE['welcome_page']);
      // If user saw welcome page and has cookie- skip redirect
      if($cookie != 1) {
        setcookie('welcome_page', 1, time()+86400);
        $destination = drupal_get_destination();
        drupal_goto('welcome', array('query'=>$destination), $http_response_header = 301);
      }
    }
  }
}

```

My goal is to keep all of the code contained inside of the module. I'd rather not use any other contrib module at this point because my module is close to completion. This redirect should only get triggered if the user does not have the cookie and is anon. Finally I do not want the site to appear before the landing page.

Thanks for any help.

**Solution:**

```
function my_module_boot() {

  if(isset($_COOKIE['welcome_page']) || isset($_COOKIE['welcome_page_admin'])) {
    // do nothing
  } else {
    $cookie = filter_var($_COOKIE['welcome_page'], FILTER_SANITIZE_STRING);
    // If user saw welcome page and has cookie- skip redirect
    if($cookie != 1) {
      $destination = '/';
      if($_GET['q']) {
        // Microtime for IE9 to properly redirect
        $destination = $_GET['q'] . '?a=' . microtime(true);
      }
      // Redirect and set cookie
      setcookie('welcome_page', 1, time()+86400);
      header("HTTP/1.1 301 Moved Permanently");
      header("Location: /welcome?destination=" . $destination);
      exit();
    }
  }

}

function my_module_user_login(&$edit, $account) {

  // Expires in one year for authenticated
  setcookie('welcome_page_admin', 1, time()+31556926);

}

```

# Answer
> 0 votes
Your suspicions are correct. If you want to do this server side on a cached page, you'll need to use `hook_boot()` and you won't be able call most Drupal functions because Drupal hasn't been bootstrapped at the stage that `hook_boot()` runs.

It seems to me that this is much better suited to client side. I would move this to a small js file (put it in the head if you're worried about the the redirect happening too late).

---
Tags: 7, redirection, hooks
---


# Question
Title: Static vs. Dynamic Queries in Drupal 7 and the Right Syntax to Use
Does anyone know of a good tutorial that explains, not with just one example of an easy query, how to create complex select queries in Drupal 7 that uses the preferred method of query writing?

I've written some complex queries in my custom module that use pretty elaborate and long, basic query syntax (a select clause, order by, where, etc.). I'd like to write them in the preferred format for Drupal 7 that I BELIEVE is supposed to look something like this:

https://www.drupal.org/dynamic-queries

I don't find that to be a very useful primer however. I want some actual guidelines for putting together complex statements with all the various options (if something like this exists).

And is it always better to write the queries like this?

I'd like to add a pager and this seems to be the only way to that.

I hope this question isn't too ambiguous. I'm really just looking for a tutorial on constructing these types of queries. Thanks!

# Answer
> 2 votes
If you're creating a query that will need to be modified by a 3rd party or if your creating drupal.org project code then use things like db\_select().

For all other use cases I prefer db\_query() as the mental overhead is a lot lower.

---
Tags: 7, database
---


# Question
Title: How to display search block in a modal dialog
What I would like to accomplish is to display the search block in a modal dialog when the user clicks on a search button that I have created. I have created a search button block (basically an image with a link) and now I would like to point to the search block and have it appear in a modal dialog. I just don't know to go from here, or if it is even possible to go this route. Can someone provide some pointers on what I need to do?

# Answer
You can use Lightbox or Colorbox (there are modules for both).

Each has the ability to display inline content in a modal.

All you would need to do is add your search block to the page and hide it with CSS, then adjust your search button link to trigger the lightbox/colorbox.

If using colorbox, you would do something like the following:

> Load content in a Colorbox
>
> Check the "Enable Colorbox load" option in Colorbox settings.
>
> This enables custom links that can open content in a Colorbox. Add the class "colorbox-load" to the link and build the url like this "\[path\]?width=500&height=500&iframe=true" or "\[path\]?width=500&height=500" if you don't want an iframe.
>
> If you want to pass the width and height of the Colorbox as a percentage (useful for responsive designs), you can format the link like this "\[path\]?width=90%25&height=90%25&iframe=true" or "\[path\]?width=90%25&height=90%25", where the "%25" is the HTML entity for "%".
>
> Other modules may activate this for easy Colorbox integration.
> 0 votes

---
Tags: 7, search, javascript
---