# Question
Title: How to use Form API and and node_submit to insert taxonomy data
I have a content type with a number of text fields and a field linked to a taxonomy vocabulary with about a dozen terms.

I have successfully developed code using the Form API to insert data from my custom form into my node using node\_submit for the text fields. A sniped of the code I use is for the text fields is:

```
$node->field_s_phone[$node->language][0]['value'] = $form_state['values']['phone'];
$node->field_s_email[$node->language][0]['value'] = $form_state['values']['email'];

node_submit($node);
node_save($node);

```

I would like to implement a single set of checkboxes of my vocabulary terms on the custom form, then pass the values using node\_submit in a similar fashion to the text fields (sort of like):

```
$node->field_catagories[$node->language][0]['value'] = $form_state['values']['catagories'];

```

I would be grateful for any thoughts or insight.

Thanks, Bill

# Answer
Try this, if I completely understood you, this should help.

```
    $i = 0;
    foreach($form_state['values']['catagories'] as $tid) {
      $node->field_catagories[$node->language][$i]['tid'] = $tid;
      $i++;
    }

```
> 0 votes

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


title: Acquia drupal new site creation problem

text:
# Question
Title: Acquia drupal new site creation problem
I have installed Acquia Dev Desktop on my Windows 7 PC. I cannot import the new Drupal site from its control panel. Whenever I try to do it, it shows the following error:

> Cannot write file C:\Windows\system32\drivers\etc\hosts

I don't know how to solve it. I have attached some images with this mail.

I have Nod32 antivirus software installed on my PC.

# Answer
> 2 votes
For the permission issue, I suggest you also try the following steps.

Take ownership of the hosts file and change the permission for it

=================================

1. Right click on hosts file and click “Properties”.
2. Switch to “Security” tab and click “Advanced” button.
3. Switch to “Owner” tab and click “Edit…”.
4. Highlight your user account or administrators group and click “OK” twice to quite the “Advanced Security Settings” dialog box.
5. On the “Security” tab of “Properties” dialog box, click “Edit…”.
6. Highlight Administrators group, check the box for “Full control” under “Allow” and click “OK”.

---
Tags: installation, acquia-dev-desktop
---


# Question
Title: How to use taxonomy terms(with depth) on a views exposed filter?
I have a taxonomy vocabulary with 'Countries' as parents and 'Cities' as children. I want to expose the terms with two views exposed filters,one for the parents and one for the children.But both filters show all parents and children terms. How can I accomplish that,to show only parents term to one filter and children terms to the other filter? Thanks in advance

# Answer
> 1 votes
**Option 1:**

Use Hierarchical Select module and you can show the related child term whenever you select the parent. (For example if you select the country UAE, then it shows the UAE cities like dubai, abu-dhabi,..). See the below screenshot for how it works.

If i select the community "Downtown Burj Dubai", it automatically loads the another list of child terms for Downtown Burj Dubai.

**Option 2:**

You can also try Simple hierarchical select. Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.

# Answer
> 1 votes
http://drupal.org/sandbox/ser\_house/1832320 is not done but i am using it on my site and works fine even with other exposed filters.

Only problem not really related to this module is that my vocabulary is 5000+ terms and its Drupal taxnonomy core issue on how to handle large amount of terms.

# Answer
> 0 votes
Here **Depth means-The depth will match nodes tagged with terms in the hierarchy.** For example, **if you have the term "COUNTRIES" and a child term "CITIES", with a depth of 1 (or higher) then filtering for the term "COUNTRIES" will get nodes that are tagged with "CITIES" as well as "COUNTRIES". If negative, the reverse is true; searching for "CITIES" will also pick up nodes tagged with "COUNTRIES" if depth is -1 (or lower).**

this can be of help if u don't mark any node with the COUNTRIES tag,but mark all nodes with the some children tags of COUNTRIES.

The **Views** module has a taxonomy\_term View which can be used. You need to edit the View so that under the **Arguments -\> Taxonomy: Term ID (with depth) -\>** change the depth depending on your requirement. If you want to exclude the parent item, you can do this by adding a filter to exclude the parent term.

I found a link as well that might help: **Display terms only if associated** with a node

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


# Question
Title: Implement a custom PHP library into a custom block module?
I have a PHP class and it's files in the folder:

```
/var/www/include_php/**the_folder**

```

How should I include this into Drupal?

```
ln -sf /var/www/include_php/the_folder /var/www/drupalSite/sites/all/libraries/the_folder

```

and then do `drupal_add_library('the_folder')` or something else in my block module?

# Answer
If your PHP Library is a class or set of classes, you can add them to the registry. This is what I am doing in the Mobile Detect module. I got the idea from another module, but I don't recall which one:

```
/**
 * Implements hook_registry_files_alter().
 *
 * Adds the Mobile_Detect() class to the registry so that autoloading works.
 * See http://drupal.stackexchange.com/questions/42266 for a discussion.
 */
function mobile_detect_registry_files_alter(&$files, $modules) {
  $library_path = _mobile_detect_get_library_path();

  $files[$library_path . '/Mobile_Detect.php'] = array(
    'module' => 'mobile_detect',
    'weight' => 0,
  );
}

```

This adds the class to registry so it will be autoloaded if instantiated as `$detect = new Mobile_Detect();`. You can edit the `$library_path = ...` line to suit your situation.
> 2 votes

# Answer
`drupal_add_library()` is for Javascript/CSS libraries; Drupal doesn't have a similar registry for PHP libraries/classes.

To include a file inside a module in your installation, use `module_load_include()` e.g.

```
module_load_include('inc', 'mymodule', 'mymodule.pages');

```

For all others just defer to the standard PHP functions (`include`/`require`, etc.)
> 2 votes

# Answer
In your module symlink library's folder

```
ln -sf /var/www/include_php/the_folder /var/www/drupalSite/sites/all/mymodule/the_folder

```

Then in you mymodule.info add series of lines:

```
files[] = the_folder/first.inc
files[] = the_folder/second.inc

```

and so on. That way your module will know about them and Drupal will be able to autoload them.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Where do I set anonymous checkout without users hit the login page?
After adding an item to the Drupal Commerce cart, I hit the cart review page. Then I click on checkout and I'm hit with the login page, is there a setting where users don't have to login and just checkout anonymously. And if they already have an account on the site their order would be added to their account in reference to their email.

# Answer
You aren't just using Drupal Commerce, are you? It sounds like you're using Commerce Kickstart or Drupal Commerce with the Commerce Checkout Redirect module enabled. That's what's responsible for the behavior you're describing. Just disable it and enable the "Access checkout" permission that David Thomas pointed to.
> 12 votes

# Answer
You may need to check the permission, under `Admin > People > Permissions : "Access checkout"` for anonymous users.

If the user does log in, their anonymous order will be added to their authenticated user cart.
> 9 votes

---
Tags: 7, commerce, users
---


# Question
Title: How to have two view panes in one Panel, so that selecting a node title in View A displays the content for that node in View B? Do I HAVE to use AJAX?
I have been playing around with view panes, panels and context, and am struggling to find the best approach for the below:

1. I have a Panel which, say, is my Home Page and contains various elements.
2. Inside that panel, in a certain area, I wish to have Two View Panes
3. View Pane A - Contains, say, a list of node titles
4. View Pane B - Upon selecting a node title in View Pane A, I want View Pane B to display the content for that node

(My implementation uses Video Titles in Pane A which should display the relevant Videos in Pane B)

Current Approach:

* Panel is set with URL: homePage/%currentVideo
* In Page Manager, %currentVideo argument is configured to be assigned to the context Node:ID
* View Pane B has a contextual filter of Node:ID
* View Pane B has the Content ID from the Node assigned as the context for Argument Input
* When adding View Pane B to the Panel, I set the contextual filter to get it's input from %currentVideo
* View Pane A lists all the titles, and Rewrites the titles to a link that points to homePage/\[nid\] -- where \[nid\] is the input for the currentVideo

This works but I would ideally like to do this without using Arguments in the URL, since I want there to be several such Pane A/Pane B combinations on a home page, where selecting something in Pane A outputs content in Pane B. Therefore, the URL would just be /homePage, and wouldn't be used to pass arguments in/out in order to facilitate such a process.

Questions:

1. Do I need to use Ajax? If so, - could someone suggest how the above process is best implemented?
2. Or is there another approach using views, view panes, context and panels, that allows selection in one View Pane to trigger output in another View Pane within the same Page/Panel? (I'm not averse to re-loading the page, I just don't want to have to stuff multiple arguments in the URL as I feel it will get unmanageable over time.)

I have found an tried this Excellent tutorial on writing a module to implement an Ajax Callback, but am *sure-ish* that it could be all done within Views/Panels...

"Creating a Simple AJAX Interface with Views" : http://mrkadin.com/blog/node/70

Many Thanks in advance

# Answer
There is sort of a hackish way to implement such behavior, described on this answer: https://stackoverflow.com/a/1596756/1421920

In short, the answer suggests two displays of the same view, one with the titles on the left with exposed filters (hidden by CSS) and the other one with the acutal content of the nodes. Add JS to the titles to fill the other view's exposed filter (also hidden by CSS) and submit. The relevant node loads on the second view with AJAX.
> 1 votes

---
Tags: views, ajax, panels, 7
---


# Question
Title: how to use hook_webform_submission_presave on a site with multiple webforms
I've got a question on the use of the hook\_webform\_submission\_presave function for D6/webform 6.x-3.4

I've got a multi-lingual D6 site that has one webform for each language, I'm trying to create a new module that will catch the submitted form info and send it to a third party email marketing company (the forms are newsletter signups and the third party is cheetahmail).

My specific question is: Currently I have 6 webforms on my site, and I need to send info to identify which language the signup has come from.

Do I have to write a hook for each language/form ID? or is there a way I can set up an admin panel and list the webform IDs that I'd like to hook?

Thanks for the help, please let me know if I need to provide more detail Steph

# Answer
> 0 votes
Ok, So I've figured this one out:

```
function cheetahmail_webform_submission_presave($node, &$submission) {
Do something here
}

```

Without calling a specific form, will effect all webforms. in my specific instance, i'm trying to catch the submitted/validated info before it enters the DB.

---
Tags: 6, hooks, webforms
---


# Question
Title: Set data (current nid) to entity reference field with rules and VBO
I'm currently stuck in the creation of a custom rule.

I would like to show a button on some content type, this button called a list of other content called "guide". I list these contents (guide) in a view and I added a field to associate a rule vbo. In the type of content I have a guide entity reference fields might add my id of the current node content (the button add to the guide) to guide one or more listed.

How to perform the action:

1. get the nid of current content
2. define the fields at the end of the reference entity or selected guides
3. save the guide(s)

Note : The list of guides is showed in a lightbox when button "add to guide" in a content was clicked.

Thank you very much in advance

# Answer
> 1 votes
I will first confirm if I understood this correctly.

* You have a content type where you will show a button. Let's call this content type `MainType`.
* You have another content type called `guide`.
* You have an entity reference field on `guide` which points to a particular node (nid) of content type `MainType`.
* In nodes of `MainType`, there is a button which shows all guides pointing to the visible node. You already have this view.
* You want to add a link which will create a new `guide` node with entity reference pointing the node on which the link was clicked.
* From your comment: You want to use VBO to set referenced field in selected `guide` nodes to the current node.

I can't think of a way to do this without code, as the context of the original node is probably lost in the view of `guide` nodes. However, you can do it in a slightly different way:

Create a Rules component with two variables, both of `Node` type. First one is your `guide` node, set by VBO and the second will be your reference to the node.

You should then write your rules actions to set entity field value for `guide` node's field to the nid of second reference. You can take a look at this video which implements a very similar requirement.

I hope this helps.

---
Tags: rules, entities, views
---


# Question
Title: Conditionally run a view if another view has no results
I have a client who has an Upcoming Events view. However, when there are no upcoming events, he wants to show another view (Past Three Events) which shows the past 3 events. Basically he doesn't like it when the page doesn't show any events so he wants to show something.

I thought of attaching another block of the Past Three Events to the bottom of the main view (Upcoming Events) and then using jQuery to hide it if the main view (Upcoming Events) is populated.

But I was hoping that someone knows a more elegant solution where perhaps either I can conditionally run a view (perhaps using EFQ which I know nothing about) or somehow adjust views to combine 2 queries in one.

# Answer
> 8 votes
When editing the view, under *Advanced \> No results behavior* select `Global: View area`. Select the view you wish to show if the first has no result, and check if you want the replacement view to inherit the contextual filters of the first.

---
Tags: views
---


title: Using db_query in Drupal 7

text:
# Question
Title: Using db_query in Drupal 7
I'm in the process of porting my contrib module from Drupal 6 to Drupal 7, and I'm getting a little stuck with how I should got about using db\_query() in Drupal 7. I know it now uses a similar syntax to PDO, but I'm not quite sure how to translate the following line from the Drupal 6 version of the module:

```
if ($result = db_query('SELECT name FROM {variable} WHERE name LIKE "%%%s%"', 'csm_node_temp_')) {
while ($array = db_fetch_array($result)) {
  $variables[] = $array['name'];
}

```

}

This code removes all of the variables that my module has added to the variable table; i.e., all variables with names that start with the string "csm\_node\_temp". How should I rewrite these lines for the Drupal 7 version of my module?

# Answer
> 6 votes
The D7 equivalent would be:

```
$sql = 'SELECT name FROM {variable} WHERE name LIKE :name';
$args = array(':name' => db_like('csm_node_temp_') . '%');

foreach (db_query($sql, $args) as $result) {
  $names[] = $result->name;
}

```

Or if you wanted a structured query using `db_select()`:

```
$variables = db_select('variable', 'v')
  ->fields('v', array('name'))
  ->condition('name', db_like('csm_node_temp_') . '%', 'LIKE');

foreach ($variables->execute() as $result) {
  $names[] = $result->name;
}

```

n.b. the above are the most basic use of either of those functions. With some of the helper methods they get a bit more powerful.

For example, you're just looking for a single column of data from your query. The DB API can handle this with the `fetchCol()` method. So for the first example you can do:

```
$sql = 'SELECT name FROM {variable} WHERE name LIKE :name';
$args = array(':name' => db_like('csm_node_temp_') . '%');
$names = db_query($sql, $args)->fetchCol();

```

and for the second:

```
$names = db_select('variable', 'v')
  ->fields('v', array('name'))
  ->condition('name', db_like('csm_node_temp_') . '%', 'LIKE')
  ->execute()
  ->fetchCol();

```

In both cases `$names` will contain an array of the names found by the query. Much easier than looping over the results manually :)

---
Tags: 7, database
---


# Question
Title: override views-view-fields.tpl.php in custom module
Hi i want to Override **views-view-fields.tpl.php** in our **custom module**. kindly help me by example.

# Answer
> 5 votes
You need to define a theme hook for the field-template in your module and place a template in custom\_module/theme/your-custom-template.tpl:

```
/**
* Implementation of hook_theme().
*/
function custom_module_theme($existing) {
  return array(
    'views_view_field__view_name__field_name' => array(
    'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
    'template' => 'your-custom-template',
    'original hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'custom_module') . '/theme',
   ),
  );
}

```

To narrow down which field-templates you want to replace you can name your return key to:

* views\_view\_field\__view\_name: Override all field templates of the view named "view\_name"
* views\_view\_field\__view\_name\__field\_name: Override only this specific field

This example is taken from grayside.org

# Answer
> 1 votes
The view object is available in the tpl file, so by having an `if-else` statement it is possible to filter the views that need to the override by inspecting the name/display of the view.

A sample piece of code might help say for example using hook\_field\_attach\_view\_alter():

```
function MYMODULE_field_attach_view_alter(&$output, $context) {

  $field_name = 'test';
  $to_display = array('a');

  if (isset($output[$field_name]['#field_name'])) {
    if ($field_name == $output[$field_name]['#field_name']) {
      foreach ($output[$field_name]['#items'] as $delta => $item) {
        if (in_array($item['value'], $to_display)) {
          unset($output[$field_name][$delta]);
        }
      }
    }
  }
}

```

---
Tags: views, hooks, theming
---


# Question
Title: How can I force a user to submit webform before viewing certain pages?
I have a client who wants a webform to pop up when a user views a search result page. They want to user to submit their contact info in order to view the results, but only once in case they search multiple times.

# Answer
> 1 votes
Your best bet is to use this the splasify module: https://drupal.org/project/splashify

As for popping it up only once, you'll have to set a cookie somehow to track that it has popped up already. It might be suppored in that module already.

---
Tags: 7, webforms
---


# Question
Title: How to print "rendered node" version of Node Reference field in template?
I have two content types: Type A and Type B. I have a Node Reference field on content Type A (using References module) that is set to be displayed using the "Rendered Node" version of that referenced node. It references nodes of content Type B. How can I print the content of that field as a rendered node in a custom template file for content Type A?

# Answer
In your `$node` object, you will find the subordinate node object at `$node->field_fieldname['und'][0]['node']`. To render this in a page you have to turn it into a renderable array. You do this with `node_view()`,specifying the type of display mode. Try:

```
<?php
if(isset($node->field_fieldname['und'][0]['node'])) {
  $second_node = $node->field_fieldname['und'][0]['node'];
  $view_mode = 'teaser'; // or 'full' as the case may be
  $render_array = node_view( $second_node, $view_mode);
  print render($render_array);
}
?>

```

EDIT

MPD is correct. The above assumes that the field is a Node Reference field. If you are using an Entity Reference field, the code should be changed to:

```
 <?php
    if(isset($node->field_fieldname['und'][0]['entity'])) {
      $second_node = $node->field_fieldname['und'][0]['entity'];
      ...

```
> 4 votes

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


# Question
Title: After enabling repeat date on node, calendar won't show repeated dates
I made a calendar view that displays all my events. When I created the view the content type Events wasn't enabled for repeating dates.

But now I do want repeating dates, so I enabled the repeat date modules en settings in the content type.

So when I input repeated dates it shows correctly in my node buildmodes but it doesn't show the repeats in my calendar only the first one. Can I still change the calendar to display repeated dates?

Thanks in advance

### UPDATE

There's an issue in the date module The last solution is for drupal 6 I think because I can't find Global Settings of 'Number of values as 1' in Drupal 7 http://drupal.org/node/1391464

# solution

I had to delete my field\_event\_date and recreated to be repeating I only lost my dates instead of my full nodes.

# Answer
After deleting and recreating the date field on your content type (as in the Original post), re-add it to the list of fields in the Views context filter (Date: date(node)).
> 1 votes

# Answer
Edit your user permission settings to allow display of repeat dates.
> 0 votes

---
Tags: datetime
---


# Question
Title: js files inside custom directory deleted after cache clear
I have 2 files with jquery code in custom directory www.mysite.com/files/js/...Every time I clear cache, the files are deleted from server. How is this possible? Anyone came across this issue?

# Answer
> 0 votes
Files were added using drupal\_add\_js inside node body using php filter. Path was 'files/js/myfile.js' without using domain name. I resolved it by changing directory name from 'js' to 'js-custom'. I think 'js' directory was created by some module there and was emptied after each cache flush. Now everything works ok.

---
Tags: 6, caching
---


# Question
Title: Will all Drupal 7 Ubercart 3 orders be deleted if I disable & uninstall all Ubercart related modules?
I'm working on migrating a Ubercart site to Commerce and wanted to know if all Ubercart orders and tables will be deleted if I disable & uninstall all related modules. Since I don't need the old data, I don't mind it having it completely deleted.

# Answer
If you uninstall them, then yes.

EDIT:

No, they will not. Good call, duckx (I shouldn't have assumed that the D7 version implemented `hook_uninstall_schema()`).
> 0 votes

---
Tags: 7, commerce, ubercart, migrations
---


# Question
Title: Create block user flag, hide users from view
I have created a social site where users can flag other users as "blocked". The primary view for the site lists users along with a bit of profile2 data and a "block" flag link. Users cannot see themselves in the view.

What relationships and filter criteria do I need to add to hide blocked users from the view on a per-user basis?

Example use case: 4 users, User A blocks User C

User A's view:

* User B
* User C (message about how you blocked them)
* User D

User B's view:

* User A
* User C
* User D

User C's view:

* User B
* User D

User D's view:

* User A
* User B
* User C

# Answer
> 1 votes
I couldn't find a way to do this within Views, despite the seemingly simple task and the various decent explanations found around the internet (nit3ch's comment included). The explanations limited the view results too much or in the wrong way.

I ended up using a Views PHP filter field to perform the filtering task:

```
global $user;
$flags = flag_get_user_flags('user', NULL, $row->uid);
if( array_key_exists('block', $flags) && array_key_exists($user->uid, $flags['block'])){
    //dsm($row); // optional debug
    return TRUE; // prevents row from being displayed
}

```

---
Tags: 7, views, users, flags
---


# Question
Title: how to Remove "Add new Content" from the Main page
I have a front page in which blocks and some contents (ie story) were displayed. These stories were marked as "Promoted to front page"; later, I unchecked them. These stories are now gone, yet the blocks were present.

Now I have the following content on my front page:

"No front page content has been created yet.

Add new content"

How do I remove this content or text?

# Answer
> 8 votes
Just add this code to the page.tpl.php or page--front.tpl.php on Drupal 7.

find

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

```

and replace with below code.

```
<?php  if(drupal_is_front_page())
                {
                    unset($page['content']['system_main']['default_message']);
            }
        print render($page['content']);
    ?>

```

And i believe you surely get all blocks or contents you posted on page.

and to remove page title on page like

Welcome to "website name"

find this code on page.tpl.php or page--front.tpl.php

```
<?php if ($title): ?><h1 class="title" id="page-title"><?php  print $title; ?></h1>
<?php endif; ?>

```

and you can remove this code or else just make a comment over.

# Answer
> 1 votes
There are a couple of ways in which you can accomplish this:

1. **Front Page**
2. **Views**

If you go the views route, enable the **frontpage view**, then go to admin/config/system/site-information and change the "Default front page" path to 'frontpage.'

# Answer
> 0 votes
First create one sample page using node/add/page in admin side of your website.

After creating the page, you can set the homepage of your website using admin/config/system/site-information of your website. there you need to paste the url of your previously created page path in "Default front page" textbox. After saving the configuration, the home page content will be replaced with your new page content.

Hope this can work for you!

# Answer
> 0 votes
Out of the three ways above, which is the best way and guaranteed to work for drupal 7 bartik and zen themes?

# Answer
> 0 votes
If you just want a bunch of blocks on the home page (a very common requirement), the best easy way to do this is to use the empty\_page module.

To use it you can:

1. Create an empty page (via the settings page of the module) with the path "home" (or similar) and the title being the name of your site (unless you want some other title for the home page).
2. On the site information settings page (admin/config/system/site-information), set the home page path to "home" (or whatever you made the path in the previous step).

This approach is good because you are not loading a node unnecessarily (in the case you use a blank node page as your home page) or processing the default drupal home page code, which is good for performance, and the module is simpler than the front page module.

# Answer
> 0 votes
The D7 main content is now a block, so just set the Main page content under blocks settings. Go to Structure \> Blocks \> Click configure on Main page content. On "Show block on specific pages" choose "All pages except those listed" and fill with `<front>`.

Source.

# Answer
> -1 votes
Just edit to /modules/node/node.module, look for $default\_message line (around line 2621) and change 'No front page content has been created yet' to simply ''.

---
Tags: 7
---


# Question
Title: Cache clearing takes too long: What can I do to improve it?
Everytime I clear all the caches, the process takes too long. This is from the log to a prod site I am currently working with.

> 368829 | \[someuser\] | dbname | Query | 3376 | updating | `DELETE FROM cache_page WHERE expire != 0 AND expire <= 1370891317`

As you can see, it was executing for 3376 seconds. I am wondering if this is a known issue, or it is simply because there is just too much in that table.

Also, is there anything I can do to improve this?

# Answer
> 1 votes
I have a pure MySQL approach to clearing the `cache_page` table quickly.

```
use dbname
ALTER TABLE cache_page RENAME cache_pageoff;
CREATE TABLE cache_pagenew LIKE cache_pageoff;
INSERT INTO cache_pagenew
    SELECT * FROM cache_pageoff
    WHERE expire > 1370891317
;
ALTER TABLE cache_pagenew RENAME cache_page;
TRUNCATE TABLE cache_pageoff;
DROP TABLE cache_pageoff;

```

This script will do the following:

* take the `cache_page` offline
* create a new `cache_page`
* load the new `cache_page` with the most current data
* put the new `cache_page` back online
* remove the old `cache_page`

Give it a Try !!!

BTW the reason the process is taking long has to do with the range of the delete and the storage engine is use.

* If your `cache_page` tables is using the MyISAM storage engine, the `DELETE` query would be traversing almost the entire table and deleting each row.
* If your `cache_page` tables is using the InnoDB storage engine, this is orders or magnitude worse that MyISAM. Why? All the rows you are deleting are stored in the Undo Logs within ibdata1.
    + When the `DELETE` query has completed successfully, all the Undo Logs for the `cache_page` table are purged.
    + If the `DELETE` query is interrupted by a rollback operation, all the Undo Logs are used to restore the `cache_page` table in its original state. If `cache_page` is InnoDB, I strongly recommend not interrupting the `DELETE` query. Let it goes its full course.

---
Tags: database
---


# Question
Title: How to override node content in Drupal 7
So I see in the archives how to override a node's $title (How do I overwrite node title for specific content type?), but how would I override the node's content in Drupal 7? I see that Drupal 7 no longer uses $vars\['content'\], which was really handy in Drupal 6

# Answer
> 2 votes
In Drupal 7 the content is in $content.

See node.tpl.php

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

```

The $content definition:

> An array of node items. Use render($content) to print them all, or print a subset such as render($content\['field\_example'\]). Use hide($content\['field\_example'\]) to temporarily suppress the printing of a given element.

---
Tags: theming
---


title: Drupal Views overflow

text:
# Question
Title: Drupal Views overflow
I have a Drupal 7 / Views question... I have a site with some data reports displaying in various graphs/ gauges etc. I also have a "Data" page that shows all of the data used so the user can look through it and/or even download it. My problem stems from the views table overflows past the screen on the right with data. This in itself is not a big issue, but I was wondering if there was a way to contain the view inside a fixed size box/container that is scrollable. Much like a text box.

Again, not that it would help the functionality but sure would make it look nice and clean.

Thank you in advance.

# Answer
If you are focusing on the problem of data overflow from the views table, CSS could solve the issue.

For example if you write a code similar to this:

```
<style>
  .container
  {
    background: #fee;
    height: 400px;
    width: 400px;
    display: -webkit-box;
    display: -moz-box;
    display: box;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    box-orient: vertical;
  }
  .header
  {
    background: #fee;
    -webkit-box-flex: 0;
    -moz-box-flex: 0;
    box-flex: 0;
  }
  .footer
  {
    background: #eef;
    overflow: auto;
    -webkit-box-flex: 1;
    -moz-box-flex: 1;
    box-flex: 1;
  }
</style>

<div class="container">
  <div class="header">...</div>
  <div class="footer">...</div>
</div>

```

The only factor that is missing and could prevent the overflow is:

```
width: 100%;

```

Often you need to set the height of Content as well. If the height attribute is not set, the div will grow vertically as tall as it needs to. You may also try using a **FixedHeightContainer**
> 1 votes

---
Tags: views
---


title: nodeaccess configuration problems

text:
# Question
Title: nodeaccess configuration problems
I created a view that I called gallery (in Drupal 7) which links to a number of sub galleries (http://quaaoutlodge.com/gallery). The sub galleries are of content type gallery. So, I installed the nodeaccess module because the galleries and the gallery main page should only be accessible by my GalleryViewer (and GalleryEditor) so I set the Gallery node type up accordingly (no checks for anonymous user). I saved grants and rebuilt permissions. Now, even tho I did the above, any user caan browse my gallery types that are linked from http://quaaoutlodge.com/gallery. Why is this? What am I doing wrong? :o

# Answer
You have to set the permission inside the Views BLOCK SETTINGS \> Access
> 1 votes

---
Tags: users
---


# Question
Title: Should I choose MyISAM for notification tables?
Using Drupal6 with a MariaDB 10 InnoDB engine for all tables, I have noticed that insert queries into notifications\_\* tables are very inefficient on InnoDB tables. For example, these frequently in my slow\_query\_log:

```
INSERT INTO notifications_event (module, type, action, oid, uid, params, created, counter)
VALUES ('XXX', 'XXX', 'XXX', XXX, XXX, 'XXX', XXX, XXX);

INSERT INTO notifications_fields (sid, field, value, intval)
VALUES(XXX, 'XXX', 'XXX', XXX);

```

# QUESTIONS

* Would be a good idea to convert such tables into MyISAM?
* Any downside for using such mix of storage engines?
* Is there a better solution to shorten the insert time?

# Answer
> 2 votes
# *DISCLAIMER : Pure MySQL Perspective*

IMHO, you should leave it as InnoDB. MyISAM is not good in high-write situations. Why ?

# **LOCKING GRANULARITY**

Each time you issue an INSERT, UPDATE, or DELETE query on a MyISAM table

* The query performs a full table lock
* All other queries needing to do the INSERT, UPDATE, or DELETE queries are handled on a first-come first-serve basis

InnoDB has row-level locking. In order to accommodate this, InnoDB caches INSERTs, UPDATEs, and DELETEs in the Buffer Pool, Log buffer, and Undo Logs.

# **DATA CACHING**

MyISAM caches index pages from each MyISAM table's `.MYI` file in the key buffer.

MyISAM does not cache data. It has to piggyback from the OS for that. You can change the row format of the MyISAM to increase read speed from disk at the expense of double the table's disk usage. Write speed may be adjusted with concurrent INSERTs.

InnoDB caches data and indexes pages in the InnoDB Buffer Pool. You may need a decent size to accommodate data and indexes.

# **EPILOGUE**

You just have to tune some vital settings. Here are some of my past suggestions from the DBA StackExchange.

## In favor of InnoDB

## In favor of MyISAM

Although I lean towards InnoDB, I will leave it to you to decide which storage engine you want to use and tune for.

# Answer
> 1 votes
Using SQL database for everything is well known Drupal problem. A lot of data, like notifications and watchdog, does not need SQL anyway, they are just a key-value pairs.

InnoDB uses a much more sophisticated locking strategy. It's perfect for tables you often read and write at the same time, but slower for any single task. MyISAM is simpler, and way faster if you only add occasional and seldom try to read at the same time. I.e. you write to it at night and read it all day.

Joins between different engines are slow, keep that in mind.

If feasible, move Notifications' table to nosql solution. RAM-based if you have a plenty of RAM, just mirrored to disk. It might need hacking the very module, though, so it might end up next to impossible.

# Answer
> 1 votes
You say you have plenty of RAM. If you feel like risking a bit, try MemSQL. It removes main bottleneck - HDD - from the equation. It also claims to be lock-free and optimized for frequent inserts.

And it's developers says transitioning from MySQL is easy as it should be drop-in API-compatible replacement.

Idea taken from syedrakib's question.

---
Tags: performance, notifications, database
---


# Question
Title: form ajax forget's changes made in previous ajax callback calls
Why do changes don't get saved in `$form`, or what is it that's overriding it?

I would like to set custom class to multiple fieldsets in an ajax callback function:

```
if (something) {
  $form['fieldset_01']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_02']['#attributes'] = array('class' => array('custom_class'));
}
elseif (somethingelse) {
  $form['fieldset_11']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_12']['#attributes'] = array('class' => array('custom_class'));
}

return $form;

```

When `$form` is returned, the element that I have set in this call is rendered fine, with a new CSS class but the elements I have rendered in previous calls have lost this new class, as if they were rendered with default values.

EDIT: my form creation function

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

$nid = $form_state['values']['nid'];

$ajax = array(
'callback' => 'mynode_ajax',
'wrapper' => 'mynode_form',
'event' => 'change',
'method' => 'replace',
);

$node = node_load($nid);
$title = $node->field_title['und'][0]['value'];

$form = array();
$form['#prefix'] = '<div id="mynode_form">';
$form['#suffix'] = '</div>';

$form['nid'] = array(
  '#value' => $nid,
  '#type' => 'hidden',
);

$form['fieldset_0'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 0',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_0']['textfield_0'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 0?'),
  '#ajax' => $ajax,
);

$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 1',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_1']['textfield_1'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 1?'),
  '#ajax' => $ajax,
);

if (isset($form_state['triggering_element']['#name'])){
  $key = $form_state['triggering_element']['#name'];
  switch($key){
    case 'textfield_0':
      $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b',   'c'));
      $form['fieldset_1']['#attributes'] = array('class' => array('a',   'b'));
    break;
  }
}
else{
  //only the first time
  $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b'));
  $form['fieldset_1']['#attributes'] = array('class' => array('a', 'b'));
}
return $form;
}

```

# Answer
AJAX callback function is meant to only tell Drupal what to update. By design all you do in it is for one call only.

Permanent changes needs to be done in main form creation function. I usually see them done in block like that:

```
if (!empty($form_state['values'])) {
  //here you are supposed to use these values
}

```
> 3 votes

---
Tags: forms, ajax
---


title: Pager for basic pages in Drupal

text:
# Question
Title: Pager for basic pages in Drupal
I am working on site, on site for certain set of basic pages i want to provide a numeric navigation with previous/next buttons. Is there a module to achieve it easily or else we need to hard code it.

Please suggest me some solutions to get this functionality.

# Answer
Smart Paging have the option to navigation with previous/next links with numeric navigation see the below image and add a css style to prev/next class to achieve the button effect. See the demo

also worth checking this module Pagerer for providing a collection of pager themes to enhance Drupal and Views standard pagers. See Demo
> 1 votes

---
Tags: paging
---


# Question
Title: Changing menu paths for existing nodes in Drupal 7
So I have created around 100 articles of a specific content type and provided all of them a menu path under a specific menu.

Now the requirement is to alter these menu paths and give these nodes a new menu path under another menu. The longer and obvious way to go about doing this is to edit each of these content types manually and then edit the menu path to edit and point it to the new menu. This is a painstaking procedure that shall consume time. I am sure there are alternatives such as a Drupal module that let's you mass alter menu paths for a specific content type?

Alternately, is there a way for me to get into the drupal database and find out where these menu paths for a specific node/content type are stored? And I can simply execute a query that goes in and changes that?

Thanks!

# Answer
> 1 votes
Take a look at the Pathauto module. You can configure it to create paths automatically with a given pattern for individual content types. It also has options to bulk delete and update existing paths.

# Answer
> 1 votes
1. I think you can just use Pathauto module for this.
2. Refer Pathauto
3. Rename the URL pattern and use the Bulk update function to regenerate all aliases.
4. You can also do this through the content overview screen (/admin/content) by filtering out the content type and then select all and choose "Update URL alias" from the drop down menu

# Answer
> 0 votes
You might want to check out these modules:

D6 - Menu Editor \- provides a better interface to make it easier to edit the paths in case you have to do it manually.

D6/D7 - Menu Import \- I believe you can use this by writing up a properly formatted/syntax text file, with all of your new menu items, and import it into Drupal. If you are handy with keyboard and copy/paste regex or whatever, this might be faster.

---
Tags: 7, uri, routes
---


# Question
Title: Which IPs/hosts does Drupal query for updates?
I recently migrated a Drupal 7 installation from my own development server to a hosted solution, which runs all nice and dandy, however Drupal now can't load the data anymore to check for available updates.

It says,

> Fehler beim Abrufen der Daten über verfügbare Aktualisierungen.

Or in English, I think the translation is:

> No available update data

I asked the technical support of the web hoster if they could remove any kind of firewall or filter that'd block Drupal's external requests, and they replied to me that they needed to know which URLs / IPs or hosts are called so they could whitelist them.

What are these URLs?

# Answer
> 5 votes
From `update.module`:

```
/**
 * URL to check for updates, if a given project doesn't define its own.
 */
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');

```

Each module and theme is allowed to define it's own URL, it'll be in it's info file, but this one will cover most cases.

Note you need an access to all paths under this one, ie for Views updates Drupal will query http://updates.drupal.org/release-history/views/7.x

---
Tags: 7, updating
---


title: How to remove "pending update"?

text:
# Question
Title: How to remove "pending update"?
I updated a module, ran update.php, made some edits and backed up it's table for migration. And then HDD on server failed. Admins restored it from nightly backup, and from my backup as well (both was in proper backup directory). So I had new table structure and data, but old files. I uploaded module's files and it all works, but it shows I have one pending update. Update that is bound to fail as columns it's supposed to rename are already renamed.

Is there an easy way to tell Drupal manually "it's done already, don't try to run this update"?

# Answer
> 9 votes
I've never done this before so I'm not sure if this will work but I assume you can manually update the `schema_version` column in the `{system}` table to the highest `hook_update_N` number. For example if there's `mymodule_update_7101` in the .install file of `mymodule` then update the `schema_version` column of the system table for `mymodule` to 7101.

I don't get it though, how come if you have updated fields in the module table of same database, how is it that the system table is older?

---
Tags: 7, updating
---


# Question
Title: Adding multiple checkbox in drupal using cck
I am trying to add multiple checkbox. My requirement is how can you travel the place with

1. Plane
2. Train
3. Bus
4. Ship

One can select all the four above options. For that I added a new field `Travel Details` , field type `Boolean` , Widget `Check boxes/radio buttons` . From Drupal CCK

I made `Number of values` equal to `4` . But I am getting only two fields, also without their names ! How can I able to make this content type to behave like normal HTML checkboxes with their names ?

# Answer
> 2 votes
A **Boolean** field/value can only store `True` or `False`. What you need is a **List (text)** field with **Check boxes/radio buttons** widget.

Then put

```
Plane
Train
Bus
Ship

```

in the Allowed Values list.

You can set **Number of Values** to `4` but I'd set it to `Unlimited` just in case you add more allowed values and forget to update the number of values.

---
Tags: 7, nodes, forms
---


# Question
Title: Is there an ready-made solution to mark edited form fields?
When you edit something in text editor or IDE, you get visual feedback - star next to file name, bolded file name et cetera. That way you easily know what has been edited and what not.

Is there a ready made solution to introduce that to Drupal? Either system-wide or manually using Form API? It would make sense to see if any changes was made or not, especially if one opens dozen of nodes for updates and then sees some of them are already up to date and does not need a save (and associated boost cache clears).

In large setting forms, like permissions or Elysia Cron, it would help too.

The ideal would be to add some class to each field with value not equal it's default value, so the theme could deal with it using only CSS.

Anyone written it already?

# Answer
I've only seen Track Field Changes, but that doesn't give immediate visual feedback.

**Edit:** I know you asked for something that was already out in the wild, but the following *might* be useful.

I guess you could write something custom *relatively* easily though using jQuery's .change event.

Something like the following I guess (code will need checking but it should be pretty near).

**JavaScript**

```
(function ($) {
    Drupal.behaviors.formFieldTracker = {
      attach: function(){
        $(input).change(function(){
          $(this).addClass('field-edited');
        }));
      }
    }
})(jQuery)

```

**Module**

```
function MYMODULE_preprocess_page(&$vars) {
  // Only add the JavaScript on admin pages as defined by hook_admin_paths()
  if (path_is_admin(current_path())) {
    $path = drupal_get_path('module', 'MYMODULE');
    drupal_add_js($path . '/js/MYSCRIPT.js');
    $vars['scripts'] = drupal_get_js();
  }
}

```

Then you could add whatever CSS you fancy afterwards:

```
.field-edited:after {
  content: 'Edited';
  display: inline-block;
  color: #F00;
  font-style: italic;
}

```
> 3 votes

---
Tags: theming, forms
---


# Question
Title: Module for enforcing mandatory minimum number of tags in content type field?
The built-in tag field functionality allows definition of a *maximum* number of tags, but not a minimum number.

Is there a contrib module to enforce a minimum?

# Answer
You should be able to use Field Validation.

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.

Just create your term/entity reference field and set up a validation rule using the *Number of Selections* rule.

Leave the maximum number of fields empty, and enter the minimum you require as the minimum required values.
> 3 votes

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


title: Undefined index: #attributes

text:
# Question
Title: Undefined index: #attributes
I have these errors :

> * Notice: Undefined index: #attributes in theme\_container() (line 3251 of /Applications/MAMP/htdocs/drupal-7.22/includes/form.inc).
> * Recoverable fatal error: Argument 1 passed to drupal\_attributes() must be of the type array, null given, called in /Applications/MAMP/htdocs/drupal-7.22/includes/form.inc on line 3251 and defined in drupal\_attributes() (line 2374 of /Applications/MAMP/htdocs/drupal-7.22/includes/common.inc).

And I do not understand why since I checked on other similar posts and my code seems ok :

.module file :

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

 $items['admin/config/media/gestionvideos'] = array(
 'title' => 'Gestion vidéos',
 'description' => 'Configurer le plugin VOD Infomaniak',
 'page callback' => 'drupal_get_form',
 'page arguments' => array('gestionvideos_configuration'),
 'file' => 'gestion_videos.admin.inc',
 'access arguments' => array('administer site configuration'),
 'type' => MENU_NORMAL_ITEM,
 );
return $items;
}

```

and .admin.inc file:

```
function gestionvideos_configuration() {
  $form = array(
    '#submit' => array('gestionvideos_configuration_submit'),
  );
  $form['config'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administration du plugin VOD'),
    '#description' => t('Pour fonctionner, le plugin a besoin de s\'interfacer avec votre compte VOD infomaniak.<br/>
                    Pour des raisons de securites, il est fortement conseille de creer un nouvel utilisateur dedie dans votre admin infomaniak avec uniquement des droits restreints sur l\'API.<br/>
                    Pour plus d\'information, veuillez vous rendre dans la partie "Configuration -> Api & Callback" de votre administration VOD.
                '),
  );
  return system_settings_form($form);
}

```

Do you have any idea how I could solve this ? Thanks a lot !

# Answer
You need to accept the `$form` (and `$form_state`) parameters as part of the function signature, and not overwrite the form, rather add to it:

```
function gestionvideos_configuration($form, &$form_state) {
  $form['#submit'][] = 'gestionvideos_configuration_submit';

  $form['config'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administration du plugin VOD'),
    '#description' => t('Pour fonctionner, le plugin a besoin de s\'interfacer avec votre compte VOD infomaniak.<br/>
                Pour des raisons de securites, il est fortement conseille de creer un nouvel utilisateur dedie dans votre admin infomaniak avec uniquement des droits restreints sur l\'API.<br/>
                Pour plus d\'information, veuillez vous rendre dans la partie "Configuration -> Api & Callback" de votre administration VOD.
    '),
    '#default_value' => variable_get('config', ''),
  );

  return system_settings_form($form);
}

```

Choosing a different name than 'config' for your variable might also be wise. It's always preferable to provide a pseudo-namespace to variables as a prefix, usually the module name (e.g. `gestionvideos_config`). Don't forget to add the default value as in the above example as well, otherwise next time you go to the form it will have forgotten your config option.

If the above doesn't work for whatever reason, then the bug is somewhere else; try systematically disabling custom/contrib modules until you find the culprit.
> 2 votes

---
Tags: 7
---


# Question
Title: Use another token value if the first one is empty
I am using the \[message:user:profile-fname\] token to get the first name of the user, but some users are without first name; the value shown for that token is a blank string.

How can I use another token (e.g. \[message:user\]) if the first token is an empty string?

# Answer
Seems like there was Token Logic module, once upon a time, and it got abandoned: https://drupal.org/node/354039

You can try and wrote your own token to fill that niche, or contact original's authors.
> 2 votes

---
Tags: tokens
---


title: How to put links into description text?

text:
# Question
Title: How to put links into description text?
In my field's description, I want to link to more documentation. If I do it like this:

```
$form['field_name'] = array (
  '#description' => t('Here are some words about') . ' <a href="http://mysite.com/blah">' . t('stuff') . '</a> ' . t('and things and whatnot'),
);

```

It works. It looks like this:

> Here are some words about stuff and things and whatnot.

If I do it the proper way, like this:

```
$form['field_name'] = array (
  '#description' => t('Here are some words about @stuff and things and whatnot', array('@stuff' => l('stuff', 'blah')),
);

```

Then the HTML is generated and then output into my description as raw text, like so:

> Here are some words about \<a href="http://mysite.com/blah"\>stuff\</a\> and things and whatnot.

Why is the "correct" way not working?

# Answer
> 6 votes
Firstly, here are some of the ways ***NOT*** to pass links to the `t()` function:

```
// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => '<a href="http://drupal.org/handbooks">'. t('the Drupal Handbooks') .'</a>'));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at <a href="http://drupal.org/handbooks">the Drupal Handbooks</a>.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

```

And these are the accepted ways *to* pass that type of arg:

```
// Do this instead.
$external_link = t('Look at Drupal documentation at <a href="@drupal-handbook">the Drupal Handbooks</a>.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to <a href="@administer-page">the Administer screen</a> in the main menu.', array('@administer-page' => url('admin')));

```

This all comes from Dynamic or static links and HTML in translatable strings, which contains justifications for that reasoning.

---
Tags: forms, navigation, i18n-l10n, theming
---


# Question
Title: drupal 7 remove logon & password for anonymouse users
I have a username and password for my site for development purposes and now want to take the site live and remove the username and password for anonymous users. How do I do that?

# Answer
> 1 votes
Go to admin/structure/block and look for the user login block set Region dropdown to none. If you are using the default Drupal theme, it would be under sidebar first category

**UPDATE**

but users can still create new accounts from /user page. To disable this, go to

configuration -\> people -\> account settings -\> registration and cancellation and set "Who can register accounts?" -\> "Administrators only".

---
Tags: security
---


# Question
Title: How to force to upload a image with exact sizes?
When adding an image field to a content type I can set the minimum sizes under which the image will not upload. I also can set maximum sizes but if the image is bigger the system will resize the image. How can I change this?

I need to set both limits: minimum a maximun sizes. This mean a exact size for the image, then if the image has not the exact size it shouldn't be allow to upload.

# Answer
> 3 votes
This is mostly based on memory, so some details might be off.

The image field widget assumes that downsizing an image is a valid action in all cases, so you'll need to override it.

Implementing your own field widget requires a little bit of fiddling with the field api, but since your change is fairly small, you should be able to just wrap a number of image field function and add a single validation step.

Since image field already is mostly a wrapper around a file field, looking at the image field itself for how to implement the above is probably a good start.

# Answer
> 0 votes
Simplest but hardcore solution is to disable GD in your PHP. It will disable all built-in scaling and cropping, including the one you don't want here.

Then you could try to re-implement things you want to happen using ImageMagick.

---
Tags: entities, media
---


# Question
Title: Exclude some, not all, user profiles from search engine results
Is there a way to let users choose if they want their user profile to be excluded from external search engine results? Any modules or hooks known?

It should be based on the de/selection of a boolean field "Display my user profile in search engine results".

# Answer
There is and there is not, there are two sides of that question.

Bad side is - external search engines are just that: external. You can send them suggestion but you cannot make sure they respect them.

Good side is - you can create a field, and if it's checked output: `<meta name="robots" content="noindex" />` Some search engines, including Google, Bing and apparently Yahoo! *(can't find a link for that one)*, will respect that.
> 2 votes

---
Tags: users
---


# Question
Title: Changing URL alias for search module action
I'm struggling to make the Search module recognize the presence of a URL alias that I created for 'search/node'. It however stubbornly uses the default path.

In my template I use something like:

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id){
  case 'search_form':
    $form['#action'] = drupal_get_path_alias('/search/node'); // = '/' . drupal_get_path_alias('search/node') does not work either
    break;

  }
}

```

When the results are displayed, the URL still reads:

```
/search/node/[search-string]

```

Does anyone know whether the path is hard-coded and omits the alias function?

# Answer
I've had a lot of misery trying to customise the URLs for the search module so I feel your pain!

It's a submit handler that redirects to the `search/node` page so you'll need to add your own handler to override the redirect:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#action'] = 'search';
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
  else if ($form_id == 'search_box_form' || $form_id == 'search_theme_form') {
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
}

function MYMODULE_search_form_submit(&$form, &$form_state) {
  $default = search_get_default_module_info();
  $form_state['redirect'] = str_replace("$default[module]/", '', $form_state['redirect']);
}

```

That code comes from a module who's sole purpose is to allow users to search at `search/string` rather than `search/node/string` so you'll probably need to change a couple of things to match your alias settings, but it might help start you off.

Here's a bit of extra code that's used to override the search URL using a `hook_menu_alter()`:

```
function MYMODULE_menu_alter(&$items) {
  drupal_static_reset('search_get_info');
  $default_info = search_get_default_module_info();
  if ($default_info) {
    foreach (search_get_info() as $module => $search_info) {
      $path = 'search/' . $search_info['path'];
      unset($items[$path]);
      unset($items["$path/%menu_tail"]);
    }

    $items['search/%menu_tail'] = array(
      'title' => 'Search',
      'load arguments' => array('%map', '%index'),
      'page callback' => 'search_view',
      'page arguments' => array($default_info['module'], 1),
      'access callback' => '_search_menu_access',
      'access arguments' => array($default_info['module']),
      'type' => MENU_CALLBACK,
      'file' => drupal_get_path('module', 'search') . '/search.pages.inc'
    );
  }
}

```

It basically removes the menu items for the search path and replaces them with a single one. It's only useful in very specific conditions (i.e. when you've only got one search type enabled) but it's something to go off at least.
> 3 votes

# Answer
Thanks to the Clive i managed to make my own search module which adds another search path, so under mysite.com/searchpath I get search results from SEARCH\_MODULE which I use.

Example "variables":
MYMODULE - your custom module which implement hooks below
SEARCH\_MODULE - search module which you would like to use
searchpath - path for search results

```
// Custom search path alias
function MYMODULE_form_search_form_alter(&$form, &$form_state, $form_id) {
  $form['#action'] = 'searchpath';
  $form_state['action'] = 'searchpath';
  $form['#submit'][] = '_MYMODULE_search_form_submit';
}

function MYMODULE_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = '_MYMODULE_search_form_submit';
}

function _MYMODULE_search_form_submit(&$form, &$form_state) {
  $form_state['redirect'] = 'searchpath/'.$form_state['values']['search_block_form'];
}

// Add searchpath to available paths
function MYMODULE_menu_alter(&$items) {
  $path = 'searchpath';
  $items[$path] = array(
    'title' => t('Search'),
    'page callback' => 'search_view',
    'page arguments' => array('SEARCH_MODULE', 1),
    'access callback' => '_search_menu_access',
    'access arguments' => array('SEARCH_MODULE'),
    'type' => MENU_LOCAL_TASK,
    'file' => drupal_get_path('module', 'search') . '/search.pages.inc',
    'weight' => -10, //Don't know what is it for
  );
  $items["$path/%menu_tail"] = array(
    'title' => t('Search'),
    'load arguments' => array('%map', '%index'),
    'page callback' => 'search_view',
    'page arguments' => array('SEARCH_MODULE', 1),
    'access callback' => '_search_menu_access',
    'access arguments' => array('SEARCH_MODULE'),

    // The default local task points to its parent, but this item points to
    // where it should so it should not be changed.
    'type' => MENU_LOCAL_TASK,
    'file' => drupal_get_path('module', 'search') . '/search.pages.inc',
    'weight' => 0,

    // These tabs are not subtabs.
    'tab_root' => 'searchpath/%',

    // These tabs need to display at the same level.
    'tab_parent' => 'searchpath',
  );
}

```

Hope that this example helps.
> 2 votes

---
Tags: 7, search, path-aliases
---


title: "Flexible Field" for Drupal

text:
# Question
Title: "Flexible Field" for Drupal
I am sorry for the vague question but I have no idea about where to start.

Please think of a scenario that, you created a **video** content type and you want your site visitor either **upload** their video files to your site, or they use the **embed codes** from any third party providers (youtube, vimeo etc.). For the sake of providing a clean GUI, you do not want to show both fields, but based on the choice of your user (maybe an image combo), you either show the **file upload field** or **text area field** (where they put the embed code in)

My question is, I wonder if there any elegant way to do it in Drupal without making any PHP, HTML or CSS modification?

# Answer
> 3 votes
I have done this in the past by adding a drop down that gives the user an option of selecting "embed" or "upload" then use the Conditional fields module to show or hide the required field.

---
Tags: entities
---


title: how to validate minimum age in webform

text:
# Question
Title: how to validate minimum age in webform
I've got a question about webform and webform validation.

I'm in D6.19 with webform 6.x-3.4 and webform validation 6.x-1.3

I'm adding a date field to capture age, and I need to validate that the age of the user is at least 13 years from current date.

Does anyone know how I can do this? Thanks Stephanie

# Answer
You can do it using the hook\_webform\_submission\_presave() exposed by the Webform api in a custom module.

Another alternative is to make use of this sandbox project

> This module provides a way to calculate values for Webform components and/or to add custom validation code without the need for creating custom modules that implement hooks. It offers a PHP-like macro scripting language to use instead.
>
> Differs from Webform PHP in that there is no eval() evil and macro code has no direct access to Drupal environment or functions, i.e. macro code is contextually jailed.
>
> Differs also from Webform Calculator in that it permits logic-driven calculations and also integrates with the Webform Validation module.
> 0 votes

---
Tags: 6, webforms, forms
---


# Question
Title: During a Drush pm-uninstall, is there a way to see what sql queries were run?
Is there a way to find out what sql queries were run during a drush pm-uninstall module? The reason I want to find out is because I want to see if certain tables were removed during the uninstall. Sometimes modules like ubercart leave orphaned tables even though you uninstall them. I had to find the hard way after installing and testing a few other modules and see my database tables balloon up.

# Answer
> 2 votes
You could try to adapt the devel query log as Letharion suggested, but that would involve some coding. I have done similar things (for a different purpose) by using the Mysql General Query Log. This requires restarting mysqld with an additional parameter, but beyond that minor inconvenience, works pretty well and shows you absolutely everything that's going on with the database.

---
Tags: drush, installation
---


# Question
Title: How do I customize node.tpl to print an entity reference field in a specific format
I have content type called collection that has an entity reference field (multiple) that references another content type called books. One the collection node page, I want to render all of the books as linkable titles, with a button next to them that says "add annotation to book" this will link the user to create a third type (entity) that has a reference field pre - populated.

So my question is this, how do I re- format the books fields of my collection type to meet my use case. So far I have toyed with the following options.

1. Add a custom node--book.tpl.php file and place code that take the reference field, loops through it, does and entity load on each referenced entity, then adds custom html to the add form of the third content type
2. Alter the field--type.tpl,php and add it in here - can't figure out this option because I'm not sure how to retrieve the nid, link, and title from this template.
3. Create a custom display for my book entity and set the field on my collection to render as this new display (this created other problems, I don't know if it's possible to have a separate template for this new display, and this complicated it).

# Answer
I think your information architecture in inverted. It sounds more like *Book* is in *Collection* rather than *Collection* has *Book*. In other words *Collection* is an attribute of *Book*, not the other way around. It would be easier to put the reference field on the Book content type, and create a view of all *Book* s referencing a *Collection* to display on the *Collection* content type, using a Contextual filter to limit the list. No changes required to template files!

Then using the Prepopulate module, you can use the $\_REQUEST variable to set your field\_book value in the new node, and it is a simple matter to add the `Content:Nid` to the view and rewrite the field to create the link.

First, install and activate the Prepopulate module. Then put your Entity Reference field on the *Book* content type and limit it to the *Collection* content type. Then add an Entity reference field to the `Annotation` content type and limit it to `Book`. In other words, you are identifying the *Book* the annotation belongs to.

Then create a view of Content (Book) with a display type of Block. In the views configuration, create a Contextual filter on `Content: Collection (field_collection)` and configure it to *Provide default value* and select *Entity ID from URL*.

Add the field `Content:NID` and configure the field. Select *Rewrite results* and check *Rewrite the output of this field*. In the text box enter something like:

```
<a href="/node/add/annotation?edit%5Bfield_collection%5D%5Bund%5D%5B0%5D%5Btarget_id%5D=[nid]">Annotate this book</a>

```

(%5B = "\[" and %5D = "\]"). The actual link code may vary depending on how you have implemented the Entity reference field in your content type. The module has good documentation.

Save your view and under `/admin/structure/block` find the block created by the view and set it to display only on pages of type *Collection*.

The block will then display a list of book titles (linked to their content) and the custom link to add an Annotation page with field\_book prepopulated, and limited to those books which reference the Collection being viewed.
> 1 votes

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


title: remove tabindex -1 from views accordion

text:
# Question
Title: remove tabindex -1 from views accordion
the view accordion is automatically assinging a tabindex -1 to header field. like this :

```
<a href="#how_to_become_a_grantee-block-0" tabindex="-1">

```

how can I remove that tabindex -1 ? thank you

# Answer
> 1 votes
it sounds like you want to modify the source contributed module :(.

You just write some custom CSS in your theme to target the item. In your theme.info file:

```
scripts[]=my_theme_overrides.js

```

Then in your javascript file you write the following, as an example (untested, should work, you may need to tweak it.):

```
/* in my_theme_overrides.js */
(function ($) {
  $("#how_to_become_a_grantee-block-0").removeAttr("tabindex");
})(jQuery);

```

---
Tags: views, navigation
---


title: Get edit form from a webform submission

text:
# Question
Title: Get edit form from a webform submission
I want to get the edit form from a Webform Submission to handle this in the logged in user area.

Like `node/{node_id}/submission/{submission_id}/edit`

How do I do this?

# Answer
> 0 votes
If I understand correctly your question, you should click **"Use the administration theme when editing or creating content"** in ***admin/appearance***

Even better, try Administration theme module which will allows you to use you Administration theme on more pages like:

```
node/*/webform-results
node/*/webform-results/*

```

---
Tags: webforms, forms
---


# Question
Title: What can I use to layout the content type form input when creating content?
I have created a content type with about 15 fields.

I'd like to improve the layout of the form for creating content of this content type.

Currently all the input fields are listed one after the other which means a lot of vertical scrolling and not everything can be seen on one page.

I looked at the Display Suite module ( http://drupal.org/project/ds ) but I could only see how to layout the resulting content *not* the input form used to create it. (*UPDATED*: answer below from Елин Й. says that display suite can actually layout the input form)

Another option would be to create a theme with form layout (good question - and answers here: How to a use a template file to theme a form? ). That's fine, but before I do that I wanted to look at other options available (don't wish to re-invent the wheel.)

Or should I use entities and EntityForm instead if that provides better layout options.

Finally, I'd prefer *not* to use webform module as EntityForms and ContentTypes provide better integration with built in Drupal features, so I've read.

# Answer
> 4 votes
Display Suite is capable of formating form layout, as well.

> Modules included:
>
> ```
> Display Suite: The main module to rearrange your fields.
> Search: extend the search results for Drupal core or Apache Solr.
> Extras: extra functionality like semantic fields, region to block, hide page title etc.
> Forms: style the layout of forms.
> Format: provides a PHP filter with entity context (only 7.x-2.x and higher)
> UI: Manage custom fields, classes and view modes through UI (only 7.x-2.x and higher)
>
> ```

You should enable the **Display Suite Forms** module, which is shipped with DS.

Under the 'manage fields' tab of your content type

```
admin/structure/types/manage/your_content_type/fields

```

At the bottom, you have an option to select a layout for the form.

# Answer
> 2 votes
You can make use of the Field group Module

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

There are also other modules you can use with it such as the Multistep module

> Multistep adds multiple-step functionality to content type editing forms. It does so by assigning a step number to each fieldgroup within the content type and hiding all the groups that do not belong to the current step. The user can then use different submitting buttons that will redirect to the previous, next, or current step.

# Answer
> 1 votes
There is also another way to theme the node form, that you can do it completely with code in your theme folder without using any other module.

First, in your theme folder, edit `template.php` file, and implement hook\_theme() to tell about your template file.

```
function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'your_content_type_node_form' => array(
      'render element' => 'form',
      'template' => 'your-content-type-node-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates/forms',
    ),
  );
}

```

The above code assumes that your theme name is `YOURTHEME`, and you want to use a template file named `your-content-type-node-form.tpl.php`, and you want to put this template file in your theme folder under `YOURTHEME/templates/forms`.

Then, you can create the specified file under the specified folder and you can build your custom template file from scratch, which will be a very painstaking job, but at the end you will have a layout that you have a full control over it.

You can print individual fields in this template file like:

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

```

You will have also many other variables and functions available.

After building the form completely, printing all the fields you set in your content type, you should always print the rest of the form, which includes all the hidden fields and tokens that Drupal adds to you form.

```
<?php print drupal_render_children($form); ?>

```

If you don't include that, your form will probably not work. That line does also make sure that no fields are missing in the form that you would forget to print.

If you want to apply also some logic or another functionalities to your form or form elements, you can use hook\_form\_FORM\_ID\_alter() in your `template.php` file, which requires a good knowledge about Form API.

An example implementation of `hook_form_FORM_ID_alter()` for this post would be:

```
function YOURTHEME_form_your_content_type_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#size'] = 30;
}

```

This would set the size of the title field to 30, which is not possible using the Fields UI.

---
Tags: 7, theming, forms, input-formats
---


title: field type for True/False/Empty

text:
# Question
Title: field type for True/False/Empty
I have a field on a content type which is an optional override for another field. I want the value to only be either 0, 1, or empty, the last meaning "no override". What field type should I use for this? I was looking at a select list for a good user experience, but I was unable to get empty as a value in the list.

I also need another field that can only have values "img", "txt" or "". How should I accomplish this? I want to avoid having users type in "img" or "txt" in case they misspell it.

# Answer
Select lists have always the option `None` if they are not set as *Required*. That said, you can create a *List (Text)* field with select list widget and set only two options, `0` and `1`, and you will get the `None` option automatically.
> 3 votes

---
Tags: entities
---


# Question
Title: What are the URL Alias pattern replacements for taxonomy parent terms when building up Node paths?
## **SCENARIO:**

1. I created taxonomy terms with 3 depth levels. Example:

```
Term 1 ( Root )
   Term 2 ( Child of Root )
      Term 3 ( Child of Term 2 )

```
2. In the URL Alias for my vocabulary I set:

```
[term:parent:parent]/[term:parent]/[term:name]

That successfully creates a path that looks like this:

"http://mydomain.com/term-1" for the root term
"http://mydomain.com/term-1/term-2" for the root's child term
"http://mydomain.com/term-1/term-2/term-3" for the child's child term

```
3. In my Content Type, I created a Term Reference field that forces the user to select the deepest term ( 3rd term down ) with the help of Simple hierarchical select module.

---

## **ISSUE:**

When creating nodes, I would like to set the node's URL Alias to `term-1/term-2/term-3/node-tile`. I am having trouble finding the Replacement Pattern for doing just that.

Does path auto allow me to do that out of the box? If so, what pattern should I use?

# Answer
> 9 votes
There are some advanced uses of tokens (not sure off the top of my head if that's just in the context of pathauto or not). You can get what you're looking for with `join`:

```
[node:field-name:parents:join:/]/[node:field-name:name]/[node:title]

```

You could also replace your term pattern with:

```
[term:parents:join:/]/[term:name]

```

Using that method your vocabulary can grow gracefully to 4 (or more) levels without having to change the pathauto pattern.

You'll need to go to `admin/config/search/path/settings` and set the `Slash (/)` option to "Do not Replace" under "Punctuation" for that method to work.

# Answer
> 4 votes
Yes there is a token for that. Assuming the machine name of the Term Reference field in your content type is `field_myterm`, the pattern for the path should be:

```
[node:field-myterm:parent:parent]/[node:field-myterm:parent]/[node:field-myterm]/[node:title]

```

Notice the underscore in the field name is replaced with a dash in the token.

Edit: I just realized that these tokens come with Entity Tokens module which is included in Entity API module.

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


# Question
Title: How to force a dev release of my module?
Whenever I go to create a release for my contrib module, it gives me one option - 6.x-1.x (6.x-1.x-dev) - but if I select that it says "The version you have selected (6.x-1.x-dev) is already in use by another release." IIRC dev releases are packaged automatically every twelve hours, so why is this option even appearing? And it seems like dev releases aren't being packaged automatically for my module ...

# Answer
> 2 votes
In the "Release" tab of your project you've a checkbox with "Show snapshot release". If you check it, you should see the dev releases appear.

---
Tags: 7, community-official-site
---


# Question
Title: How do I create a link to add a new entity form from the referenced entity
I've created an entity (using Entity Construction Kit) that has an entity reference field referencing a node. I would like to create a link on that node to create a new entity. I want to do this on the node template file. I have looked into sandbox module Prepopulate Create Node Links but I'd rather just code it.

# Answer
> 1 votes
The entity\_connect module will do that for you.

---
Tags: theming, entities
---


# Question
Title: Why is my block not showing up on the Blocks page?
I don't remember where exactly my return needs to be. It had worked at one point, but stopped at a random time. Google'd and didn't find my answer.

```
function bobby_name_generator_block_view($delta = '') {
  switch ($delta) {
    case 'bobby_name_generator':
      $block['subject'] = t('Generate Bobby Name');
      if(user_access('access content')) {
        $block['content'] = drupal_get_form('bobby_name_generator_form'); // insert bobbyname variable here!
      }
      return $block;
  }
}

```

# Answer
Here is an example for hook\_block\_info found in examples module. This defines the existence of block and this will make the block show up in the block page. You could use hook\_block\_configure to provide additional fields for you block in block page and save the it using hook\_block\_save.

```
function example_block_info() {

  $blocks['example'] = array(
 'info' => t('Example: configurable text string'),
 'cache' => DRUPAL_CACHE_PER_ROLE,
 'status' => TRUE,
 'region' => 'sidebar_first',
 'visibility' => BLOCK_VISIBILITY_LISTED,
 'pages' => 'node/*',
 );

return $blocks;
}

```
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: Why do all my urls look like 'content/name-of-page'
I just installed pathauto module. After installing it the path sticks to 'content/' in front of all the url names. So how to change the default URL.

# Answer
Go to /admin/config/search/path/patterns to configure your content types appropriately. I believe the first one acts as a default if you do not define the other paths for content types.
> 4 votes

---
Tags: 7, nodes, path-aliases
---


# Question
Title: Recoverable fatal error after form submission in drupal7
Iam new to drupal.I have created a custom module named firstmodule .I have created a form using the tutorials section of drupal 7 when is submit i want to store this details in the registration which is present in db.

firstmodule.module

```
function firstmodule_form1_submit($form, &$form_state)

{

$firstname = $form_state['values']['name'];
    $username = $form_state['values']['username'];
    $password = $form_state['values']['password'];
    $year_of_birth = $form_state['values']['year_of_birth'];
    $email = $form_state['values']['email'];
    $file = $form_state['values']['file'];

```

I am using the insert query in the following way:

```
        db_insert('registration')->fields(array(
          'firstname' => $firstname,
          'username' => $username,
          'password' => $password,
          'yearofbirth' =>$year_of_birth,
          'email' => $email,
          'file' => $file,))
          ->execute();
}

```

it is showing me the error

> Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase-\>execute() (line 2168 of /var/www/drupal-7.22/includes/database/database.inc).

please help with it

# Answer
> 2 votes
Here is an example of a file upload with some validation, hope it helps

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

  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('txt csv'),
    'file_validate_size' => array(10000000),
  ));
  // If the file passed validation:
  if ($file) {
    // Move the file, into the Drupal file system
    if ($file = file_move($file, 'public://')) {
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', 'there was an error uploading the file');
    }
  }
  else {
    form_set_error('file', 'No file uploaded');
  }
}

function file_upload_form_submit($form, &$form_state) {
  $file = $form_state['storage']['file'];
  // We are done with the file, remove it from storage.
  unset($form_state['storage']['file']);
  // Make the storage of the file permanent
  $file->status = FILE_STATUS_PERMANENT;
  // Save file status.
  file_save($file);
  // here you can save your data
  $firstname = $form_state['values']['name'];
  $username = $form_state['values']['username'];
  $password = $form_state['values']['password'];
  $year_of_birth = $form_state['values']['year_of_birth'];
  $email = $form_state['values']['email'];

  db_insert('registration')->fields(array(
    'firstname' => $firstname,
    'username' => $username,
    'password' => $password,
    'yearofbirth' =>$year_of_birth,
    'email' => $email,
    'file' => $file->uri,))
  ->execute();

}

```

---
Tags: 7
---


# Question
Title: How should I alter forms shown in a block?
I want to alter the login form to display only the @username and @password inputs.

1. Is it mandatory to write another module to overwrite the user module? Can it be done from my PHP block by using these 2 variables? If yes, how can I find the name of the variables?
2. What is the Drupal recommended way for doing this?

# Answer
> 0 votes
There are two ways to display only some fields:

1. Get the original form, and remove unneeded fields. This can be done 2 ways, in hook\_form\_alter() or by calling drupal\_get\_form() and working on outputted array. This way is risky - save handler might be unable to save if some fields it expects are missing.
2. Create your own form, with your own inputs, validators and save handlers. Copy strings from form you are copying to keep using any translations already available. This is safer, but requires a bit more work.

In theory you can handle form in a block with php filter. I would not recommend it. It's way more manageable to keep code in files. And if you have APC, it's also way faster. Thus, modules are the way to go.

---
Tags: users, forms
---


# Question
Title: Inserting PDF files via the Image icon in ckeditor. Is there a better way?
I would like to insert inline files throughout the text editor, without having to attach them all at the bottom of the page. I figured out that I can upload them via the image icon, remove the blank image, and then insert the link by browsing to the file I just uploaded. But surely there is a better way?

Can anyone share?

# Answer
The canonical "Drupal way" is to keep files in file fields. You are free not to display them in your theme for readers and only keep links in body. Having them explicitly linked to a node has some advantages: you can keep track if files are used or should be deleted, you can display them in views, in search you can possibly add "with attachment" option and so on.

You can write a CKEditor plugin - copy image uploading one, change output from `<img src="` to `<a href="` and you have what you wanted. It's what you want, but be careful, you might regret it in the future if you'll ever need that node-file relation.
> 1 votes

---
Tags: files
---


title: How to correct term alias?

text:
# Question
Title: How to correct term alias?
I don’t know why in Drupal 6 some of my parent taxonomy terms have duplicate URLs. For example, I have http://example.com/carrers-0 instead of http://example.com/carrers.
I am not finding any duplicate taxonomy term.

How can I correct it?

# Answer
Once you had something under that alias, alias is treated as "used" and blocked from reuse.

Search http://example.com/admin/config/search/path (or similar page in 6, if address was changed) and look there for aliases you want. Remove them. Remove aliases with -0. Re-save your node / term / anything. That should do it.
> 0 votes

---
Tags: 6, taxonomy-terms, path-aliases
---


title: Record admin changes in log?

text:
# Question
Title: Record admin changes in log?
Is there a way of recording changes made to a Drupal site in a log?

Im working as part of a team and some members are off site. We're running into issues where changes are made to the path pattern of nodes by other members, and it would be really useful to be able to check what changes have been made recently. Even better would be to know which admin user made the changes. Thanks

# Answer
In Drupal 8 configuration is also stored in files, so you can commit it to git and have a full log. As far as I know there is no mechanism to record all actions of users in any version of Drupal.

If you insist, you can implement hook\_form\_submit() for every form and add additional save function to record who, when and what, but it will be hard to use log created this way.

Other approach is to use Features \- let them develop their parts on their copies and just send you packages with working pieces.
> 1 votes

---
Tags: 7, users
---


title: Apache Solr & Boost module conflict?

text:
# Question
Title: Apache Solr & Boost module conflict?
I'm running Drupal 7, Apache Solr module 1.2, Boost 1.3

When performing a search as an anonymous user, I (most of the time) just get redirected to the front page. I suspect some conflict with the boost module as this only happens for anonymous users and removing the .htaccess rules for boost seems to fix the problem. Although the eratic behaviour is quite confusing.

I notice that the form submit action for the search is always "/" In the access logs, I see that the normal flow is:
\- POST on "/"
\- 302 Redirect on node/search/...

When having the problem as anonymous user, the flow is:
\- POST on "/"
\- 200 Status code and the boost cached index page is returned. No 302

Here are my boost .htaccess directives:

```
  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

# Caching for anonymous users
# Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [S=4]

##Added as the front page was displaying the content of index.php instead of cached html
RewriteCond %{REQUEST_URI} ^\/index.php$
RewriteCond cache/normal/drupaltestsite.com/_\.html -s
RewriteRule .* cache/normal/drupaltestsite.com/_\.html [L,T=text/html]

# GZIP
RewriteCond %{HTTP:Accept-encoding} !gzip
RewriteRule .* - [S=1]
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html,E=no-gzip:1]

# NORMAL
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

```

As the action is a POST, none of these directives should be executed I think, so I am not sure where the problem is.
Where is the 302 redirect made to forward the request on search/node... ?

Any help appreciated.
Jerome

# Answer
Add your search paths to list of pathes boost ignores, either via UI or in the line

```
RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]

```

Boost should always be skipped for dynamically generated pages, it can't handle it to well.
> 0 votes

# Answer
I think I found a solution, but can't really explain the reason why it works, maybe somebody here could.

I suspected the DirectoryIndex directive to be part of the problem. I modified my .htaccess to comment out the DirectoryIndex index.php line and change the boost part to:

```
  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
RewriteRule .* - [E=boostpath:normal]

# Caching for anonymous users
# Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|search/node|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [S=3]

# GZIP
RewriteCond %{HTTP:Accept-encoding} !gzip
RewriteRule .* - [S=1]
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteCond %{REQUEST_METHOD} ^GET$
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html,E=no-gzip:1]

# NORMAL
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteCond %{REQUEST_METHOD} ^GET$
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

```
> 0 votes

---
Tags: search, caching
---


# Question
Title: how can I make view_slideshow module thumbnail pager scrollable?
I am using the view\_slideshow module. When user goes to the property page(**Content type property**) I am showing the images using view slide\_show module. Main image is moving as a main slider image and thumbnail are being shown under the main image as thumbnail pager.

Now here is a problem: Thumbnail pager is coming in a div its working fine if the number of images are 3-4. But if the number of images are 8-10 then they are not being shown in the thumbnail pager div.I want to make the thumbnail pager div scrollable with arrow buttons on both end.

So if user clicks on the next arrow of thumbnail pager then that thumbnail will comes into the thumbnail pager div.

Thanks

# Answer
Views Slideshow JCarousel will suits your problem description best . Before Installing it you need to have views and views slideshow enabled.One extra work you need to do is to create two folders in sites/all/libraries folder

1) sites/all/libraries/**jcarousel** \- download the .tar file from https://codeload.github.com/jsor/jcarousel/legacy.tar.gz/0.2.9 and extract here.

2) sites/all/libraries/**jquery.cycle** \- save here the .js file you get form http://malsup.github.io/jquery.cycle.all.js link.

Now .

* create a view of content of TEST (let here be the content type is TEST).
* Select Format slide show and click settings . Now in Bottom Widget(you can select top widget also) check the pager checkbox.
* It will ask all the requirements like *Number of visible pager item* and *scroll items* . Save it and you are done.
> 3 votes

---
Tags: 7, views
---


title: mrss(Media RSS) feed for drupal 6

text:
# Question
Title: mrss(Media RSS) feed for drupal 6
Is there a MRSS module for drupal 6? I have been asked to create a mrss feed of a site video content. This will enable AOL to access all the videos of the site via mrss. Will I have to create a custom module to achieve this?

# Answer
> 0 votes
MRSS is just an XML.

There are many Views plugins to export data as XML. Specifically for MRSS, there is Views RSS. Or you can simply use template files to output data with proper tags.

It should be possible to use Feeds XPath Parser module to import MRSS, too.

The Views RSS module is only for Drupal 7 and 8.

---
Tags: media
---


title: exposed filter views criteria

text:
# Question
Title: exposed filter views criteria
I have a view that exposes a filter for user input to "search" a list of taxonomy. My problem lies in sorting the results, which are by default alphabetically sorted.

The filter criteria takes user-inputted data from exposed form and uses the "contains" operator on a taxonomy vocabulary, thus returning (alphabetically) any taxonomy term names that contain the given input text. There is no sort criteria applied, thus defaulting to an alphabetically sorted list of taxonomy terms.

The exposed filter uses "contains" as the operator, but is it possible to show "starts with" operator results before or at the top of the alphabetical list of "contains" operator results.

I have tried using combined fields filter, but seem to only be able to combine fields, and not these operators such as contains, starts with, is equal to, ends with.

How might i implement a way to have my view display results that start with the given exposed filter (user) inputted value, then the results that contain the same given exposed filter input.

Combined fields filter seems to only allow multiple fields, not multiple operators or operators with && || and or type options.

Any advice is appreciated. Thanks in advance.

# Answer
> 2 votes
Well, that's obvious mister - filter criteria has nothing to do with results sorting. On your first screenshot, see "SORT CRITERIA" in the left bottom? you can setup sorting there by adding content field or fields to be sorted by.

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


# Question
Title: Storing anonymous user information in a cookie
I want to store the zip code of a user, if they use it for a proximity search in a cookie. However, I don't know where or how to start to implement this.

How do I store anonymous user information on a cookie?

# Answer
> 10 votes
Since Drupal 7, there are two functions to store data in a cookie: user\_cookie\_save(), and user\_cookie\_delete(). Despite the function names, the functions work also for anonymous users, since they don't get information from the `$user` object or any information that is related to the user ID.

comment\_form\_submit() uses `user_cookie_save()` in the following code lines:

```
if (user_is_anonymous()) {
  user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
}

```

If you are using a version of Drupal that doesn't define that functions, you can implement similar functions in a module you use.

```
function mymodule_cookie_save(array $values) {
  foreach ($values as $field => $value) {
    // Set cookie for 365 days.
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  }
}

function mymodule_cookie_delete($cookie_name) {
  setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
}

```

Keep in mind that setrawcookie() is only available in PHP 5. If you are developing a module that could be used with PHP 4, then you should use setcookie(), and the code of the functions should be accordingly changed: the parameter needs to be declared as `$values` (not `array $values`), and the call to rawurlencode() needs to be removed as the cookies are already URL encoded from `setcookie()`.

# Answer
> 3 votes
Setting cookies in Drupal is not different from how you would do it with any other PHP site:

`setcookie` is the function that PHP provides for this. There is also the `$_COOKIE` super global variable to use.

Code example:

```
$cookieval = 'my cookie value';
if ($_COOKIE['my_cookie_key'] != $cookie_val) {
 setcookie('my_cookie_key', $cookie_val);
}

```

# Answer
> 0 votes
If you have Drupal installed in subfolder so that your site root URL has the form www.mydomain.com/mysite, you should probably use base\_path() instead of '/' when setting the cookie.

Functions in kiamlaluno's answer would then be:

```
function mymodule_cookie_save(array $values) {
  foreach ($values as $field => $value) {
  // Set cookie for 365 days.
  setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, base_path());
  }
}

function mymodule_cookie_delete($cookie_name) {
  setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, base_path());
}

```

---
Tags: cookies
---