# Question
Title: What is the best way to minify drupal's aggregated javascript (automatically)?
Have just run Google pagespeed over my newly created drupal 6 site, and it reports:

```
Minifying the following JavaScript resources could reduce their size by 15.6KiB (12% reduction).

    Minifying http://[sites]/sites/default/files/js/js_9f19b87ffb72ca233ea7e45dda2f20f9.js could save 15.3KiB (18% reduction). See optimized version or Save as.

```

The above file was generated through drupal's default JavaScript aggregation method, but apparently it could be 18% smaller (which is a big deal for this site). What approach is considered the best when it comes to minifying JavaScript on a drupal site without breaking any existing code?

# Answer
You could use the Javascript Aggregator module for that or install PageSpeed (the Apache module, not the Firebug extension) if you use Apache and can install extensions (e.g. not a shared webhost), combined with Drupal's own aggregation, with the added benefit that PageSpeed could also minify CSS.
> 4 votes

# Answer
I created a new module to tackle a lot of the aggregation issue & I hope to get a large chunk of it into D8; and yes it's a D6 module: http://drupal.org/project/advagg. Uses the jsmin+ lib for compression of JS and the CSSTidy lib for CSS compression. Main advantage of this is the css/js aggregate file doesn't change names unless it needs to; these files also have a 1 year cache lifetime & has imagecache generation so 404s to your CSS file should be a thing of the past.

Update: AdvAgg 7.x is being developed and comes with minification of JS as an optional sub module. Other D7 options:
http://drupal.org/project/speedy
http://drupal.org/project/uglifyjs
> 6 votes

# Answer
You can use Minify module to do the same. Minify module minify the JavaScript using Google compiler. It also works with "Aggregate JavaScript files" so you can also get advantage of combining multiple JavaScript files which is default option in Drupal 7.

Minify module also minify HTML.
> 2 votes

---
Tags: javascript, performance
---


title: How to add reviews to the book

text:
# Question
Title: How to add reviews to the book
I've two content-types "Book" & "Review". I want users of role `reviewers` to add reviews to any book they desire.

**How I did it?:**

I've added entity-reference to Book from Review with (auto-complete) widget. This just allows reviewers to add review node and select book from auto-complete. Who does that way? I'm not satisfied with it.

**How I want it:**

I've a page for every book `/book-details/title-of-the-book`, where I want to provide a link/button which says `Add Review` and then it should show them the fields of Review content-type and reviewer fills it and submits. His review is submitted. and the same page shows list of all reviews for that book.

How to achieve this in drupal-7?

# Answer
> 0 votes
Add review content type form while viewing book content type is viewed by using hook\_nodeapi().

1. Create one field on review content type(node reference of book node).
2. Add that node\_form in book content type view with $form\_state of the book node id.
3. Create a view for review list with a filter of book content type and use this block under book content type view.

# Answer
> 0 votes
1. Create an entity reference field called **Book** (field\_book) on the content type **Review**
2. Download and enable Advanced Form Edit
3. Create a block for your Add review form at **admin/settings/advanced-form-blocks** (type of the block: **add**, content type: **Review**
4. Now add this block to your region at admin/structure/block. Set it to appear under the content region and make. In the visibility settings set it to only be visible on the book content type
5. Create a custom module enable it and paste in the following code in the mymodule.module file:

-

```
  function MYMODULE_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'review_node_form') {
      if (arg(0) == 'node') {
        $nid = arg(1);
        $form['field_bookie'][LANGUAGE_NONE]['#default_value'][$nid] = $nid;
        $form['ajax-submit']['#ajax']['callback'] = 'MYMODULE_create_callback';
      }
    }
}

function MYMODULE_create_callback($form, &$form_state) {
  return $form;
}

```

Finally create a block view with a filter on content type review and add a contextual filter for Content: Book (Select "Provide default value" and "node ID from URL")

---
Tags: 7, views, nodes
---


title: Create a form without creating a page

text:
# Question
Title: Create a form without creating a page
It seems simple enough to create a form in Drupal 7 with the Form API, however, everything I find shows that you have to use hook\_menu() to add a page and then generate the form that way.

I would like to create a standalone form, then just display the form using drupal\_get\_form() and drupal\_render() to render the form.

How do I create a custom form without creating it's own page?

# Answer
> 5 votes
It's very simple...add a function to your module:

```
function MYMODULE_some_form($form, &$form_state) {
  // Build and return your form.
}

```

Call `drupal_get_form()` from whatever context makes sense to your use case, and render the result:

```
$form = drupal_get_form('MYMODULE_some_form');
$rendered_form = drupal_render($form);

```

Then you can use `$rendered_form` as the output wherever it makes sense to do so (usually a template file).

---
Tags: 7, forms
---


# Question
Title: How do I re-attach AJAX behaviours to a managed_file field?
I currently have a form which is generated by the FAPI via an jQuery AJAX call, and then is inserted into the DOM.

This works fine, but the problem is that managed\_file field within the newly generated form have lost all their AJAX behaviours. I've tried a couple of things to try get Drupal to reattach the behaviours after the form is generated but I'm having no luck.

Here's my code for retrieving and inserting the new form into the DOM:

```
$.ajax({
type: 'POST',
url: '/example-get-form',
dataType: 'json',
data: 'get=1',
success: function(response){

  //insert new form into DOM
  var newForm = response.data.form;
  $('.profile-form.edit').append(newForm);
  Drupal.attachBehaviors();
}
});

```

As you can see from the frontend code, we retrieve the rendered form HTML via AJAX and then insert it into our container div with the selector ".profile-form.edit". The form is rendered and inserted into the DOM correctly, but the problem is that the dyanmic form's managed\_file field can either be empty or contain an image, so both the "Upload" and "Remove" buttons needs to have their AJAX behaviours reattached.

Here's the code for generating the form via the callback URL called from my jQuery script:

```
//generate form and send via JSON
$response['data']['form'] = drupal_get_form('mymodule_example_form');
$response['data']['form'] = render($response['data']['form']);

return drupal_json_output($response);
drupal_exit();

```

Any help to put me on the right track would be greatly appreciated!

# Answer
> 2 votes
The main problem is that you're not loading the form in Drupal way in the AJAX requests. When you use the normal jQuery ajax to load the form, then the necessary actions(Generating new scripts and re-attaching the behaviors) won't happen.

So you should follow the below process to achieve it.

* Create a page with ajax Link/button - clicking on it should load the form(This may change based on your need)
* Create form generation callback
* Create a ajax callback which will returns the form

Below is the complete example module which loads the form with the managed file field using ajax.

```
<?php

/**
 * @file
 * Provides File module pages for testing purposes.
 */

/**
 * Implements hook_menu().
 */
function test_menu() {
  $items = array();

  $items['file/test'] = array(
    'title' => 'Managed file test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access content'),
  );
  $items['ajax/test'] = array(
    'title' => 'Managed file test',
    'page callback' => 'file_ajax_page',
    'access arguments' => array('access content'),
  );
  $items['ajax/form'] = array(
    'title' => 'Managed file test',
    'page callback' => 'file_ajax_form',
    'access arguments' => array('access content'),
  );

  return $items;
}

/**
 * Generates the Test page.
 */
function file_ajax_page() {
    // Make sure Drupal Ajax framework javascript is around.
  drupal_add_library('system', 'drupal.ajax');
  $output = '';
  // Generate a Ajax Link to load the form.
  $output .= l(t('Delete'), 'ajax/form', array('attributes' => array('class' => 'use-ajax')));
  // Specify the container for the form.
  $output .= '<div class="form-container"></div>';
    return $output;
}

/**
 * Returns the processed file form.
 */
function file_ajax_form() {
    $commands = array();

    // Treat them in Drupal way to load the form in AJAX, so that all the necessary scripts will be loaded.
  $commands[] = ajax_command_html('.form-container', drupal_render(drupal_get_form('test_form')));
  ajax_deliver( array(
    '#type' => 'ajax',
    '#commands' => $commands,
  ));
}

/**
 * Form constructor for testing a 'managed_file' element.
 *
 * @see file_module_test_form_submit()
 * @ingroup forms
 */
function test_form($form, &$form_state, $tree = TRUE, $extended = FALSE, $default_fid = NULL) {
  $form['#tree'] = (bool) $tree;

  $form['nested']['file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Managed file'),
    '#upload_location' => 'public://test',
    '#progress_message' => t('Please wait...'),
    '#extended' => (bool) $extended,
    '#size' => 13,
  );
  if ($default_fid) {
    $form['nested']['file']['#default_value'] = $extended ? array('fid' => $default_fid) : $default_fid;
  }

  $form['textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Type a value and ensure it stays'),
  );

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

  return $form;
}

/**
 * Form submission handler for file_module_test_form().
 */
function test_form_submit($form, &$form_state) {
  if ($form['#tree']) {
    $fid = $form['nested']['file']['#extended'] ? $form_state['values']['nested']['file']['fid'] : $form_state['values']['nested']['file'];
  }
  else {
    $fid = $form['nested']['file']['#extended'] ? $form_state['values']['file']['fid'] : $form_state['values']['file'];
  }
  drupal_set_message(t('The file id is %fid.', array('%fid' => $fid)));
}

```

This way Drupal will do all the works for you if you specify what/how do you want:)

I took File Test module in the core as the base for this example.

---
Tags: forms, ajax, javascript
---


# Question
Title: Get a list of all the modules in code base
This is more of a developer question.

I need a list of all the modules that are present in my code base. I am not looking for enabled or install modules. I am just looking for all the modules(code) present in my code base.

# Answer
> 0 votes
Use the following command in the terminal at the root of your site.

```
grep -hr '^name =.*' . | sort

```

This is the non drush way and also helps me identify the duplicate code for a single module if any.

---
Tags: 7
---


title: Include date module in custom module

text:
# Question
Title: Include date module in custom module
I have а custom module that will show some reports. It will have two textfields, so when a user clicks one of the fields "starting date" and "end date" a calendar will popup and will able to select the dates. After selecting the dates, it will show the table with the results.

I've been using "Date" module with content type/fields, but I've never done in a custom module.

If these are the two fields:

```
<?php

$content['starting_date'] = array(
     '#type' => 'textfield',
     '#title' => 'Starting date',
);

$content['end_date'] = array(
     '#type' => 'textfield',
     '#title' => 'End date',
);

?>

```

How can I show the popup calendar when a user clicks on some of the textfields and show the results?

I'm using Drupal 7.

EDIT: I'm marking Clive's answer, but the date\_popup works only on forms, not custom fields.

# Answer
> 3 votes
Assuming you have the date popup module installed and enabled:

```
$form['starting_date'] = array(
  '#type' => 'date_popup',
  '#title' => 'Starting date',
  '#date_format' => 'd/m/Y',
  '#default_value' => date('Y-m-d'),
);

```

---
Tags: datetime
---


title: Openlayers Feature Popups

text:
# Question
Title: Openlayers Feature Popups
I am trying to use the Openlayers Feature Popups module for my map.

Just ran into some issues which I am yet to find a solution. Under the behaviors tab of the map I have tried to adjust the settings so that the popup can have the name of the node on the popup all I get is a blank popup on click and .undefined on hover.

How do I get the node title and any other field for that matter to show up on the popup just for a starting point at least.

# Answer
> 2 votes
Did you create a Data Overlay with the fields you need in Views? In Views, when you create a Data Overlay that you decide to later use in your map, you define the fields you want to pull from the node (Title, location, etc.) and then assign them inside the Data Overlay dialogue.

---
Tags: 7, javascript
---


title: Openlayers is not showing markers

text:
# Question
Title: Openlayers is not showing markers
I'm using openlayers module with geofield. The markers are showing fine on the views preview and all looks good. but when viewing the display page through it's path the markers don't show. Any ideas ?

Thanks

# Answer
> 0 votes
I can't comment, so I'll add my suggeston here. I had a similar problem. The thing is - if your field is a polygon, polygons won't appear as markers on the map. To solve this, in Views, under the settings for your location field in the data overlay, instead of full geometry, choose "use centroid".

---
Tags: views, javascript, location
---


# Question
Title: How to auto-insert a sequence number in a Webform?
Is there a way to add a Webform field that serves a unique sequence number? Hopefully the number can be sequentially counted for each Webform type.

# Answer
There is a module for this: Webform Serial number: https://drupal.org/project/webform\_serial

> This module provides an auto-incrementing number field for webforms.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: site slogan in h6 following h2 site name not matching WCAG 2.0 requirements
Configuration : Drupal 7.26 / Omega 3 / Delta module
An accessibility check made with achecker.ca on a website gives me one result :

> Success Criteria 2.4.6 Headings and Labels (AA)
> Check 38: Header nesting - header following h2 is incorrect. Repair: Modify the header levels so only an h3 or any header less than h3 follows h2. Error Line 112, Column 7:

`<h2 class="site-name"><a href="/fr" title="website homepage"><span>for ...`

As I understand, it comes from the file : "sites/all/modules/delta/delta\_blocks/includes/delta\_blocks.theme.inc"
The delta for the site slogan is defined as a h6, which doesn't match with WCAG 2.0 (AA) requirement :

> The header following an h2 is h1, h2 or h3

(http://achecker.ca/checker/suggestion.php?id=38).

So I might need to use a hook to change it, but I am such a newbie with hooks. I found this : https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook\_block\_info/7 but it seems to hook the core module. Not very sure I want to do it.

Any help?

# Answer
> 3 votes
Hooks won't help you with this - the markup for the slogan is in the region--branding.tpl.php template file:

```
<h6 class="site-slogan<?php print $class; ?>"><?php print $site_slogan; ?></h6>

```

To fix, you can just create your own region--branding.tpl.php file in your sub-theme, and alter the markup to your needs.

---
Tags: theming
---


title: Multiple slideshows on a page

text:
# Question
Title: Multiple slideshows on a page
On the home page of a site I want to list each node as an individual slideshow. Each node shown will be of the same content type. I am using views slideshow and panels if it helps.

# Answer
Yes it is possible to achieve this, You have to use views along with Scrollable Content

It provides a scrolling functionality for your content. Scrollable Content will give you a nice content slider preview of your site's nodes, and provides some display options.

> The basic use is via blocks page, you'll find a block called "Scrollable Content" and if you want more control & you know how to use Views, you should use the Views style for Scrollable Content.

or you can check Scrollable Views , I'm using this in my website, but it no longer supported.
> 1 votes

# Answer
This has been achieved using the Fields Slideshow module.

https://drupal.org/project/field\_slideshow

In views you can then select the image format for the field as slideshow, similar to colorbox.

This seems to be working fine for me but I am open to other suggestions
> 1 votes

# Answer
I recently had this problem while having multiple views slideshow block from same view on same page the following link may help

http://crudpixel.com/content/drupal-multiple-slideshow-blocks-same-view-same-page
> 1 votes

# Answer
first of all you need to create extra field and add some node images to that field and after that you can call a function from home page and in that function you have to write

```
$query = db_select('node', 'n');
  $query->join('field_data_field_slider_actve', 'sa', 'sa.entity_id = n.nid');
  $query->fields('n', array('nid'));
  $query->range(0, 5);
  $query->condition('n.type', 'home_slider');

  $results = $query->execute()->fetchAll();

```
> 0 votes

---
Tags: javascript, views
---


title: Organic groups and "Create content"

text:
# Question
Title: Organic groups and "Create content"
I want to replicate the Drupal "Create Poll,Event" links etc of the Drupal groups. How can I accomplish that with Organic groups? Thanks

# Answer
> -1 votes
You can do this using a custom block with format as php option. You need to use l function to generate links.

```
$links = "";
$linkList .= l(t('Create Poll'), 'node/add/poll', array('html' => TRUE, 'query' => array('gid[]' => arg(1))));
$linkList .= l(t('Create Event'), 'node/add/event', array('html' => TRUE, 'query' => array('gid[]' => arg(1))));
print $links;

```

# Answer
> 0 votes
In case you use panels, Organic Groups module comes with a content create panel pane that allows to select the content types to include in such a links list.

---
Tags: organic-groups
---


# Question
Title: Is there a way to automatically have a copyright attribute when content is submitted?
I have a website where all users submit content and that content is often also plagiarism, which I don't want.

Can this be done with rules? How would the copyright attribute fetching work?

What I want to accomplish and what I tried without luck in short:

After content is submitted, cross check websites database and look if there's some copyright attribution to be made, if positive add the copyright attribute to the end of the text.

Am I doing it right?

# Answer
> 1 votes
The only ready-made solution I know of is Plagiarism Checker - Authentication Framework.

> The module is a framework which supports various search APIs (plugins) to scour the net looking for possible plagiarized content. The framework provides support for 2 different types of APIs - Standard APIs (Google and Yahoo plugins are included here) and Custom APIs (such as the 3rd party paid authentication service from iThenticate (www.ithenticate.com)).

Note that these APIs are either not designed to plagiarism discovery, giving a lot of false positives, or may be paid. Also, low usage count and *Development status: Maintenance fixes only* should make you careful.

---
Tags: rules
---


# Question
Title: How to change the url pattern of user revisions?
How can i change the url pattern of a user revision ? I want to change

```
users/jon-doe/revisions/123/view

```

to

```
users/jon-doe/archive/123/view

```

There is no option in pathauto to influence the url patterns of revisions.

# Answer
> 2 votes
This path is defined by revisions module `hook_menu()`, so if you want to alter it, use `hook_menu_alter()` in your module.

```
function mymodule_menu_alter(&$items) {
  // Copy element to new path:
  $items['users/%/archive/%/view'] = $items['users/%/revisions/%/view'];

  // Optionally remove original - this may break some links!
  unset($items['users/%/revisions/%/view']);
}

```

And of course remember to clear the caches!

---
Tags: users, nodes, path-aliases
---


title: Drupal menu depth limitation

text:
# Question
Title: Drupal menu depth limitation
I am facing a problem that in my drupal web site, I am having menu depth level is more then 15. By default drupal 7 provides depth level is 9. Is it any way to increase it's menu depth level?

In short :- I need to add more then 15 childrens in my single menu item.

Expamle:-

Menu

-1

--2

---3

----4

-----5

------6

-------7

--------8

---------9

===========Drupal doesn't allow to add more childrens =====

# Answer
> 2 votes
Firstly I would suggest having a hard think about whether you actually need a menu that deep and why. Then try to think of an alternative way to structure your data to achieve what you need to do.

The reason is that this is not an easy thing to change (and 15 levels of menu suggests possible information architecture issues).

There is a drupal.org issue https://drupal.org/node/274270 relating to this that has some examples on how you can make the change. The example is for drupal 6 but pretty much the same thing applies to drupal 7.

The problem is that each level has it's own column in the menu links table, so you have to alter the menu links database table to add new columns and then make some changes to drupal core to use these new fields.

As a side note, there is a module called menu depth limit that allows you to set a lower limit but not a higher one.

---
Tags: 7, routes
---


title: Some Database Tables Have dr_ prefix

text:
# Question
Title: Some Database Tables Have dr_ prefix
Hello ive been messing about with drupa for 8 years now and im still YET to get a website to go live :( After about 10 reinstalls of my new website idea i was just about to go live and then i had a wee look in the database and ive noticed a load of tables prefixed dr\_

I know some softulicious installs add this db prefix.

My site works well enough but the tables prefixed as per attached are worry to me. Should they be a worry to me?

Can i fix it easily enough?

Thanks

ps all my other db tables are unprefixed which is the desired effect. All help appreciated as im close to startingmy site again from scratch :(

My electricity is about to get cut off for 12hrs so cant reply till then.

# Answer
> 1 votes
This can sometimes happen if you are using softaculous installer (or similar one-click installer provided by your web host). Perhaps you installed several instances of Drupal using the same database name, and just left the 'dr\_' prefix in place for one by accident.

If I were you, I wouldn't worry too much about it. Having the additional tables there won't cause any problems with your Drupal installation (the one using the non-prefixed tables), and the 'dr\_' prefixed tables won't increase in size as time goes on.

You should be able to safely leave them as they are, or, if you want to, remove them using phpMyAdmin to permanently delete (drop) the tables prefixed with 'dr\_'.

---
Tags: database
---


title: Public:// doesn't work

text:
# Question
Title: Public:// doesn't work
I am trying to code as follows:

> $uri='public://admin/myfile.txt';

but `if (file_exists($uri))` fails

the complete path

> $uri='/var/www/html/www.mydomain.com/sites/default/files/admin/myfile.txt';

works and passes `(file_exists($uri))`

`drupal_realpath('public://')` returns `/var/www/html/www.mydomain.com/sites/default/files`

What am I missing here?

# Answer
> 2 votes
The path 'public://admin/myfile.txt' is not a real path (because of the 'public://'-part, which is a drupal-custom), it's a stream-wrapper-path (see link at end of answer).

> file\_exists() can only process real-paths and registered stream-wrapper-paths

**This means for you: Either your Drupal-installation didn't register it's custom stream-wrapper or your server-isp deactivated the stream-wrappers on your server/account.**

You should check your php-config for Filesystem and Streams Configuration Options: http://www.php.net/manual/en/filesystem.configuration.php

More info on php's stream-wrappers:
http://www.php.net/manual/en/wrappers.php

BTW: Registering of custom stream-wrappers is supported by PHP 4.3.2+

---
Tags: files
---


# Question
Title: How can I stop Google Analytics from tracking a certain user?
I have the Google Analytics module installed. How can I prohibit the code snippet appearing on pages served to a particular user. Say user #15, for example?

# Answer
> 1 votes
I would consider creating a separate user role for that purpose and disabling Google Analytics for that role. The setting can be found at the module config page (/admin/config/system/googleanalytics) under Tracking Scope -\> Roles.

# Answer
> 1 votes
I don't think you need to create a new role just to stop tracking a single user. If you want the user to be able to opt-out from being tracked, go to the Google Analytics module settings page (/admin/config/system/googleanalytics) and under Tracking Scope -\> Users, select:

"Tracking on by default, users with opt-in or out of tracking permission can opt out"

Then you can give user roles you wish (e.g. "Authenticated User") permission to opt-out of Google Analytics tracking ("Opt-in or out of tracking").

The user can then log in to their account and opt out of tracking.

Having said that, if you want to prohibit a certain user from being tracked, or you don't want to give anybody else permission to opt out, then I agree that adding a new user role might be the best way to go for this.

---
Tags: google-analytics
---


# Question
Title: trigger a form submission button using custom cron
It's possible to create a cron that trigger the submission of a form ? To be clearer, when my drupal cron is executed, this form will be submitted automaticlly ?

**EDIT :**

This is an explantion for what reson is the cron :

Im using apachesolr for indexing articles in my website, some times it happen that some editors in the site delete articles, but the problem, these articles still exist in apachesolr... and when solr try to index again, the hole website crashes !!

so that's why I need to find out these deleted articles and delete them from solr indexing also... this module do exactly what I need : apachesolr\_integrity

this module add a new submission button in apachesolr configuration page : `/admin/config/search/apachesolr` to Delete orphaned nodes..

But I don't need every time the site crashes, I click on this form button, maybe the site administrator is not available that time, and the site still breaking :(

I thought about cron to do this this, and also if it can be made with rules, it will be a better solution because with rules I will tell system to directly delete Orphaned nodes when a content has been deleted, and with a cron, the site can still crashed until the next cron execution..

Anyway, the question is how can I add the code made by this module in either a cron or a rule.

Thanks in advance

# Answer
> 1 votes
This seems a little bit odd. Form submission are meant to be dealt with by humans in order to transfer information to a specific service.

So if you want to send any kind of request to a dedicated service, yes, that is possible using drupal\_http\_request.

> This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.

If you want to submit a Drupal form on cron, then you can use drupal\_form\_submit.

> This function allows you to supply values for form elements and submit a form for processing. Compare to drupal\_get\_form(), which also builds and processes a form, but does not allow you to supply values.

If you want to execute any custom logic (which might also be the result of a form submission by humans) then this is also possible using custom code.

For all that, you will need to implement hook\_cron() in a custom module.

If anything else, please elaborate on what it is that you want to achieve.

---
Tags: 7, forms, rules, search, cron
---


# Question
Title: How to preserve discount set with query parameters into cart?
Using Drupal Commerce, I've been experimenting with applying a simple discount to a product using query string parameters. The goal is to allow a user to navigate to a product display page and see a discounted price based on this syntax:

http://example.com/product\_display?code=discount\_code

Where 'discount\_code' represents some kind of discount to apply to the product.

By writing a custom action that's triggered on the event "Calculating the sell price of a product", it's pretty easy to alter the price of a line item with rules with something like:

```
function mymodule_apply_discount_via_url($line_item) {

  if ((isset($_GET['code'])) {

    // code to figure out if code is valid

    // code to figure out type of discount

    // code to alter the unit price and add difference as a component

```

Which works fine - the user will see the discounted price on the product display page. This is nice, because the user has access to all product information along with the discounted price.

However, on "add to cart", the product will appear in the cart at the original price. I assume this is because the pricing rules are run again but without the query parameter.

How can I preserve a discount applied this way through the add to cart step?

# Answer
My current implementation:

1. Custom action triggered on "Calculating the sell price of a product":
    * looks for the query parameter "code" in the url
    * verifies code is valid and active (uses commerce\_coupon)
    * applies it to the line item on product landing page
    * saves code as a session variable
2. Custom action triggered on "After adding a product to the cart"
    * looks for code as a session variable
    * verifies code is valid and active
    * uses 'commerce\_coupon\_redeem\_coupon' to apply to cart order
    * clears the session variable

This seems to work, though it seems a bit rube goldberg. Still looking for a better way to preserve a discount that arrived as a query parameter, and apply it to a cart order, if there is one.
> 0 votes

---
Tags: commerce
---


# Question
Title: Deleting non-active users (e.g., users who didn't log in for 90 days)
We use Drupal as an employee portal; as such, when new starters join the business they create an account.

However, we are trying to figure out a good leaving process; right now I get a list and have to manually delete all the users.

Ideally, we would like something which send an email to a user after 14 days and then again after 30 days informing them that they have not logged in into the system; then, after 60 days, they are automatically deleted.

I am guessing that using Rules is the answer, but I cant find any option to delete users.

# Answer
> 5 votes
Maybe this module can help: inactive user

From the module page:

> After configurable periods of inactivity, one or more of the following actions can be automatically taken:
>
> * send an email to the user
> * send an email to the site administrator(s)
> * block the account (a warning can first be issued)
> * optionally notify user and/or site administrator(s) that account was blocked
> * delete the account (a warning can first be issued)
> * optionally notify user and/or site administrator(s)1 that account was deleted

# Answer
> 2 votes
If the Rules module doesn't have a predefined action that allows deleting a user, then you can choose the action that executes the code necessary to find the users that didn't log in the past 90 days, and deletes them.

You can create a rule that is executed when Cron maintenance tasks are performed (that is one of the events you can select when creating a rule), and add an "Execute custom PHP code" action.

```
$query = db_query_range("SELECT uid FROM {users} WHERE access < %d", time() - 7776000, 0, 20);

while ($uid = db_result($query)) {
  user_delete(array(), $uid);
}

return array();

```

The result would be something similar to the following one:

The `return` statement is probably not necessary, but as I understand, the Rules module is expecting the code returns an array containing something that needs to be saved; the code could return a node that needs to be saved, for example, and which will be saved if the node has been modified.
The 7776000 value I used is the number of seconds in 90 days.

This is the solution I would adopt if you are already using the Rules module. If you are going to install it just to be able to accomplish this task, then it would be better to use a custom module that implements `hook_cron()`, or using a module that already does the task.
Which one to choose depends from what you plan to do with the module you are going to install; if you are using few of the module's features, then a custom module is probably a better solution.

# Answer
> 1 votes
I also use Views Bulk Operations for this. I set up a query that does what I want, and then execute the "delete user" action. Before doing that, I do a "send email" action to tell them why they're being deleted.

# Answer
> 0 votes
Been in search how to complete similar task. Found an answer @Drupal.org - if your Rules don't have 'Delete user' option then you have to install Views Bulk Operations module - it provides such operation (and lots of others :) Of course, it can be done with custom PHP code in different ways, but this solution is useful if your site has disabled PHP input for security reasons (and you don't want to write the action by yourself).

---
Tags: 6, users, rules
---


title: How to open modal form on page load

text:
# Question
Title: How to open modal form on page load
I'm using modal form in drupal7.26 with WEBFORM module and is working fine when I click a link the form opens in new modal.

What I want is to open the same WEBFORM with out clicking any link instead it should be open on page/body load event.

I'm using modal form with CTOOLS and WEBFORM modules.

Any help would be appreciated.

Cheers -Zafar

# Answer
I'm not sure why you would want to automatically load a modal when the page is loaded, IMO that's a bad user experience. But if you must, you can use a bit of jQuery in the theme to make it happen. Maybe something like the following:

```
  /**
   * Open Modal window on page load.
   */
   Drupal.behaviors.openModalOnPageLoad = {
    attach: function(context, settings) {
      // Just create some kind of ID or class for the modal link, add whatever extra
      // classes you need to be more specific if necessary.
      $(".page-node-number #myModalLink").click();
    }
  };

```
> 0 votes

---
Tags: 7, webforms, chaos-tool-suite, javascript
---


# Question
Title: How can I use drupal_get_form() outside a menu?
I am trying to use `drupal_get_form()` outside of a menu, but I haven't found examples of how this could be done.

I pass control from a script using an href HTML tag passing to another script that will then read what has been passed to the new script and build a form based on the action that has been passed in. I am using `drupal_get_form()` just as I would call any PHP function.
I get an error message that says `drupal_get_form()` is an unknown function.

This script is the initial calling script that contains an html href link to the called processing script.

```
function view_payment_methods() {
  try {$result = db_select('tls_connect_cashier_payment_methods', 'q')
    ->fields('q', array('id', 'payment_method', 'payment_desc', 'logically_deleted', 'system_or_user'))
    ->orderBy('payment_desc')
    ->execute();
  } catch(Exception $e) {
    watchdog_exception(
      'view_payment_methods',
      $e,
      'Select from tls_connect_cashier_payment_methods has failed.',
      null,
      'Alert'
    );

    return false;
  }
  $payment_methods = $result->fetchAll(PDO::FETCH_ASSOC);

  $col1_label           = t('Payment Method');
  $col2_label           = t('Payment Description');
  $col3_label           = t('Disabled');
  $col4_label           = t('Created By');
  $col5_label           = t('Action');
  $edit_label           = '(' . t('Edit') . ')';
  $delete_label         = '(' . t('Delete') . ')';

  $markup  = "<h1>" . t('Payment Methods') . "</h1>";
  $markup .= "<table>";
  $line    = "<tr>";
  $line   .= "<td>" . $col1_label . "</td>";
  $line   .= "<td>" . $col2_label . "</td>";
  $line   .= "<td>" . $col3_label . "</td>";
  $line   .= "<td>" . $col4_label . "</td>";
  $line   .= "<td>" . $col5_label . "</td>";
  $line   .= "</tr>";
  $markup .= $line;
  if (isset($payment_methods[0])) {
    foreach ($payment_methods as $entry) {
      $disabled          = '';
      $created_by        = '';
      $id                = $entry['id'];
      $payment_method    = $entry['payment_method'];
      $payment_desc      = $entry['payment_desc'];
      $logically_deleted = $entry['logically_deleted'];
      $system_or_user    = $entry['system_or_user'];
      $line              = "<tr>";
      $line             .= "<td>" . t($payment_method) . "</td>";
      $line             .= "<td>" . t($payment_desc) . "</td>";
      if ($disabled == 0) {
        $disabled      = 'No';
      } else {
        $disabled      = 'Yes';
      }
      $line             .= "<td>" . t($disabled) . "</td>";
      if ($system_or_user == 'S') {
        $created_by    = 'System';
      } else {
        $created_by    = 'User';
      }
      $line             .= "<td>" . t($created_by) . "</td>";
      $line             .= "<td><a href = '/TLSConnect3App/sites/all/modules/custom/TLSConnectPackage/cashier/PaymentMethodEditDelete.php?action=edit&id=" . $id . "'>" . $edit_label . "</a>
                        <a href = '/TLSConnect3App/sites/all/modules/custom/TLSConnectPackage/cashier/PaymentMethodEditDelete.php?action=delete&id=" . $id . "'>" . $delete_label . "</a></td>";
      $markup           .= $line;
    }
  }
  $markup .= "</table>";

  return $markup;
}

```

This script is the called script accessed by way of the html href link for the edit link.

```
if (isset($_GET['action'])) {
  $id = $_GET['id'];
  switch ($_GET['action']) {
    case 'edit':
      $form_id = 'edit_form';
      return drupal_get_form($form_id);
      break;
    case 'delete':
      break;
  }
}

function edit_form($form, &$form_state) {
    global $id;
    die('chuck');
    $form = array();
}

```

# Answer
> 0 votes
As I understand it, you want to link to a page that displays a form and accepts certain parameters that will influence the form.

> 2) I am also getting a message that says drupal\_get\_form is an unknown function.

That is because `drupal_get_form()` is not known when Drupal hasn't been formally loaded (bootstrapped). When you call `PaymentMethodEditDelete.php` directly, then Drupal doesn't know about it, and PHP doesn't know about any Drupal API functions. In order to have all Drupal functionality available, the point of entry must be the index.php in the webroot and not a custom script somewhere.

In order to achieve what I think you want, you need to define a so called `menu callback`. This is simply a url that is associated to a callback function. You can find more on the menu system in the docs to hook\_menu().

In order to use this menu callback with `drupal_get_form` you would define the menu item like this:

```
function mymodulde_menu() {
  $items = array();
  ...
  $items['my/custum/url/to/form'] = array(
    'title' => 'My form title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_custom_form_id'),
  );
  ...
  return $items;
}

```

This is the bare minimum to define a page that will render as a form.

Now in order to handle arguments, you can either pass them in as ordinary `$_GET` parameters that you can access normally inside your form builder function.

Or you alter the newly defined menu so that it will accept additional arguments and passes them into the form builder, as arguments to drupal\_get\_form (see Wildcards in Paths). Also have a look at this question for more information: https://drupal.org/node/2054083.

Some more reading I can recommend:

---
Tags: forms
---


# Question
Title: Making user profiles publicly accessible in Drupal 7
How can I make user profiles publicly available to anonymous users and search engine bots accessing my website?

Details: User profiles are not publicly accessible by default. Without being logged in to Drupal, if you try to access `/user/123` for example, you get the `You are not authorized to access this page` error message. I want to display the user profile details instead.

# Answer
Simply go to `/admin/people/permissions`, scroll to the bottom of the page and turn on all check boxes for the `View user profiles` permission.
> 0 votes

---
Tags: 7, users
---


title: Table too wide for view

text:
# Question
Title: Table too wide for view
I created a view (from Views module) where I display my content in a table.
The table contains about 22 columns:

The table continue to the right of the screen (see screenshot above). How to fix that? (fit it to view boundaries or make the view area wider)

# Answer
I would recommend using the FooTable Views plugin. I've used it before and it's quite helpful when dealing with responsiveness and smaller content areas.
> 2 votes

# Answer
My suggestion would be to check that you have this set in your CSS:

```
table{
    width: 100%;
}

```

If you do, check it is not being overridden. Maybe you could add a bit more context or CSS code to your question so we can understand what's going on a bit better.
> 0 votes

# Answer
I've seen this type of issue in other view instances. For example, lets say you have photos your laying on a sidebar of a width of 250 px. If the image styles you choose are bigger than the set width of 250px, then view will override that 250px setting. Thus the view will bleed over the edge like in your case. So what I recommend is looking/matching the width of the grid your setting the view in and add a horizontal overflow scroll via css :`#block-views-*your_view_name*-block {
 width: 960px;
 overflow-x: scroll;
}`

Also a reminder that if your using responsive design, then you need to use @media queries with the CSS above for **EACH** of your sizes: mobile, 720, 960 etc...
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to create a views listing of all groups including a join link in OG 7.2x
The 7.2x version of OG leverages the Entity Reference module to create the relationship between the group node and entity. There about 8 possible OG Entity Relationships to choose from in views that upon review seem pretty ambiguous. I just need to figure out which one(s) are required to create a join link when listing all of the groups on the site.

# Answer
Add a field to your view of the type Content: Group - set the formatter to OG subscribe link - screenshots in this thread on drupal.org:

http://drupal.org/node/1816096
> 2 votes

# Answer
If you want to use displays you can just create a code field with a link that points to /group/node/$groupID/subscribe/og\_user\_node using code fields. Otherwise you can fields and Content: Group as posted earlier.
> 0 votes

---
Tags: views, organic-groups
---


# Question
Title: Why do many Drupal themes markup images with typeof="foaf:Image" attribute?
Does this attribute simply enhance semantics?

# Answer
> 4 votes
Yes, it’s about semantics of your content. That way, your page/content is part of the Semantic Web.

### **Background**

The `typeof` attribute is defined by RDFa.
RDFa is a syntax to embed RDF in markup languages like HTML.

The value `foaf:Image` (most likely) refers to the Friend of a Friend vocabulary/ontology. The namespace `foaf:` typically stands for the URI of that vocabulary (`http://xmlns.com/foaf/0.1/`), so the value is actually the URI `http://xmlns.com/foaf/0.1/Image`.

`http://xmlns.com/foaf/0.1/Image` is a *class*. It’s (= what it means) documented here: http://xmlns.com/foaf/spec/#term\_Image.

---
Tags: media, theming
---


title: Drupal Isn't Finding My CSS

text:
# Question
Title: Drupal Isn't Finding My CSS
My stylesheet is mentioned in my .info file, but it's not adding it to the page source and using it. The only style I have in *Styles.css* is `body {background:#444}`. I've tried clearing the site's cache as well as my browser's. CSS compression is off. Any ideas?

It's a theme I made from scratch.

info file:

```
name = PBmedia 14
description = The Site Theme
core = 7.x
engine = phptemplate

; Regions
; --------------------------------
regions[header] = Header
regions[content] = Content
regions[footer] = Footer

; Stylesheets
; --------------------------------
stylesheets[all] [] = html5reset-1.6.1.css
stylesheets[all] [] = styles.css

```

html.tpl.php

```
<!DOCTYPE html />

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

page.tpl.php

```
<div id="page-wrapper"><div id="page">

<header id="header">

  <?php if ($main_menu): ?>
  <nav id="navigation">
    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t(''))); ?>
  </nav><!-- #navigation -->
  <?php endif; ?>

  <?php print render($page['header']); ?>
</header> <!-- #header -->

<?php print $messages; ?>

<div id="main-wrapper"><div id="main" class="clearfix">

  <div id="content">
  <div class="section">

    <?php print render($title_prefix); ?>
    <?php if ($title): ?><h1 class="title" id="page-title"><?php print $title; ?></h1><?php endif; ?>
    <?php print render($title_suffix); ?>
    <?php if ($tabs): ?><div class="tabs"><?php print render($tabs); ?></div><?php endif; ?>
    <?php print render($page['help']); ?>
    <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>
    <?php print render($page['content']); ?>
    <?php print $feed_icons; ?>
  </div><!-- /.section -->
  </div> <!-- /#content -->

</div></div> <!-- /#main, /#main-wrapper -->

<footer id="footer">
  <?php print render($page['footer']); ?>
</footer><!-- #footer -->

</div></div> <!-- /#page, /#page-wrapper -->

```

# Answer
> 2 votes
There should not be a space after "\[all\]" ...
Change:
`stylesheets[all] [] = styles.css`
to:
`stylesheets[all][] = styles.css`

---
Tags: theming, .info
---


title: Get or Create a Node in a Custom Module

text:
# Question
Title: Get or Create a Node in a Custom Module
This is my first time doing any custom module work in Drupal and need some advice. I have a django background.

I am accessing data on an external non-Drupal server to display on the Drupal site. I think I want to create a custom field type that holds the unique integer mapped to the data's ID on the external site.

> 1) user visits `/mymodule/1234` where `1234` maps to the external data source (not the drupal node)
> 2) module performs a kind of `get_or_create` and either gets the node that matches the unique ID or creates one
> 3) the user will see get a node returned to them (can handle comments, statistics, etc) that also displays the external data (which I will query via REST)

I'm basically asking for advice if this approach is tenable in Drupal and how to implement the get\_or\_create part of this if it is.

# what I can imagine so far

First, custom module and a url handler:

```
<?php
function mymodule_menu() {
    $items['mymodule'] = array (
        'testing' => 'I am just testing',
        'page callback' => 'mymodule_view',
        'access callback' => TRUE,
        );
    return $items;
}

```

Then a custom view function to do the heavy lifting when user visits `/mymodule/1234`:

```
<?php
function mymodule_view($data_id = 0) {

    // custom REST function to get the data via the $data_id
    $data = get_my_data_cleverly($data_id);

    if (!$data) {
        //return 404
    }

    // not sure about this part
    get_or_create_node($data_id);

    // then return output to theme combining both node and $data
    // this is an oversimplified render array output that doesn't
    // work mostly because I don't understnand how Drupal does this yet
    $output =  array(
        'node' => $node,
        'data' +> $data,

    );
    return $output;

}

```

The result would be a node, with additional non-node information passed to the template.

Thanks

# Answer
Create or use an existing content type for your nodes. Add a field (`field_ext_id`) on the content type to track your external content id. When building your page, use EntityFieldQuery (note that it may have performance implications on very large sites) to look for a node with `field_ext_id = your id`. If no node found, create one:

```
$node = new stdClass;
$node->type = 'your_content_type';
$node->status = 1;
$node->uid = 1;
$node->title = 'my node';
$node->created = REQUEST_TIME;
$node->updated = REQUEST_TIME;

// set your other field values (including field_ext_id), as necessary

node_save($node);

// your new node's id is now available as $node->nid

```

For working with fields, have a look at Rendering Drupal 7 Fields The Right Way and Entity Metadata Wrapper.
> 2 votes

# Answer
I would suggest using the entity method as opposed to the node class method:

```
$node = entity_create('node', array('type' => 'content_type'));
$entity = entity_metadata_wrapper('node',$node);

 //Set properties
 $entity->author = $user->uid; // Author
 $entity->title->set("String");  //Title
 $entity->field_name->set("String"); //Textfield
 $entity->body->set(array('value' => "String or HTML")); //Body
$entity->save();

```

Much cleaner and preferred way.
> 2 votes

---
Tags: nodes
---


title: Display suite removing class id

text:
# Question
Title: Display suite removing class id
I split 2 columns my contetnt node with Display Suite and add custom class to the columns. (with Bootsrap responsive class col-sm-3) But display suite still render column with old style: group-left and group right. How can i remove old style?

# Answer
> 2 votes
The classes are only added to the existing ones, they don't replace them. If you want to remove the old styling, you can create a new layout and either add different default classes, or no classes at all.

Adding custom layouts to your theme (Display Suite)

You also might want to consider using Display Suite Bootstrap Layouts. Bootstrap 3.0 layouts are still in dev, but it's worth taking a look.

---
Tags: theming, display-suite
---


# Question
Title: Nodewords: how do I use hook_metatags_default_values_alter?
I posted this question a week ago on the *nodewords* issue queue, but have had no reply and I'm stumped.

I want to programatically set the default value for a couple of tags, but the code comments for hook\_metatags\_default\_values\_alter read like hieroglyphics to me. An example would allow me to understand clearly. If I want to set the og:latitude tag to the value 43.701536, what should the call look like?

Thanks!

# Answer
Without ever having used that hook, I would suppose that you could do it very similar to the example in the documentation for hook\_metatags\_default\_value\_alter():

```
function hook_metatags_default_values_alter(&$values, $parameters) {
  if ($parameters['phase'] == 'post_load' && $parameters['type'] == NODEWORDS_TYPE_USER) {
    $values['og:latitude'] = 43.701536;
  }
}

```

For a better understanding it might be worth the effort to dig through the code of \_nodewords\_tag\_value which seems to have the only invocation of the hook. You can see there, that it is invoked twice with a different `$phase` parameter. I think I would go for `post_load`, assuming that the defaults are not empty.

For the `type` parameter, you can see the available constants in the nodewords.module doc under constants. This value depends on where you want to alter the tag.

If the above code doesn't work, use dpm or something similar to inspect the `$values` that are passed in. That should give you enough information concerning the expected data.
> 1 votes

---
Tags: 6, meta-tags
---


# Question
Title: Drush Enable a module and all its submodules
For example when I enable `coder` module, I also want to enable `coder_review`, `coder_sniffer` and `coder_upgrade` modules.

# Answer
There's nothing out of the box, however you can just list the three modules and then coder will also be enabled as it's a dependency.

E.g. `drush en coder_review coder_sniffer coder_upgrade -y`

If there are more modules than this that you might want, then seriously try taking a look at the Master module.

> The module provides utilities for controlling the module status of all modules in \> the whole installation by a single drush command.

I've got various scopes set up on all of my sites, (including local scopes for my machine) so that when I run `drush master-exec --scope=mattlocal`, I get modules enabled that no other environment should have (e.g. DummyImages, Devel, Coder)

Lastly, a cheap workaround would be to have a custom module (maybe a controller module if you have one), and just make Coder and all of it's submodules dependencies and enable that.

E.g.

```
name = MyModule
description = This module does nothing except for handle dependencies.
package = Custom
core = 7.x
version = 7.x-1.x

dependencies[] = coder
dependencies[] = coder_sniffer
dependencies[] = coder_upgrade
dependencies[] = coder_review

```

and then

`drush en mymodule`
> 4 votes

# Answer
There is nothing out of the box to automatically enable *submodules*, but it is, in fact, possible to specify similarly-named modules via a wildcard:

```
drush en 'coder*'

```

As previously mentioned, this is only useful in certain niche situations. I have never used it in any practical situation. If you happened to need it, it would be just the thing, though.
> 6 votes

---
Tags: drush
---


title: Get page title in webform

text:
# Question
Title: Get page title in webform
I have a webform block on a page and i am looking for a way to get the webpage title in one of my fields. I have been looking for a while now and have not found a solution to my issue. One of the things that i found was using `[current-page:title]` but i cant get it to work i keep getting `[current-page:title]` to return in the field.

I found it off of this post: https://drupal.org/node/1782042, but i am afriad that i am using it the wrong way from what they explain and i may not understand what they are doing.

I have tried:

`[current-page:title]` and got `[current-page:title]` to return

`%get[current-page:title]` and got `%get[current-page:title]` to return

Does anyone know where i am going wrong or possibly have a solution to returning the title of the page in the webform field? I am pretty new to drupal development and any help would be much appreciated. Thank you!

**---EDIT---**

The reason why `%title` is not an option is because it will only grab the title of the block. I need the current title of the page that the block is on. Any ideas?

# Answer
> 1 votes
I was able to do this by upgrading to the webform 4.0 beta version. and used `[node:title]`.

---
Tags: 7, webforms
---


# Question
Title: Trying to disable mail on contact form, but it's still required on submit
I am trying to make optional the mail field from the contact form. I manage to remove the asterisk by implementing the hook\_form\_alter:

```
function contact_field_form_alter(&$form, &$form_state, $form_id) {
    $form['mail']['#required'] = FALSE;
}

```

However on form submission, I get the message "You must enter a valid e-mail address". I seems that, although the field is optional on the form, it still tries to validate it. Can somebody tell me how to make it really optional?

Thanks in advance

# Answer
> 6 votes
Are you talking about the site wide contact form or the personal contact forms that each user can have? I'll talk about the site wide form, but the following roughly applies to the personal one as well.

The email validation is hard wired in contact\_site\_form\_validate, and the `$mail` is also needed in the submission handler, so there is no nice way around it.

Easy way: Set the default value for the mail field to an address that you own and then disable access to the field like this:

```
function contact_field_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contact_site_form') {
    $form['mail']['#required'] = FALSE;
    $form['mail']['#default_value'] = 'me@my-site.com';
    $form['mail']['#access'] = FALSE;
  }
}

```

This will completely hide the mail field.

Hardcore way: In your form alter you could overwrite the default validation and submission callbacks (using `$form['#validate']` and `$form['#submit']`) and replace them with your custom ones. This does not come without the risk of side effects. If you have other modules that want to add custom stuff and logic for contact forms, then this will probably break them.

As an alternative, you could use the webform module. It gives you a lot more flexibility concerning the information that you want to request and having an optional email field in there is very easy to do.

**Update:** You can also try the following (untested):

```
function contact_field_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contact_site_form') {
    $form['mail']['#required'] = FALSE;
    $form['mail']['#default_value'] = '';
    // This makes our custom validation come first.
    array_unshift($form['#validate'], 'my_custom_validation');
  }
}

function my_custom_validation($form, &$form_state) {
  // This fills an empty mail value with a default one.
  if (empty($form_state['values']['mail']) {
    form_set_value($form['mail'], 'me@my-site.com', $form_state);
  }
  // After this the default validation will run.
}

```

This will remove the asterisk, hide any preset value and in the validation handler a default value for the mail field is set if none has been submitted by the user. That way the hard wired validation shouldn't have a reason to complain.

---
Tags: forms, emails
---


# Question
Title: Navigation buttons move around in responsive design
This is kinda strange, I'm using **flexslider module** in which my navigation (previous & next) buttons on 1320.css, 960.css are centered fine on the slider. When I get to the 720.css and mobile.css versions, that is when the navigation buttons start moving around. Ether they are above or below the slider in which it's pointless to even display on :hover by ~50px. Lastly, I noticed that I cannot replicate on a desktop/laptop browser, it only gets introduced when using a mobile browser of any type of phone.

Below is a snippet from the **Flexslider.css** that pertains to the navigation:

```
.flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%; z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}

```

Any ideas? I noticed that 'top: 50%;' moves them but again a can't figure out a way to get them to always be centered. Also I should mention that I'm running alpha 2 but it occurs in both alpha 3 and alpha 2 versions of Flexslider.

# Answer
> 0 votes
To resolve the problem I used @media queries to distinguish a different setting per responsive size. So I copied and deleted line 58 (**.flex-direction-nav a**) from the flexslider.css. I then added this code below at the bottom for the CSS file. \*This is also good as you can control the nav in all variations of size. for instance in the mobile @media below I dropped the buttons down (removed top: 50%; from mobile) some to help users see the flexslider on a small screen better.

```
/* LANDSCAPE PHONE TO DOWN MOBILECSS */
@media all and (max-width: 480px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LANDSCAPE PHONE TO PORTRAIT TABLET MOBILECSS */
@media all and (max-width: 759px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LANDSCAPE DESKTOP TO DOWN 720CSS */
@media all and (min-width: 481px) (max-width: 760px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* PORTRAIT TABLET TO LANDSCAPE AND DESKTOP 720CSS */
@media all and (min-width: 761px) and (max-width: 980px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LAGACY DESKTOPS 960CSS */
@media all and (min-width: 981px) and (max-width: 1289px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%; z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

```

---
Tags: theming, javascript
---


# Question
Title: Clicking any hash/"#" link, even in Seven themed edit page tabs, scrolls to top of page?
I have a custom themed Drupal 7 site here. If you click on the left or right arrows in the top slide show or bottom "logo parade", the browser will scroll to that hash tag (undesired). Also, when logged in and looking at an edit page (uses Seven admin theme, not custom theme), clicking on a vertical tab e.g. "Menu settings" will scroll to the top of the page. This is disorienting and disruptive!

What's most troubling is that I can't reproduce this issue on the local test version of the site. The home page slide show and logo parade cause no scrolling when clicking around. The edit pages are a dream without unwanted scrolling...

FireBug isn't reporting anything odd. I'm not seeing noticeable differences between the live and local sites. Another Drupal 7 site I have on the same production server is not having this issue. It works great locally. I'm stumped.

This might be unrelated (maybe a related clue!), but for this site specifically I'm also having some odd ajax issues when editing views via Seven theme (and it's working great on my local version). When attempting to add a field to any view I'm getting this message, followed by the overlay instead loading as its own page:

```
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /admin/structure/views/ajax/add-item/articles/block/field
StatusText:
ResponseText:
ReadyState: 4

```

Any thoughts on where I should start to troubleshoot this issue? I truly appreciate the assist in advance! :D

# Answer
> 1 votes
Your problem appears to be that the arrows for the slide show and "logo parade" are linked directly to their container `<div id="logo-parade">` with the anchor `href="#logo-parade"`, which causes the page to essentially "snap" to the container, since the div id is the same as anchor when called as a hash (you can see in the url that `#logo-parade` gets appended).

This could be caused because of a portion of javascript is not being called/run properly which should trigger the carousel without needing to use anchors.

Since your problem doesn't occur in development (you can test this by clicking on one of the arrows and making sure that in your URL bar you don't see `#logo-parade` appended) it leads me to believe that perhaps a file hasn't loaded correctly on the server, or perhaps the .htaccess rewrite has something to do with it

---
Tags: 7, ajax, javascript, navigation
---


# Question
Title: Can I render a region of my drupal site on a non-drupal site?
Here is my situation.

I'm in the process of implementing Drupal as the primary CMS for a large site with hundreds of pages. But until the data input into Drupal can be done (which will be an ongoing process over months), I'd like the older "non-drupal" pages to at least be faked into looking like they are part of the same site. Basically I just want to tack onto the old pages, the new drupal header and footer (which are independent regions).

I was wondering if there is a known way to show a region from your drupal site on a regular php page? Such as a simple drupal "region rendering function" or something?

ps. The navigation has dropdown menus so iframes are out of the question.

Any constructive insight into how I should approach this would be helpful. Thanks.

# Answer
You can try Web Widgets module to embed.

> Create dynamic snippets of your Drupal site that users can copy and paste to their websites.
>
> * Supported widget styles: iframe, inline, UWA or Google Gadgets.
> * Build a view and make a widget from it.
> * Embed any other web site content in a widget with a simple widget API.

also look in to Embed widgets module.
> 2 votes

---
Tags: theming
---


# Question
Title: media_youtube plugin doesn't work with ckeditor 4.3.x
I try to setup D7 + ckeditor 4.3.x in conjunction with wysiwyg + media (v1) modules.

Everything is ok for text edition and image insertion with the media browser button in ckeditor.

The problem is: I try to add the media\_youtube plugin and videos do not show in content. Instead I have a placeholder.

Downgraded to ckeditor 3.6 and everything worked perfectly again.

But I'd like to keep the new features in the newer version of ckeditor.

Any idea what the problem could be?

thks

pl.

# Answer
> 0 votes
This just may be a temporary problem with the editor, or a preference setting that may be overlooked. I know the Media module and related modules have had some significant updates and changes, so if that preview feature was unreliable at some point then deactivating it would be the right solution until a better solution comes around.

---
Tags: wysiwyg, media
---


# Question
Title: setting content to display on a basic page
I'm creating a classified section on my site, and I have a basic page created for the content. How do i set content to go to that specific page?

Thanks for the help

# Answer
set up a block view with all your classifieds and then via admin/structure/blocks find your classified block and configure it to show on your basic page.
> 0 votes

# Answer
I think what you're looking for is a "View", which requires the Views module. It'll allow you to easily create pages that list content of any type you create.

Install and enable the Views module, and add a new View. You will see a simple wizard that creates your listing page. Make sure you add the custom path (URL) for your custom page.
> 0 votes

---
Tags: nodes
---


title: How can I add <div> to all checkboxes?

text:
# Question
Title: How can I add <div> to all checkboxes?
I just want to wrap checkboxes like this in all the forms, automatically.

```
<div class="inline field">
  <div class="ui checkbox">
    <input type="checkbox">
    <label>Checkbox</label>
  </div>
</div>

```

How can I achieve this? Is there any hook available for this?

# Answer
> 2 votes
Yes, there is a theme hook that will let you alter every instance of a checkbox. The two theme hooks you'll want to look at are:

1. `theme_checkbox()` \- https://api.drupal.org/api/drupal/includes!form.inc/function/theme\_checkbox/7
2. `theme_checkboxes()` \- https://api.drupal.org/api/drupal/includes!form.inc/function/theme\_checkboxes/7

## Sample Code

Here's some sample code, available in the API doc links I provided above.

```
function theme_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

You can override the markup returned by implementing this theme hook.

---
Tags: theming, hooks
---


title: Apache Solr Search Results

text:
# Question
Title: Apache Solr Search Results
The apache solr search results object doesn't seem to be indexing one of the fields I've added, a field with the machine name of field\_resource\_type.

How do I add this? Is it in a configuration file?

The actual content type (resource) is being indexed, and several fields inside of resource are being indexed.

How do I index this one field?

# Answer
Typically text based fields are automatically added to the Solr index, as a convenience feature. It is up to the site builder to exclude fields. One reason the field may not appear in the index could be it's data type, but if it's a standard field type (shipped with Core) then there is something much simpler incorrectly setup (or it's just not indexed itself yet).
> 0 votes

---
Tags: search
---


# Question
Title: Display discount ad when people visit the page
A client of mine wants to display a discount advert on top of the site when user visited the page, so I imagine it will be triggered by the onload handler of my front page. I thought I can display the ad content in a colorbox to raise it even more above the content. How can I trigger a colorbox to show up with the onload handler of the site?

# Answer
You are looking for Splash Offer module. It will show the popup on page load.

> Allows the management of one or more "splash offers", which are modal popups with an accept or reject form. If a user accepts the offer then a new page will open with a provided accept url. If they reject the offer, the modal will close. (If they select Do not Show Again, then a cookie is set so as to avoid further display.) You may define the who, when and where of the splash offers with precision controls. Factors such as: user role, site url, device, and whether the offer has been previously viewed (cookies), cookie duration, etc. are configurable for each splash offer created.

also take a look at this modules - Splashify, Splash and TinyBox (Simple Splash).
> 1 votes

---
Tags: javascript, advertising
---


title: Attach a 5-star widget to a custom form

text:
# Question
Title: Attach a 5-star widget to a custom form
How do you add a FiveStar widget to a (non-node) form using hook\_form\_alter?

# Answer
```
  $path = drupal_get_path('module', 'fivestar');
  drupal_add_js($path . '/js/fivestar.js');
  drupal_add_css($path . '/css/fivestar.css');

  $rating = votingapi_select_single_result_value(array(
        'entity_id' => YOURENTITY_ID,
        'entity_type' => 'YOURENTITY_TYPE',
        'tag' => 'vote',
        'function' => 'average',
   ));
   $form['votes'] = array(
      '#markup' =>  theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')),
   );

```
> 5 votes

# Answer
It can be done using the following code.

```
$form['presentation_ratting'] = array(
  '#type' => 'fivestar',
  '#stars' => 5,
  '#title' => t('Presentation.'),
);

```
> 4 votes

---
Tags: 7, rating
---


# Question
Title: How to execute a query taken from views in custom module
Please don't suggest query builder, this is the single query I need run from my custom module with passing arguments.

I create a View with desire fields and copy/past the query in phpMyAdmin the query is not showing the actual values for columns instead showing value as NODE :(

Is there any way to achieve this?

Thanks

# Answer
> 0 votes
Goto admin/structure/views/settings and enable the setting

> Show other queries run during render during live preview

As the help text for the setting reads, probably during the view rendering time there are some changes that could be happening. Enabling this setting will give you an insight into what is happening.

---
Tags: views
---


# Question
Title: Is there way to use existing content type field to custom form in drupal?
I want to use existing content type field in my own custom form. Like In content type, we can use existing field.

# Answer
In Drupal 7 you can use **field\_attach\_form**

```

function hook_form($form, &$form_state) {
  $form['fname'] = array(
    '#type' => 'textfield',
    '#title' => t('first name'),
  );
  $form['lname'] = array(
    '#type' => 'textfield',
    '#title' => t('last name'),
  );
  //attaching existing content type fields
  $node = new stdClass();
  $node->type = 'article'; //content type
  field_attach_form('node', $node, $form, $form_state); //it will attach all the fields
  unset($form['body']); //unset other fields like this.
  //..
  return $form;
}

```
> 6 votes

# Answer
You should consider using field\_attach\_form function.

An example use of this in user.module is as follows.

```
field_attach_form('user', $form['#user'], $form, $form_state, $langcode);

```
> 2 votes

---
Tags: commerce
---


# Question
Title: Proper way to cache custom entities with Entitycache?
I am trying to figure out how to cache custom entities with Entitycache module. As I know Entitycache module doesn't support custom entites created with Entity API, that's why I'm doing like this:

created cache table for own entity: `cache_entity_carroza_user`

created own controller, extent `EntityCacheDefaultEntityController`, implemented `EntityAPIControllerInterface`:

```
class CarrozaEntityController extends EntityCacheDefaultEntityController implements EntityAPIControllerInterface {
  ...
}

```

implemented `hook_entity_info`, specified entity controller:

```
$return = array(
  'carroza_user' => array(
    'label' => t('Carroza User'),
    'controller class' => 'CarrozaUserEntityController',
....

if(module_exists('entitycache')) {
  $return['carroza_user']['field cache'] = FALSE;
  $return['carroza_user']['entity cache'] = TRUE;
}

```

created `CarrozaUserEntityController`:

```
class CarrozaUserEntityController extends CarrozaEntityController {
  public function __construct($entityType) {
    parent::__construct($entityType);
  }

  public function resetCache(array $ids = NULL) {
    EntityCacheControllerHelper::resetEntityCache($this, $ids);
    parent::resetCache($ids);
  }

  public function load($ids = array(), $conditions = array()) {
    return EntityCacheControllerHelper::entityCacheLoad($this, $ids, $conditions);
  }

  public function create(array $values = array()) {
    $values += array(
      'carroza_uid' => '',
      'is_new' => TRUE,
      ...
    );

    $carroza_user = parent::create($values);
    return $carroza_user;
  }

  public function save($carroza_user, DatabaseTransaction $transaction = NULL) {
    return parent::save($carroza_user, $transaction);
  }
}

```

I'm doing everything Entitycache documentation says, but can't see any records in `cache_entity_carroza_user` table. Am I missing something else?

# Answer
entitycache.module and entity.module integrate, so that just just work.

All you need to do is make sure that the cache table for your entity table exists and set the keys in hook\_entity\_info() as you already do.

Not sure why it doesn't work, but I'd start by removing the custom controller and rely on the default one from entity.module.
> 1 votes

---
Tags: caching, entities
---


# Question
Title: Updating Entity Properties with hook_update_N()
I have a custom module which defines a custom entity. Now I would like to add a new field to this entity without reinstalling my module. I tried it with the `hook_update_N()` function:

```
/**
 * Description
 */
function MY_MODULE_update_7100() {
  $spec = array(
    'type' => 'int',
    'description' => 'Description',
    'not null' => FALSE,
  );
  db_add_field('my_table', 'my_new_field', $spec);
}

```

in my Module, I updated my existing `hook_entity_property_info_alter` to add the definition for this field:

```
function MY_MODULE_entity_property_info_alter(&$info) {
  $props = &$info['my_entity']['properties'];
  // snip
  $props['my_new_field'] = array(
    'label' => t('My Label'),
    'type' => 'integer',
    'description' => t('My Description'),
    'schema field' => 'my_new_field',
  );
  // snap
}

```

After updating, I can still create and update the entity, but sadly not my new Field which I created.

What did I wrong?

I looked for an example in the commerce module. But the module is using `drupal_write_record` instead of `entity_save`.

PS: I already saw this issue but it didn't worked.

# Answer
I've had this problem myself in the past and almost pulled all my hair out! :)

It turned out that I had forgotten to update my hook\_schema declaration within the .install file of my module, and include the definition of the new database field for my entity table.

Adding in the definition *should* make the new field available to you.
> 6 votes

---
Tags: entities, updating
---


# Question
Title: Change Add to cart button text in Drupal 7
I am using Drupal 7 and Ubercart 3. I want to change the text for the button "Add to cart", how can I achieve this?

Any help, thanks.

# Answer
The string overrides module is handy for these kind of things.

Provides a quick and easy way to replace any text on the site.

> Features
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 1 votes

---
Tags: 7, ubercart
---


title: What is the meaning of views displays?

text:
# Question
Title: What is the meaning of views displays?
I know how to create a view as a page or block and etc.

But The **Displays** seems meaning I can create lots of views?

This following is my guess:

* Is it will group all kind of views to a single page?
* Does **Displays** just easily use the previous view configuration and just Put similar view together to manager easily?

# Answer
> 1 votes
Views displays helps you manage your views that are similarly the same.

Basic example is articles:

On your home page, you want a simple block that shows 5 articles, no pager. At the bottom of this block, you want a link "read all articles". It redirects you to a page with all the articles, 10 per page, with a pager at the end.

Instead of creating 2 views, which is a waste of time, you'll create one view with 2 displays.

For this example, you will create two views displays, one "Block" and one "Page". First you create your "Page" display (or "Block", as you want), set it to filter only articles content type, show the title and the date of publication. Then you can create the other view display, and you only need to override the "Pager" settings.

Tomorrow, if you add an image to your articles, and you want them to appears on both the block and the page, you just need to add the image in the fields, and it will appear on both views display.

Beware that each views display has its own purpose, for example "Feed" will all you to create Rss display, "Page" needs it's own URI, etc.

# Answer
> 0 votes
You should create:

* **New view** when you need a **new set of data** selected.
* **New display** in existing view when you need different page or block for **already existing data set**.

Of course border between the two is fluid. Use your experience and intuition to decide, with above as strong, but only guideline.

---
Tags: views
---


title: List All vocabularies and their terms

text:
# Question
Title: List All vocabularies and their terms
How can i list my vocabularies and their terms in this way . Is there a module that can help me to do this . or i should go with custom VIEW and jQuery.

thanks :)

# Answer
> -1 votes
You can do with Taxonomy Term Reference Tree Widget module.

> This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

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


title: Simplenews css theming using mime mail

text:
# Question
Title: Simplenews css theming using mime mail
I am using **simplenews** for my newsletter and **mime mail** to send them by mail.

I am trying to use the same CSS for my newsletter mail than my newsletter displayed on the web site.

Is it possible to refere the same css file?

# Answer
> 1 votes
On admin/config/system/mimemail you can tell mimemail to try and use the site's stylesheet when sending an email. You'll have to make sure that your css selectors apply to the elements of your email message or adjust it appropriately.

Alternatively if you want more control over the styles, do not tell mimemail to use the site's stylesheet but instead create a file named mail.css in your theme. Mimemail will automatically use it when sending emails.

Also make sure your theme is set as "Theme to render the emails" under admin/config/system/mailsystem, otherwise you might get the wrong stylesheets when your emails get sent via cron, for example.

---
Tags: theming, emails
---


title: Admin Landing Page - How to create?

text:
# Question
Title: Admin Landing Page - How to create?
Ok, I know there is a tutorial out there somewhere for this, I used it once before. Now, no matter how I search, I can't find it. Basically, I want to create this:

In other words, an admin landing page with sub menu items.

I have Panels and Page Manager installed and can create the admin page to the point where it shows on the path, but the sub-menu items don't appear. Instead I get this:

I've cleared the caches, made sure that sub-menu item is under this page, made sure that all the proper permissions are set . . . You know all the stuff that good Drupal developers are supposed to do.

So my two questions are this:

1. What am I doing wrong?
2. Can any one give me the step by step for creating what's on the first image with my own custom menu items? Or at least point me in the direction of some tutorials?

Thank you in advance for any help you can provide.

# Answer
> 1 votes
The reliable way to add and see menu options on admin pages is through \[PHP\] code, using `hook_menu()`. Be sure each URL is prefixed with `admin/...` (for example, `admin/sub-section/page-1`, `admin/sub-section/page-2`).

Here's a quick snippet paraphrased from the `hook_menu()` Drupal API docs:

```
  function mymodule_menu() {
    $items['admin/sub-section/page-1'] = array(
      'page callback' => 'mymodule_page1_view',
    );
    return $items;
  }

  function mymodule_page1_view() {
    // ...
  }

```

I haven't tried tricking the admin screen by adding custom links with "admin/***" at the front, which may or may not work - but the code option will definitely work, I've used that hook more than a thousand times.

# Answer
> 0 votes
In Drupal 7 you can create using **hook\_menu**

```

    /**
     * Implements hook_menu().
     */
    function hook_menu() {
        $items = array();
        $items['admin/structure/types1'] = array(
            'title' => 'Types 1',
            'description' => 'Your menu types 1 description',
            'page callback' => 'types1_menu_callback',
            'access arguments' => array('Administer types 1'),
        );
        $items['admin/structure/types2'] = array(
            'title' => 'Types 2',
            'description' => 'Your menu types 2 description',
            'page callback' => 'types2_menu_callback',
            'access arguments' => array('Administer types 2'),
        );
        $items['admin/structure/types3'] = array(
            'title' => 'Types 3',
            'description' => 'Your menu types 3 description',
            'page callback' => 'types3_menu_callback',
            'access arguments' => array('Administer types 3'),
        );
        return $items;
    }

    function types1_menu_callback() {
    //Your code for type 1 menu...
    }

    function types2_menu_callback() {
    //Your code for type 2 menu...
    }

    function types3_menu_callback() {
    //Your code for type 3 menu...
    }

```
* Create your own permissions using **hook\_permission**

```

    /**
     * Implements hook_permission().
     */
    function hook_permission() {
        $perms = array(
            'administer types1' => array(
                'title' => t('Administer types 1'),
                'restrict access' => TRUE,
            ),
            'administer types2' => array(
                'title' => t('Administer types 2'),
                'restrict access' => TRUE,
            ),
            'administer types3' => array(
                'title' => t('Administer types 3'),
                'restrict access' => TRUE,
            ),
        );
        return $perms;
    }

```

# Answer
> -1 votes
in admin/config/system/site-information set the front page to admin/structure

or

go to admin/structure/menus. create a menu with all the links you want on your page. go to admin/structure/blocks - find your menu and configure it to show on the page you want.

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


# Question
Title: How to use "taxonomy_get_childern" function
//TID of current loaded node

```

<?php
$nid = arg(1);
$tid1 = db_query("SELECT data.name,data.tid FROM field_data_field_books book
 INNER JOIN taxonomy_term_data data ON data.tid = book.field_books_tid
 WHERE book.entity_id = $nid ");

 foreach($tid1 as $t){
    print "Name ==> " . $t->name;
    print "Tid ===> " . $t->tid;
 }

 //function to load child term
 $child = taxonomy_get_children(32);
 foreach($child as $ch){
   print "Name===>" . $ch->name;

?>

```

my question is that I want load tid dynamically instead of hardcore value I am using the above code in block please tell me how I am handle this situation?

# Answer
In Drupal 7 you can use this code

```

  $nid = arg(1);//get the arugument
  if (arg(0) == 'node'  && is_numeric($nid)) {//check for node page
    $query = db_select('field_data_field_books', 'book');
    $query->fields('data', array('tid'));
    $query->innerJoin('taxonomy_term_data', 'data', 'data.tid = book.field_books_tid');
    $query->condition('book.entity_id', $nid, '=');
    $tid = $query->execute()->fetchField();//only one field
    $child = taxonomy_get_children($tid);//get your children
    foreach ($child as $ch) {
      print "Name===>" . $ch->name;
    }
  }

```
> 0 votes

---
Tags: blocks, 7, taxonomy-terms
---


# Question
Title: Save checkboxes value into another checkbox field
I'd like to save the value of a checkboxes field which is link to a product once I save my content type.

I've created the code needed to create the product and the node. When the node is in creation mode everything appear as it should and my node get's save, the product created but I struggle to save the value into the field field\_permission that I've added to the product type.

Permission field.

Label: Permissions Machine Name: field\_permission Field Type: List(text) Widget: Check boxes/radio buttons

The values inside this field are:

permission1|Permission1 permission2|Permission2 permission3|Permission3

I've selected the number of value to 3. I got my check-boxes field created. Great !

Then, I've created a content type and alter form to save a custom node. I had this form element which appear on the form.

```
    $options = array(
      permission1|Permission1
      permission2|Permission2
      permission3|Permission3
    );

    $form['permission'] = array(
      '#type' => 'checkboxes',
      '#options' => $options,
      '#title' => t('Select permissions:'),
    );

```

Then when I save the new node using a custom submit, I create a product and it works fine, But:

I want to save the value selected inside $form\[permission\] and copy those values to the field\_permission I've create onto the product type. I've read that I have to use the wrapper and call the newly created product. Fine. It works but the value aren't still save into my new field. Any idea How to save checkboxes values ?

Thanks.

```
function myform_submit($form, &$form_state){
global $user;

$node = new stdClass();
// Set content type
    $node->type = 'event';
    // Prepare defaults
    node_object_prepare($node);

    $node->title  = $form_state['values']['title'];

    $node->language = LANGUAGE_NONE;

    //create path with pathauto
    $path = 'mycontent' . date('YmdHis');
    $node->path = array('alias' => $path);
    $node->uid = $user->uid;

    //create new product type
    $price = $form_state['values']['field_cost']['und'][0]['value'];
    $extra = array(
    'sku' => 'event-' . drupal_hash_base64(microtime()),
    'title' => $node->title,
    'uid' => $node->uid,
    'status' => TRUE,
    );
$reg_id = _create_product('event_product', $price, $extra);

//add permissions value to the product
$product = commerce_product_load($reg_id);
$wrapper = entity_metadata_wrapper('commerce_product', $product);

$permissions = $form_state['values']['permission'];

    --- HERE IS THE PROBLEM --- How to copy those values ???

   foreach ($permissions as $key => $value){
      $wrapper->field_event_permission['#default_value'] = $permissions;
   }

$wrapper->save();

dsm($wrapper->getPropertyInfo());

   //save the field attached to the node
.....
   node_save($node);
}

```

# Answer
Yes, it's solved.

I don't need to add the permission to the product. I just check the permission that are check on the field\_permission related to this node and then I display the Add to cart button only if the user meet the required permission.

Thanks
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Putting any fields of referenced entity in lightbox frame
I want output a field as a link to an overlay that has fields of a referenced entity in it. I can output the actual link just fine as long as it doesn’t have to be an overlay. Content type A is called ‘performance’, content type B is ‘performer’ (to which is being referenced).

So, for now, in my view there are only two fields: ‘Performer name’(of content type B also the title) and ‘title’ (of content type A). ‘Performer’ is arranged above ‘title’ and display set to none. ‘Title’ has ‘ouput field as link’ checked and has the token in the URL that is the title of ‘Performer’.

So this makes the link that is the title in the view go to the node of the performer that is referenced in the ‘Performance’ node.

I know that in the ‘rewrite results’ fieldset, I can fill in ‘lightbox2’ in the ‘rel’ attribute of my link. When I do this though, the lightbox shows, but is empty. No image, no values of any field, no nothing.

# Answer
> 0 votes
This doens't necessarily have to be done using lightbox. It ended up being a lot easier using a jQuery plugin like Simple Modal

I made extra fields in views and gave them a class the jQuery could latch on to using

```
$('hideMe').hide;

```

and using jQuery's `click();` method to go and say `(this).modal`

A different question here at Drupal Answers went into the same issue but it was more about how to write the jQuery code so definitely more of a jQuery question. Anyway the question with the exact code can be found here.

# Answer
> 0 votes
The rel attribute should be "lightframe". It is used for HTML elements you want to open in lightbox.

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


# Question
Title: Creating Image Captions using File Entity module
The purpose is to create image captions to all images uploaded in Drupal.

What I did:

* installed media 2.0 / file entity 2.0 alpha2
* added a new field called 'captions' in the image file types: admin/structure/file-types

Now I can add captions in the body field images.

I need the captions to be visible for other fields like image upload field.

How to exposed file\_entity's fields in the content type form fields?

# Answer
# Exposing file\_entity fields in forms

A simple solution to this issue is to change each upload image field's widget type from default 'Image' to 'Media file selector'. Thus throught Media all file fields can be edited.

An alternative solution is File Entity Inline (https://drupal.org/project/file\_entity\_inline) which exposes the file entity fields as form fields.

# Displaying file\_entity fields in pages

If file\_entity fields are not displayed in the page, test first if they are exposed using Views (field image). If you want to display them in a simple page with image fields already created try to workaround by adding new theme suggestions / template: e.g. file--image.tpl.php

The theme suggestions provided by the File Entity module are:

```
file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}

```
> 1 votes

---
Tags: media, files
---


# Question
Title: display status report even though the module is disabled
I want to execute some code in my custom module to display status reports even though my custom module is disabled.

`hook_requirements()` can be used to display status reports, but it only works when the module is enabled. I want this to work even when the module is disabled.

How can I achieve this?

# Answer
That's not possible.

For hooks to be executed, your module **must** be enabled. From the docs:

> To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in **all enabled modules** that implement it.

Emphasis mine.

Allowing modules to run code even when they're not enabled would be a massive security risk, and could cause all sorts of other unforeseen problems.
> 5 votes

---
Tags: hooks, log-messages
---


# Question
Title: Views: filter content by two taxonomy terms
I have vocabulary with these terms:

* Sport
    + Soccer
    + Hockey
    + ...
* term
    + subterm
    + ...

And I have content where is chosen one of those subterms.

Then there is a second vocabulary (countries):

* France
* GB
* ...

I need to create view that will show content by path.

For example: /sport/soccer - this will show content with soccer term. (This is done by default)

But I need also this: /sport/soccer/france - content with terms soccer and france.

I know that I have to user Views with contextual filters. I am using Drupal 7 with Views 3.

Thanks for your help.

# Answer
Create three contextual filters: 1) global null (it's at the bottom), this will ignore the first argument 2) normal contextual filter for the first vocabulary, 3) normal contextual filter for the second vocabulary.

By normal I mean that you first select Term ID then Specify validation criteria, Taxonomy term, pick your vocab, Term name converted to term ID. It's a good idea to give these filters an Administrative title found under the More section, so that you can keep track which is which, as they need to be in the right order.

To reduce duplicates, in the view details "Advanced" \> "OTHER" \> "Query settings", check the box "Distinct" (thanks user2171413).
> 1 votes

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