# Question
Title: How to deal with too much product variations / attributes?
I'm quite new to Drupal Commerce, but I've seen some Drupal before (not actually a guru).

Dealing now with handmade models, each product has 9 **sizes**, 6 **colors**, 6 **materials**. They have now about 130 models. I started dealing with it creating a product per variation (commerce\_bpc). But 300+ variations per product display became a little unbearable, because it was intended for a local shop and they should be able to create new models and edit old ones a little bit faster.

We decided to make the products just size dependant (price changes only according to **size**, and there would be no special images for **colors** and **materials**).

So, my first approach was to use the image as a product display field. But:

* What about the attributes? Is the correct way to use **material** and **color** as select list in the Display, too? Will I be able to use them later in the checkout and the orders?
* Or should I stick to 1 product per variation and handle them in some other way? I think that's the NATURAL way, but it just feels like overkilling.

Also, any insight on how to handle a large list of products (edit, bulk actions, add them to display, etc..)?

# Answer
Views Bulk Operations? There is also the Commerce Bulk Product Creation. Some more details about it (from its project page):

> This module facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.
>
> The module also provides various ways to create display nodes for the newly-created products:
>
> * Redirect user to node creation form (with title and product reference filled in).
> * Silently create display node referencing all created products.
> * Silently create one display node for each created product.
>
> This will greatly speed up the task of adding numerous products at once.
> 1 votes

---
Tags: commerce
---


# Question
Title: Does securelogin module needs to have a certificate?
**securelogin** seems to be a must to protect against spying login/password.

However it is not clear (to me) **whether it requires a SSL Certificate**.
I couldn't find this info neither in its module page nor anywhere else :
http://drupal.org/project/securelogin
(is it too obvious that it does not need to say ?).
Thanks

# Answer
> 1 votes
Yes, the securelogin module requires an SSL certificate. From the README file:

> Before enabling the module, you need to set up your server to support 23 SSL.

---
Tags: users, security
---


# Question
Title: how to create single flag for choosing multiple bookmarks?
I want to create a flag which can be used to bookmark multiple content. In my site i am allowing user to publish their own articles. Each article has a genre type taxonomy. I want to make a flag which will be displayed below the article content page, and on clicking on the flag the user will be able to subscribe to both the article and its genre (taxonomy). I tried using flags for taxonomy but that flag does not appear on the bottom of every content page. Instead it appears on the view when we seea ll the content related to a genre. I am using drupal 7. Thanks for your help.

# Answer
> 1 votes
This is possible but you need to use the Flag API hooks and the Flag Actions module. Enable the Flag Actions module that comes with the Flag module if you haven't already. You will now have an option under the flag tab on the triggers page to fire off an action based on whenever anyone flags something with your flag.

```
/admin/structure/trigger/node

```

None of the actions available will match what you are trying to do but you can create one. In your site module (or create one), you need to just define two functions: the action definition hook, and the function that fires.

For the action definition, you're using hook\_action\_info() to declare a function

```
/**
 * Implements hook_action_info().
 */

function YOURMODULE_action_info() {
  return array(
    'MYFLAG_action' => array(
      'label' => t('Action to take after MYFLAG is flagged'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

```

and then you want to create the function to trigger your taxonomy flag

```
/**
 * Action function for report action
 *
 * @see action_example_action_info()
 */
function MYFLAG_action(&$entity, $context = array()) {

   // Use the name of the taxonomy flag here
   $MYFLAG = flag_get_flag("name of taxonomy flag");

   // add logic to find your taxonomy_id, probably from the node object available through the $entity variable

   $taxonomy_id = ( SOME OPERATION )

   //execute the flag operation
   $flag->flag('flag', $taxonomy_id);

}

```

Finally, flush cache and go back to your triggers page to associate the trigger of flagging a node with your new custom action.

# Answer
> 0 votes
if you can write code in a custom module or in a template, you could use flag\_create\_link($flag\_name, $content\_id) to make it appears where you whant.

for taxonomy, here the how to.

---
Tags: 7, taxonomy-terms, flags
---


title: Custom url inside the button

text:
# Question
Title: Custom url inside the button
I was creating my first project with drupal and now my problem was the **request new password** since this is a link and i want to make it into buttons so i generate my hook\_form\_alter but i got a problem with the url i'm not sure if markup is working.

Here my code for form\_alter:

```
  $form['actions']['request'] = array(
'#markup' => l(t('Forgot Password?'), 'user/password', array('attributes' => array('class' => 'form-request','title' => t('Request a new generated password via e-mails.')))),'#weight' => 2, '#type' => 'button' );

```

I'm not sure if this is correct. Thanks for the help folks!

# Answer
> 2 votes
Here how your code should look like:

```
/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'FORM_ID') {
    $form['actions']['request'] = array(
      '#type' => 'submit',
      '#value' => t('Forgot Password?'),
      '#submit' => array('mycustom_submit_redirect'),
      '#limit_validation_errors' => array(),
      '#attributes' => array(
        'class' => array('form-request'),
        'title' => array(t('Request a new generated password via e-mails.')),
      ),
      '#weight' => 2,
    );
  }
}

function mycustom_submit_redirect(&$form, &$form_state) {
  // sometimes it seems to fail
  //$form_state['redirect'] = 'user/password';

  // alternative method to redirect
  $options['absolute'] = TRUE;

  $url = url('user/password', $options);

  header('Location: ' . $url);

  drupal_exit($url);
}

```

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


# Question
Title: How do I force-indicate a vocabulary as a source for node breadcrumbs?
I have two vocabularies on my site, each node of certain content type has 2 term reference fields - one per vocabulary, single value only. For browsing through both vocabularies I am using Taxonomy Menu and Taxonomy Breadcrumb modules.

As long as I'm browsing through terms, the breadcrumb is ok, the problem starts when I step down to a node instance - the breadcrumb path is then always taken from vocabulary A, while what I want is the path from vocabulary B.

In the content type definition I checked vocabulary A as the source of active trail for menu (this is Taxonomy Menu setting most probably). Apparently that does not influence the breadcrumb. However, none of the options in the Taxonomy Breadcrumb config screen seems to have any impact on the source of the breadcrumbs.

What else should I check?

# Answer
You can try Crumbs instead of taxonomy breadcrumb.
You can be bold and try the 7.x-2.x branch (\*)

Documentation for Crumbs + Taxonomy: http://drupal.org/node/1984484

I have not personally tried it in combination with taxonomy menu, but think it should work ok.

To solve the problem on node pages:

* Install Crumbs
* Visit Admin \> Structure \> Crumbs to adjust the plugin priorities (\*).
* The `taxonomy.termReference.field_vocab_B.node.certain_node_type` (\**) needs to be moved up, into the "Enabled" section.

You can do more stuff with Crumbs (you could even replace taxonomy menu with menupoly), but one question at a time.

(\*) The crumbs-7.x-2.x, among other things, has a revamped admin UI to set the plugin priorities. It is still not perfect, which is the main reason there is no 7.x-2.0 stable yet.

(\**) Thanks to the wildcard system, you could also move `taxonomy.termReference.field_vocab_B.node.*` or even `taxonomy.termReference.field_vocab_B.*` into "Enabled", instead of `taxonomy.termReference.field_vocab_B.node.certain_node_type`. Doing that would activate this behavior for other node types and/or other entity types that have field\_vocab\_B.
> 0 votes

---
Tags: taxonomy-terms
---


title: Rendering Module Code to HTML

text:
# Question
Title: Rendering Module Code to HTML
Semi-new to Drupal. I'm trying to find a way to render HTML inside my custom module.

Right now I'm using this method

```
$page = 'hello world';
return $page;

```

Which can get pretty dirty once you had some logic into it.

Is there a better way to do this? Maybe render it to some kind of template file and pass an array of vars?

Any help is appreciated :)

# Answer
> 0 votes
Clive is right that using the drupal theme system is your best bet if you're going to be doing significant variable manipulation but if you just want to load a big blob of HTML into your module you can do it a couple of ways in PHP.

For short blobs, try the EOF method

```
$str = <<<EOF
  <p>Hello</p>
  <p>$world</p>
  ... etc.
EOF;

```

For longer blobs, use file\_get\_contents()

```
$myhtml = file_get_contents(path_to_module().'/my_html.tpl');

```

---
Tags: 7, theming
---


title: Hierarchical taxonomy breadcrumb

text:
# Question
Title: Hierarchical taxonomy breadcrumb
I have a view that displays terms hierarchically via a view attachment, but neither the URL nor the breadcrumb keep track of where it is in the hierarchy. For example, a taxonomy structured like the following.

* Category
    + Term I
        - Term A
            * Term 1
    + Term II
        - Term B

It displays a page listing Term I and Term II. Upon clicking on *Term I*, the user is taken to the page for *Term A*, which is a list of its sub-terms (*Term 1*). Upon clicking, the user is taken to a list of nodes tagged with that therm.

The path and breadcrumb for each of these pages is, sequentially, the following.

* /category
* /category/term-i
* /category/term-a
* /category/term-1

I would like instead for the breadcrumb and path to be the following.

* /category
* /category/term-i
* /category/term-i/term-a
* /category/term-i/term-a/term-1

I've tried the Hansel and Custom Breadcrumbs modules, but I have been unable to configure them properly, or they just don't provide the functionality I need.

I'm using Drupal 7 with a theme based on Omega, so any answer that include instructions to insert code into template or other theme files need to include information about where that code belongs in Omega.

# Answer
> 2 votes
These are two separate questions. One about the path, another about the breadcrumb.

**Breadcrumbs:**

Disclaimer: The solution presented here may need more tweaking, if your taxonomy/term/% is replaced by a views page with contextual filter. (I never do that, there are other ways to achieve the same)

Crumbs will do the trick. 90% of the task out of the box. If not, check this doc: http://drupal.org/node/1984484

You need some manual work to make "/category" the top-level breadcrumb item for all the terms: (this explanation is for the 7.x-2.x branch)
Visit Admin \> Structure \> Crumbs \> Entity parent \> Taxonomy
Set 'category' as the parent path for your vocabulary.
Go back to Admin \> Structure \> Crumbs
Move crumbs.entityParent.\* into the "Enabled" section, and give it a low enough priority.

**Path:**

I suppose you have pathauto installed already.
Go to Admin \> Configuration \> Search and metadata \> URL aliases
Look at "Taxonomy term paths".

I read somewhere that the following pattern will do the trick:

```
category/[term:parents:join-path]/[term:name]

```

Not tested myself. Good luck with it :)

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


# Question
Title: How to add classes to h2 block title tags in sidebar region
I need to add a class to the h2 block titles in a sidebar. How can I do this in pre-process? I haven't been able to find an example that shows how to isolate certain blocks. I'm using Omega.

# Answer
> 8 votes
template\_preprocess\_block()

Inspect the block object in this preprocess function. You could use either the 'module' and 'delta' properties to target a specific block or the 'region' property to target all blocks in a certain region.

H2 css-classes are listed in the title\_attributes\_array. The code below shows how to add a new class. This example is based on a block generated by Views:

```
function MYTHEME_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->module == 'views' && $block->delta == 'name_of_my_view-block') {
    $variables['title_attributes_array']['class'][] = 'my-new-class';
  }
}

```

Sidenote: dpm() by the Devel module is a handy tool for printing out the available data in variables:

```
function MYTHEME_preprocess_block(&$variables) {
  dpm($variables);
}

```

---
Tags: 7, theming
---


# Question
Title: What happened to the edit links in the Page Manager UI?
I uploaded a site to a shared hosting environment and suddenly I can't use the *edit* links in the Page Manager UI any more. As you can see in the screenshot, they've simply disappeared. I can click the triangle and get a *disable* link but no *edit*.

I cleared the cache multiple times to no effect. I then made a database dump of the server mysql and imported it into a local copy and experienced the same problem, even after clearing the cache multiple times. I then turned off all of the aggregation options on the **Performance** configuration page and cleared the cache again, but no change.

Is this a typical problem or something I have uniquely done to screw things up?

EDIT: Upon further inspection, I noticed something else weird. I am able to access the pages by typing in the URL manually, but when I go to edit a piece of custom content, the *Edit* option, which is usually just under *Disable this pane*, is missing:

# Answer
Found the problem-- I had been lazy and replaced the "Edit" translation string with a space to remove it from some of the pages on the site, forgetting that it would remove "Edit" from all pages on the site. Restoring the string fixed the problem.
> 0 votes

---
Tags: panels
---


# Question
Title: Login Users action in, $action_links, how do i edit it?
I am still very new to drupal and have let to use all the hooks and coding needed to do everything, now I have come up with a problem, which I can not seem to fix either with a module or by looking at code posted online.

I am using the forum core module from drupal 7 to build a forum, within my page.tpl file I have the render($action\_links) option printed on each page. This works fine for logged in user. It displays a 'add new forum topic' as a link. However when a non-user views the forums, its displays 'Log in to post new content in the forum'.

My problem / issue is that only the 'Log in' words are linked to the user login in page and not the whole text. I would like to move the tag drupal placed after the 'Log in' and move it to the end of the text!

I think I would have to use hook\_menu something but I can't really find any information on how to do this for the $action\_links. All the hook\_menu options I find seem to deal with controlling the main menu output.

Any help give would be most welcome...

Thanks

Glenn Curtis

# Answer
In D7, if you visit core FORUM module & open forum.module file you will find this code between line no 186 to 208 -

```
if (empty($links)) {
        // Authenticated user does not have access to create new topics.
        if ($user->uid) {
          $links['disallowed'] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
              'title' => t('You are not allowed to post new content in the forum.'),
            ),
          );
        }
        // Anonymous user does not have access to create new topics.
        else {
          $links['login'] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
              'title' => t('<a href="@login">Log in</a> to post new content in the forum.', array(
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }

```

This is responsible to generate the link & text which you are talking about. But hacking core is not advisable so please find a way to do it in some other way..
> 0 votes

---
Tags: theming, navigation, routes
---


# Question
Title: Render view array programatically within template
I would like to print the array of a specific View within a template, so I can then access each specific field and theme as I wish. The view I am using will only be outputting one row. All my attempts seem to be returning 'previously declared' errors.

Your help is appreciated. Thanks

# Answer
> 0 votes
There are a few steps involved with applying a template to view. But thankfully they are all fairly simple.

I found one of the most helpful tutorials was this one, which goes through the process. I think this process should give you sufficient control over the theme for each field.

I'm not sure why you might be getting the 'previously declared' errors though.

---
Tags: views, theming
---


# Question
Title: drupal is welcoming other user after login
I have website built on drupal 6.26.
Now i am facing a trouble that sometimes when the user logs in, the website is showing him Welcome message to another user!! for example if you login using user X, after reload of the page, it will show you a message of "Welcome Y" and shows the profile page of Y. fortunately, it shows profile Y but without Editing permission. and if you try to visit X's profile, it will be editable!!.
Any idea what could cause such ambiguity??

# Answer
Thanks a lot guys, I found the problem,,, the caching of the login block was set to 1, i just made it no-cache for this block

```

mysql> select * from blocks where module like '%ajax%';
+-----+---------------+-------+---------+--------+--------+-------------+--------+----------+------------+-------+--------+-------+
| bid | module        | delta | theme   | status | weight | region      | custom | throttle | visibility | pages | title  | cache |
+-----+---------------+-------+---------+--------+--------+-------------+--------+----------+------------+-------+--------+-------+
|  35 | ajax_register | 0     | sky     |      1 |    -40 | rightheader |      0 |        0 |          0 |       |  |     1 |
|  39 | ajax_register | 0     | garland |      0 |      0 |             |      0 |        0 |          0 |       |        |     1 |
+-----+---------------+-------+---------+--------+--------+-------------+--------+----------+------------+-------+--------+-------+
2 rows in set (0.00 sec)

mysql> update blocks set cache=-1 where bid=35;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update blocks set cache=-1 where bid=39;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

```
> 0 votes

---
Tags: 6, users
---


# Question
Title: what is the meaning of $Id$ at the head of module files?
I have seen this line at the head of many files in Drupal modules:

```
; $Id$

```

what the meaning of it? What does it do? Is it important ? Should I put it when I am writing my own module?

# Answer
> 4 votes
Its legacy left behind of a no longer used version control system (CVS) used by Drupal.org/projects *before* the current version control system (git) was adopted.

You should *not* use this when writing your own code. The automated code checker tool at Drupal.org will actually complain if these are present.

And, btw: Git rules!

# Answer
> 4 votes
Its a keyword which is used by version control system. Whenever a file is checked in, it will replace that keyword with info related to file. There are other keywords such as Date, Author, Revision ....

> **Id**
>
> This keyword is a compressed combination of the other keywords. Its substitution looks something like $Id: calc.c 148 2006-07-28 21:30:43Z sally $, and is interpreted to mean that the file calc.c was last changed in revision 148 on the evening of July 28, 2006 by the user sally.

If you are using SVN which supports keyword substitution you can use that. It will help you identify easily last modified date and by whom. So you know whom to blame when something goes wrong ;)

---
Tags: 7
---


title: How to remove views first title

text:
# Question
Title: How to remove views first title
I have a list of titles in a view block. But I never want the very first title of the view to display is this possible? I am using Drupal 7 with views 3.X

# Answer
In the pager settings of your view select the wanted amount of items and then specify an offset by 1, so the first item won't be displayed.
> 3 votes

# Answer
You can use the "Pager" settings for that. Set it to the kind of pager you want and use the "offset" to skip the first items.
> 0 votes

---
Tags: views
---


title: styling the views pager

text:
# Question
Title: styling the views pager
I'm using drupal 7 and i made a view that has a pager.
Is there any way to put the pager-item (pagers number) inside any html tag?

`<ul class="pager">`
`<div>// new html tag`
`<li class="pager-current first">1</li>`
`<li class="pager-item">2</li>`
`<li class="pager-item">3</li>`
`<li class="pager-item">4</li>`
`</div>`
`<li class="pager-next">......`

# Answer
> 2 votes
Ofcourse you can...

Make a copy of views-view.tpl.php in your theme.

Then you put your tag around the output of the $pager variable.

```
  <?php if ($pager): ?>
    <somemadeuptag>
       <?php print $pager; ?>
    </somemadeuptag>
  <?php endif; ?>

```

---

**UPDATE**

> *"no that is not what i looking for, i need put html tag inside $pager variable"*

You need to use **hook\_pager\_link()** in your theme.

Search for 'hook\_pager\_link' in your sites code directory to see example.

---
Tags: 7, views
---


title: Page not found SEO

text:
# Question
Title: Page not found SEO
Drupal offers us the possibility to set the 404 page displayed for the end users (this can be set in the admin configuration).

Ex : If you type

http://www.example.com/doesntexist

you are redirected to

http://www.example.com/my-custom-404-page (alias for a node)

While this is a good approach for end users, what about the side effects for the `Google bot` ?

Generally speaking, if the Google Bot received a 404 error for a page, it will stop crawling it.

However, with the solution displayed above, the headers of the response page are :

> HTTP/1.1 302 Found

So my question is : is there any way to have the 404 HTTP code while having a nice custom error page ?

# Answer
Installing Custom Error will fix this problem.

I am using this module and I've set up custom 403 and 404 page for my site. Example: http://www.nemo-project.org/board/doesntexist \- and it returns 404 according to http://www.seoconsultants.com/tools/headers

(I am not sure if this module is *necessary* to get the correct HTTP response codes, but it is a nifty module and does the job - I use it on all my Drupal 7 sites.)
> 3 votes

---
Tags: 7
---


# Question
Title: What is the hook to alter links in the Book Outline tree?
What is the theme hook to alter links in the book outline like theme\_menu\_link\__menu does for menus? Or is there a way to make theme\_menu\_link\__menu apply changes to a tree view of the Books? Not the book navigation but the Outline.

# Answer
> 0 votes
Turns out there isn't one. Had to go back to an ajax approach and update the book outline in the client browser.

---
Tags: navigation, nodes
---


# Question
Title: Existing Page not getting registered by hook_menu to trigger Drupal AJAX on page load
This Drupal example is working with the 'virtual' paths that are not actual nodes, and when I add a node/page with the same fake path 'vms-custom-path/trigger-page but with an existing named node/page like my\_drupal\_site/test-ajax-page and adding `$items['my-ajax-page'] = array()` never seems to get called.

```
//PHP Module
/// path to our REAL page with a menu block on it in Drupal site
// first to load the js file only on this page

  $items['test-ajax-page'] = array(
    'title' => 'My custom ajax callback',
    'page callback' => 'addCustomJS',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

 // then to register the actual ajax call back

  $items['test-ajax-page/ajax'] = array(
    'title' => 'My custom ajax callback',
    'page callback' => 'My_ajax_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

```

I need to use AJAX to update a Drupal page when it loads with data look ups from the server. Most examples use a click or other form event, this for a menu page without any forms and has to happen when the page loads without any user events.

I found a deeson-online's example using Drupal.ajax.prototype.specifiedResponse but it is throwing AJAX errors.

How can I run Drupal AJAX with jQuery when the page finishes loading?

Here's the basic version that did work with the Drupal AJAX Object approach - when I have the jQuery version, as Austin suggested, working for our situation I'll add that.

```
//PHP Module
// Returns AJAX commands if the URL has 'ajax' in it
$items['My-custom-path/ajax'] = array(
  'title' => 'My custom ajax callback',
  'page callback' => 'My_ajax_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

/**
* AJAX callback that prints text and link ID. ID will be used for looking up additional data.
*/
function My_ajax_callback() {
  // Define a new array to hold our Drupal AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX commands that will be run in the Browser

  //In this case arg(3) is the Node ID in the URL passed back
  if(is_numeric(arg(3)) ){
  $ajax_commands[] = ajax_command_after('#'.arg(3), 'Hello '. '#'.arg(3) . '!!!');
  $ajax_commands[] = ajax_command_append('#'.arg(3), 'Updated');
  $ajax_commands[] = ajax_command_append('#'.arg(3), arg(3));
  }
  else {
    //return;
    $ajax_commands[] = ajax_command_after('#'.arg(3), 'No data available.');
  }

  // Return our commands in JSON.
return drupal_json_output($ajax_commands);
}

```

```
// JavaScript
(function ($) {
  Drupal.behaviors.My_ajax = {
  attach: function(context, settings) {
  var $MyAjaxLink = $('.My-ajax-link');

  // Add IDs to the Menu links to query them on the server
  $('div.block div.content div.menu-block-wrapper ul.menu li.leaf a').each(function(index, element) {
        var url =      $(this).attr('href');
        var urlArray = url.split("/");
        var lastPath = urlArray.length -1;
      $(this).attr('id', urlArray[lastPath]);
    });

  /**
   * Add an extra function to the Drupal ajax object
   * which allows us to trigger an ajax response without
   * an element that triggers it.

   * From post on  http://deeson-online.co.uk/labs/trigger-drupal-managed-ajax-calls-any-time-drupal-7
   */
  Drupal.ajax.prototype.specifiedResponse = function() {
    var ajax = this;

    // Do not perform another ajax command if one is already in progress.
    if (ajax.ajaxing) {
      return false;
    }

    try {
      $.ajax(ajax.options);
    }
    catch (err) {
      alert('An error occurred while attempting to process ' + ajax.options.url);
      return false;
    }

    return false;
  };

  $('div.block div.content div.menu-block-wrapper ul.menu li.leaf a:not(.ajax-processed)').each(function(index, element) {
        var $MyAjaxLink = $(this);
        // make sure it is a numeric ID
        if( !isNaN(this.id) ) {
          DrupalAjax =  new Drupal.ajax('.My-ajax-link', $MyAjaxLink, {
            url: $MyAjaxLink.attr('href'),
            settings: {},
            event: 'onload'
            //event: 'click tap'
          });

          $(this).addClass('ajax-processed');

          // not working yet did loop and throw errors
          DrupalAjax.specifiedResponse()
        }
    });
    }
  }
})(jQuery);

```

# Answer
i've done this a few different ways but there are many ways to handle this. i dont know whe version you are using so i just pulled a d6 implementation. also, `$(document.ready()function() {} );` should fire off right when the DOM is ready.

also, have you reviewed ajax in drupal using jQuery ?

one way i've done this is to write my own module that has an external js file. first i need to have a path available for the ajax callback. in `mymod_menu()` i added something like

```
$items['some_path/update'] = array(
    'page callback' => 'mymod_json_update',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
);

```

i created another function called `mymod_json_update` which you see in the `page_callback` option.

```
function mymod_json_update() {
// do some work and get your data together to be pushed to JSON output
print drupal_json(array('html' => $html));
exit();
}

```

in my js file, i make the actual ajax call. Note you could also use something like `$.getJSON()` but `$.ajax()` works too. up to you

```
(function ($) {
  $(document).ready(function() {
    var type = Drupal.settings.type;  // some value i've attached to Drupal.settings so i can pass a value back to the mymod_json_update() function in my module.
    $.ajax({
       type:    "GET",
       url: "some_path/update",
       cache:   false,
       data:    'type='+type,
       success: function(html) {
          var result = Drupal.parseJson(html);
          $('div.content').html(result['html']);
       }
    });
  });
})(jQuery);

```
> 1 votes

# Answer
Appears you cannot register an existing page. But you can code in the callbacks with your own path defined in the module menu callback. One thing I did find is no matter what any example may show you, do not use any leading or trailing slashes "/" in either the module hook\_menu or in the url used in the javascript ajax call. Thanks again everyone, and austin in particular, your replies were great clues in getting to the solution.
> 0 votes

---
Tags: ajax
---


# Question
Title: how to get the form id of a particular form using Devel execute PHP in drupal 7?
I wanted to get the form id of particular forms to customize those forms. I dont want to use form alter hook to obtain the form id every time. I wanted a simple way to acquire the form\_id of the forms. Like a simple PHP snippet that can be executed in Devel execute PHP to obtain the form ID. or is there any other way to do it?

# Answer
I don't think it's possible to do this without something (either your custom module or another module) implementing `hook_form_alter()`. The Devel execute PHP form is in a block which has no real idea what forms are available on the page.

I'm sure you know the way to get the form ID but just in case this will print it at the top of every form:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('whatever permission you want')) {
    $form['mymodule_form_id'] = array(
      '#markup' => '<p>Form ID: ' . $form_id . '</p>',
      '#weight' => -10000
    );
  }
}

```

If you really don't want to do this, though, why not just use developer tools/firebug to inspect the form element on the page itself...you'll find the form id in one of the hidden input fields.
> 2 votes

# Answer
I know this is outdated but I'll post it for googlers who end up here - I wanted to improve upon the answer previously posted. In your custom module implement hook\_form\_alter(), and using the Devel module, use the dpm() function.

For example:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
dpm($form_id);
}

```

Save, clear cache, and then load the desired form in your drupal website. You should see a green system message that displays the form ID, for example, article\_node\_form.

Make sure you have the devel module enabled and sufficient permissions to use the devel module.
> 1 votes

# Answer
Use Get Form ID module to easily find out form id of any form in Drupal: http://drupal.org/project/get\_form\_id
> 0 votes

---
Tags: debugging
---


# Question
Title: In a view, how can I link a field to the node?
In a fields view, the "title" field has a check box "Link this field to the original piece of content". But this check box isn't available for other fields. How can I achieve this functionality for other fields?

E.g. in my case I have a custom "subtitle" field, and I would like to list the nodes subtitles. The subtitles should be links that point to the node.

# Answer
> 25 votes
as @Daphna mentioned and you can see here: drupal.org/node/1234862 you can use `Content: Path` field value as a token for the field you want to be linked to the content:

1. add `Content: Path` field and in the `configure field` modal box check `Exclude from display` to hide this field from being displayed and rearrange fields so this field is above the field you want to be linked to the content.
2. click the field you want to be linked to the content to open `configure field` modal box and in the `Rewrite results` section check `Rewrite the output of this field`.
3. in the opened textarea under `Rewrite results` write this: `<a href="[path]">[field_name]</a>`. you should replace `field name` with proper token of the field you want to be linked. you can find all the fields token in the `Replacement patterns` section under `Rewrite results`.

# Answer
> 6 votes
What the subtitle field to know is, where to link it. This is done with the NodeID field (nid).

1. add the "Content: Nid (The node ID)" field; Select the hide it from Display option
2. Rearrange that field. Push it higher than your subtitle (so it can grab that nid)
3. rewrite the output as a link with the nid, like node/\[nid\] or something
4. Voilà

Adding the hidden Nid field makes the token \[nid\] available in the subtitle field when making it a link. Also you need to have Token installed.

Or http://drupal.org/node/1234862 maybe?

---
Tags: 7, views
---


# Question
Title: Linking terms to views instead of taxonomy pages
I have created a view for movie genres, with contextual filters to generate such pages as /horror, /comedy, etc.

When I tag content or users, I want the links which then appear on these pages to refer to the view. Right now they go to the term page.

I have heard that the TVI module is the way to go, but I can't find any documentation about it.

I don't even want these term pages to exist at all - I have essentially made my own, to my own specs. How can I make this happen?

# Answer
> 0 votes
If you're dealing with a limited number of terms (genres), you can do the following:

1. Head to Structure \> Taxonomy \> List Terms (next to your genre category)
2. Click Edit next to a term.
3. Uncheck "Generate automatic URL alias" under the URL Path Settings.
4. Enter the path to your View.
5. Repeat.

You can also use the PathAuto module to set up rules for automatic forwarding of Taxonomy links to your Views. Install PathAuto, enable, click Configure, select the Patterns tab, and rewrite the URL path for Taxonomy.

# Answer
> 0 votes
I would suggest installing the path automodule and configuring the taxonomy terms patterns to whatever path you wish.

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


# Question
Title: Disable Product Display upon purchase of the Product or it's variations
I have a site of products wherein each *Product Display* has 2 *Variations* (*Products*).

I would like it so when a single variation is purchased the Product Display get's unpublished (regardless of a variation still being available for purchase).

I've been trying to do this with **Rules** with little success, has anyone come across this before or know of a solid solution?

# Answer
> 0 votes
The Disable product when it was purchased issue on d.o. deals exactly with this problem.

---
Tags: rules, commerce
---


# Question
Title: Optional extra products on add to cart form
We're trying to have it so that on a product display there are optional extras which can be added all at the same time as the main product by selecting checkboxes. These products are optional extras which are product specific.

We have tried the Commerce Product Add On module but it breaks with an ajax error when there is more than one main product variation and another option is selected on the product display front end.

We are trying to debug the error but we are also wondering if this can be created using something which already exists such as views bulk operations and rules. Any help would be much appreciated!

# Answer
There is for example Commerce add to cart extras:

> This module provides alternative ways of adding products to cart.
>
> The initial version provides a views field handler ("Commerce Product: Quantity input field") that relies on the Views Form API (a part of Views 3 since RC1) to output a quantity textfield that turns the view into an add to cart form. The default quantity can be configured, and only products with a quantity larger than 0 are added to the cart.

Also, you can find 2 approaches (VBO + Rules, and custom VBO action) at Add multiple products to cart with VBO.
> 1 votes

---
Tags: commerce
---


# Question
Title: Hook_init() and Hook_exit not triggering in template.php
I have implemented hook\_init and hook\_exit in template.php

```
<?php
/* Alter variables */
function mytheme_exit(){
  var_dump("template Hook exit called");
}

/* Alter variables*/
function mytheme_init(){
  var_dump("template Hook init called");
}

```

When I cleared cache, loaded the page, it didnt print anything I would really appreciate any help from you guys since when I implemented the hook\_init and hook\_exit in a custom module , it did work. Does these hook not work in template.php??

# Answer
Unfortunately it's as you suspect - those hooks aren't invoked for themes.

Themes can implement `hook_theme()`, a variety of process/preprocess hooks, and `alter hooks` (there may be others but I can't find a reference right now).

For `hook_init()`, `hook_exit()`, and most other non-alter hooks you'll need to implement them in a custom module.
> 7 votes

---
Tags: 7, theming
---


# Question
Title: Showing previous and next pager links regardless of the page one is in
Drupal hides the previous link of a pager if you are the first page,and the next link if you are on the last page. Is there way I can keep the links from disappearing, just in a disabled state? Can I do this without using php?

# Answer
> 1 votes
Probably not, to do this you would have to use **theme\_views\_mini\_pager()**.

**Reference:** http://drupalcontrib.org/api/drupal/contributions%21views%21theme%21theme.inc/function/theme\_views\_mini\_pager/7

**Example:**

```
if (empty($li_previous)) {
   $li_previous = " ";
}

```

That is whats doing it...

# Answer
> 1 votes
No - not without PHP, not without overriding the pager template in Views to do this. You could be able to do this in CSS if the views pager rendered the links but did not display them but the template excludes them. If you're willing to try creating a custom pager template, this article explains the basic steps.

---
Tags: views, navigation, paging
---


# Question
Title: Image field is not showing up in view/block
I am currently using Drupal 7, and I am trying to get my images to be displayed in a view on the main page. So far I have created:

* Created a content type containing a title, body and image field
* Created two nodes that both contain an uploaded image
* A view and a block that has
    + fields: title, nid, and image
    + filtered by: published and type (set to the content type I created)

When I look at my content type I can see the name, body and the image that I uploaded. When I go to the main page, I can see my view with the content, but it only shows the name and the body; it doesn't show the image.

Is there anything I can download and/or do to make this work? I just want the images to appear within the block (in my view).

# Answer
> 2 votes
check admin/user/permissions page. if you use imagecache check view imagecache permission and set it. and set view image field permission.

# Answer
> 1 votes
@Kyra, I do have the exact same issue with image field not showing in view, and this, since I've updated the view module, I'd say. The thing is I use Drupal Commerce (with Drupal Core 7), but I don't think the issue is directly related : I set a view on the front page, displaying products.

In the "Format" area :

* Format: Grid | Settings
* Show: Fields | Settings

In the "Fields" area :

* Content: Title
* Content: Body
* Field: Illustration

In the "Filter" criteria :

* Content: Published (Yes)
* Content: Sticky (Yes).

The view only displays the title and the body. Of course, when I look at the content types, outside the view, their image is shown. This occurs for all content types and products created before the update of the view module. Because, if go through the process of creating a new product type, product, product display and finally a content (dedicated to the product I've just created), there, I get the the image of it in the view. So it feels like some constraints in some tables have been messed up. Did you manage to solve this issue Kyra ?

# Answer
> 0 votes
For future reference, check the content type "manage display" tab. There is a subtab for "content" and "teaser", so you have to make sure the picture field is being displayed there (and not hidden). You can also change the format, etc.

# Answer
> -2 votes
When you create a node, below the body field there is the "Text format" combobox; choose "Full HTML," and everything will be ok.

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


# Question
Title: What are some benchmarks with Mysql vs MariaDB while on Drupal 7?
I was wondering how much faster is MariaDB vs Mysql in a Drupal 7 setup.

# Answer
When you have applied full due diligence, the difference between MariaDB and MySQL should be virtually negligible. Why would I say this?

MariaDB has done some benchmarking with some settings that give all MySQL processes the same level playing field : See **Sysbench OLTP: MySQL-5.6 vs. MariaDB-10.0**. In fact, here were the setting used in the benckmark.

```
[mysqld]
sql-mode="NO_ENGINE_SUBSTITUTION"
back_log=500
user=root
port=3306
max_connections=4096
max_connect_errors=5000
max_prepared_stmt_count=50000
table_cache=2048
transaction_isolation=REPEATABLE-READ
loose-skip-external-locking
innodb_status_file=0
innodb_data_file_path=ibdata1:200M:autoextend
innodb_buffer_pool_size=1G
innodb_additional_mem_pool_size=20M
innodb_log_file_size=650M
innodb_log_buffer_size=100M
innodb_support_xa=0
innodb_doublewrite=0
innodb_flush_log_at_trx_commit=0
query-cache-size=0
query-cache-type=0
symbolic-links=0
skip-grant-tables

```

Please note

* the settings do not accommodate use of more read and write I/O threads.
* double write buffer disabled, good for speed, bad for data consistency in case of a crash

---

The key to really deciding which version of MySQL to choose is to effectively tune all the versions under test and then benchmarking with actual Drupal data. I would look into getting all MyISAM converted to InnoDB as much as possible (If you are using FULLTEXT indexes, you must go with MySQL 5.6).

Here are some of my past posts from the DBA StackExchange on what settings to look for when tuning InnoDB and why:
> 2 votes

---
Tags: database
---


# Question
Title: View/query to show latest node related to each term in a taxonomy vocabulary
I have a node type (stories) which is related to a taxonomy vocabulary (countries).

Each story is related to one country only.

I want to create a view of the latest story from each country, ordered by published date. I only want 1 story from each country (if there is one).

I looked into doing this with views and couldn't see a way to limit the results to only 1 result per country.

Does anyone have any suggestion how I can do this without writing a custom query?

Thanks,

# Answer
I think that's the purpose of the module Views Grouping Row Limit.
> 0 votes

---
Tags: views, database
---


# Question
Title: Count of entities with a certain field value, filtered by created date
I’ve got users with a gender field and I want to display counts of how many males and females were registered on or before a particular date. So:

```
COUNT(user.gender=male) and COUNT(user.gender=female) where user.created < {date}.

```

Using views aggregation I can easily get the male/female counts for ALL users, but when I try to add either a filter or a contextual filter on user.created I get no results (and my brain goes flatline—see “extra credit”, below).

Is it possible (within Views) to do what I’m trying to do, and if so, how?

Extra credit: 4,000 brownie points for anyone who can help me understand why when you add a filter you specify aggregation rules. When filtering, I'm thinking about constraining the results, not aggregating them. What am I missing?.

Thanks!

# Answer
> 0 votes
Found a work-around -- http://drupal.org/node/847698#comment-3174900

Disable aggregation, then add filter, then re-enable aggregation.

---
Tags: views
---


# Question
Title: Autoload files by patterns instead of listing each file
Drupal's "autoloading" requires one to include the files in files\[\] declarations in the .info file.

When there are a lot of files, this becomes:

* A large, huge, list.
* Hard to maintain.

Is there a way to e.g include with patterns. Say `lib/*.php`?

# Answer
I agree with mpdonadio about implementing `hook_registry_files_alter()`, but I would rather use the following code.

```
function mymodule_registry_files_alter(&$files, $modules) {
  $include_path = drupal_get_path('module', 'mymodule') . '/includes';

  foreach (file_scan_directory($include_path, '/\.inc$/') as $file => $object) {
    $files[$file] = array(
      'module' => 'mymodule',
      'weight' => 0,
    );
  }
}

```

By default, file\_scan\_directory() checks the content of any sub-directory; if you want to avoid it, you can replace the `foreach()` loop with the following one.

```
  foreach (file_scan_directory($include_path, '/\.inc$/', array('recursive' => FALSE)) as $file => $object) {
    $files[$file] = array(
      'module' => 'mymodule',
      'weight' => 0,
    );
  }

```

The code can also be simplified by removing the `foreach()` loop, and using a callback that `file_scan_directory()` calls for each file.

```
function mymodule_registry_files_alter(&$files, $modules) {
  $include_path = drupal_get_path('module', 'mymodule') . '/includes';
  $array = &drupal_static('mymodule_add_files', array());
  $array = $files;

  file_scan_directory($include_path, '/\.inc$/', array('recursive' => $recursive, 'callback' => 'mymodule_add_files'));
}

function mymodule_add_files($uri) {
  $files = &drupal_static('mymodule_add_files', array());

  $files[$uri] = array(
    'module' => 'mymodule',
    'weight' => 0,
  );
}

```

Replace `$recursive` with `TRUE` if you want the function looks for files in the sub-directories for the directory passed as argument, or with `FALSE` in the case you don't want that.
> 1 votes

# Answer
You can potentially use hook\_registry\_files\_alter along with the PHP directory functions. Something like

```
function foo_registry_files_alter (&$files, $modules)
{
  $include_path = drupal_get_path('module', 'foo') . '/includes';

  if ($handle = opendir($include_path)) {
    while (($entry = readdir($handle)) !== FALSE) {
      if (preg_match('/\.php$/', $entry) === 1) {
        $files[$library_path . $entry] = array(
          'module' => 'foo',
          'weight' => 0,
        );
      }
    }
  }
}

```

This is untested, but the idea is to use scan an "include" directory for PHP files, and then tack them onto the array that the class registry uses for the autoloader. This should work, but I can't remember exactly what `readdir()` returns, so you may need to adjust the paths a bit.
> 1 votes

# Answer
xautoload does that since quite a long while :)

Doc page: http://drupal.org/node/1976198

This should be enough for your case:

```
dependencies[] = xautoload

; Only look at the top level directory
files[] = lib/*.php

```

or

```
dependencies[] = xautoload

; Scan the top level and deeper.
files[] = lib/**/*.php

```

More stuff, if you need it:

```
; Ignore the top level, only scan deeper directories.
files[] = lib/*/**/*.php

; Ignore the top level, scan second level, ignore deeper levels.
files[] = lib/*/*.php

```

Good luck with that!
> 1 votes

---
Tags: .info
---


title: Class Autoloading

text:
# Question
Title: Class Autoloading
I seem to remember some autoloading functionality for classes in d7. Is there any documentation on this?

* How should one organise the files containing the classes?
* How can one make sure that parent-classes are loaded on instantiating a child-class?

I would like to avoid writing an autoloader for each module that has Classes.

# Answer
Drupal 7 maintains a code registry and uses it for its classes autoloader. To populate this registry with your module's classes, you should add their files to the `files[]` entry in it's `.info` file:

```
files[] = includes/Foo.inc
files[] = includes/Bar.inc

```

PHP's class autoloading will make sure that the parent class file is also loaded.
> 8 votes

# Answer
Yep, Pierre is correct.
Besides that, you can use xautoload module to abbreviate your info file with wildcards.
Doc page: http://drupal.org/node/1976198

Syntax:

```
files[] = includes/*.inc

```

And besides that, you can attempt to be forward-compatible with Drupal 8, and use PSR-0 for your modules. This is also supported by xautoload.

Namespace and class: `\Drupal\my_module\OptionalSubNamespace\MyClass`
File: `(module dir)/lib/Drupal/my_module/OptionalSubNamespace/MyClass.php`

Doing this will make the files\[\] stuff obsolete.
> 6 votes

---
Tags: 7
---


# Question
Title: How to use the Theme Page reactions in context
In the context module, how does the reaction Theme Page work? I am confused how to use it in my theme

I am using an Omega subtheme and want to display the Section title used in the context to show up in a region. How can I get this value to show?

# Answer
> 1 votes
You need to use a theme preprocess hook to pass the variable to the right zone template. Here's how I added it to my header zone:

```
function my_theme_preprocess_zone(&$vars) {
    $zone = $vars['zone'];

    if ('header' == $zone) {
        $theme = alpha_get_theme();

        // set via context module
        if (isset($theme->page['section_title'])) {
            $vars['section_title'] = $theme->page['section_title'];
        }
    }
}

```

Then in your zone--header.tpl.php file

```
<?php if (isset($section_title)): ?>
<div class="grid-<?php print $columns ?>">
    <h1 class="section-title"><?= $section_title ?></h1>
</div>
<?php endif; ?>

```

---
Tags: 7, theming
---


# Question
Title: Output an empty alt tag for an image in with views?
I have an image field in a view. How can I output empty alt text for the image.

(For decorative images this is the correct markup http://www.w3schools.com/tags/att\_img\_alt.asp )

# Answer
If you have disallowed the "alt" text in your field configuration, the system will output and empty value as you want. But if the field has a value in the attribute, you could modify it with `hook_preprocces_field()`.
> 0 votes

---
Tags: views
---


# Question
Title: Validation error on term-reference field when ajax'd option is submitted?
I get the error "Illegal choice" when I submit a form with a multi-select option that was freshly created via ajax. Workflow is like this:

1. User loads node edit form
2. User needs to select a non-existant job title (job titles are drupal taxonomy terms)
3. User presses my custom ajax button that (1)takes their new title, (2) adds their new title as a drupal term, (3) updates the form in the browser, (4) selects the new title

When I submit the form, drupal doesn't seem to see that the new title has a corresponding (therefore valid) TID and errors out in the validation.

I tried creating custom validation on the title element, but despite passing that validation, drupal still does its own check, which fails.

Anyone know how to work around this?

# Answer
> 0 votes
Drupal checks the integrity of the form to make sure submitted values match up with the available options when the form was built; it's a security feature. Manipulating the form on the client-side, without informing the backend that something has changed, causes the integrity check to fail.

Rather than work around it (which is possible but messy), I'd recommend using the AJAX functionality already built into the form API.

The AJAX Forms in Drupal 7 page, FAPI AJAX reference and the AJAX Example in the Examples module are excellent resources for learning about this.

---
Tags: 7, taxonomy-terms, ajax, forms
---


# Question
Title: Using Invisimail within a Contemplate Template
I'm in Drupal 7 and using Contemplate and Invisimail, but I can't figure out how to get my emails to be obfuscated.

I think it is because the display of the node is using the contemplate template, which simply says:

```
<?php print $node->field_email['und'][0]['email'] ?><br/>

```

I figure I have to wrap that in a call to `invisimail_encode_email`, as such:

```
<?php print invisimail_encode_email($node->field_email['und'][0]['email'], 'html_entities') ?><br/>

```

but that did not work (error message about undefined array index). So, maybe I'm calling that function with the wrong parameters? or maybe I'm calling the wrong function.

Basically, how do I call invisimal from within php?

# Answer
> 1 votes
I'm doing a similar thing, but in a node template. To get the javascript obscured code to return, use the js\_entities encoder similar to this:

```
<?php
$email = render($content['field_email_address']);

// this takes the email address and turns it into a "mailto:" link, otherwise use 'link' => 0
$email_settings = array('link' => 1);

echo "<p>" . invisimail_encoder_js_entities_encode($email, $email_settings) . "</p>";
?>

```

Also, I use the Quick Javascript Switcher extension in Chrome to quickly toggle js off/on to see if things like this are working:

https://chrome.google.com/webstore/detail/quick-javascript-switcher/geddoclleiomckbhadiaipdggiiccfje

---
Tags: 7, theming, emails, advertising
---


# Question
Title: Drupal used as a project management tool
I have been working with drupal for the past 2 years and I'm well aware of its power and extensibility.

I have been thinking for a long time, but has anyone been successful been using drupal as a project management tool.

What modules should be used for making drupal a project management tool.

*Please keep in mind, we are not looking at some very advanced features, just basic set of features, to get you started.*

# Answer
> 12 votes
Open Atrium is ready drupal system for you (it's free of course). At least, you can investigate modules and theme used there (.\profiles\openatrium folder)...

# Answer
> 5 votes
Everyone **over designs** project management systems. They end up not being used, or used marginally with only the minimal features. Plus they waste tons of time simply by being confusing. Although I've not used Open Atrium, I've looked into others and found them lacking. Seriously, terribly lacking.

I've had **great** success with the following zero-budget solution:

1) Use the Node Comments module to promote comments to full nodes.

2) Use CCK to make your comment Content Type contain additional fields, such as "start time", "end time", "time worked", "supported by \[team members\]" and so on.

3) Each "Project" is simply a Page with the project description. Each comment is someone's contribution to the project, with any tracking fields you cared to add to the comment Content Type.

4) Additional "reporting" logic in a custom module that looks at these "time record" comments and generates useful aggregate summaries.

Butt simple.

Total time to get system working: 1 day.

Total time to get company using system: same fricking day!

Feeling of control over their environment by client company: total.

# Answer
> 4 votes
For Drupal 6, there exists the Project module can be extended for providing Bug Tracking as well.

# Answer
> 3 votes
Things are moving forward in the Drupal community and now there is a complete distribution for project management called ERPAL. See http://erpal.info for more details. ERPAL has full functionality for project management, with invoicing and expense tracking, gantt charts, timetracking, requirements management an much more.

# Answer
> 2 votes
The list of modules for Drupal 7 that are in the category of project management are visible in this page; both the Project module, and the Case Tracker module are absent in the list.

If you need to use a module that has been already ported to Drupal 7, then I would suggest you to use one of the modules listed in that page.
If you can wait, then I would suggest to wait until Case Tracker will be ported to Drupal 7; between Case Tracker and Project, Case Tracker is probably the module that will first have a Drupal 7 version.

# Answer
> 2 votes
I would use Storm and its associated modules. It can also be used with Open Atrium.

# Answer
> 2 votes
Check out this page http://groups.drupal.org/node/17948 for a comparison of Project Management / Ticket Tracking Systems

# Answer
> 0 votes
Just to note for completeness, the Storm module, which was mentioned in one of the comments has now changed its name to Project Management. The name change is active for the Drupal 7 version onwards.

---
Tags: 7
---


title: KML file upload on OpenLayers map

text:
# Question
Title: KML file upload on OpenLayers map
When I tested modules in Feb I am sure I got this working but nothing works now; I want the user to be able to upload a KML file when creating a node, and for that to display on a map. I am not even trying to combine multiple, just display each node's KML on an OpenLayers map.

I have tried the following module combinations:

**Geofile**

This is giving me an error which may just be an issue with the latest OpenLayers version. Issue on Drupal.org: EPSG fix is needed

**OpenLayers KML Layer**

The instructions on the module make it sound simple but I have not managed to get this to work.

**Geocoder**

Module home page suggests that you can set a field to geocode from an uploaded KML file, but I have not managed to get this to work and I do not see any errors.

Does anyone have this working?

**Note**: I know one can define a static KML layer in admin/structure/openlayers/layers, that is not helpful as I need a person to be able to upload a KML file on a node.

# Answer
* EPSG is fixed in Geofile 7.x-2.x
* Geofile provides a map formatter for the file field. more instructions

If you don't want to use the new version of Geofile, then go to the module(sites/all/modules/geofile) folder, open geofile.openlayers.inc in a text editor. if 'projection' and 'displayprojection' are assigned just numbers '4326' or '900913' change it to 'EPSG:4326' or 'EPSG:900913'
> 2 votes

---
Tags: 7, javascript, location
---


# Question
Title: Edit tab available to anonymous user on some but not all pages?
On a Drupal 6 site that I've inherited, there is a custom content type for staff profiles. Editing should be limited to two user roles "content creator" and "careers." This has worked fine for the past 2+ years, but a few weeks ago we noticed that some, but not all, of the individual staff page/nodes are editable buy anonymous users (anyone!).

I've looked at the permissions for this content type as well as for all our user roles-- nothing indicates that this should be possible at all.

The only way I've been able to "fix" this is by recreating the nodes 1-by-1 and deleting the "broken" ones.

I'm particularly curious as to why this only affects some nodes-- I have so far been unable to detect any sort of pattern that connects them.

Any ideas where I should be looking to diagnose this?

# Answer
We finally found out what was happening. Drupal was configured so that when an authorized user account was deleted, the owner for all their content was changed to Anonymous. Modified the setup so that the owner of all "orphaned" pages is set to Admin.
> 1 votes

---
Tags: 6, users, entities
---


title: Ajax filtering a Drupal7 View

text:
# Question
Title: Ajax filtering a Drupal7 View
I have a View where i would like to expose filters to permit the user to customize the view output. I know i can use exposed filters but, instead of a drop down (or checkbox/radiobutton of exposed filters) i want to put a list of DIV or LI that, when clicked, can update the view output through ajax. In which way is it possible using Views 3 and Drupal 7?

# Answer
> 3 votes
You can install Better Exposed filters in D7, edit the view and in the advanced fieldset change the exposed form style to "Better exposed filters", then in the settings for this you can choose how you want to display the filters, choose "Links". Also check the boxes for "Autosubmit" and "Hide submit button"

# Answer
> 2 votes
Views allow to use Ajax fro filtering out of the box - edit view, click on "Advanced" link and in "Use AJAX" option select "Yes"

If you want to theme checkbox/radiobutton as div - you can use JQuery. There are a lot of libraries that can do such themisation.

# Answer
> 2 votes
Better Exposed Filters doesn't currently support ajax filtering on the links view. I posted how I was able to accomplish this, without BEF, in https://drupal.org/node/1111712#comment-7370826.

---
Tags: 7, views
---


title: Drupal and Domain

text:
# Question
Title: Drupal and Domain
I have a strange redirect if I access my Drupal installation without subdomain:

http://efg-zoar.de

leads to

http://www.efg-zoar.de/drupal7

and the "drupal7" is just wrong.... If I enter

www.efg-zoar.de

directly, everything works fine. I already asked my webspace provider for support, but these settings are completly fine. The Drupal installation was installed intially with an other domain. May this change cause this problem? And how can I fix this?

Thanks a lot! Saduras

Edit: I found some entries in the database table prefix\_locales\_source which has "/drupal7/install.php?profile=standard&locale=de" in the field 'location'. Are these somehow related to my problem?

# Answer
> 0 votes
When I acccess the URL http://efg-zoar.de/ in Firefox with the HttpFox extension installed, it shows this response header.

```
(Status-Line)   HTTP/1.1 301 Moved Permanently
Date    Thu, 02 May 2013 21:45:41 GMT
Server  Apache/2.2.22
Location    http://www.efg-zoar.de/drupal7/

```

This shows that you have Apache installed, and something is performing a server-side redirect. As an earlier post mentioned, this redirect might take place at different levels.

The web browser hits Apache first. Apache can store redirects in both the httpd.conf and .htaccess files. It sounds like you're hosting in a shared environment, so my bet would be the .htaccess file.

Apache then passes the request to PHP and Drupal. A four-line PHP file can perform the same redirect, as shown here. http://www.cyberciti.biz/faq/php-redirect/

I checked the headers when accessing the home page with the WWW prefix http://www.efg-zoar.de/. This shows the header X-Powered-By: PHP/5.3.10. This makes me suspect that http://efg-zoar.de/ is hitting plain Apache with no PHP or Drupal involved. Here's the header from http://www.efg-zoar.de/.

```
(Status-Line)   HTTP/1.1 200 OK
Date    Thu, 02 May 2013 22:02:30 GMT
Server  Apache/2.2.22
X-Powered-By    PHP/5.3.10
X-Generator Drupal 7 (http://drupal.org)

```

You should contact your web host and ask them how to change the Apache redirect in either the .htaccess or httpd.conf file. Sometimes web hosts allow you to FTP the .htaccess file, but you need to configure your FTP client to show hidden files (file names preceded by a period, like .htaccess).

Here's the HttpFox extension for Firefox. It's helpful for debugging these issue. https://addons.mozilla.org/En-us/firefox/addon/httpfox/

# Answer
> 0 votes
i think you have this:

```
www.domain.de in /bla/bla/drupal7

domain.de in /bla/bla/drupal7

```

you need:

```
www.domain.de in /bla/bla

domain.de in /bla/bla

```

redirect folder /bla/bla via .htaccess or php to /bla/bla/drupal7

---
Tags: 7, redirection, subsites
---


title: OG menu default links are not adding up

text:
# Question
Title: OG menu default links are not adding up
I am using og\_menu 7.x-3.x-dev I am trying to create some default links to the og menu, but links are not adding.With a new group node its creating the og menu but the default links are not coming.Do I need to apply any patch? Thanks in advance. On the og menu settings page I have checked the "Automatically create a OG Menu for new Organic Group" checkbox and in the default links section I have tried adding absolute url and internal drupal path but no success.Am I missing some settings.

# Answer
> 0 votes
I figure out later the link I was adding were actually the nodes I was creating programmatically as a new group is created and I was creating the path alias programmatically as well, when i check the db table menu\_links I found there was no router for these node menu links,so to make them work I am putting the default links as external urls for example `http://yoursite/node/test`, I believe there must be a better way to get this done,good for now.

---
Tags: routes, organic-groups
---


title: Need to change node's path to CCK value

text:
# Question
Title: Need to change node's path to CCK value
I have a content type that has been turned into a Feature named "Earth News". It includes an optional CCK field called "Source URL". When that CCK field is not blank I want the site visitor to be able to click on the teaser and go straight to that URL.

I've added the following preprocess function to the .module file for this feature:

```
function earth_news_preprocess_node(&$vars) {
  $path = drupal_lookup_path('alias','node/' . $vars['nid']);
  $url = $vars['node']->field_se_news_source['und'][0]['url'];

  path_save(array($path,$url));
}

```

The path\_save is throwing a fatal error:

```
Only variables can be passed by reference

```

Am I on the right path? What's that error all about?

Thanks.

# Answer
> 0 votes
I think what you should be doing is something along the lines of the following:

```
  $node=$vars['node']; // or however you get the node object

  $source = 'node/' . $node->nid;
  $alias = $node->field_se_news_source['und'][0]['url'];

  if (!empty($alias) {
    $paths=array('source' => $source, 'alias' => $alias);
    path_save($paths);
  }

```

but I would do in it hook\_node\_presave() instead.

Also be aware that I imagine this won't work if the url in your CCK field is not local to the host system.

More info:

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_presave/7

http://api.drupal.org/api/drupal/includes!path.inc/function/path\_save/7

And oh, the error is because you were passing `path_save()` the return value of the `array()` constructor and not an actual variable.

---
Tags: theming
---


# Question
Title: Search template suggestions from a module
I have created a custom search module that integrates with Drupal 7 Search Interface. My module is called `history_search` and in the module I have two files: `history_search.module` and `history_search.info`.

These are the contents of my `history_search.module`:

```
<?php

function history_search_search_info()
{
    return array(
        'title' => 'History',
        'path' => 'history',
        'conditions_callback' => 'history_search_search_conditions_callback',
    );
}

```

When I try to use it, it works correctly: Drupal creates a search tab for me and uses the results data I provide. However, I can't figure out how to get it to use my template suggestion for a single search result. I created a file in my module's folder called `search-result--history_search.tpl.php`, however it doesn't seem to be used when I perform searches in my module. However, if I place this file in my theme, then it suddenly works fine with no problems.

So my question is, how do I get Drupal to use `search-result--history_search.tpl.php` when I place it in my module's folder?

# Answer
> 0 votes
Thanks to the comments from @AlexGill and @Beebee I was able to figure out what's the actual suggestion name for my template file. Here's how I solved it:

```
<?php

function history_search_theme()
{
    return array(
        'search_result__history_search' => array(
            'template' => 'search-result--history_search',
            'path' => drupal_get_path('module', 'history_search'),
            'base hook' => 'search_result',
        ),
    );
}

```

---
Tags: 7, theming, search
---


# Question
Title: how to add html elements inside block and get data when saving
i want to add few html elements call first name and last name,company name in top of user/register page and save that data when user click create account button..,how can i achieve that,i add html elements in block as normal html tags like but dont't kow how to get data...thanks

# Answer
Does it have to be in a block?

If you want to add fields to the registration form and do something with the values when they submit, you really have to add them to the registration form itself, not in a block somewhere nearby.

To do this you can create a custom module that implements a form alter.

For example:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MODULENAME_form_user_register_form_alter(&$form, &$form_state) {
  // Add your fields.
  $form['firstname'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#description' => t("This is help text that will display with this field. you can leave it off if you don't need it."),
    '#required' => TRUE, // Leave this line out if you don't want a required field.
    '#weight' => -10, // This controls the field order. Smaller number is higher up the form.
  );
  $form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
  );
  $form['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company'),
  );

  // Add your own submit handler to save the values.
  $form['#submit'][] = 'MODULENAME_custom_submit_handler';
}

/**
 * Custom submit handler for user register form.
 */
function MODULENAME_custom_submit_handler($form, &$form_state) {
  // Do whatever you need to save the values here.
  // Submitted values are in $form_state['values'] like this.
  $fname = $form_state['values']['first_name'];
  $lname = $form_state['values']['last_name'];
  $company = $form_state['values']['company'];
}

```

Now having said all that, is there some reason you want to do this custom? It is possible to use a module that lets you add fields to the register form, like the profile2 module. That module lets you add profiles (essentially a group of fields, similar to a node) to users, which can also be displayed on the registration form for the user to fill out at that point.

The module handles saving the data for you, along with a lot of other features, like views support.
> 5 votes

# Answer
Just go to the people category on your configuration page , click on account settings and select the the manage fields tab, and create your new fields. You don't need html elements to do that
> 2 votes

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


# Question
Title: Maintaining the integrity of URLs while moving pages between site sections in Drupal 7
Could anyone please tell me how does drupal 7 handle urls when moving or reordering the pages within and between the sections witithin the site. Is it possible to preserve the urls or not?

# Answer
If you are referring to the normal url, like node/3, then the url is always the same.

If you are referring to the path alias, which is the pretty url you can give to a page, or configure to generate automatically with tokens via the pathauto module, then when you move a node in to a different section the alias can change (this depends on how you have the alias generation configured, for example if there is nothing related to the section in the path alias then there will be no affect).

If your alias changes when you change a node, then normally the old path will no longer work and you can end up with people linking to those pages having their links break.

A workaround for this is to use the redirect module.

If you have pathauto and redirect both installed, then on the pathauto settings page you can configure the "Update action" option to create a redirect between the old and the new alias when a node is updated. This will stop incoming links from breaking when you change a node and its alias changes.

I would also recommend configuring the redirect module to delete old redirects if they haven't been used for a period of time (say 4 months for example). This means if no one has used the old path in 4 months then it will delete the redirect as you likely don't need it anymore. Set the period to whatever you feel comfortable with.

I recommend not using this auto-redirect on alias change feature during development if content is likely to change a lot. This is because you end up with a lot of redirects that are not needed and if you change a node so that the alias changes from alias1 to alias2 and then back to alias1 again, you can get errors. If you care to learn more about those errors, see:
> 0 votes

---
Tags: navigation
---


# Question
Title: What may cause "An illegal choice has been detected. Please contact the site administrator"?
When a user goes to create content, usually for a forum the following error is received.

> An illegal choice has been detected. Please contact the site administrator.

The forum topic can still be created however. This doesn't happen if the user is administrator.

The following errors can be seen in error report

```
Type form
Date Wednesday, May 1, 2013 - 12:24
User 222_test
Location
Referrer    /node/add/forum
Message Illegal choice 423 in term_node_tid_depth_1 element.
Severity error
Hostname
Operations

Type form
Date Wednesday, May 1, 2013 - 12:24
User 222_test
Location /node/add
Referrer    /node/add/forum
Message Illegal choice 427 in term_node_tid_depth element.
Severity error
Hostname
Operations

```

# Answer
> 1 votes
I would say that this means that the user has selected term 423 for term\_node\_tid\_depth\_1 and 427 for term\_node\_tid\_depth, but those values are not actually options in that field.

Usually the way this happens if you have custom code that sets the field value to an invalid value, or if it changes the field and removes some of the possible allowed values.

You say it doesn't happen when you are the admin, so I would guess that the admin has access to all the options in the field but other users are just seeing a subset of the field values, but somehow are still setting the field to one of the values they aren't allowed to see.

Do you have any custom code or are using any unusual field or forum related modules?

---
Tags: taxonomy-terms
---


title: Optimized way to use media queries

text:
# Question
Title: Optimized way to use media queries
I'm looking for the best way to use media queries within a drupal theme (based on Zen 5)

The options I've found are :

1. Defining media queries in the info file eg :

```
stylesheets[all][] = styles/base.css
stylesheets[all and (min-width: 480px)][] = styles/480up.css
stylesheets[all and (min-width: 720px)][] = styles/720up.css
stylesheets[all and (min-width: 960px)][] = styles/960up.css

```
2. Include all the css file and wrap all definitions within the media queries in the files
3. Use base.css and use media queries at the end of this file to import others stylesheets.

Of theses three options, which is the lightest? Is there a fourth one?

# Answer
> 4 votes
The second option would be better, because of aggregation.

For the first option, if you turn on aggregation on your site, the files will be bundled by media query. So, in your case, you would have at least 4 bundles, so 4 requests to fetch your site CSS files.

For the 3rd option, the browser will request the imported CSS files seperately, so you lose the benfit of aggregation completely.

If you put the media queries inside the CSS files, they will be aggregated together, resulting in only one bundle. This is better for performance, especially for mobile devices.

---
Tags: theming
---


title: Print base path in html.tpl.php

text:
# Question
Title: Print base path in html.tpl.php
Im trying to print the full path to my theme in my html.tpl.php file. In the following code the 2nd part prints correctly but the first part does nothing.

```
<?php print base_path() . path_to_theme(); ?>

```

# Answer
I assumed my code wasnt working as I was expecting an absolute url but Ive now realized that when Drupal is in the route it just returns a /. So it is in fact working fine.
> 0 votes

# Answer
It should be

```
base_path().drupal_get_path('theme', 'THEME_NAME')

```

Other Examples of path

```
$GLOBALS['base_url'] => http://example.com/drupal
base_path() => /drupal/
request_uri() =>    /drupal/documentation?page=1
request_path() => documentation
current_path() => node/26419

```
> 4 votes

---
Tags: theming, uri
---


# Question
Title: Drupal7 creating breadcrumb from url of custom page template
I have a template file: called: page--movies--movie-details.tpl.php

which make my url: http://mydomain.com/movie/movie-details/

question is: How can i make my own breadcrumb using that url:
My breadcrumb should like this:

ex: Home \> movie \> movie details

how can i do that in drupal7?

thank you.

# Answer
The custom breadcrumbs module can handle adding breadcrumbs to views.

The readme has information on how to use it.

The recommended module for breadcrumbs is path breadcrumbs.
> 1 votes

# Answer
This module might be what you seek. I've tried it when I was trying to solve another issue I had with breadcrumbs, but it sounds to do exactly what you need:
http://drupal.org/project/easy\_breadcrumb
> 0 votes

---
Tags: breadcrumbs
---


# Question
Title: Drush without SSH access on remote server
Following my previous question, I plan to duplicate my website so that I have a production website and a staging site. I am going to have the staging site on a local version on Ubuntu, and it was recommended that I use Drush to keep them synced. Installing Drush locally should be no problem since I will be the full, and only, administrator. However my production site is hosting using shared hosting and the hosting company do not allow access to SSH, I have asked. Is it still possible to use Drush to sync the sites, and if so, how?

If however it is not at all possible, I would appreciate if you could suggest an alternative way of achieving the same thing please.

I'll admit that I'm diving in at the deep end here. I think I pretty much know what it is, however you can't say I'm too familiar with it.

Thanks in advance

# Answer
> 4 votes
Things are pretty rough without shell access. You'd have to do a lot of work to make this function correctly. First, take a look at the implementation of the drush rsync command. You're going to need to build something similar that uses sftp, or whatever your host allows access to, to transfer files.

Next, you're going to want to take a look at the file examples/sync\_via\_http.drush.inc. This shows how you can use the Drush sql-sync command, but use an http GET to fetch your database. Dumping the database and putting it in a location that it can be served up by the web server (securely!) is left as an exercise for the reader. You also have to make sure that your Drush alias records define the 'database' record for your remote site; if you don't, Drush will try to fetch it via a remote ssh call to Drush on the remote system.

Once you have this, you can use your sftp command to push your code to your hosting site, and drush sql-sync to pull your database to your dev site. You'll have to run updatedb manually through the admin interface whenever you push new code.

However, you will find that whatever you think it's going to cost you to switch sites, you'll probably find that the cost is worth it in terms of your time savings.

# Answer
> 1 votes
I have a hosting provider with WebDAV activated and SSH is not activated.

1. On my MAC, I installed drush Drush install on Mac OS
2. I mounted WebDAV to Finder (File Browser)
3. On terminal

```
cd /Volumes/<mywebsite.com>/public_html/

```
4. Finally drush on local and let WebDAV synchronize your file.

```
drush dl views
drush en

```

---

## Warning

My WebDAV and (hosting) do not provide SSL enabled WebDAV. If you do not mind security, **use at your own risk** If you need more secure connection, pay for SSH/SFTP or/and SSL certificate

---
Tags: 7, drush
---


# Question
Title: Moving a div down if a zone is present using jQuery
I'm trying to move a `<div>` down if a zone is present, but I'm having a little trouble targeting the right classes, etc.

```
// See http://jsfiddle.net/xgbzm/.
(function ($) {

  if (!$(this).hasClass('responsive-layout-normal')) {
    if ($('.page .section-header .zone-ticker-wrapper', this).length < 0) {
      $('.qtip .qtip-wrapper', this).css('margin-top', '65px');
    }
  }

})(jQuery);

```

How can I achieve it?

# Answer
At a guess I'd say your problem is context...`$(this)` won't be defined in your current code.

First thing to do is make sure the code runs on document ready so the elements you're targeting actually exist:

```
(function ($) {
  $(function() {
    // ...
  });
})(jQuery);

```

Next you need to handle `$(this)`. In your current context you would need to check the `<body>` tag for that class, e.g.

```
if (!$('body').hasClass('responsive-layout-normal')) {
  // ...
}

```

And finally, since you're using a responsive theme you probably want that code to be responsive, and run when Omega changes its media query. Note that now, since you're binding to the `<body>` tag, and have proper context, `$(this)` will refer to the element you're expecting:

```
(function($) {
  $(function() {
    $('body').bind('responsivelayout', function(e, d) {
      if (!$(this).hasClass('responsive-layout-normal')) {
        // Make changes
      }
      else {
        // Undo changes
      }
    });
  });
})(jQuery);

```
> 1 votes

# Answer
Turns out I had the right answer this whole time. The reason it did not work was simply because the 'qtip' class had a 'display:none' set, effectively hiding it from the source code. Using another class that was visible, solved the issue.

I did try using this method but it didn't really help. Although I am sure that if someone stumbles across a similar issue in the future, this link might help them.

Thank you all for your help :)
> 0 votes

---
Tags: 7, javascript, theming
---


title: EntityFieldQuery with date field

text:
# Question
Title: EntityFieldQuery with date field
I am running the following code, retrieving a list of job openings that will expire in 7 days.

```
$triggerDate = new DateTime();
$triggerDate->add(new DateInterval("P7D"));

$query = new EntityFieldQuery();
$query->entityCondition('entity_type','node')
  ->entityCondition('bundle','job')
  ->propertyCondition('status',1)
  ->fieldCondition('field_expires','value',$triggerDate->format('Y-m-d'),'=');

```

This is returning 0 jobs, even though I have several that will expire in 7 days. For example, one of my job nodes, has the following value

```
[field_expires] => Array
     (
         [und] => Array
             (
                 [0] => Array
                     (
                         [value] => 2013-05-09T00:00:00
                         [timezone] => America/Los_Angeles
                         [timezone_db] => America/Los_Angeles
                         [date_type] => date
                     )

             )

     )

```

When I leave the filter off altogether, the query succeeds and retrieves all items. I've tried many variations of the date format including `Y-m-d\T00:00:00` and `Y-m-d 00:00:00`.

The field is of type: `Date (ISO format)`. What am I doing wrong?

# Answer
> 4 votes
This works perfectly fine:

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type','node')
  ->entityCondition('bundle', 'product_display')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_expires','value', '2013-04-30T14:02Z', '>')
  ->execute();

```

---
Tags: database
---


# Question
Title: Module to view node in a grid layout with the ability to quickly change the reference
I'm looking for a module which allows me to have a grid layout presenting nodes in a certain view mode (like teaser or even a module own one). In the end it should look something like this:

(The picture shows some node references. I didn't prepend all titles, but all blocks should be rendered the same way, except the first one, which should be rendered bigger)

Now I could do this with either views or panels, but I want to add as many blocks as I want and the first one should be rendered differently as the rest. Note that there are pictures in the node which should also be shown in different size.

I already tried it with Mini Panels, but the problem with Mini Panels is, that I can only append one node - and it is a little tricky for end users who should be able to change the node reference quickly.

Is there a good module which comes with such a solution?

# Answer
> 0 votes
Maybe someone is interested in my solution:

I'm using DraggableViews to have some sort of Drag'n'Drop feeling (it's not exactly what I wanted, but good enough. The problem with the first picture was not as hard as I thought. I simply changed the field-template of the view (I'm using *views-view-field--front-view--field-images.tpl.php*) checking if it's the first element, or not:

```
<?php
$image = $row->field_field_images[0]['rendered'];
if ($view->row_index == 0):
  $image['#image_style'] = 'primary';
endif;

print render($image);
?>

```

# Answer
> 2 votes
You don't really need a module - just some css. If you are using the views module to create your html then something like this should suffice:

```
.view-content .views-row {
    display: inline-block;
    margin: 0 20px 10px 0;
    vertical-align: top;
    width: 207px;
    font-size: 0.8em;
}
.view-content .views-row img {
    width: 170px;
}
.view-content .views-row-1 {
    font-size: 1em;
    width: 439px;
}
.view-content .views-row-1 img {
    width: 350px;
}

```

Here is an example in jsfiddle: http://jsfiddle.net/42LHW/3/

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


# Question
Title: How to programmatically delete all values in custom CCK field for a given node?
I'm on Drupal 6, and I have a multiple value CCK field. I need a PHP function to delete all the values in that field so I can later repopulate it. I am currently doing this:

```
if (isset($node->field_received_email[0]['value'])) {
  foreach($node->field_received_email as $key => $value) {
    $node->field_received_email[$key]['value'] = NULL;
  }
}

```

However, sometimes when I later repopulate it, I get Drupal dblog errors like:

> Duplicate entry '16026-133' for key 'PRIMARY' query: INSERT INTO content\_field\_received\_email (vid, nid, delta, field\_received\_email\_value) VALUES (16026, 15888, 133, 'whatever@email.com')

It appears that the primary key is remaining, and so when I go to write data again to the field it gives the duplicate primary key error.

Any suggestions on how to really delete all the values and keys from a multiple value CCK field in a given node so I can later re-write them?

Thanks a lot!

# Answer
Try to unset item

```
if (isset($node->field_received_email[0]['value'])) {
  foreach($node->field_received_email as $key => $value) {
    unset($node->field_received_email[$key]);
  }
}

```
> 5 votes

---
Tags: entities
---


# Question
Title: Module: Extend "Authoring information"-tab and adding new field to it
I'm looking for a way to attach a custom field of my module to "Authoring information"-tab.

Thanks for any hint

# Answer
> 2 votes
Use hook\_form\_alter(), add your form item to `$form['author']` fieldset (see node\_form() function), add your own submit function to `$form['actions']['submit']['#submit']` array (or `$form['#submit']`) and you're good to go! And always remember, Form API Reference is one of your best friends!

---
Tags: nodes, entities
---


title: How can I join content in Drupal

text:
# Question
Title: How can I join content in Drupal
I'm having a little bit of trouble with joining 2 different content types in a view. I'm am using Entities and View modules.

What I have is about 50 satellite offices and each office has a varying number of employees. I have created a content type of "Office" and created a separate content type of "Employee". Using the Entities module, I enter a new employee into the system and assign them to a particular office.

Now, what I want to do is basically build a view where I can look at an office, see it's information (address, etc) and also see a list of employees associated with that office.

I've got the relationships and everything set up so the data pulls over, however, the issue I'm running into is duplication of some fields that I don't want to show twice.

Here's what happens: If Office 1 has two employees, the data returned shows Office 1 twice, each with a different employee. What I want is for Office 1 to show ONCE, with a list of all employees at that office.

I've tried grouping options, but that doesn't work right either.

Any ideas on how to get this formatted the way I need?

# Answer
> 1 votes
Try to exclude the field you're grouping by from display:

---
Tags: nodes, entities
---


# Question
Title: How do I get a new database connection with a new setting?
I want to set the GLOBAL variable `innodb_flush_log_at_trx_commit`, and then run a migration after getting a new connection since changes to a global variable does not affect the current session.

So the raw mysql would go like this...

```
-- set the variable that speeds my migrate up by 40x
SET GLOBAL innodb_flush_log_at_trx_commit=0;
-- reconnect (starts a new mysql db session)
connect;

-- Do the import

-- at the end of the import
SET GLOBAL innodb_flush_log_at_trx_commit=1;
connect;

```

I've not tried anything yet, but I'm interested to see if anyone else has looked at this, and the issues encountered, and the end solution.

# Answer
I like your gutsy move in this regard.

I wrote about changing **innodb\_flush\_log\_at\_trx\_commit** in the DBA StackExchange

I also wrote about tuning InnoDB for better INSERT performance

# EPILOGUE

You have the right idea. You should experiment with this on a Staging DB Server (load data, test drive the setting, kick the tires)

Note the difference between setting **innodb\_flush\_log\_at\_trx\_commit** to 0 and 2

* Setting to 0 : any mysqld process crash can erase the last second of transactions. The log buffer is written out to the log file once per second and the flush to disk operation is performed on the log file, but no writes are done at a transaction commit.
* Setting to 2 : only an operating system crash or a power outage can erase the last second of transactions. The log buffer is written out to the file at each commit, but the flush to disk operation is not performed on it. Before MySQL 5.6.6, the flushing on the log file takes place once per second. Note that the once-per-second flushing is not 100% guaranteed to happen every second, due to process scheduling issues. As of MySQL 5.6.6, flushing frequency is is controlled by innodb\_flush\_log\_at\_timeout instead.

Based on this difference, you have to decide who do you trust flushing data, the Operating System or the mysqld process. Using 0 leans in favor of mysqld. Using 2 seems to be OS oriented.
> 1 votes

---
Tags: 7, migrations, database
---


# Question
Title: Retrieving jsonp data with callback function
I need to call a service to retrieve the available values for a select in a form I am creating. Therefore, I need to do this in the .module file and load the options with an array of items that I received from the service.

I retrieve that results but due to it having a callback function, I cannot seem to iterate through the data to retrieve only certain values from the data.

I have the following.

```
$request = drupal_http_request('http://[local]/TemplateManager/GetRenderingStrategies?Wizard=false&callback=jsonCallback');

```

I get back this.

```
jsonCallback([
{
    "HTMLRenderingStrategyId": 1,
    "IsEnabled": true,
    "CreatedDate": "2013-04-19T10:30:36.563",
    "CreatedBy": 1,
    "UpdatedDate": "2013-04-19T10:30:36.563",
    "UpdatedBy": 1,
    "RowGuid": "19223fcf-45c2-452b-aac6-ba357169ff26",
    "Name": "DEFAULT",
    "FormTemplateView": "/Templates/Default/FormTemplate.cshtml",
    "ManagedChoiceTemplateView": null,
    "NoMatchTemplateView": null,
    "ThankYouTemplateView": null,
    "NoThankYouTemplateView": null,
    "CSSPath": "/Templates/Default/css/Base.css",
    "CrossSellTemplateView": null,
    "CrossSellMaxProgramsToDisplay": null
},
{
    "HTMLRenderingStrategyId": 2,
    "IsEnabled": true,
    "CreatedDate": "2013-04-19T10:30:36.563",
    "CreatedBy": 1,
    "UpdatedDate": "2013-04-19T10:30:36.563",
    "UpdatedBy": 1,
    "RowGuid": "2ea1ecb7-0281-4361-87ee-d4cfe12c9b0c",
    "Name": "EMD",
    "FormTemplateView": "/Templates/EMD/FormTemplate.cshtml",
    "ManagedChoiceTemplateView": null,
    "NoMatchTemplateView": null,
    "ThankYouTemplateView": null,
    "NoThankYouTemplateView": null,
    "CSSPath": "/Templates/EMD/css/Base.css",
    "CrossSellTemplateView": null,
    "CrossSellMaxProgramsToDisplay": null
},
{
    "HTMLRenderingStrategyId": 3,
    "IsEnabled": true,
    "CreatedDate": "2013-04-19T10:30:36.563",
    "CreatedBy": 1,
    "UpdatedDate": "2013-04-19T10:30:36.563",
    "UpdatedBy": 1,
    "RowGuid": "e2d7ed2e-7ed7-4d2e-aecb-0a589c7ad338",
    "Name": "ELEARNERS",
    "FormTemplateView": "/Templates/eLearners/FormTemplate.cshtml",
    "ManagedChoiceTemplateView": null,
    "NoMatchTemplateView": null,
    "ThankYouTemplateView": null,
    "NoThankYouTemplateView": null,
    "CSSPath": "/Templates/eLearners/css/Base.css",
    "CrossSellTemplateView": "/Templates/eLearners/CrossSellTemplate.cshtml",
    "CrossSellMaxProgramsToDisplay": 10
}]);

```

What is my next step to pull out only the "Name" from the result set?

I am at a loss here. I tried looking for the answer and it seems all the jsonp calls are done in javascript/jQuery and that doesn't really suit me.

If you feel I am doing this incorrectly, please let me know. I have never worked with jsonp or json and Drupal for that matter.

# Answer
You can create a custom function called `jsonp_decode` with one argument to convert **JSONP** format to **JSON** format and return decoded **JSON**

```
function jsonp_decode($jsonp) {
  $jsonp = preg_replace('/^.*?\(/', "", $jsonp);
  $jsonp = preg_replace('/\);\s*$/', "", $jsonp);
  return drupal_json_decode($jsonp);
}

```

Then you can pull the "Name" from the result set as the following code:

```
$request = drupal_http_request('http://[local]/TemplateManager/GetRenderingStrategies?Wizard=false&callback=jsonCallback');

$names = array();

$items = jsonp_decode($request);

foreach($items as $item) {
  $names[] = $item['Name'];
}

var_dump($names);

```
> 2 votes

---
Tags: 8
---


# Question
Title: Exposed Form Block results on another Panel page
Using Drupal 7.16 and Panels 7.x-3.3: I have created a View and exposed it's form in a Block. Then I have created two Panel Pages:

* `/search` which displays the Exposed Form Block
* `/results` which displays the View's Content Pane

Now whenever I submit the Exposed Form Block, it redirects to the root page (`/`). I am aware of the "Inherit Path" setting, but that changes nothing to me. As far as I understand, this setting isn't what I'm looking for, anyway.

How do I get the Exposed Form Block to submit its query to the page where the corresponding View Content Pane is placed? Is modifying the code the only way to achieve this?

# Answer
> 0 votes
In my theme's template.php I did the following which seemed to work

```
/**
 * Implements hook_form_alter()
 */
function cmfzen_form_alter(&$form, &$form_state, $form_id) {

  // change the main search form
  // see http://drupal.stackexchange.com/questions/28404/easiest-way-to-add-x-webkit-speech-to-the-search-blocks-input-element
  // see http://adaptivethemes.com/html5-placeholder-text-for-your-drupal-7-search-field
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-site-search-page"){
    // dsm($form);
    // redirect to a panels page with an embedded search_api view with facets.
    $form['#action']='hello';
    $form['site-search']['#type'] = 'searchfield';
    $form['site-search']['#attributes'] = array(
      'class' => array('search-site'),
      'placeholder' => t("I'm looking for..."),
      'speech x-webkit-speech spellcheck' => 'false',
      );
    // change form submit button
    //$form['submit']['#type'] = 'button';
    //$form['submit']['#value'] = '<span class="icon-untitled-8"></span>';
    $form['submit']['#attributes'] = array('class' => array('search-button'));
  }
}

```

Notice the part `$form['#action']='hello';` ? Make sure your using the right formid and also change "hello" to whatever page you want the results to go to

Maybe that will lead you in the right direction?

---
Tags: views, panels
---