# Question
Title: Create form for image selection from the content
I have a content type with title and image field in it. Now, I want to show a form to the user which will show the image thumbnail, title and a checkbox below each image with the value of respective nid. So that user can select the image they like and submit it. Which will eventually take the nid and do some actions depending on the selected nid.

My question is how I will create such form from that content.

# Answer
> 0 votes
Like most things in Drupal there are a couple of different ways you could do this. A quick look into the challenge, reveals the Webform View module. Basically, it allows you to pull in a viw (list of your nodes) as selectable items, for a webform. Webforms are good if all you want to do is store (and email of course) the submitted values of a form for manually processing later. Webforms are typically used for feedback, survey, contact forms.

If you need to do something a little more flexible with the submitted values, alternatively you could use the Views Bulk Operations (VBO) module (add-on for Views) which provides this kind of functionality plus a lot more if you need it for other purposes too.

Basically, you would create a view listing your content items with the fields you want to display, and then add a "Bulk operations: Content" field, and select the "Pass ids as arguments to a page", and then specify the path you want the arguments sent to. The path could then be defined in your custom drupal module, and you could use the $arguments = func\_get\_args(); to get all the arguments sent through. e.g. in a sandbox\_test.module

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

  $items['test-submit'] = array(
    'title' => 'VBO Test Submission handler',
    'page callback' => 'sandbox_test_vbo_test',
    'access callback' => TRUE,
  );

  return $items;
}

function sandbox_test_vbo_test() {
  $output = '';

  $args = func_get_args();
  if (is_string($args[0])) {
    $items = explode(",", $args[0]);
    $output .= '<pre>' . print_r($items, true) . '</pre>';
  }
  else {
    $output .= 'None found';
  }

  return $output;
}

```

---
Tags: forms, media, nodes
---


# Question
Title: How to trim text fields entered in the node automatically
Just now i've discovered that my operator was entering many times organization name prefixed/suffixed with a space. For example " Microsoft" or "Microsoft ".

That is causing problem when this value is being passed as contextual arguments in the views with this space character making a difference.

I need help as to how I can trim already fed in text and secondly store only trimmed version of text.

I could only find this useful page about this issue.

# Answer
> 3 votes
To correct all those values entered into the database already, I'd suggest doing a mysql trim on those values and resetting them. Make sure you backup the tables first of course, but something like this should do it (if your field name is field\_text\_test):

```
UPDATE field_data_field_text_test SET field_text_test_value = TRIM(field_text_test_value);
UPDATE field_revision_field_text_test SET field_text_test_value = TRIM(field_text_test_value);

```

After you've run those statements, do a flush all caches on your drupal site.

And then to avoid this happening again, you could use the Form API Validation module which adds a trim filter on fields.

---
Tags: 7, entities
---


# Question
Title: Need to display fields in a different format
I have following fields in my content type:

Title: \[some value\] Year: \[2011,2012,2013,2014,2014,2016\] Volume: \[01,02,03,04,05\] Issue: \[1,2,3,4,5\] Description: \[some text\]

## And I want a output display like the below Format.

OUTPUT:

2013 Volume 01: Issue 1, Issue 2

2012 Volume 01: Issue 1, Issue 2, Issue 3

2011 Volume 01: Issue 1, Issue 2, Issue 3

---

All Issues will be hyperlinked. If I click 'Issue 1' under year '2013' it should take me to a page where all posts having value 2013, Volume 01, Issue 1 should be displayed.

How this is done using Views in Drupal 7?

Thanks

# Answer
> 0 votes
For the above implementation

create a view with url issue/arg(1)/arg(2)/arg(3)

where arg(1) = year arg(2) = volume arg(3) = issue

like above u can pass argument

then by using contextual filter u can filter the view content and show the specific issue u want to.

# Answer
> 0 votes
create a page type view

then under **PAGE SETTINGS** tab there is path option add **path** as issue/%/%/%

then by using contextual filter u can filter the view content and show the specific issue u want to.

while hitting the url u need to use issue/year(num)/volume(num)/issue(num)

---
Tags: views
---


# Question
Title: Migrate module. Users from D6 to D7 with preserved UIDs
I'm trying to migrate a Drupal 6 site to a totally new implementation of Drupal 7.

I'm using the migrate module, and I am able to successfully migrate users and passwords, as well as their roles, but the users UIDs is not being maintained.

I believe that the issue is that UIDs must be explicitly set on the user object before saving it, and migrate is not doing that for me.

http://drupal.org/node/712966

Any tips on how I can do that? I need my UIDs on Drupal 7 to be exactly the same as Drupal 6!

# Answer
For migrating to Drupal 7, it's much simpler:

```
// Pass the old uid through
$this->addFieldMapping('uid', 'uid');
// Tell user_save to create a new account with the given uid (otherwise it sees the
// uid and assumes you're updating an account).
$this->addFieldMapping('is_new')
     ->defaultvalue(1);

```
> 6 votes

# Answer
Cribbing from this

> 1. Delete the original UID column in the destination users table
> 2. Create a new UID column (w/o primary and auto increment settings)
> 3. Map the source UID to the UID column
> 4. Perform the import
> 5. Add primary and auto increment settings to the UID column

If you need UIDs to be the same there is a chance that you are misusing them. There are a few cases where it matters (theme overrides perhaps) but in most cases it shouldn't matter.
> 2 votes

---
Tags: migrations
---


# Question
Title: Passing object by reference in form element of type 'value'
Given that in PHP5 objects are said to be passed by reference automatically, are there reasons why one must not pass an object through forms ('programmatically')? I hope to create acceptable persistence through using `$form_state` for use with AJAX or form submit handlers. I've tried the following and it works (but I don't want to be doing something in poor practice/ that might get blocked).

```
$foo = new stdClass();
$foo->bar = 'foobar';

$form['foo-bar'] = array(
    '#type' => 'value',
    '#value' => $foo,
);

```

Which then appears in $form\_state when the following element triggers an AJAX request

```
$form['numbers_required'] = array(
    '#type' => 'textfield',
    '#title' => t('Numbers needed'),
    '#ajax' => array(
        'callback' => 'numbers_required_callback',
        'wrapper' => 'numbers_remaining',
    ),
);

```

Furthermore, the following passage from the drupal\_build\_form() documentation suggests I might have to set the form 'cache' property to TRUE. Perhaps for others this is the case if they aren't using an AJAX callback. Given that I am, I assume I can ignore this, but thought others might find it useful to know.

> cache: If set to TRUE the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form\_state are built from scratch during each of these page requests. Often, it is necessary or desired to persist the $form and $form\_state variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. A prominent example is an Ajax-enabled form, in which ajax\_process\_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.) Note that the persistence of $form and $form\_state happens automatically for (multi-step) forms having the 'rebuild' flag set, regardless of the value for 'cache'.

# Answer
> 1 votes
Objects are 'passed by reference' in the context of being passed to a function in a *single page request*.

Once the page has reloaded (e.g. when you submit your form), the memory for the original object is freed and it's impossible to maintain a reference to it (at least with standard PHP to the best of my knowledge).

You can keep a *copy* of the object (which is what Drupal does), and instantiate a version of it on the next page, one that has exactly the same characteristics as the original even, but it's not a reference to it.

What you're doing is absolutely fine, but if you're worried about changes being made to the object after it's been attached to a form, but before it's been submitted, then you should keep hold of the object's identifier instead, and use whatever helper function is available to re-load that object in the submission process. That would be safest I think.

But if your class is dumb, and doesn't have DB persistence/unique identifiers/something that's going to be changed by some other part of the system, then just add it as a value as you're doing already.

---
Tags: forms, ajax, caching
---


# Question
Title: what is a reasonable value for max_allowed_packet for Drupal 7 with moderate traffic？
I need to know some ball park number for this variable for my drupal 7 site. I recently got a "drupal "PDOException: SQLSTATE\[08S01\]: Communication link failure: 1153" error. I am a newbie to mysql and am using shared hosting. I probably need to ask the administrator to do it for me.

Thanks in advance.

# Answer
> 14 votes
I saw an interesting answer to a question about the biggest BLOB you may have. Here is the statement I saw in ServerFault : **innodb\_log\_file\_size and innodb\_log\_buffer\_size combined must be larger than ten times your biggest blob object if you have a lot of large ones**.

Based on that ServerFault post from **Nils-Anders Nøttseter**, you should query the table and find out which BLOB is the biggest, multiply that number by 11 or more, and use that answer as the **max\_allowed\_packet** going forward.

It's funny that **I addressed another question where I suggested sizing the max\_allowed packet to hopefully solve the issue**.

# CAVEAT

According to the Book

Here is what Page 99 Paragraphs 1-3 says about MySQL Packets:

> MySQL network communication code was written under the assumption that queries are always reasonably short, and therefore can be sent to and processed by the server in one chunk, which is called a *packet* in MySQL terminology. The server allocates the memory for a temporary buffer to store the packet, and it requests enough to fit it entirely. This architecture requires a precaution to avoid having the server run out of memory---a cap on the size of the packet, which this option accomplishes.
>
> The code of interest in relation to this option is found in **sql/net\_serv.cc**. Take a look at **my\_net\_read()**, then follow the call to **my\_real\_read()** and pay particular attention to **net\_realloc()**.
>
> This variable also limits the length of a result of many string functons. See **sql/field.cc** and **sql/intem\_strfunc.cc** for details.

Knowing this about MySQL Packets allows a DBA to size them up to accommodate multiple BLOBs inside one MySQL Packet, even if they are obnoxiously large.

Regarding your situation, you should find out what is the biggest BLOB in your database, multiple that number by 11 and set your **max\_allowed\_packet** to that number. You should be able to set it for the server without a mysql restart (Personally, I would set it 256M because it would address other problems regarding migration and replication, which is beyond the scope of this forum). To set it to 256M for your database for all incoming connections, please run this:

```
SET GLOBAL max_allowed_packet = 1024 * 1024 * 256;

```

Afterwards, add this setting to my.cnf under the `[mysqld]` section:

```
[mysqld]
max_allowed_packet = 256M

```

# Answer
> 4 votes
Taken from Drupal's Database Server Requirements page:

> It may be necessary to set the system variable max\_allowed\_packet to at least 16M. Some inexpensive hosting plans set this value too low (the MySQL default is only 1M). In that case, you may need to choose a better hosting plan. A value of 1M may be sufficient for Drupal 5.

Should be fine for a site on shared hosting.

# Answer
> 2 votes
It can be a little tricky to set `max_allowed_packet`. I have yet to come across a method to calculate out that value. Typically, I run into it when trying to restore a database snapshot that includes rows from the `{cache}` tables.

When I have this problem, I will pick a value between 4M and 8M. I keep bumping up the value until it stops. However, I don't know if a shared host will change this value for you.

---
Tags: database
---


# Question
Title: private file downloads don't work with IE8 only when using hook_file_download
I am trying to allow files that are within the `/sites/default/files/private/` directory to available to users with correct role and this is working correctly within all browsers (including IE9) except for the IE8 browser. It does not appear to be a particular file type since it does not work with either .pdf's or .doc's extension. It their something special that I need to do to the "mime type" so that IE8 will successfully download these files? I have listed below `hook_file_download` which determines when a requested file download is allowed based on a combination of the page `$url` and the requesting users role and I highlighted in bold the bottom of the function where it determines the mime type that is returned.

```
function atf_retirees_file_download($uri) {
  $user = $GLOBALS['user'];
  $roles = $user->roles;
  $pos_inside_atf_alias = stripos($uri, '/inside-atf/');
  $pos_nibin_alias = stripos($uri, '/nibin-user-area/');
  if (($pos_inside_atf_alias === false && $pos_nibin_alias === false) || ($pos_inside_atf_alias !== false && !(in_array('ATF Retirees', $roles) || in_array('administrator', $roles))) || ($pos_nibin_alias !== false && !(in_array('NIBIN User Area', $roles) || in_array('administrator', $roles)))) {
    return -1;
  } else {
    **$mime_type = file_get_mimetype($uri);
    return array('Content-Type' => $mime_type);**
  }
}

```

# Answer
I found that if I added "'Cache-Control' =\> 'private, must-revalidate'" to the returned array within hook\_file\_download that the file also downloads for IE8 (see below section).

```
$mime_type = file_get_mimetype($uri);
return array('Content-Type' => $mime_type, 'Cache-Control' => 'private, must-revalidate');

```
> 0 votes

---
Tags: files
---


title: Checkout settings are ignored

text:
# Question
Title: Checkout settings are ignored
I have configurations on store\>configuration\>completion messages. But they are not reflecting on the site. For example I have set the checkout page as a node I created but it's still using the default checkout page. I have cleared all the cache. What am I missing?

# Answer
> 0 votes
AFAIK the checkout page is dynamically generated by Ubercart, you cannot create a node for it. You can theme the dynamically generated page or alter it through custom modules if needed, see several very helpful Ubercart tutorials here: https://drupal.org/project/ubercart

---
Tags: ubercart
---


# Question
Title: Writing to a specific or new element in a multi-value custom field
We're trying to key track of software license keys issued to a specific user in Drupal 7. We've created a custom user field called "field\_key" with unlimited values. We'd like to add a new element to field\_key every time a new license is issued, and save the new key into the new element.

As expected, the following code saves our new key into the first element of the array every time, overwriting the original:

```
$edit['field_key'][LANGUAGE_NONE][0]['value'] = $key_save;
user_save($account, $edit);

```

If we remove the index value, changing \[0\] to \[\], what I thought should happen was that the index would be incremented and we'd write to the next element.

```
$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);

```

That ends up behaving exactly like the first example using \[0\], overwriting the original.

If I force the index (delta) value, using \[1\], for example, the result is the same. This occurs even if I create a new empty element in the user GUI. I can add additional elements and populate them in the GUI. If I do this and have, say, 5 keys listed in the user GUI, the next time we run the code using \[\], \[0\] or \[5\], the result is that all of the original elements are deleted, the field is reduced to a single element, with the new value overwriting the original.

I obviously have the command syntax wrong here. Any tips?

# Answer
You're nearly spot on, the only problem is whatever field array you put in `$edit` will overwrite the array that's in there now; no merging happens behind the scenes. This is probably the correct behaviour as you should be able to overwrite the field completely if you need to.

At the moment each time you use

```
$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);

```

The field is being re-initialised as whatever's in `$edit['field_key']`, i.e. a single element.

To append to the array you could do something like this:

```
$field_items = $account->field_key;
if (!is_array($field_items)) {
  $field_items = array();
}

$field_items[LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, array('field_key' => $field_items));

```
> 2 votes

---
Tags: entities
---


title: Theming Node Edit Forms

text:
# Question
Title: Theming Node Edit Forms
I'm having an issue with theming our node edit forms. We are converting a Drupal 6 theme to Drupal 7 and its causing a lot of problems.

In our template.php we have

```
function dupublic_theme($existing, $type, $theme, $path) {
    return array(
            'page_node_form' => array(
                    'arguments' => array('form' => NULL),
                    'template' => 'page-node-form',
                    'render_element' => 'form',
            ),
    );
}

```

This successfully points Drupal at 'page-node-form.tpl.php'

Our goal is to pull out some fields into labeled areas to make our editor's job easier. We had a more complex layout, but I've simplified it for the following example. In page-node-form.tpl.php I have the following:

```
<div class='title'>
    <?php print drupal_render($form['title']);?>
</div>
<div id='custom-form'>
    <?php print drupal_render_children($form); ?>
</div>

```

This, however, does not work. `$form` does not appear to exist, and `dpm($form);` displays as an empty array. We do not get any form fields *at all* \- unless I remove everything from the tpl file, then I get some sort of default form display, which doesn't make sense. If the tpl file is empty no form should be displayed, but everything I am reading states that `drupal_render($form['field'])` and `drupal_render_children($form)` should work! They aren't!

This is what is rendered on page load:

```
<form class="node-form node-page-form" action="/node/5/edit" method="post" id="page-node-form" accept-charset="UTF-8" data-thmr="thmr_33">
    <div>
        <div class="title" data-thmr="thmr_32"></div>
        <div id="custom-form" data-thmr="thmr_32"></div>
    </div>
</form>

```

As you can see, no form fields!

# Answer
In your `template.php` the hook\_theme implementation should look like that:

```
function dupublic_theme($existing, $type, $theme, $path) {
  return array(
    'page_node_form' => array(
      'template' => 'page-node-form',
      'render element' => 'form',
    ),
  );
}

```

Notice that in the return array `'render element'` key is without underscore, and there is no `'arguments'` key in Drupal 7 version of `hook_theme()`. It is replaced by `'variables'` key, but the documentation states that:

> Each information array must contain either a 'variables' element or a 'render element' element, but not both. Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element.

Another point that I notice is, that you used in your `page-node-form.tpl.php` file statements like:

```
<?php print drupal_render($form['title']);?>

```

I prefer to print the elements like that, and recommend you to do so:

```
<?php print render($form['title']);?>

```

It's a new function in Drupal 7 and it calls `drupal_render()` but first checks if the passed element is an array and also calls `show()` function if the element is set hidden.
> 4 votes

---
Tags: 7, nodes, theming
---


# Question
Title: Garbage values in From: in the email sent from Webform
I find some garbage values in the from field of email sent from contact us page in webmail(as in the image From= field below in the top left in which "F" is cut-off by mistake). I've configured correctly as we do in D6.

I've also sent email from my webmail account from the same email account and it's ok.

This site is the latest version( 1 month old only).

Here I'm pasting what is seen in the image in text:

From: =?UTF-8?B?Ij0/VVRGLTg/Qj9RV1J0YVhOemFXOXVJRU52ZFhKelpYTWdTVzVrYVdFaElPQ2s=?=

This snapshot is from Thunderbird email client:

Looks like it is appearing from this(snippet from the email headers ):

........ X-Mailer: Drupal Webform (PHP/5.3.23) From: =?UTF-8?B?Ij0/VVRGLTg/Qj9RV1J0YVhOemFXOXVJRU52ZFhKelpYTWdTVzVrYVdFaElPQ2s=?= =?UTF-8?B?cXVDbGplQ2tzT0NrdGVDbGgrQ2t0aURncEtvPT89CiA9P1VURi04P0I/NEtTKzQ=?= =?UTF-8?B?S1NnNEtXTjRLU3Y0S1NWNEtXTjRLU3c0S1N1SU9Da3JlQ2t2dUNrc09Da3BDRGc=?= =?UTF-8?B?cEs3Z3BZZmdwSUk9Pz0iIDxjb250YWN0dXNAYWRtaXNzaW9uY291cnNlcy5jb20=?= =?UTF-8?B?Pg==?=

I've Googled too but did not find any similar issue anywhere else.

**Am I missing anything?**

# Answer
If you fill out the form and submit it does your message contain similar encoded data in the from field?

If not, then it's likely these are spam submissions.

Try adding Spamicide and/or reCAPTCHA to filter these out.
> 1 votes

---
Tags: 7, emails
---


title: Take action on first vote only

text:
# Question
Title: Take action on first vote only
I'm using Drupal 7 with the FiveStar module to let users vote on a certain node type. When the user votes, I have a workflow rule that grants them some points to reward them for casting their vote.

The problem I'm running into is that if the user votes more than once on a given node, they are granted points again, each time they vote. There is currently no filter to check that they have already voted before awarding the points.

I could use some help building a workflow rule filter that checks to make sure the user has not already voted on the particular node.

Conceptually I would like to query the votingapi table for any records with the given node ID and given user ID and pass only if zero records are returned. But not sure how to do this in Drupal. Trying to avoid hard-coding a query too.

Thanks BH

# Answer
No need to hardcode a query. The voting api module provides some helper function for this.

The function you need is `votingapi_select_votes($criteria = array(), $limit = 0)`

The `$criteria` parameter takes a decent amount of options.

Here are the options:

```
$criteria['vote_id']  (If this is set, all other keys are skipped)
$criteria['entity_id']
$criteria['entity_type']
$criteria['value_type']
$criteria['tag']
$criteria['uid']
$criteria['vote_source']
$criteria['timestamp']   (If this is set, records with timestamps
                          GREATER THAN the set value will be selected.)

```

In your case you really want to pass in the 'entity\_id', 'entity\_type' and 'uid' to check if the user has voted in that particular content item before awarding him points.

This is the same way we prevent a user from voting multiple times in the same item with Fivestar.

Hope this helps.
> 2 votes

# Answer
Kind of a weird work around, but you could have a taxonomy vocabulary that adds a term every time a node of whatever type of content is being voted on is created, then when a user votes for a node, it adds the title of the node (or nid?) to a hidden field on their account that lists taxonomy terms from that vocabulary you created.

Then add a condition to your rule that says, if they have this nid or title in their hidden taxonomy field, don't give them points, or subtract the added points, however you want to work it.

It's definitely not ideal, but if you have knowledge of Rules then this is an easy work around for you.
> 0 votes

---
Tags: rating
---


# Question
Title: Create a CSV file dump/feed whenever item of Content Type A is created
I need to create a CSV dump/feed whenever a new item of "Content Type A" is created, with only that new item's info in the CSV. How can this be accomplished? For example, if 100 new items of "Content Type A" were created today, there would be 100 separate CSV files with the field values for each of those content items.

Thanks!

# Answer
> 1 votes
Look at Views Data Export. It can create a CSV from Node content.

It sounds like you need this to somehow be recurring over time ... this is a tall order and so I wont be providing much code, but will outline a possible solution:

* Implement hook\_cron\_queue\_info(). This is a cron task that runs off of a custom Queue. You can insert a `NID` every time a node is created into a custom queue you've created named `MyCSVQueue`. Every time a node is created it gets added to this queue -- when you process the queue you create individual csv files.
* Use either hook\_node\_insert or Rules to place the `NID` into the work queue.
* In your queue worker function you pass the `NID` to a custom view that uses a contextual filter to load the `NID`. Or, you may be able to use node\_export to create the CSV data as well. You then simply use the Drupal File API and file\_save() to store the csv file somewhere in your public/private drupal filesystem.

If the default Cron options of drupal dont suite your needs look at Ultimate Cron

**EDIT**

A slightly easier alternative:

Use:

* Use either hook\_node\_insert or Rules to run a snippet of custom PHP code. Simply create a file directory using the File API in public files as: `%files/csv_node_exports/MM-DD-YYYY`. Your snippet can create the directory if it doesnt exist today yet.
* then just export the node data to a CSV file. You may or may not have a `NID` yet ... you could always update the filename after the fact to reflect the actual `NID` assigned to the node.

---
Tags: 7, feeds
---


# Question
Title: Do I need hook_update_N if there are no database changes?
I wrote a little module that provides a form and does some special processing of the submission. There are no database tables involved. If I change the form or processing, how do I code the update? Do I still use hook\_update\_N if the module update doesn't affect the database?

Thanks!

# Answer
> 6 votes
If the changes are just code, (not db schema changes, content changes, variable changes, data changes in general), then you don't need an update hook, no.

Basic rule of thumb: will your code updates break anything for existing or new users? If not, you don't need an update hook.

---
Tags: updating
---


# Question
Title: How can I use the Add Product form as content in the main menu?
I am using Drupal Commerce to add products to my site. I would like to use the Add Products form as content in the main menu to make it more user-friendly to edit. How can I do that?

# Answer
*Admin \> Structure \> Menus \> Main Menu \> Add link*

* Title: Add product
* Path: admin/commerce/products/add/product

Keep in mind, that is for admins to create backend products for the inventory, not front end product displays.

It will also only be generated for admins with the relevant permissions.

To add a link for creating a frontend product display, the path would be something like

* node/add/product-display
> 3 votes

---
Tags: commerce
---


# Question
Title: Can a custom module be used to assign permissions associated with a different module?
Drupal 7. I'm using a contrib module that has one user permission associated with it. Enabling the module assigns that permission to only the "Administratror" role. I'd like to find a way of using a custom module to also assign the permission to a custom role I've created.

So far, I have within my custom module a function that runs when the contrib module is enabled.

```
function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module' => TRUE,
      ));
    }
  }
}

```

But it results in an error like this (output from Drush):

> WD php: PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 19 role\_permission.module may not be NULL: INSERT INTO {role\_permission} (rid, permission, \[error\] module) VALUES (?, ?, ?); Array ( \[0\] =\> 5 \[1\] =\> 1 \[2\] =\> ) in user\_role\_grant\_permissions() (line 3076 of /var/www/d7/modules/user/user.module). PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 19 role\_permission.module may not be NULL: INSERT INTO {role\_permission} (rid, permission, module) VALUES (?, ?, ?); Array ( \[0\] =\> 5 \[1\] =\> 1 \[2\] =\> ) in user\_role\_grant\_permissions() (line 3076 of /var/www/d7/modules/user/user.module). Drush command terminated abnormally due to an unrecoverable error.
> \[error\]

Looking at the table structure that third value \[2\] that's blank is supposed to be the name of the contrib module associated with the permission.

I think the problem is something along the lines of either the permission doesn't exist yet at that point in the execution, or maybe it's a security safeguard that prevents custom code from assigning permissions associated with separate modules. Either way I'd appreciate someone pointing me in the right direction with this.

# Answer
There are hooks\* to revoke or change permissions so there is no need to set `TRUE` or `FALSE` in your snippet.

Try this:

```
function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module',
      ));
    }
  }
}

```

In this call, you are setting the array's **value** to the permission name -- Not the key.

\*: `user_role_change_permissions()` and `user_role_revoke_permissions()`
> 2 votes

---
Tags: 7, users
---


# Question
Title: How to pass custom variables in theme_links($variables) function
I am new to Drupal. I am currently learning modifying the theme with a sub theme. For that I have created and enabled the sub theme called `ntheme` with base theme `Bartik` . Now suppose I want to pass a custom `css class` to `function ntheme_theme_links($variables)` ? I am basically trying to edit my `menu`. Also let me know if my approach is wrong. Criticisms accepted !

# Answer
First, if you want to implement a `hook`, `theme`, or `template` function you replace the prefix with your theme or module name, not prepend it.

WRONG: `function ntheme_theme_links($variables)`

CORRECT: `function ntheme_links($variables)`

To add/edit the variables you need to implement a preprocess function like:

```
function ntheme_preprocess_links(&$variables) {
  $variables['your_custom_variable'] = 'your custom value';
}

```
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How to check the modules installed date?
How to check which modules was installed on what date? I am using Drupal 6. I can not find any answer in Google.

# Answer
> 1 votes
You can't have that information with default core and contrib module.

You can get the time module upload on your server by checking last modify time of module file.

If you realy want to have module install information, you should create a patch that change the module\_enable function on includes/module.inc file.

---
Tags: 6
---


# Question
Title: Some feedback please on my hook_search_execute function?
I'm following along with Pro Drupal 7 Development by Apress (page 321) and using it as a guide to create a module that searches a legacy database of pages I've yet to import into a drupal install. I'm also using the API as a guide as well.

Everything works except for the number of results returned by dynamic query. What happens is, despite having PagerDefault and using a limit of 10, only 1 item shows up on the page. I can switch the number to any number and it's still 1.

I know for a fact there are 240 items that should be returned. And, indeed my pager list 24 pages (24 pages of 10 results). Again, however, there is only 1 result per page for a total of 24 results.

Here is my function:

```
function searchharvest_search_execute($keys = NULL) {

    // Set up and execute the query
    $query = db_select('search_index', 'i')->extend('SearchQuery')->extend('PagerDefault');

    $query->join('url_data', 'ud', 'ud.id = i.sid');
    $query->searchExpression($keys, 'searchharvest');

    //If there weren't any results return a blank result set
    if(!$query->executeFirstPass()){
        return array();
    }

    //If the first pass returned at least 1 record execute the search
    $found = $query->limit(10)->execute();

    //dsm($query);
    print_r($query->__toString());
    //Create the search results output
    foreach($found as $item){
        //dsm($item);
        //get found items from db
        $note = db_query("SELECT url, stripped_html from url_data where id = :sid",
                array(':sid' => $item->sid))->fetchObject();

        $results[] = array(
            'link' => $note->url,
            'type' => t('searchharvest'),
            'title' => 'my title ' .$item->calculated_score,
            'score' => $item->calculated_score,
            'snippet' => search_excerpt($keys, $note->stripped_html),
        );

        return $results;
    }

```

Thoughts on where the error is? Here is a photo as well with the query 'print\_r' 'ed at the top

# Answer
The `return $results` was inside the `foreach` loop, which stopped the iteration, hence only 1 result.
> 0 votes

---
Tags: 7, search
---


title: Fatal error with the tagadelic module

text:
# Question
Title: Fatal error with the tagadelic module
I have this error after the installation of the tagadelic 7.x-2.x-dev module:

> Fatal error: Call to undefined function tagadelic\_get\_weighted\_tags() in /home/www/2374fcf941c82d5986ed6d27587b81e0/web/sites/all/modules/cumulus/cumulus.module on line 120

How can I recover my site?

# Answer
> 1 votes
Log in to your database panel (for example PHPMyAdmin) and run following query:

```
UPDATE system SET status='0' WHERE name='tagadelic';

```

Additionally, if you are using Drupal 7, run:

```
DELETE FROM cache_bootstrap WHERE cid='system_list';

```

After then you can uninstall problematic module via administration panel.

# Answer
> 0 votes
had the same problem with tagadelic module, and cumulus module, and i use drupal 7.x. I copyed the code from http://www.startel.kz/sites/all/modules/tagadelic/tagadelic.module , for the tagadelic file, did wonders works great.

---
Tags: 7
---


# Question
Title: content type or normal er table, that is the question
I was wondering, when should a drupal developer use normal er table instead a new content type? Is it never? When expected node entries reaches 100 000? i googled it and i didn't find any good answer.

selecting from custom content type with number of fields is very time consuming, because all the join-s. If you have 5-10 content types, each with 10 fields, and expect a lot of nodes, is then the right time to forget about content type?

What are your experiences in this matter?

# Answer
> 2 votes
If you are using Drupal 7, instead of using plain custom tables, use a custom entity type, this is really easy to do with Entity API This gives you basic integration with Views and some other modules such as Rules 'out of the box', and customisation is very easy to handle.

I do not see entities having much overhead above a plain database table when the entities are not fieldable. I have worked on a site with millions of rows of data, which is all available as entities, and we load several thousand of them at a time when necessary, this does require a memory limit larger than 128MB, but I haven't seen memory usage go over 256MB while paginating a thousand or so entities at a time out of the possible millions. (Bear in mind though the entities are not fieldable, and we are using APC which does reduce memory usage.)

You can then also use the full power of entity\_metadata\_wrapper(), which is really awesome, and simplifies code.

Basicly, entities give you the benefits of a content type, without the overhead of revisions or comments. In fact, nodes are entities, so are taxonomy vocabularies and taxonomy terms.

It is definitely a best practice to use entity API to access entities as this allows all the proper hooks to be run, such as clearing the necessary data from entity cache. However, you are not forced to always use the Entity API to access the database entity rows, but do be aware that there are extra risks and gotcha's attached to this.

# Answer
> 1 votes
It's a judgement call, really. If you need nodes, go nodes. Hundreds of them on page with thousands hits a day can be pretty OK if your hosting company is willing to help you fine tune your database. joins are not so costly if query planner works at it's best, and most of your content should sit in Boost cache anyway, before you start to worry. Caching in RAM is also a good idea.

On the other hand, if you need to record set of data that's not exactly a content, go custom table. No need to have editable fields in a log, for example.

If you will go custom table for content, over months and years you'll be missing some stuff that's given for nodes. So you will implement workarounds, reinventing the wheel. And you risk ending up with something just as complicated as core nodes, but unsupported and not versatile.

---
Tags: nodes, database, theming
---


title: Drush pm-update needs a module?

text:
# Question
Title: Drush pm-update needs a module?
When trying to run \`Drush pm-update' in a site i get the error

```
Command pm-update needs the following modules installed/enabled to run: update.                              [error]
The drush command 'pm-update' could not be executed.

```

Oddly this command was recently working (on other sites in the same core installation), and further more I have no idea where to find or what is this 'update' module. Can anyone point me in the right direction?

# Answer
> 17 votes
It's in `<drupal_root>/modules/update`. If not, it means you damaged your core.

Try `drush en update` \- it should re-enable it for you. After performing updates you are allowed to disable it again.

---
Tags: drush
---


# Question
Title: Error when creating a product Drupal commerce kickstart 2
I am using a Drupal commerce kickstart 2, whenever I create a product it gives me an error as it shows in the image,

!\[enter image description here\]\[1\]

any Ideas why?

# Answer
> 4 votes
That's just a notice, I know it's unsightly but it doesn't necessarily indicate there's anything horribly wrong with your site.

If you can confirm this happens on a blank install of Drupal Commerce (which I'm pretty sure it won't), you should report it as a bug to the Kickstart issue queue.

Otherwise, looking at the backtrace, you're dealing with a bug/incompatibility between something in Commerce Kickstart and Pathauto/Page Manager,

Since pathauto is enabled by default in Kickstart, and Page Manager isn't, I'd strongly suggest the problem is incompatibility between Kickstart and Page Manager in some way. Try turning off Page Manager and see if you get the same problem.

If not, you've found the culprit, and should report it to the CTools issue queue

---
Tags: commerce
---


# Question
Title: How can I hide the content to the users who didn't like the Facebook page?
I need to do a site where the content will be inaccessible to the visitors who have not liked the Facebook page. It is necessary to display a popup with the like button the visitor should use to like the Facebook page and see the content.

How can I do it in Drupal?

# Answer
You can do it using Jquery/javascript. Access the facebook like of the page, if it isn't liked then hide the page on the fly(by changing background color etc) and then prompt.

You can load any javascript file in Drupal using drupal\_add\_js in a module.

This procedure will be easiest and also will not require any time delay in showing the page.
> 0 votes

---
Tags: social-network, javascript
---


# Question
Title: Nested Image/Video Galleries in Drupal 7
Alright so after looking around for awhile and not finding exactly what I am looking for hopefully someone can help me out with this.

On my website I plan on having both image galleries and video galleries. I can configure a views gallery or using Media Gallery which works wonders except for what I want to do(media gallery that is).

My videos (or even images if this is possible) section I would like to have nested galleries potentially up to 3 tiers at a time. I am assuming I can do this taxonomy but I don't want to add a new term every time a new 'series' comes out, as I don't necessarily know the name of said series before it comes out.

I would like my gallery to flow as such:

1. Galleries Overview
    * Gallery A
        + Gallery A1
            - Nested Gallery A11
            - Nested Gallery A12
            - Nested Gallery A13
        + Gallery A2
            - Nested Gallery A21
            - Nested Gallery A22
            - Nested Gallery A23
        + Gallery A3
            - Gallery A31
            - Gallery A32
            - Gallery A33
    * Gallery B
        + Gallery B1
        + Gallery B2
        + Gallery B3
    * Gallery C
        + Gallery C1
        + Gallery C2
        + Gallery C3

I am probably over thinking this and there must be an easier way to do this because I have read posts of sites with nested galleries I just cant seem to figure it out.

Final option would be to downgrade to Drupal 6. If it is truly easier this way, it is not that big of a deal, (no real content on my site yet). I know nested galleries are done on D6, and a few years back I had a D6 website with Nested Galleries which is why I am surprised this is an issue now.

# Answer
> 2 votes
The trick is information architecture. I suggest you use the book module to define the hierarchy. This is an underestimated core module, which works amazingly well and has good integration with Drupal. In a recent site I've architected, all the site navigation was built dynamically using views, book-related contextual filters, and the viewfield module (which allows to put a view inside view). Play with the setup below and enjoy!

Detailed instructions:

1. Enable the book module.
2. Define top galleries as toplevel books, without a parent:
    * Go to the node editing screen.
    * Click on the new 'Outline' toplevel tab created by the book module.
    * Click on the 'Add to book outline' button. This will create a new book.
3. For each child gallery, select it's parent gallery

* The parent gallery may be one of the toplevel galleries created on the previous steps, or one of the previous child galleries created on this step.
    * The child gallery may either be selected on the on the 'Outline' tab (when editing existing nodes) or on the 'Book Outline' vertical tab displayed below (when creating new nodes).
4. Create a new view, which will show your toplevel galleies. let's call it "top galleries"

* Open a 'block' display
    * Make the view field-based.
    * Add the title field to show the gallery title.
    * Add a viewfield to show the sub-galleries of this book.
    * The viewfield will refer to a new view we will create in the next step.
    * And, most imprtantly, use a filter criteria of Book: Depth (=1)
5. Create a "gallery-inner" view.
    * Open the 'Advanced' setting
    * Create a relationship from the node to Book: Parent - the parent book node.
    * Set a contextual filter to "Content: Nid" taken from the parent book node.
    * Now the view show all children of it's parent book.
    * I haven't tried it but you may also try to add another viewfield here to show the children of those child views recursively, until there is a level with no more children (if it doesn't work, then create anorhter "gallery-grandchildren" view for the 3rd level. Please report back here and write which way succeeds.

Notes: \- The screenshots were taken from a similar solution, where I've implemented all of the site navigation menus using the book hierarchy defined by the user. So please add an image field to each view where appropriate.

# Answer
> 0 votes
First, you might take a look at a gallery I've made for the company I work for. http://www.vilavitaparcgallery.com. Bear in mind my goal is not to display photos (you can use any Gallery/lightbox module for that), but to allow our partners to download images in high-resolution. While I found several problems in common with what you ask.

It's done in Drupal 7, using Views and taxonomies.

Basically, I created a Taxonomy Vocabulary that showcases the various categories and arranged them into a hierarquie. That hierarqy is then shown as a menu in a block with the **Taxonomy Menu module**.

I also use **Hierarchical Select module**, to allow for a simple taxonomy selection while an administrative user is inserting new content. It's just a fancy way of tagging the categories.

Finally, on the front page I display a simple view that gets all photos with the selected Taxonomy, through the **Hierarchical Select Taxonomy Views** feature.

It turned out to work very well, and the organization feature ends up being highly flexible (its just managing tags) and very standard (it's just a view!). And this means I can use it in any layout, or theme without much fuss.

Hope it helps.

# Answer
> 0 votes
For Multiple galleries in one site like photos, videos, Presentations and e-books:
In my case I need 4 different galleries with 3 levels:
1) Level 1-\> front page block for any albums new image
2) Level 2-\>Album page where there are lots of albums for ex: animals, plants etc
3) Level3-\>individual album items with their default content link !st step
Create Taxonomy : create a taxonomy called “Album”
Add Vocabulary: add vocabularies
1) Photos
2) Videos
3) Presentations
4) E-books
Create Content type : we have to handle all galleries from only 1 album content type and album items content type
Add content types Album and Album type
Album Manage field Album Item Manage field
Title Title
Body Body
Album type: term ref(taxonomy: albums) Album type: term ref(taxonomy: albums)
Album Thumb: image Galleries: entity ref(ex Animals, Plants)
Comment: closed Album Thumb: image
Album Video: video embed
Comment: open

Install module: Node Gallery , its automatically create two new views in your views section after that just need to node gallery summaries 3 more times Album Types Node views Summaries (customize it name when done ex: photos, videos, presentations, e-books)
Photos In fields add this:
Content : Album types: Photos
Videos In fields add this:
Content : Album types: Videos
Presentations In fields add this:
Content : Album types: Presentations
E-books In fields add this:
Content : Album types: E-books

# Answer
> 0 votes
I think you can do this by just a content type, a block and views 1) add a content type with field of image and gallery group 2) and than add a view with create a block and you can show your gallery on that block

---
Tags: views, taxonomy-terms, files, media
---


# Question
Title: Module to list menu_router / path debug info?
Every now and then, mostly when looking at a new site, I find myself wanting to know

*What's the source of this particular page?*

Usually, I end up starting to dig in the `menu_router` table, and possibly also alias tables. Is there a module that will be helpful in finding and displaying this, and other relevant, information for me?

# Answer
I'm not sure there's a module specifically for that, if anything I think it would come under the domain of Devel as you mentioned in the comments. I haven't seen anything like that in Devel before though.

Getting the router item for the current path itself is very easy:

```
$item = menu_get_item();
$callback = $item['page callback'];
// etc...

```

You could just wrap that in a `hook_init()` and `dpm()` it out for a quick solution, or maybe build a patch up for Devel.
> 4 votes

---
Tags: debugging, routes
---


# Question
Title: Escape of Upscaling image in Scale and Crop option
I am using Image Style with `Scale and Crop` option with the dimension `110 * 110`. If the style applies on small image it upscales the size to `110 * 110`. I don't want to upscale it. How to do that?

# Answer
* A separate scale image effect followed by a separate crop image effect won't give you what you want.
* Imagecache Actions does not offer a single image effect that does what you want.

However, what you could do is use the aspect switcher image effect of imagecache\_actions:

* aspect switcher:

+ if portrait: scale to 110x(empty) (no upscaling)
    + if landscape: scale to (empty)x110 (no upscaling)
* crop to 110x110
> 2 votes

# Answer
ImageCache Actions module gives you way better control. Using it, you can create an "downscale, crop, put on background" set of commands that will give you 110 x 110 px image without upscaling.
> 1 votes

# Answer
With the image style `scale and crop` option, it will always upscale the image. It is only with an image style like `scale` that you have the options of not up-scaling. So your best option is to find another image style that might meet your need. For more image style options, check out the Imagecache Actions
> 1 votes

---
Tags: 7, media
---


title: Customize the user-edit page

text:
# Question
Title: Customize the user-edit page
I want to customize the user-edit page. So in my template.php in my custom theme i direct Drupal to look for my custom template as:

```
function mytheme_theme() {
return array(
// The form ID
'user_profile_form' => array(
// Forms always take the form argument.
'arguments' => array('form' => NULL),
'render element' => 'form',
'template' => 'templates/user-profile-edit',
),
);
}

```

This works fine as Drupal is able to pick my custom user-profile-edit.tpl.php. Inside that file i have rendered some elements as :

```
<?php

print render($form['form_id']);
print render($form['form_build_id']);
print render($form['form_token']);

print render($form['field_birthday_user']);
print render($form['field_real_name_user']);

```

And so on.I have two questions...How do i get the user picture field, username, password, and email id fields to edit and how do i get to save the profile, i.e., how to get the save button. For the first part i tried doing:

```
print render($form['account']);

```

However, this does not displays the user picture.

For the second part, i tried doing this :

```
<input type=”submit” name=”op” id=”edit-submit” value=”Save”  />

```

at the end of my custom user-profile-edit.tpl.php. However i get an error regarding syntax.

Would appreciate any suggestions especially regarding the user picture thing.

Thanks

# Answer
> 1 votes
```
print render($form['picture']);

```

Yups..thats all that is required...but i am still stuck at that save button...i have used, for the time being,`print drupal_render_children($form);` to get the save button..if someone can suggest how to do this by code then i would implement it

# Answer
> 2 votes
```
 print drupal_render($form['actions']);

```

that should output the save button

# Answer
> 0 votes
```
print drupal_render_children($form);

```

will take care of the hidden and submit inputs. Try to print\_r or dpm() your $form to render the other fields.

or if you use profile2 module this could be handy http://thanhsiang.org/faqing/node/178

---
Tags: 7, users, theming
---


# Question
Title: filedownloading is making the file to view instead of download in drupal7
Hi i have followed Working with files in Drupal 7 and created the content type for file download.Everything is working fine i can upload a file and displaying it in the front page.But when i click on particular file for downloading it is just viewing the file in another tab in the browser with url like this

drupal7.22/sites/default/files/file.txt

I can view the file but not able to download it.Can you just say me where i did the mistake.

# Answer
Read Force Files to Download Instead of Showing Up in the Browser as the page suggests you can achieve this by adding these lines to `.htaccess` file

```
<FilesMatch "\.(?i:doc|odf|pdf|rtf|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

```

Or alter mime type
> 1 votes

---
Tags: 7
---


title: How to choose a mentor on drupal.org

text:
# Question
Title: How to choose a mentor on drupal.org
Sorry for the off topic question, it may seem in wrong direction as it is not relevant to coding and other stuff.

The problem is that I am developing a module called Amazon send to kindle. It is right now in sandbox module. I am getting problem, as i am not able to share on amazon kindle.

I need a guidance from some expert users, to help and guide me in the development. Drupal.org allows us to select the mentors, but i don't know how should i approch other user to be my mentor.

Is there any official way to ask users to be my mentor ?

# Answer
> 19 votes
There is a posting from Dries Buytaert titled Drupal mentors needed, where he basically asks senior people to become mentors ("Find, motivate, guide and empower people to take on a role within the Drupal community"). So if Dries is the *official* voice of the Drupal community (and I suppose he is), you're supposed to hang around until some aspiring mentor finds you `:-(`. Unfortunately, this very rarely gives the prospective student access to a mentor.

There has been some attempts from other community members to improve on this situation. For instance, there is the Drupal mentor group. with first and last posts in October 2010 (and one spam post from 2012). You could try to introduce yourself there, but the group seems to be dead.

There is also Drupal Kitchen. There is a handful of people signed on to the site as tutors, but to me, this site looks like yet another failed effort.

If you want to learn how to contribute to the core, there is core contribution mentoring. It uses @drupalmentoring (twitter) to set up office hours and sprints for mentoring aspiring core contributors. This may be educational, but is very much oriented towards the core contribution workflow, and not suitable for learning about Drupal in general-

Here is what I suggest: Start by getting a user account on *Drupal.org* and *Groups.Drupal.org* (unless you've already done so). In *Groups.Drupal.org*, look for groups in your geographic area. Join those groups and try to find someone local to communicate with, and look for local meet-ups and sprints you can attend.

Also, use this site (Drupal Answers), the forums on Drupal.org, and IRC to ask *specific* questions about the problems you have developing. You will not get a specific mentor, but you will usually get relevant help from the community.

However, in my experience, when developing a module, the best way to get the attention from senior members of the community ("mentors") is to join the Review bonus program. This requires some effort on your part, since you're supposed to mentor *others* (by reviewing their modules) - but you learn a lot from doing so! Do not be afraid of being a novice reviewer. You'll get feedback from the other reviewers about your reviews. It is OK to make mistakes, and you'll learn from them.

# Answer
> 10 votes
That part of the profile is for giving credits to the community members who have influenced your contributions to Drupal. For example, people who mentored you in the issue queue, IRC, user groups, sprints, Core contribution mentoring hours, etc. This is mentioned in as a description on the edit profile page on drupal.org.
Which clearly means that this place is not to ask somebody to be your mentor, but to give credits to those who have already mentored you in some way.

I would suggest you to raise your questions here, on IRC, or during one of the regional sprints and see if you could get help.

You can find the list of IRC channels and "how to"s at : http://drupal.org/irc

# Answer
> 4 votes
It's important to distinguish between "mentoring" and simply needing guidance on a specific problem. Mentoring implies that there is an ongoing relationship over time that helps a person develop various facets or skills. However your question suggests that you simply need an answer to a specific problem. If that's the case you should just post your question here, or if it's complex, try and break it down into several questions.

If it really is mentoring you are looking for, in other words you want someone to really care about your long term development, you'll probably need to demonstrate that you are going to be worth the mentor's time and energy. Mentors like to mentor people with the potential to become mentors themselves or are at least willing and able to give back to the community.

I would suggest that finding a mentor is a long term project that involves building up your karma by making regular contributions to the community, preferably in an area where potential mentors will notice. By being positive, enthusiastic and helpful you'll find that potential mentors will respond in kind.

---
Tags: community-official-site
---


# Question
Title: Create a faceted search like eRecruiter without solr?
I am in need to create a search results page & filter like the eRecruiter demo page: http://drupaljobs.epiqo.com/search/job

The filter on the right hand side shows the amount of results for specific tags or taxonomy terms, clicking enables that filter, updates the number of results for each filter etc ..

I am using D7 and views3

I do not have apache solr on my server and I wonder if it is possible to create the filters (in my case by taxonomy terms attached to the nodes of a specific type) like they are in this example using mysql and search api?

So far I have used exposed filters in views, but I really need the amount of results for each term behind it.

I have tried something along these lines:

```
Add new view
Show -> taxonomy terms
Continue
Relationships -> Taxonomy term: Content with term
Use aggregation:Yes
Taxonomy term: Name -> Group results together
Add field -> Content: Nid
Aggregation -> Count DISTINCT
Make your own style for Content: Nid field (Set prefix to "(" and suffix to ")" to get
the count between brackets)

```

but without getting the right results.

Is this possible at all?

Thank you all in advance!

# Answer
> 6 votes
You can also use the Facet API module. It allows site builders to easily create and manage faceted search interfaces. Facet API works with the core Search and Search API.

# Answer
> 0 votes
Check out these tutorials for faceted / "drill-down" / filtering searching and browsing navigation *without* the need for solr. They use the Database Search module: https://drupal.org/project/search\_api\_db but the settings can be modified later to use SOLR for when your site hits the big time and needs the sophistication and scalability that SOLR provides. But for now, database search gets you going without needing SOLR.

Myself I'd like some guidance as to how to use: https://drupal.org/project/facetapi\_pretty\_paths \- this module aims to make your URLs generated by the faceted filtering and search pretty. Currently mine are not, even though I have tried to use this module, the documentation appears to be very minimal - there is no step-by-step guide. I'd be sure to write one if I figure it out before anyone helps though :)

Update:

The drupal recruiter distribution is an example of using facetapi\_pretty\_paths : https://drupal.org/project/recruiter \- on this page you'll find more information including how to run a demo via simplytest.me with just a few clicks!

---
Tags: 7, search
---


# Question
Title: Module that adds &nbsp after one letter words
I'm Polish. In my language leaving one letter words at the end of the line is a mistake. I know i can deal with it adding ` ` after such words. Is there a module which takes care of it (eg. while saving the content to db)?
RtL

# Answer
> 1 votes
Traditional Drupal way is to use Text Filters. Here you have introduction text \- it's for Drupal 6, but nothing important changed since then. Examples for Developers contains example filter. Use regex replace or other method from stackoverflow to make actual replacement:

```
preg_replace('/(?<=\b[a-z]) /i', ' ', $s);

```

All the rest you can copy-paste from Examples.

# Answer
> 0 votes
You do NOT want to do this when the node is displayed. String functions are costly, and on this scale it would be an absolute nightmare.

My suggestion is that you make use of `hook_node_submit`

When the node is submitted (aka created or updated) you can run string functions on the body of the node and add your non-breaking space there.

note that this is still going to be a hit to performance, so make sure you're using the appropriate string search functions to make it faster.

---
Tags: 7
---


# Question
Title: Store the Logged in Users's Country in the DataBase
How could I store the country of the registered user, when he/she logs in. I am hoping I could store it in the DB to later retrieve it within the reports.

I am using Drupal 7.

Many Many Thanks.

# Answer
> 1 votes
Turns out there's a pre-built solution for just that: ip2country

> This module uses a visitor's IP address to identify the geographical location (country) of the user. The module makes this determination and stores the result as an ISO 3166 2-character country code in the Drupal $user object, but otherwise has no effect on the operation of your site. The intent is simply to provide the information for use by other modules. A function is also provided for you to perform your own lookup, to use in your own manner. Features include automatic updates of the IP-country database and admin spoofing of an arbitrary IP or Country for testing purposes.

---
Tags: 7
---


# Question
Title: Commerce product with customer defined attributes
Is it possible to create a product, for which before adding to the cart, customer must define some attributes. For example, I need a number field where the customer defines the size of the product (105x200mm, or 1000x600mm). There are no predefined sizes, I only need an empty text field for width and height where the customer can type their specific size.

After that I want to add it to the cart but without price. I only want to collect customer orders where the products have sizes. Information about final prices will be sent later by email. We don't want to display prices and no payment.

Thanks a lot

# Answer
> 4 votes
Absolutely. What you need is the Commerce Customizable Products module.

That allows you to set up Line Item Types that are entirely fieldable! You can add text fields, select boxes, radio buttons and any field you want to be displayed as the user is adding the product to their cart.

Once the module is enabled, do the following

* Add a new Line Item Type at /admin/commerce/config/line-items
* Add any fields you need to it (in your case, just a text field)

* Make sure to check the box that asks whether this is a field you want added to the 'Add to Cart' form

* Finally, go to the 'Manage display' tab of the content type you have that displays your product, and go into the settings of the 'Product' field. You will see a new option which allows you to choose a 'Line item type' to display. Select the one you just created, Update, and Save!

Final result:

Let us know if this works for you...

---
Tags: commerce
---


# Question
Title: Views Contextual Filter - Full Month display
I created a View and it is working perfectly. There is only an issue with how it's formatting the dropdown list for Month filtering. Right now it's displaying the months in abbreviated format (ex. Jan, Feb, Mar, Apr). I'd like it to display the months in full format (ex. January, February, March, April).

Is there a way to override this behavior?

Thanks for any help.

# Answer
```
function your_module_name_date_select_process_alter(&$element, &$form_state, $context) {
  $element['month']['#options'] = array
  (
    '' => t('Month'),
    1  => t('January'),
    2  => t('February'),
    3  => t('March'),
    4  => t('April'),
    5  => t('May'),
    6  => t('June'),
    7  => t('July'),
    8  => t('August'),
    9  => t('September'),
    10 => t('October'),
    11 => t('November'),
    12 => t('December')
  );
}

```
> 1 votes

# Answer
I think its possible you can achieve it by doing like this

views -\> arguments

And then add Node: Created year + month:

it worked for me.

What does a monthly archive block achieve?

This Answer might also help you on your way.

Hope it helps

best regards

Vic
> 0 votes

---
Tags: views
---


# Question
Title: Rendering fields with node display settings
I would like to take advantage of the settings I can set under `admin/structure/types/manage/node_type/display` when i render my custom fields in `node--node_type.tpl.php` but using the following code I just get some sort of default display setting:

```
<?php
  print render( field_view_field('node', $node, 'field_date', array('label' => 'hidden')) );
?>

```

This prints my date in the long format, but under /display I already set it to medium. Also I have already set the label as hidden under the display settings.

How can I use those settings and only override them if I want to? Or is field\_view\_field() not the right function?

# Answer
> 2 votes
The content array should already contain an element for each field with the display settings applied. You can just print that directly:

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

```

---
Tags: 7, entities, theming
---


# Question
Title: empty optional fields: saved node contains the token name instead of an empty section
I have created a content type that has some tokens within the read-only body section so that other custom fields that the user enters when they create content based on this content type are mapped to its associated token within the body section. If the user enters information within a optional field then that entered information replaces the token when the node is saved. The problem is for optional fields when they don't enter a anything within it then the saved node contains the token name instead of an empty section which is what we want.

# Answer
> 0 votes
I have figured it out with my own custom module:

function mymodule\_tokens\_alter(&$replacements, $context) { if ($context\['type'\] == 'node') { $keys = array\_keys($context\['tokens'\]); foreach ($keys as $key) { if (isset($context\['tokens'\]\[$key\]) && !isset($replacements\[$context\['tokens'\]\[$key\]\])) { $replacements\[$context\['tokens'\]\[$key\]\] = ''; } } } }

---
Tags: nodes, tokens
---


# Question
Title: Form API Ajax - how to disable also form elements that will be changed, not only triggering element?
So, element that triggered AJAX gets disabled. But how to make Drupal also disable everything inside `['#ajax']['wrapper']`? After all, allowing user to edit something that will get replaced as soon as AJAX response is ready isn't the wisest idea, and I'd like to prevent that. And my AJAX created elements have their own AJAX too, race conditions are pretty bad already.

Is there any ready-made module for that? Or API way I'm missing? If no, where exactly should I put that code to minimize risk of incompatibilities?

Edit: I'm looking for a safe and stable way. It means **no hard-coded identifiers** in JavaScript files. Solution that breaks when someone edits form definition, or one that works for only one AJAX in form is not enough. After all, I need to avoid race conditions, and I already noted I have multiple AJAX actions, working on different sets of elements, on one page - so **no marking elements for disabling at PHP level**. I can eventually mark them with classes like `disable-on-X` and `disable-on-Y`, but I need to know if it's X or Y AJAX happening. And ideally I'd just disable everything inside `['#ajax']['wrapper']` without any additional marks, as they are not really needed - but again, I would need to know proper `['#ajax']['wrapper']` in javascript.

# Answer
You can disable/enable some elements during ajax using this jQuery script:

```
// Disable filters on ajax call.
  $(document)
    .ajaxStart(function() {
      // Place here all elements that must be disabled during ajax.
      $("#path-to-the-element").attr("disabled", "disabled");
  })
    .ajaxComplete(function() {
      // Place here all elements that must be enablec after ajax.
      $("#path-to-the-element").removeAttr("disabled");
  });

```

**Update. Some helper suggestions:**

* You can loop all inputs in wrapper element and disable each of them using jQuery.each
* You can see what is the class or id attribute of your generated
element html. Also you can add some special CSS class disable-on-ajax to all your elements or wrappers that must be disabled on ajax. Then you will be able to handle them with one line of jQuery code.

**Update 2**

I can suggest one more solution. E.g. you have added class for your target elements 'disable-on-ajax'. Then you can write function that will be triggered on blur, select change, click etc.(You'll need to implements all target triggger checks). In this function you'll check if element has class "disable-on-ajax". And add second class "ajax-disabled". Then on ajaxStart you'll handle only element with class "ajax-disabled"

You can populate form ajax-triggering elements, add property like ajax\_wrapper="wrapper", ajax\_event="event type" and then in behavior attach events
> 3 votes

---
Tags: ajax, forms
---


# Question
Title: Display all Nodes associated to a Taxonomy term?
I currently have a list of Taxonomy terms: Fruit, Meat, Vegetables..etc. And I would like to add a drop down to a content type that will display all nodes and only the nodes that are associated to a Taxonomy Term. I am currently using the Node Reference- Select List, but the list is growing and will eventually become unmanageable.

To Summarize: In example, I select a Taxonomy term and then a "select list" displays only nodes that have been previously associated to that same Taxonomy term. I select Fruit and it displays oranges, apples, and lemon nodes only. Not... lemons, oranges, carrots, ribeyes...etc, in which, is my ever growing Node reference list now.

Thank you for any help you may lend.

# Answer
> 1 votes
You could accomplish this by writing code (in a custom module) to ajaxify the relevant select fields. Check out the Examples module (ajax examples -\> dependent dropdown) for implementation help. Here's what needs to be done roughly:

1. Use hook\_form\_alter or hook\_form\_FORM\_ID\_alter to add necessary `#ajax` options (`callback` and `wrapper` at minimum) to the taxonomy select field. The node reference field needs a wrapper (via `#prefix`, `#suffix`) and `#options` changed when a term has been selected (value set in `$form_state['values']`).
2. A function for the ajax callback returning the node reference form field.
3. Custom functionality checking which nodes are associated with the selected term to set the right options for node reference. Easiest way might be by querying them directly from the `taxonomy_index` database table (if you need other data (like type) include the `node` table as well).

---
Tags: nodes, taxonomy-terms
---


title: Entityforms validation

text:
# Question
Title: Entityforms validation
What is the best way to add some validation to the fields in an Entityforms form? I did some googling can't find any good answers.

Thanks, Jonathan

# Answer
Just in case someone else finds this.

You can use Entity Rules This was made for Entityform 1.x but could be used with 2.x

You could probably also use Field Validation if you didn't want to use Rules.
> 2 votes

---
Tags: forms
---


# Question
Title: Execute a Backup and Migrate backup via PHP
I'm trying to create a custom module that will overwrite my testing site with a copy of my live site (I can't use SSH and I can't install my own PEAR modules, so Drush is a no-go).

I've been using PHP execute() commands to manipulate the file system and dump the database, but I'm getting errors on the testing site when importing the SQL dump, and I usually have to resort instead to the Backup and Migrate module, using a profile that copies my main database over to my testing database.

Now I'm wondering, is there any way I can hook into this and execute it as part of the chain of commands in my custom module? The goal is to turn the process of migrating to the testing site into a one-click (followed by a lot of grinding) process. But since Backup and Migrate doesn't apparently expose any API or hooks, or even the machine names of its profiles and destinations, how could I execute a backup command with a specific preset from a different module?

Say, for instance, I want a PHP command that will tell Backup and Migrate to backup database `live_db` to destination `test_db`, both of which are already recorded as mysql://\[db\_name\] in the B&M settings.

# Answer
> 2 votes
Ok, as it happens, I figured this one out. Below is a sample function meant to be used as an admin form submission handler.

```
function _my_backup_handler() {
  $destination_hash = 'yourhash'; // See below.

  backup_migrate_include('profiles');
  $settings = _backup_migrate_profile_saved_default_profile();
  $settings->destination_id = $destination_hash;
  $settings->source_id = 'db'; // Your primary Drupal database. This is probably redundant.
  backup_migrate_perform_backup($settings);
}

```

As for what `$destination_hash` is, it turns out the "machine name" of a custom BM destination is a random hash. It can be found in the URL if you go to `http://www.yoursite.com/admin/config/system/backup_migrate/destination` and click the "edit" button for your destination; you'll end up at `http://www.yoursite.com/admin/config/system/backup_migrate/destination/list/edit/[hash]`. Just copy \[hash\] and plug it in as a string for the value of `$settings->destination_id`.

---
Tags: 7, hooks, backups
---


# Question
Title: Defining Devel generation rules for custom nodes
I have Devel module installed, I use it mostly for generating content.

I wanted to know if it was possible to define some custom rules to generate content for my custom nodes.

For example: I want the node titles to be fetched from a php array or another source instead of the automatic Lorem Ipsum fragments.

I've done some google researches but I can't find a starting point to do this.

Thanks

# Answer
> 0 votes
I usually create a simple custom module for migratig data from an external data source and no need to use devel for this kind of tasks.

you have a very good example here :

http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7

you can simply adapt the code and make a foreach loop on your array.

---
Tags: nodes, debugging
---


# Question
Title: D7: Add a class to a list item when the created date is less than 14 days old
Using Drupal 7 and Views, I currently have a view that produces a list of 5 teasers of the content type "News." 5 teasers is a hard rule. I'd like to conditionally format the rows so that when their "created date" is less than 14 days old so that I may styles them as "New" with CSS styles. So if there are 3 "New" rows, the balance are 2 unmarked rows.

How to do so?

## Update

I had the idea of using the "time ago" date format to populate the class name. However, the format for "time ago" changes. Unfortunately, I can't set the granularity to "days" which would have allowed me to add the text as a class, i.e., date1 through date24 for the past 2 weeks.

## Update #2

My genesis subtheme is ignoring any preprocessor routines, see more here. However, I can add the routine to my base template.php.

## Update #3

Thanks to Елин Й. for the working code:

```
function genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    foreach ($view->result as $key => $result) {
      if (time() - strtotime($result->node_created_day) < 14 * 24 * 60 * 60) {
        $variables['classes'][$key][] = 'new';
        $variables['classes_array'][$key] = isset($variables['classes'][$key]) ? implode(' ', $variables['classes'][$key]) : '';
      }
    }
  }
}

```

In an offline discussion, Елин Й. explains why this works; "I took a look in the views theme.inc and found out that, the classes array is flattened to another variable called 'classes\_array' you need to do it as well in order to get your new class also added in this array.

# Answer
You can do that using a preprocessor function for the view you created. You need to preprocess the view and check the creation date of nodes for each row and give them a relating class.

Given that your view's machine name is `recent_news_widget`, your diplay format is HTML lists, and your theme name is `genesis`. You need to use template\_preprocess\_views\_view\_list() function in `/sites/all/themes/genesis/template.php file`

```
genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    // dpm($view);
    // Here comes your logic
  }
}

```

In the above code you see 2 lines commented out. First one is a helpful function for developers to print out the given array/object/string etc in a browsable style. This function comes with Devel module, which I would strongly recommend to install it.

After browsing the variables, you will probably find where the results are listed and where the classes for the rows are assigned. You need to browse the variables until you find all values you need to build your logic to assign new classes, for example the 'created date' of the node. After you have all the variables you need, you can loop through the results, check the creation date and add a relating class.

UPDATE: The preprocess functions for other display types than HTML List:

Grid: template\_preprocess\_views\_view\_grid() Table: template\_preprocess\_views\_view\_table() Unformatted: template\_preprocess\_views\_view\_unformatted()

UPDATE #2 (According the discussion on chat and your updates on the question): I find the code in your Update #3 was in the right direction, but with a few mistakes. The corrected version should look like that:

```
function genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    foreach ($view->result as $key => $result) {
      if (time() - strtotime($result->node_created_day) < 14 * 24 * 60 * 60) {
        $variables['classes'][$key][] = 'new';
        $variables['classes_array'][$key] = isset($variables['classes'][$key]) ? implode(' ', $variables['classes'][$key]) : '';
      }
    }
  }
}

```

The 2 mistakes in your code were:

1. You passed the argument as &$variables to the function, but used $vars to assign classes, $vars is not defined in the function so the class was not added.
2. You wanted to use the key number of the result but in `foreach` you loop only through the values, and `$result` variable is an object. In the corrected version of your code above, I used `$key => $result` by defining the loop so that I can access the key number as well.

UPDATE #3 I added a new line that flattens the classes into classes\_array.
> 4 votes

# Answer
Hope this will help you!!

As you need to add the class to the row, you can achieve by overriding the default view template file

You can achieve this by the following steps

* Open your view and go to **Advance tab** \+ **other** category you can see the **theme - information** click **Information** link.
* As per your requirement you need to override the row style. you can see **Row style output**, the default template file is **views-view-fields.tpl.php** which is highlighted. Means this template file is active now. And also you see list of tpls will be there, so **choose any one of the tpl name** (eg.., views-view-fields--comments-recent.tpl.php or views-view-fields--comments-recent--page.tpl.php) for your **new template file**.
* You need to override this template file so navigate to VIEWS module + THEME folder + get the tpl file which you want to override(here views-view-fields.tpl.php)
* Copy and paste template file to your theme template folder(sites/themes/your\_theme/templates/) and rename it to the **choose template name**
* Click **Rescan template file** to active new template file.

+ No you can modify the template file and add the class.
> 3 votes

# Answer
```
function genesis_preprocess_views_view_list(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

  if ($view->name == 'recent_news_widget') {
    foreach ($rows as $id => $row) {
      $data = $view->result[$id];
      // Assumption this if condition works and node_created_day exist in row
      if (time() - strtotime($data->node_created_day) < 14 * 24 * 60 * 60) {
       // Add custom class if condition satisfies
       $vars['classes'][$id][] = 'custom-new';
      }
    }
  }
}

```

Also can you try replacing the classes line with this one and tell me does it work. $vars\['row\_classes'\]\[$id\]\[\] = 'custom-new';
> 1 votes

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


# Question
Title: Passing Timestamp in the SQL Query to filter results
I've a query where I want to filter query results based on today, yesterday and week. I've written queries within Drupal 7 and it is as follows:-

```
$result = db_query("
    SELECT
  n.title, n.nid,
  COUNT(*) AS times
FROM
  {node_view_count} a, {node} n where a.nid = n.nid AND a.uid = :uid AND n.nid <> 2120 AND DATE(from_unixtime(:mydate)) = CURRENT_DATE
GROUP BY
  n.title
ORDER BY
  times desc",
array(':uid'=>$_GET['uid'], ':mydate'=> date('Y-m-d H:i:s', "a.timestamp") )) -> fetchAll();

```

My question is, that could I pass two variables in the array as a parameter? Also if I could why is this query not working when I pass two parameters in it. The problem is that I need to convert the timestamp to date before using it and I am using a query Variable in the parameters.

Do you think you could assist in this?

Thanks.

# Answer
> 1 votes
I don't have a copy of D7 handy, but this seems to work on D6 for me. There's at least two problems with your code. I'm going to pare your query into a short bit of SQL, then transform it into drupal code.

## Use `JOIN`s

Whenever you're using multiple tables in SQL, you'll almost always have to use the `JOIN ... ON ...` syntax. Using `JOIN` tells MySQL that you want to connect certain rows on the two tables if a given field from those tables matches. This is a very basic SQL concept, so you'll need to master this if you want to write your own SQL or troubleshoot it. Try W3Schools tutorial for a better explanation.

Here's a simplified, pure SQL query that works for me using a `JOIN`:

```
SELECT
  n.title, n.nid, COUNT(*) as times
FROM
  node n
JOIN
  node_view_count a
ON
    a.nid = n.nid
GROUP BY
    n.title
ORDER BY times DESC;

```

In my D6 installation, I have a table called `node_counter`, but you probably have `node_view_count` instead on D7. `JOIN node_view_count` tells MySQl that we're connecting the `node` table to the `node_view_count` table. The `ON a.nid = n.nid` tells MySQL to only connect rows from these two tables when the `nid` field matches.

## `WHERE` Clause

Next, let's add in a simplified `WHERE` clause. On my D6 database, the `node_counter` table's `timestamp` field is an unix timestamp (an integer). We can do the conversion from unix timestamp to datetime using pure SQL as well (no need to use a parameter to `db_query()`):

```
...
ON
    a.nid = n.nid
WHERE
    DATE(from_unixtime(a.timestamp)) = "2012-12-21"
GROUP BY
...

```

## Add a Paramater to `db_query()`

We can change "2012-12-21" to whatever date we want to search on. So, next let's make this changeable part of our query into a parameter that gets passed to `db_query()`:

```
<?php
$query = <<<SQL
SELECT
  n.title, n.nid, COUNT(*) as times
FROM
  {node} n
JOIN
  {node_view_count} a
ON
    a.nid = n.nid
WHERE
    DATE(from_unixtime(a.timestamp)) = :mydate
GROUP BY
    n.title
ORDER BY times DESC
SQL;

```

I've put `{` and `}` around the table names so that you use this query inside `db_query()`. By adding `:mydate`, you can now add in parameter called ':mydate' with a date string to your `db_query()` call:

```
$result = db_query($query, array(':mydate' => '2012-12-21'));

```

Hopefully, this gets you 90% of the way there.

---
Tags: datetime, database
---


# Question
Title: hook_library: if two libraries share common file, might this cause files to get loaded in wrong order?
I am using hook\_library to define two libraries:

* mymodule\_views\_plugin\_style\_library
* mymodule\_views\_plugin\_row\_library

The "style" library gets loaded in my custom style template: `drupal_add_library('mymodule', 'mymodule_views_plugin_style_library')`

The "row" library gets loaded in my custom row template: `drupal_add_library('mymodule', 'mymodule_views_plugin_row_library')`

Each library contains 3 javascript files, which must be added in the specified order.

The style library contains these 3 files:

1. mymodule\_views\_lib.js
2. mymodule\_views\_style1.js
3. mymodule\_views\_style2.js

The row library contains these 3 files.

1. mymodule\_views\_lib.js
2. mymodule\_views\_row1.js
3. mymodule\_views\_row2.js

Note that both the "style" and "row" library have a file in common (`mymodule_views_lib.js`) and that this file needs to load first.

Here is my hook\_library code:

```
function mymodule_library() {
  $path = drupal_get_path('module', 'mymodule');
  $libraries = array(
    'my_views_plugin_style_library' => array(
      'js' => array(
        $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_style1.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_style2.js' => array('group' => JS_LIBRARY),
      )
    ),
    'my_views_plugin_row_library' => array(
      'js' => array(
        $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_row1.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_row2.js' => array('group' => JS_LIBRARY),
      )
    ),
  );
  return $libraries;
}

```

My problem: The file `mymodule_views_lib.js` does not load before `mymodule_views_row1.js`. It does not load until the "style" library (which happens to load after the "row" library) is loaded.

Question #1: I see here that there is a solution to my problem: I can create a separate library for the common js file, and then add this library as a dependency. I am wondering, though, whether this is the only solution. Is it possible to specify the relative load order when two different libraries share a common file?

Question #2: Assuming my libraries do not share any js files, is it safe to assume that the library files will be loaded in the same order in which they are listed, in hook\_library? Or must I explicitly specify a weight?

**UPDATE**

I added a weight to each js file, as suggested by tenken below, and that solved the problem. The javascript files now load in the desired order:

```
   function mymodule_library() {
      $path = drupal_get_path('module', 'mymodule');
      $libraries = array(
        'my_views_plugin_style_library' => array(
          'js' => array(
            $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY, 'weight'=>1),
            $path . '/mymodule_views_style1.js' => array('group' => JS_LIBRARY, 'weight'=>2),
            $path . '/mymodule_views_style2.js' => array('group' => JS_LIBRARY, 'weight'=>3),
          )
        ),
        'my_views_plugin_row_library' => array(
          'js' => array(
            $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY, 'weight'=>4),
            $path . '/mymodule_views_row1.js' => array('group' => JS_LIBRARY, 'weight'=>5),
            $path . '/mymodule_views_row2.js' => array('group' => JS_LIBRARY, 'weight'=>6),
          )
        ),
      );
      return $libraries;
    }

```

# Answer
> 1 votes
For question #1 --

`$options` in `hook_library()` supports all the options in drupal\_add\_js.

`$options` in drupal\_add\_js supports a `weight` value to determine ordering:

**From hook\_library:**

> 'js': An array of JavaScript elements; each element's key is used as $data argument, each element's value is used as $options array for drupal\_add\_js(). To add library-specific (not module-specific) JavaScript settings, the key may be skipped, the value must specify 'type' =\> 'setting', and the actual settings must be contained in a 'data' element of the value.

From drupal\_add\_js:

> weight: A number defining the order in which the JavaScript is added to the page relative to other JavaScript with the same 'scope', 'group', and 'every\_page' value. In some cases, the order in which the JavaScript is presented on the page is very important. jQuery, for example, must be added to the page before any jQuery code is run, so jquery.js uses the JS\_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js depends on) uses the JS\_LIBRARY group and a weight of -19, drupal.js uses the JS\_LIBRARY group and a weight of -1, other libraries use the JS\_LIBRARY group and a weight of 0 or higher, and all other scripts use one of the other group constants. The exact ordering of JavaScript is as follows:

For question #2 -- the safest thing todo is to always specify the inclusion order; eg `weight`.

---
Tags: javascript
---


# Question
Title: Manually changing URL alias values via phpmyadmin? What does this affect?
I have a bunch of aliases in my url\_alias table. I want to change the source of certain rows, but I'm not sure if it would affect anything. What I need to know is if the column **PID** in the url\_alias table is linked to anything else. Currently I just want to switch node/33 to node/2343, but im afraid I might break something if im doing it via phpmyadmin. I can't do it via the site as I have over 100+ entries I have to modify. The easiest way is by doing it in mysql.

Also is there a drupal database table map I can generate that shows me how each table is linked to each other?

# Answer
Doing **any** manual updates to the Drupal database is a bad idea unless you know exactly what you are doing.

The `{url_alias}` table is written to with `path_save()`. If you look at the source, two hooks may be fired, depending on whether the path is new or update: `hook_path_insert()` or `hook_path_update()`.

So, if you update `{url_alias}` manually, you don't give any other modules the chance to react via the hooks. Whether or not anything bad will happen depends on whether *your* system has any of these hooks in use. Off the top of my head, I am unaware of any modules that do, but you would need to run a `module_implements('path_insert')` and `module_implements('path_update')` to be sure.

Your safest bet is to always use the API. Write a standalone script, and execute it with `drush -u 1 scr yourscrpt.php` to make sure all of your hooks execute.
> 2 votes

---
Tags: 7, path-aliases, database
---


# Question
Title: How can I stop Views from eating my query strings when rewriting a link?
I have a view and I am trying to rewrite the links by appending a query string.

`[name_1]` is the name of the location. The various values for `age[]` are the taxonomy term IDs for an exposed filter, and `friends` is a profile field.

Under **Rewrite results**, I have checked *Output this field as a link*. This is my link:

```
location/[name_1]?age[]=27&age[]=31&age[]=35&age[]=39&age[]=43&age[]=44&friends=1

```

When I cut and paste the query string into the URL bar, it works fine. However, when I tell views to rewrite the string I get URLs that look like this:

```
location/mexico?friends=1&age[]=44

```

This gives me no results and a broken view.

It appears that the query strings are processed in reverse, and it only accepts the first value for `age[]`-- even though when I type the same thing into the URL bar it is OK.

I tried replacing the symbols in the rewriting string like this:

```
location/[name_1]age%5B%5D=27&age%5B%5D=31&age%5B%5D=35&age%5B%5D=39&age%5B%5D=43&age%5B%5D=44&friends=1

```

Now, when I access the view, I no longer get an error, but none of the age (taxonomy term) checkboxes are checked and the URL looks like this:

```
http://localhost:8888/en/location/mexico?age%255b%255d=44&friends=1

```

So, clearly most of the `age[]` values are still disappearing for some reason.

How can I rewrite the query string so that views outputs it properly?

EDIT: According to Jimajamma's comment, D6 Views suggests using `%5B%5D`, as I have already tried (I'm on D7). `[]` didn't work for me either (this combo doesn't even work in the URL bar). Perhaps this is a bug in Views?

EDIT 2: As per the answers, this appears to be a bug in Drupal Core/Views, not a configuration error. So I attempted to avoid using Views *rewrite results output as a link* feature and instead just *rewrite results* and code the link in HTML.

The only problem with this approach is that some of the terms have spaces in their names, and I was using the *convert spaces to dashes* option provided by the *output as a link* setting to get around this. So now the links for terms that have no spaces work properly, but the links for terms with spaces are broken...

# Answer
> 2 votes
Issue is not with views. What views does is it calls `drupal_get_query_array` to build the query array. And as of now `drupal_get_query_array` does not support same name array in the query params. All it does is just explodes the query and saves it as follows;

```
$result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';

```

So if you see the see it is going to be overridden and it is just going to store

```
array ('age' => 44, 'friends' => 1)

```

I have created a ticket and reported this issue and attached a patch as well at https://drupal.org/node/2023815

The same patch should work for 7.x as well.

**Alternatives**

So Views php / Custom module looks like a good alternative without hacking the core.

# Answer
> 0 votes
Odd that VIEWS is doing that. Here's a fresh approach for you.

My recommendation would be to use the views\_php module.

1. install/enable views\_php, Then
2. exclude the field rather than rewriting it as a link.
3. add field "global php" to the view \[not sure i got that name right, but it has php in it\]
4. in that php field write a small script to take the $data attributes and use the drupal l() function to let Drupal build the url.

Mind you.... The better solution would be to hook into this view and programmatically create the link rather than using views\_php to run the eval() on each result. But nonetheless, the views\_php module does exist for these quick-n-dirty use cases where the site builder may not be comfortable writing a custom module to hook into Views. Some one else may post the custom module solution here, OR maybe I will later.

# Answer
> 0 votes
user l() like

```
<?php
l(<Title>,<URL|URI>,
    array(
        'attributes' => array(
            'id' => 'my-id',
            'class' => 'my-class'
        ),
        'query' => array(  /* You Want this */
            'foo' => 'bar',
            'foo1' => 'bar1',
        ),
        'fragment' => 'refresh',
        'html' => TRUE
        )
    );
?>

```

---
Tags: views
---


# Question
Title: How to associate a product cost to a product in Drupal Commerce?
I have to purchase each of my products from my manufacturer. I want to store the cost for each product, so I can run reports and get my gross profit. I have not found any site that demonstrates how to do this. It seems like this should be basic for Drupal Commerce. Am I using/searching for the wrong terminology?

# Answer
> 2 votes
Just add a new price field to your product type, call it cost, and populate it at will. That's what I do to track my cost on realmilkcheese.com.

---
Tags: 7, commerce
---


# Question
Title: Will empty hook definitions slow down a site?
I'm working on porting over some Drupal 6 custom modules that another developer wrote, and I'm coming across some hooks that are, with the exception of comments, completely empty. I'm likely going to clean these out, for the sake of readable code, but I was curious if I would get any form of performance increase out of it.

# Answer
> 3 votes
I suspect I have been guilty of deploying code with empty hooks. Often, I will stub out hooks for debugging purposes, so I don't have to clear cache in order to `dpm()` something at the point I need. Ideally, though, dead code should be removed.

If you remove an empty hook, you will

* Save a small amount of database space from the hook being saved in the registry. I think it will save one row.
* Save a small amount of memory in APC.
* Save some query memory and some PHP memory from reading in that row from the registry
* Save a few CPU cycles from having a `module_invoke_all()` call something that does nothing.
* Potentially save you some headache of having dead code in a file.

If you have the time, and have a site that works, there should be no harm in removing these hooks. Just test it to be positive.

Whether you have a meaningful performance impact is really debatable.

In the case of cached pages, the only hook that fires is `hook_boot()`. There will be some overhead from the bootstrap process reading in an extra hook from the registry. I seriously doubt this is measurable, though.

For authenticated access, or non-cached pages, the hook may run if the invoker runs. In other words, a `hook_init()` will always run, but a `hook_node_insert()` will only run if you actually save a new node. Even in this case, I doubt that you will have any meaningful impacts. Actually profiling this would be an interesting exercise, though.

TL;DR, there should be no harm in removing them, but you will probably not notice them gone.

---
Tags: hooks, performance, migrations
---