# Question
Title: Node Post Date equals to selected date only not time?
I created a view and exposed a `Post Date` filter. I select a date and I want to show the post of that date. But it searching based on "YYYY-MM-DD HH:MM:SS". I just want to show full day data. I set the operator `is equal to`.

# Answer
> 3 votes
1. Install the date module and enable the "Date Views" module, which is a sub-module of the date module.
2. To your view add the filter "Date: Date (node)".
3. For the "Date selection form element" option set it to whatever you like.
4. For the "Filter granularity" option set it to "Day".
5. Set the "Starting year" option to whatever is relevant.
6. For the "Date field(s)" option select "Content: Post date"
7. For the "Method" option, generally leave it set to "OR"
8. Click the apply button, then continue to configure as you would normally.

---
Tags: 7, views
---


# Question
Title: Features conflicts when field bases are used by other feature
I recently downloaded the Features module and was so glad over how smoothly I now can export functionality from dev to prod. But now when I'm trying to create a second feature I'm getting conflicts because I already used a lot of the same field bases in my first feature.

What can I do to resolve this? Are you not suppose to be able to use the same fields in different features? It doesn't seem right that I should have to define as many fields for "body text" that I have features, or image fields for that matter. Those fields could and should be shared right?

What are my options here?

# Answer
> 7 votes
Say you have two Features, and one field that is used in both Features, then you only need to export the field base ONCE.

This is why I generally have a "controller" Feature that contains field *bases*, update hooks etc, and then for every other Feature I export the field *instance*, and then add a dependency on my controller feature.

Basically, you are right - you don't need to export the field bases every time, just export them once and then add dependencies.

---
Tags: features
---


title: Views block contextual filter question

text:
# Question
Title: Views block contextual filter question
I have a content type called slides, for now it has an image field, a body, a title and a link field (linked to the page that the slide is advertising... by the way some pages are views).

So for now I made a Views block to make them all appear in a Slideshow and it works. But now I would like to create a new Views block that will only show the slide related to the page you visit. So for example, on the homepage you have the slideshow of all my slides but when you click on one of them, you go visit the specific page advertised (e.g. contact slide linked to contact page).

But when you visit the page, you should see the new block with the specific slide related to the page. I search for answers and I think Contextual filter is the option to use in Views, but I am not accustomed to it and the examples that I found are not exactly using available value for me.

I am thinking I might be able to filter the slides vs the path they have vs the page they are on. But I am not sure if it's possible and have no idea how to do it. So please let me know how or send me a few thoughts on where to look at. Thanks!

# Answer
> 0 votes
Also display the block on *slides content* in full page view, and in your view add the contextual filter "Content: Nid" with the following settings :

> Provide a default value : Content ID from URL

It will be automatically filtered, but will still display all slides on your home page

---
Tags: 7, uri, views
---


# Question
Title: Displaying the username of the user who created the node in the node template file
I created file node--my\_content\_type.tpl.php, where I'd like to print the username as string. I tried the following code, but unfortunately it doesn't work. How can I do it?

```
<?php
  print $name;
?>

```

# Answer
`$node->name` will get you the name of the author who submitted the node. It will return it as string, not as link to the user account.
> 4 votes

# Answer
Usernames are stored in the `$user` object.

```
global $user;
print_r($user);

```

If you mean the fields in a node, those would be in the node object (`$node`).

I highly recommend looking at the output of the above. Get familiar with both the user object and the node object and everything will make a lot more sense.
> 0 votes

# Answer
```
$user = user_load($node->uid);
print $user->name;

```

This way you can get the name of author by loading the user.
> -1 votes

---
Tags: 7, nodes
---


title: Feeds CSV import taxonomy and file

text:
# Question
Title: Feeds CSV import taxonomy and file
I have an interesting use-case.

I have to import a lot of documents (+100) into a specific content type called "Resource". This content type consists of few taxonomy fields (mapped to a vocabulary), some textfields and PDF file.

What should be the strategy when using Feeds module. Is it possible to have multiple taxonomy terms per field ?

# Answer
**For taxonomy terms :** It is possible, simply delimit your values with commas in your taxonomy field CSV column, and in the Feeds mapping, select "Search taxonomy terms by: Term name" and "Auto create"

Make sure your Drupal field allowed number of values is set to Unlimited (or \> 1)

**For files:**

* your file is external and given a URL, feeds will download it and store it
* your file is already stored locally then the URI must be either

+ a stream wrapper (e.g.: public://import/myfile.pdf)
    + a relative path from your docroot
    + an absolute path on your system
> 2 votes

---
Tags: nodes, feeds, importing-exporting
---


title: Multiple rendering causing a ul more

text:
# Question
Title: Multiple rendering causing a ul more
I had following code in template.php this is in `function bartik_process_page(&$variables)`

```
 $main_menu_tree = menu_tree_all_data('main-menu');
 $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);

```

and in page.tpl.php

```
<?php if ($main_menu): ?>
                    <div id="main-menu" class="navigation">
                        <?php print render($main_menu_expanded); ?>
                    </div> <!-- /#main-menu -->
        <?php endif; ?>
                          <?php if ($main_menu): ?>
                    <div id="main-menu" class="navigation">
                        <?php print render($main_menu_expanded); ?>
                    </div> <!-- /#main-menu -->
        <?php endif; ?>
                            <?php if ($main_menu): ?>
                    <div id="main-menu" class="navigation">
                        <?php print render($main_menu_expanded); ?>
                    </div> <!-- /#main-menu -->
        <?php endif; ?>

```

and output it is like this in bartik

1

```
    <ul class="menu clearfix"><li class="first last leaf"><a href="/ji/" class="active">Home</a></li>
</ul>

```

2. Now u can see i m getting `<ul class="menu">` extra

```
<div class="navigation" id="main-menu">
                        <ul class="menu clearfix"><ul class="menu clearfix"><li class="first last leaf"><a class="active" href="/ji/">Home</a></li>
</ul></ul>                    </div>

```

Any idea how can i stop it

# Answer
I have found the answer of it since in render variables are passed by reference https://api.drupal.org/api/drupal/includes!common.inc/function/render/7

so i was passing $main\_menu\_expanded multiple times in render which was culprit.

Fix is

```
$variables['main_menu_expanded'] = render(menu_tree_output($main_menu_tree));
<?php if ($main_menu): ?>
                    <div id="main-menu" class="navigation">
                        <?php print ($main_menu_expanded); ?>
                    </div> <!-- /#main-menu -->
<?php endif; ?>

<?php if ($main_menu): ?>
                    <div id="main-menu" class="navigation">
                        <?php print ($main_menu_expanded); ?>
                    </div> <!-- /#main-menu -->
<?php endif; ?>

```

Now i dont get extra ul
> 0 votes

---
Tags: 7, routes, theming
---


# Question
Title: Is it possible to replace html outside form with ajax?
Is it possible to replace a `<div>` outside form with ajax on select element?

I am having some difficulties, when Drupal generates new content it wraps my HTML with `<div>` and I don't know why.

This is my form element.

```
$form['select_element'] = array(
'#type' => 'select',
'#title' => t(''),
'#options' => array(1 => 'Test 1', 2 => 'Test 2'),
'#ajax' => array(
  'callback' => 'ajax_callback',
  ),
);

```

This is my callback function.

```
$output = theme('custom_theme_function', array('test_param' => 11,));
$commands[] = ajax_command_replace("#div-id", $output);
return array('#type' => 'ajax', '#commands' => $commands);

```

# Answer
This due to this part of ajax.js

```
// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly iterpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('<div></div>').replaceWith(response.data).
var new_content_wrapped = $('<div></div>').html(response.data);
var new_content = new_content_wrapped.contents();

// For legacy reasons, the effects processing code assumes that new_content
// consists of a single top-level element. Also, it has not been
// sufficiently tested whether attachBehaviors() can be successfully called
// with a context object that includes top-level text nodes. However, to
// give developers full control of the HTML appearing in the page, and to
// enable Ajax content to be inserted in places where DIV elements are not
// allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
// content satisfies the requirement of a single top-level element, and
// only use the container DIV created above when it doesn't. For more
// information, please see http://drupal.org/node/736066.
if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
  new_content = new_content_wrapped;
}

```

This ensures that text nodes are not lost when replacing contents. The second parts of the script checks if the data sent is a single top-level HTML node, and if not, wraps it in a `<div>`

Back to your problem, the solution is to make sure that `theme('custom_theme_function', array('test_param' => 11,))` returns your content in a single HTML node (div, span, ul, li... as long as it is single)
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: CKEditor 4.2 and Media Module, Has anyone gotten this to work?
Been trying to create a working mix of these modules and only seem to succeed if CKEDitor is using version 4.0.3 or lower.

Any insight here would be huge. Thanks!

# Answer
CKEditor 4.1 introduced a feature called Advanced Content Filter. It might be stripping some code. You can test if it's the cause by adding this code your ckeditor/config.js file:

```
CKEDITOR.config.allowedContent = true

```

Granted, you shouldn't just leave it *true*, but it will give you an idea if that's the problem.
> 1 votes

---
Tags: wysiwyg, media
---


title: Drupal Commerce Caching Modules

text:
# Question
Title: Drupal Commerce Caching Modules
I've been trying to improve the speed of my Commerce site with various caching and performance modules. But the general ones recommended don't work or break my site. I can't see anything else out there that answers my question!

**Boost** \- I thought this would work on static pages such as About or Contact, but the module doesn't cache anything at all.

**Agrcache** \- breaks the JavaScript slideshow on the front page.

**Core Library** \- breaks the login page (which is odd!)

I have views cache installed and that's the only one I've got working so far...

# Answer
You can use

It will cache the commerce entities, rather than build them on each request.

While it works ok as is, after the two "Needs review" patches I added to the issue queue:

I'm using it myself without any problems.

As mentioned previously:

Also work well with Commerce
> 3 votes

# Answer
I've look at entity\_cache, then wrote bridge hooks to register the different commerce entities.

http://drupal.org/project/entitycache

I'll need to also write some business logic to expire the cache. I create both a "timed" expire of about 24 hours and a cache on create/update events.
> 0 votes

# Answer
Hi If you need to cache users on Drupal commerce I recommend using

Commerce Auth Cache

> **Authcache** provides a way to cache pages for authenticated users, updating parts of the page via AJAX requests for dynamic content. In case of Drupal Commerce, many parts of some pages are unique to the current user. For example, the cart block is unique per user, and thus cannot be cached with the page it's displayed on. With Commerce Authcache, the cart block gets loaded via an AJAX request after the page is first loaded. This means the page loads very fast, and the cart is still relevant to the current user.

And of course

Auth Cache

> The Authcache module offers page caching for both anonymous users and logged-in authenticated users. This allows Drupal/PHP to only spend 1-2 milliseconds serving pages, greatly reducing server resources.

Please note that enabling authenticated user caching will require modifying how your user-customized content displays on your pages. You should be an experienced Drupal developer if you choose to implement the full functionality of this module.

But if you need to more : then I suggest Varnish + Memcached
> 0 votes

---
Tags: commerce, caching, performance
---


# Question
Title: How to remove "catalog" from Ubercart Catalog View URL
I need to remove the word "catalog" from the URL when viewing a category of products. I am using the stock uc\_catalog view. Its Page (Table) display has a URL of "/\_catalog". What can I change so that the word catalog will be completely excluded?

For example, I'd like my category URLs to be like so:

> mysite.com/shirts
>
> mysite.com/pants

instead of:

> mysite.com/catalog/shirts
>
> mysite.com/catalog/pants

Thanks!

# Answer
> -1 votes
Logical we can't change the way the catalog link generation of Ubercart. The format must be catalog/term\_id (with default way) and catalog/term\_name (With pathauto module). For me the only thing we can deal with that is creating the URL Aliases manually.

---
Tags: 7, views, ubercart
---


title: E-mail results from page callback

text:
# Question
Title: E-mail results from page callback
I have a menu hook and page callback which takes several arguments to generate some table data in a page, the page makes heavy use of entityfield\_query and some other modules.

I need to be able to e-mail the contents of this page based on a set of periodic dates. What's the best way to achieve this?

I realise that the css will all have to be added to the page but if I could get the structure into an e-mail that would be a start.

# Answer
> 0 votes
You can use drupal\_mail() together with hook\_mail() to send email.

See also the Examples for Developers.

# Answer
> 0 votes
Check out this link with full detailed explanation on how to send and edit the contents.

How to programmatically send an email?

---
Tags: rules, emails, routes
---


title: Change the author of a node

text:
# Question
Title: Change the author of a node
We have a website which will host lots of species information. A resource is entering the data on behalf of another person. I would like to change the author information of the nodes once the data entry is completed.

Is it possible to replace all instances of the author ID of 'Person A' with 'Person B'? I assume we need to write some database query and run it in the phpMyAdmin. What query it would be? Also, is there any other efficient way?

Thanks

# Answer
> 5 votes
The easiest way I think is this:

1. Install the views, views\_bulk\_operations, and admin\_views modules.
2. Go to the content listing (admin/content).
3. Filter the results to get the nodes you are interested in.
4. Check the checkboxes next to the node (there is also an option to select all).
5. Select "Change author" from the operations dropdown and click the "Execute" button.
6. Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.

---
Tags: nodes, users, database
---


title: Removing the active language

text:
# Question
Title: Removing the active language
I'm having some trouble with removing the active language from the Language Switcher Dropdown module. I'm trying to override `theme_languageicons_icon()` with the following code, but it doesn't seem to work.

```
function themename_languageicons_icon(&$variables) {
  global $language;

  foreach ($variables as $varKey => $value) {
    if ($variables['language']->language == $language->language) {
      unset($variables[$varKey]);
      break;
    }
  }

  return theme('links', $variables);
}

```

Do you have any idea on how to achieve this? I don't want to disable the active language using CSS since I'm having different style properties for the first-child and last-child of the list.

# Answer
For a similar problem (removing the language switch links for non-translated equivalent pages), I've implemented hook\_language\_switch\_links\_alter() in my theme.

Although I haven't tried it out myself, I think the code example will point you in the right direction. Instead of setting an 'active-language' class attribute, you can unset the link.

```
function mymodule_language_switch_links_alter(array &$links, $type, $path) {
  global $language;

  if ($type == LANGUAGE_TYPE_CONTENT && isset($links[$language->language])) {
    foreach ($links[$language->language] as $link) {
      $link['attributes']['class'][] = 'active-language';
    }
  }
}

```
> 0 votes

---
Tags: theming
---


title: How to move captcha fieldset

text:
# Question
Title: How to move captcha fieldset
I am using the Captcha module to protect my site against spam.

I have put everything else on my form inside a fieldset which is collapsible by default. Howeve, the captcha fieldset is the only thing being output last and outside of the fieldset. Using hook\_form\_alter and dsm($form) I cannot see the captcha fieldset so i'm guessing it's not part of the form??

after scouring through the code i have discovered it's created via a theme function (theme\_captcha) which I can override inside my template.php.

I would like to know how can I bring this fieldset inside the form just above it? Look at the screenshot attached.

Thanks

# Answer
The fact that you are unable to view the $form\['captcha'\] element is due to the form workflow: CAPTCHA is added after your hook\_form\_alter.

In hook\_form\_alter documentation, it is stated that the order is

1. module\_A\_form\_alter
2. module\_A\_form\_BASE\_ID\_alter
3. module\_A\_form\_FORM\_ID\_alter
4. module\_B\_form\_alter
5. module\_B\_form\_BASE\_ID\_alter
6. module\_B\_form\_FORM\_ID\_alter

etc.

And

> The module order is determined by system weight, then by module name.

CAPTCHA module uses hook\_form\_alter to add CAPTCHA element on the fly. So simply alter your module's weight to place it after CAPTCHA module.
> 3 votes

# Answer
Use hook\_form\_alter to hook into the form and programmatically insert the captcha element or adjust the weight of the element or pur the element inside the fieldset.

```
function example_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_FORM_ID') {
    // 1. Put the captcha element inside the fieldset

    // OR

    // 2. Associate the capthca element to the form
    //$form['captcha'] = array(
    //'#type' => 'captcha',
    //'#captcha_type' => 'image_captcha/Image',
    //);

    // OR

    // 3. Adjust the #weight attribute in the form
  }
}

```

**References**

FORM API

How to add a CAPTCHA programmatically

If you need more details please let me have the `$form` variable in txt format.
> 3 votes

# Answer
If you are creating the form youself, you *should* be able to do something as simple as this:

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

```

where `'YOURFIELDSET'` is the `Submit Your Book` fieldset. (Just don't have the Captcha automatically add it itself.)
> 2 votes

---
Tags: forms, captcha
---


title: How do I escape a string in a query?

text:
# Question
Title: How do I escape a string in a query?
I received the following error using my module:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '%m-%d') =
DATE_FORMAT(NOW(), '%Y-%m-%d') AND is_logout = 0' at line 1: SELECT id FROM
ap_visits WHERE`current_ip` = '192.168.1.1' AND `url` =
'http://www.mysite.com/php/4220/how-build-shopping-cart-w-checkout-php.html''
AND DATE_FORMAT(date_start, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d') AND
is_logout = 0; Array ( ) in test_module_check()
(line 164 of /var/www/clients/client1/web2/web/sites/all/modules/test_module/test_module.module).

```

The error here is in the value of `url` column. It has an apostrophe at the end. So my question is on how can I escape this value so the apostrophe will not be an issue?

I am using `db_query`. This is my code:

```
$sql = "SELECT id FROM ap_visits WHERE`current_ip` = '$current_ip' AND `url` = '$url' AND DATE_FORMAT(date_start, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d')  AND is_logout = 0";

$result = db_query($sql);

```

# Answer
You should do

```
$sql = "SELECT id FROM {ap_visits}  WHERE current_ip = ':current_ip' AND url = ':url' AND DATE_FORMAT(date_start, '%%Y-%%m-%%d') = DATE_FORMAT(NOW(), '%%Y-%%m-%%d')  AND is_logout = 0";

$result = db_query($sql, array(':current_ip'=>$current_ip, ':url'=>$url));

```
> 5 votes

# Answer
Better to use the Database API, everything will be escaped properly

```
$query = db_select("ap_visits", "a")
    ->fields("a.id")
    ->condition("a.current_ip", $ip)
    ->condition("a.url", $url)
    ->where("DATE_FORMAT(a.date_start, '%%Y-%%m-%%d') = DATE_FORMAT(NOW(), '%%Y-%%m-%%d')")
    ->condition("a.is_logout", 0);

```

Output the query (for testing)

```
drupal_set_message($query->__toString());
drupal_set_message(print_r($query->arguments(),true));

```

Execute the query

```
$result = $query->execute();

```

Loop through the results

```
if ($result->rowCount())
{
    foreach ($result as $record)
    {
        //do stuff
    }
}
else
{
    // no data message
}

```

More here: https://drupal.org/developing/api/database
> 0 votes

---
Tags: 7, database
---


# Question
Title: How can I make a slideshow with tabbed navigation/menu?
I'm trying to make a slideshow that looks something like this

I'm using views slideshow but I could change it up if need be. Preferably views though.

My problem is the navigation to the right. I have created a content type for this slideshow and fields for the image, the green title and the black subtitle. The slideshow should run by itself and highlight the proper menu item in the sidebar, but also allow for the user to change slide by clicking a menu item.

Any ideas on if and how this could be done?

# Answer
In most Views slideshows I've seen, the navigation is just part of the normal slideshow, but themed to not overlap, unlike the images.

Configure the View to select whatever information you need in the navigation, end then make your theme place the navigation to the right.

I would be surprised if VS does not already have functionality for connecting clicks on some elements with sliding to a certain image, but I don't know the ins and outs of the module enough to give more specific recommendations.
> 2 votes

# Answer
In the settings for the slideshow, under Format \> Slideshow | Settings you need to add a pager widget (top or bottom is up to you). When you check the Pager checkbox, more options open up. The Pager Type is Fields by default and under that are a list of fields that have been added to the view already. You can select one or more of those fields and the fields you choose will become your pager.

Screenshot: https://docs.google.com/file/d/0B0gUI3V589rmcEJJOExCRjFpR1k/edit?usp=sharing
> 0 votes

---
Tags: javascript, views
---


# Question
Title: Location's Distance/Proximity exposed filter without Node Location Submodule but with Location CCK Submodule instead
I would like to stay a little bit more flexible and use Location CCK fields (from Location CCK Submodule) instead of Node Locations (from Node Locations submodule) on my nodes. However, in my view of nodes the "distance/proximity" exposed filter (distance from a user-entered zip code) only works when my nodes have a location attached to them via Node Locations Submodule. If I disable Node Locations Submodule and attach a location to my nodes via a Location CCK field, the "distance/proximity" exposed filter never returns any results.

Does anyone know how to get around this issue?

Best, deinqwertz

# Answer
> 0 votes
I was faced with the same problem and "solved" with a little workaround:

I use both node and cck location. The one is hidden from the user, he only sees one, and if it is changed then I copy it into the other one.

That way I have both a cck field for flexibility's sake AND the node location for the views. :)

---
Tags: location, views
---


# Question
Title: How do I programmatically get a field's value?
I copied node.tpl.php and I pasted it to node--my\_content\_type.tpl.php. My content type has a *price*. How can I get its value as a string?

# Answer
Make sure the field is displayed in the display settings of your bundle (admin/structure/types/manage/*bundle*/display; replace *bundle* with the machine name of the content type) and define its settings (e.g., delimiter, prefix suffix).

>

In your template file, add `<?php echo render($content['your_field_name']); ?>`
> 2 votes

# Answer
The documentation for node.tpl.php has the following note.

> Field variables: for each field instance attached to the node a corresponding variable is defined; for example, `$node->body` becomes `$body`. **When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables.** Otherwise they will have to explicitly specify the desired field language; for example, `$node->body['en']`, thus overriding any language negotiation rule that was previously applied.

The description for the `$content` variable is then the following:

> 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.

So, if the machine name of that field is field\_price, you can get its raw value with `$field_price`, inside the node template file; use `render($content['field_price'])` to render it.
> 1 votes

# Answer
You've mentioned that `print render($content['field_price']);` doesn't work, so if all else fails - I'd use an `EntityMetadataWrapper`. Although if everything else is failing, then I think you're missing out some vital information and this probably won't work either.

My last resort if all the other suggestions don't work would be preprocessing the node template:

In a module or `template.php`:

```
function MYMODULE_preprocess_node(&$vars) {
  if (function_exists('entity_metadata_wrapper')) {
    $wrapper = entity_metadata_wrapper('node', $vars['node']);
    $vars['price'] = $wrapper->field_price->value();
  }
}

```

Then, in your `node.tpl.php` you can just write `print $price`.

This assumes you have the EntityAPI module installed, which is a pretty fair assumption.

If even this doesn't work, then you need to revisit your actual question, because it's badly written somewhere along the lines.
> 1 votes

# Answer
You can use one of the following code snippets.

```
 $val = $node->field_price[$node->language][0]['value'];
 print ".$val.";

```

```
<?php
  $my_field_items = field_get_items('node', $node, 'field_price1');
  if ($my_field_items) {
    $my_field_first_item = reset($my_field_items);
    $my_field_value = $my_field_first_item['value'];
  }
?>

```
> -2 votes

---
Tags: 7
---


# Question
Title: Remove "add to cart button" when event date has passed
I'm making a webshop that sells tickets for events. And I want that the "Add to cart" button isn't displayed when the event date has passed. But I'm struggling with the Rules module.

Can someone help me out? I'm using ubercart

# Answer
If you're using Drupal Commerce, this question seems to provide a step-by-step of what you're looking for.

How do I use rules scheduler to disable and enable a commerce product entity based on certain date fields?

At the very least it should point you in the right direction and give you a better sense for how Rules integrates with Commerce.
> 1 votes

---
Tags: rules, ubercart, datetime
---


# Question
Title: How can I create a user list hierarchical select exposed filter?
When I create a user view, I don't see the option for having **hierarchical** select on the exposed filters. I have the hierarchical data saved using hierarchical select already. Simple hierarchical select doesn't have the option too.

How can I create a user list hierarchical select exposed filter?

# Answer
> 1 votes
Hierarchical Select for Drupal 7 does not have Views support. At this point, the HS has not been actively maintained in more than a year so it is unlikely to expect this to be added soon, if at all. There is an issue on porting the D6 functionality to D7.

If using Simple Hierarchical Select, which only works on taxonomy terms, you can follow the instructions on the module's page:

> * add a new filter using the field set-up as "Simple hierarchical select" or use "Content: Has taxonomy terms (with depth; Simple hierarchical select)" as a new filter
> * use "Simple hierarchical select" as selection type
> * select "Expose this filter to visitors, to allow them to change it"
> * enjoy ;)

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


title: Can't call hook index document build

text:
# Question
Title: Can't call hook index document build
I have installed the **apachesolr** module and it all works fine. To display more details about results, Ivs decided to add indexes.

But Im stucked, because the `hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id)` is not called.

Im using the last version of both **solr** and **Drupal module**.

# Answer
I finally resolved it. The hook is called during the indexing not during the search.
> 0 votes

---
Tags: hooks, search
---


# Question
Title: How predefine templates for webform email templates?
I need to have a bunch of different webform e-mail templates with different text - how do I create those with code in Drupal 7?

# Answer
Ok, I got this sorted out, I used `hook_form_alter` to get the stuff into the select field, and did an override on the javascript-file from the webform module. I will try to answer it more complety in the next days if I have the time to do so.
> 1 votes

# Answer
Webform emails are themeable using `.tpl.php` files just as nodes, views etc. There is a *THEMING.txt* document that ships with Webform that explains exactly how to do what you are after, although the bit you're looking for is near the top:

> If you want to edit the e-mail sent by only one particular webform, rename the file "webform-mail-\[node id here\].tpl.php", replacing \[node id here\] with the node ID of the webform.

There's also this handbook page on Drupal.org: Customising the emails sent by webform
> 0 votes

---
Tags: webforms
---


# Question
Title: How can I remove the hardcoded menus from the Navin subtheme?
I'm using Navin, a subtheme of Omega. I'm trying to hide the main menu, so that I can add a superfish menu, but I don't know where it's been hardcoded. It's not in a block (**admin/structure/blocks**). I've checked the theme settings page (**admin/appearance/settings/theme\_name**) The `region--menu.tpl.php` looks like this:

```
<?php
  $main_links = menu_tree_page_data(variable_get('menu_main_links_source', 'main-menu'));
  $main_links = menu_tree_output($main_links);
  $secondary_links = menu_tree_page_data(variable_get('menu_secondary_links_source', 'user-menu'));
  $secondary_links = menu_tree_output($secondary_links);
?>
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php if ($main_links): ?>
    <nav class="navigation">
      <?php print render($main_links); ?>
    </nav>
    <?php endif; ?>
    <?php if ($secondary_links): ?>
    <nav class="navigation-secondary">
      <?php print render($secondary_links); ?>
    </nav>
    <?php endif; ?>
    <?php print $content; ?>
  </div>
</div>

```

I appreciate any help or suggestions.

# Answer
> 2 votes
```
<?php
  $main_links = menu_tree_page_data(variable_get('menu_main_links_source', 'main-menu'));
  $main_links = menu_tree_output($main_links);
  $secondary_links = menu_tree_page_data(variable_get('menu_secondary_links_source', 'user-menu'));
  $secondary_links = menu_tree_output($secondary_links);
?>

```

Get rid of that bit for starters.

If you're not using that, then you can probably also strip out the following:

```
<?php if ($main_links): ?>
    <nav class="navigation">
      <?php print render($main_links); ?>
    </nav>
    <?php endif; ?>
    <?php if ($secondary_links): ?>
    <nav class="navigation-secondary">
      <?php print render($secondary_links); ?>
    </nav>
    <?php endif; ?>

```

Which (for reference) should just leave you with the following:

```
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php print $content; ?>
  </div>
</div>

```

# Answer
> 0 votes
Go here: /admin/appearance/settings/THEME

uncheck main menu

---
Tags: routes
---


# Question
Title: How can I debug an AJAX error in VBO? (PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri'
I have a view that lists all the user accounts on my site. With VBO, I have a rules component, **Resave user account** (action set, action: save entity (user), no *force saving immediately*).

Recently, when I attempt to re-save all user accounts, I got an error on **id=4037**:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /en/batch?id=**4037**&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file\_managed} (filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> 1 \[:db\_insert\_placeholder\_2\] =\> 1375690632 ) in drupal\_write\_record() (line 7153 of /Volumes/Bullfrog/om/includes/common.inc).

And when I attempted to save all accounts again, the error occurred on **id=4039**:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /en/batch?id=**4039**&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file\_managed} (filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> 1 \[:db\_insert\_placeholder\_2\] =\> 1375691655 ) in drupal\_write\_record() (line 7153 of /Volumes/Bullfrog/om/includes/common.inc).

So, if I simply continue to re-save again and again, eventually all the accounts will get re-saved, but to execute this bulk operation takes about 20 minutes each time, so I will waste several hours this way. How can I analyze what is the cause of this error?

# Answer
> 0 votes
This turned out to be a bizarre core bug in which image files stored in user profile fields behave oddly that was getting triggered by Rules under some weird conditions.

# Answer
> 2 votes
`Duplicate entry '' for key 'uri'` actually says a little more than AlexK realizes, it says both that there's a file without a uri, hence the `''`, and that you have more than one of these, hence the `Duplicate entry`.

I'm guessing there's a filefield on your users, and some of these have lost part of their data for reasons I don't understand. (The same thing happened to me once during a faulty export-from-one-site-and-import-to-another).

Why the process can be "forced" by repetition I don't understand, but close inspection of the user entity and any fields that could have a 'uri' key, both through devel and the raw data in the DB, should reveal what the source of the problem is.

# Answer
> 1 votes
The database error you are getting there is due to Drupal trying to insert a managed file into the database which already exists. The error **Duplicate entry '' for key 'uri'** tells us that Drupal is trying to create a file using a URI which already exists in the database.

IMO what I think is happening is that the VBO is re-saving each user account correctly, but is trying to create a new file instance for attached files, instead of updating each attached file correctly.

I'm not sure how you would fix this specifically, but it seems to me this is a problem with the way VBO handles resaving user account. Wish I could be of more help.

# Answer
> 0 votes
Re-load the user using user\_load() before passing it to user\_save(), this will ensure that fields are correctly populated, and prevent this kind of error (here uri attributes are empty) from happening

---
Tags: views, debugging
---


# Question
Title: Using FBOauth, only allow existing users to associate a Facebook account
How might I configure a login scheme where by

* if someone already has an account on the site they may associate a FB account and login with it
* But yet, deny login to any FB account that is not already associated with an existing account

Is something like this approachable?

In other words, I don't want random FB accounts to log into a Drupal instance but yet, want to allow existing users to associate a FB account with their Drupal login.

# Answer
> 0 votes
It turns out the FBOauth modules checks for the ability to create new accounts. Since we've limited our system only to User 1 and LDAP, no new FB accounts appear to be created. This leaves the user only to log in with an LDAP/AD account and then *associate* FB and their Drupal account. That is the exact behaviour for our use case!

---
Tags: social-network
---


# Question
Title: How to filter taxonomy term in views from URL
I am working on a travel website, and I made taxonomy with depth continent/country/city. I also have taxonomy locations restaurants, museums, nightlife... I have content types destinations and locations. I made a view from location content (all restaurants)

I would like to have locations filtered from destination taxonomy term in URL (e.g. destination/europe/france/paris to sort only restaurants from Paris, but destination/europe/france to list all restaurants from France).

Can anybody help?

# Answer
> 0 votes
The best way to do this is as follows:

Assuming you have fields in your content type for continent, country, and city: Add each of these fields separately in your view's Contextual Filters. You can leave them at the default settings for now.

Then, change your path settings for the page to one like such: destinations/% (the % will be replaced with your contextual filters).

After saving the view, you should then be able to visit a path such as destination/europe/france/paris OR destination/europe/france, granted you have content within those areas.

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


# Question
Title: Persistent session cookies: remember session even after closing the browser
I would like to store anonymous users $\_SESSION in a cookie so that their cart and other custom information is still available even after closing the browser.

I found this interesting post which tells me I should add this to my local.settings.php:

```
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 7);
ini_set('session.save_path', '/home/yoursite/sessions');

```

So that session cookie would be available for a week. But it also stands that we should use `session_regenerate_id()` elseway the cookie lifetime is not updated.

I could not find `session_regenerate_id`in Drupal 7 source code, but I believe Drupal might already handle this from what I read in the code comments.

**My questions are:**

* is this a good approach to have persistent cookie sessions?
* do I need to add to my local.settings.php `session_regenerate_id()` too?

Thank you very much for your advises

# Answer
> 0 votes
So far this in my *local.settings.php* seems to work just fine:

```
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 7);
ini_set('session.save_path', '/home/yoursite/sessions');

```

# Answer
> 0 votes
Hi you could use javascript for this.

Using these 3 functions. its properly the best way and then you wont have problems if your are using Varnish

```
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

```

---
Tags: sessions, cookies
---


# Question
Title: How send a node as a newsletter by rules in Drupal 7?
I want to fetch a node of custom content type that one of its fields has a specified value and send all node's fields to all users that have a specified role with rules when cron maintenance tasks are performed. Any idea? Thanks

# Answer
> 1 votes
I will only provide some pointers as it would take me an hour or more to write out the steps.

1. It would be best to use Rules scheduler, rather than a views loop to send this info. Every cron run you don't want to have to loop through all of your node to check to see if one needs to be sent.
2. Enable Rules Scheduler.
3. Create a Rules component with an action of send email. This will contain all of the email structure including your field tokens for your node. The to field will be all users of role "INSERT YOUR ROLE".
4. Then create a rule to schedule that component when a node is saved. Use condition "entity has field" to pull your "trigger field" into scope. Then add a second condition, "Data comparison" or "data is empty" (negate if needed as I do not know what type of field your going to trigger this off of).
5. Set the schedule time to be the current date. Rules scheduler only happens on cron anyway, so this will ensure the next cron run it will send.

Note: Rules and more specifically core does not support html emails out of the box, so use something like mime mail, Html mail or mandrill module to do this. If your nodes contain images that need to be sent, then you are going to need to add a special filter for those fields so that add your site root is added to all images and links. This way it doesn't use relative paths and break your images/links. Use the Pathologic module to do this.

---
Tags: 7, rules, emails
---


# Question
Title: Flag lists visible for one authenticated user but not for others
The site in question displays a table-formatted View of relevant content, with a checkbox column for flagging. \[relevant modules installed: Flag, Flag Lists, Flag Actions\] The Flag List Operations widget allows creation of custom-named lists, which are viewed in a separate node. Each list name launches a full display of the flagged content. At one point this was working perfectly for authenticated users as well as for Admin. Mysteriously, now it is working for one authenticated user but not for any other authenticated user. Specifically, these other users' List names will be shown in a table view, but when clicked, the list is empty. I tried deleting the non-working users (all experimental at this point) and creating new ones. There is no obvious difference in the config of the new ones as compared to the one that works. Any suggestions about how this inconsistency could happen?

# Answer
I found a solution to this problem, although I can't say I fully understand why it was happening. Seems to be a case of too many relationships in the View, causing some type of conflict that appeared only in some cases. During the building phase I had added a batch of 6 relationships, trying to get it to work but ended up with more than were necessary. I eliminated them one by one and tested, until the truly necessary ones were identified. It really only needed 2: "Flag lists: User" and "(List user) Flags: User's flagged content (current\_user\_flag)."
> 0 votes

---
Tags: flags
---


# Question
Title: Create an 'active' class for partial url?
I have a system of menus on a site that helps the user drill down to the page they are looking for. If they click a link in the main nav, it might take the to /category. On that page, a sidebar menu would direct them to /category/page.

Previously, I have used the active class to highlight a menu item while the user is on that page. In this case, I want both menu items to be highlighted, since the page the user is on falls is a part of the main category.

To clarify, how can I keep a link active if it points to /category and the page the user is viewing is /category/page?

Thanks for the help!

# Answer
There is a module for that - Menu Trail By Path

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at `yoursite.com/blog/category1/article1`

Menu Items with these paths will get the active-trail class on them and expand accordingly.

```
blog
blog/category1
blog/category1/article1

```

This is particularly useful if you want a lot of nodes to appear as children of certain `nodes / taxonomy term / views / referenced nodes / etc`, but do not want to add them all to the menu. eg. hundreds of blog articles.

Menu Trail By Path is best used in conjunction with Pathauto.
> 1 votes

---
Tags: routes
---


# Question
Title: How do I insert a user picture's thumbnail on the "Submitted by" field?
I want to insert user picture's thumbnail on "Submitted by" field, which is displayed in teaser such as the following.

> Submitted by \[some\_user\] \[someuser picture's thumbnail\] on xx/xx/xx

How do I do that as effortless as possible?

# Answer
> 0 votes
Hope this will help you.

In Drupal 7 you can achieve this using **template preprocess functions** \- THEMENAME\_preprocess\_node.

Steps

* First add default user picture, go to sites/default/files and create a folder **user\_pictures** and add default user picture by name **default.png**
* Now add default picture URL using **admin/config/people/accounts**.
* Add this code in template.php

```

    function THEMENAME_preprocess_node(&$variables) {
      $node = $variables['node'];
      if ($vars['view_mode'] == 'teaser') { //check for teaser views
        //get author picture uri
        $author_picture_uri = db_query("
        SELECT uri FROM {file_managed} fm
        INNER JOIN {users} u ON u.picture = fm.fid
        WHERE u.uid = :uid", array(':uid' => $node->uid))->fetchField();
        $author_picture_uri = !empty($author_picture_uri) ? $author_picture_uri : 'public://default_user.jpg';
        $usr_pic = theme_image_style(
          array(
        'style_name' => 'thumbnail',
        'path' => $author_picture_uri,
        'attributes' => array('class' => 'author-pic'),
        'width' => NULL,
        'height' => NULL
          )
        );
        if ($variables['submitted'] && isset($node->uid)) {
          $variables['submitted'] = t('Submitted by !username !userpicture on !datetime', array('!username' => $variables['name'], '!userpicture' => $usr_pic, '!datetime' => $variables['date']));
        }
      }
    }

```
* Where `public://user_pictures/default.png` equivalent to `sites/default/files/user_pictures/default.png`

---
Tags: 7, nodes, media
---


# Question
Title: How can I force the user to select dates that have passed when using the Date picker in the form API?
I need to use a pop up date picker from the Date module in the Form API. It's displaying OK, but I want to restrict the user to only have the option of selecting dates that have passed, and not future dates.

How can I achieve this?

Here is my code:

```
$form['fieldset_one']['date_field'] = array(
  '#weight' => '5',
  '#title' => t('Date of Birth'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
);

```

# Answer
> 0 votes
You can try this approach:

Pass the JS options in `'#datepicker_options`'

```
$form['fieldset_one']['date_field'] = array(
  '#weight' => '5',
  '#title' => t('Date of Birth'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
  '#datepicker_options' => array(
    'maxDate' => 0,
  ),
);

```

`maxDate => 0` should set the maximum date to today. -1 would set it to yesterday.

More info: http://api.jqueryui.com/datepicker/#option-maxDate

# Answer
> 0 votes
They are talking about datepicker options here: Customize days that can be clicked on a Calendar popup

Apparently datepicker is quite versatile, with those options you can set max-date, min-date etc.

---
Tags: datetime
---


# Question
Title: How to make a taxonomy term display a field
I set up a taxonomy vocabulary (College attended) to be a field in my profile 2 registration form.

When a new user registers, he selects one of the terms of the vocabulary (i.e colleges).

I would like to have the surname of the users (a field in the core registration form) who went to a particular college displayed when a term is selected.

Please how do I achieve this. P.S.: Presently I get only the notice "There is currently no content classified with this term", when i select a term.

Thanks in advance.

# Answer
> 1 votes
Create a view which shows surname of person given a username. Use https://drupal.org/project/viewfield and add it as field in the taxonomy and it should show surname.

By default linked users are not listed under taxonomy terms (read here : Assigning User's In Taxonomy Terms) and there is another useful post: https://stackoverflow.com/questions/11524357/how-to-link-a-user-with-taxonomy-terms

---
Tags: taxonomy-terms
---


# Question
Title: How can I replace a value already present in the database?
Is there a way for `db_insert()` to overwrite existing entries?

# Answer
As @kiamlaluno mentioned `db_insert()` inserts a new row in the table. You can use `db_update()`, to update the row if it already exists. You can use db\_merge(), to combine both of them.
See the example (taken from the documentation):

```
db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
    ))
  ->execute();

```

> In the above example, we instruct the query to operate on the "example" table. We then specify one key field, 'name', with a value of $name. We then specify an array of values to set.
>
> If a row already exists in which the field "name" has the value $name, then fields field1 and field2 will be set to the corresponding values in that existing row. If such a row does not exist, one will be created in which name has the value $name, field1 has the value $value1, and field2 has the value $value2. Thus at the end of the query, the end result is the same regardless of whether or not the row already existed.
> 4 votes

# Answer
`db_insert()` inserts a new row in the table; if you need to update an existing row, you need to use db\_update().

```
db_update('system')
  ->fields(array('status' => 0))
  ->condition('type', 'module')
  ->condition('name', $module)
  ->execute();

```

The fields passed to `fields()` are the ones that need to be updated.
> 2 votes

---
Tags: 7, database
---


title: More link not displaying on view. Why?

text:
# Question
Title: More link not displaying on view. Why?
I created a view and am expecting the *More* link to appear but it isn't.

The *Content: Body field* formatter is set to *Trimmed* and the trim length is 100. *Create more link* is ticked, and I have entered "More" in the *More link text* text box.

Any advice would be greatly appreciated.

# Answer
> 1 votes
You get a more link (that links to the node) if your view lists nodes in the teaser view mode. For any other case the situation is more complex.

Ongoing discussion about this issue: https://drupal.org/node/823380 "More link is always visible on teaser".

Perhaps the best solution for the time being: https://drupal.org/project/readmorecontrol

# Answer
> 0 votes
check node tpl for full and teaser view's, you may get a clue.

---
Tags: views
---


title: How do I use a custom template file?

text:
# Question
Title: How do I use a custom template file?
I tried using a custom template file for my theme, but using page--testpage.tpl.php (where testpage is the path alias for the page being shown) doesn't work. It just works with page--node--47.tpl.php

How could I fix it?

# Answer
> 2 votes
Read Drupal 7 Template (Theme Hook) Suggestions

> A theme hook suggestions is an alternate template (.tpl.php) file that you have created to override the base or original template file.

The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:

page--node--edit.tpl.php

page--node--1.tpl.php

page--node.tpl.php

page.tpl.php

Read Theming Drupal 6 and 7

If you still want to alter the suggestions its possible with `template_preprocess_page`

```
function template_preprocess_page(&$variables) {
  $variables['theme_hook_suggestions'][] = "page--type--" . $vars['node']->type;
  // likewise you can do
  // $variables['theme_hook_suggestions'][] = "page".GET-URL-ALIAS-HERE;
}

```

# Answer
> 0 votes
From your comments, it looks like you're using Drupal 6. In that case, use a single hypen (not a double) in the name of your template file. I.e.: `page-testpage.tpl.php` instead of `page--testpage.tpl.php`.

(Use the double hyphen syntax for Drupal 7.)

---
Tags: 6, theming
---


# Question
Title: Print specific block from a region in drupal 7
The region name is "sidebar\_first". and it has two blocks. How can I print this block separately. Please help. I can not find the way to print a specific block from a region in drupal 7.

# Answer
> 1 votes
You can use this method:

```
$module = 'my_module'; // This is the module that provides the hook_block_view
$delta = 'my_block'; // you can get $delta from moduel hook_block_info
$block = module_invoke($module, 'block_view', $delta);
print render($block['content']);

```

---
Tags: views, migrations
---


# Question
Title: How can I retrieve indexed facet options for a particular field using Search API?
I currently have the Search API module configured with an Apache Solr server instance, and have created an index which indexes a custom entity.

I'm looking to somehow retrieve the options displayed within a Facet I have created for a particular field, to as options for a select field on a custom form. So in other words, the function a particular Facet would use to query Apache Solr when it is populated.

Does anyone know how I can retrieve this data using the Search API?

I've tried playing around with the example given in this very useful post on querying using the Search API. So far I've had no such luck retrieving the indexed Facet values as the appear in their Facet blocks.

Any help would be appreciated thanks.

# Answer
I seem to have found the answer after some major trial and error, and some digging through the FacetAPI source code. The issue is linked to the same issue explained in the post Display facets on non-search pages

I created a facet block in Views for each facet that I'm trying to access, and set them to "hidden" in the block settings within Views. Then by adding a block from my custom module directly below them in the same region, I was able to access the facet data using the following code:

```
$searcher = 'search_api@MY_CUSTOM_SEARCHAPI_INDEX';
$realm_name = 'block';

$build = facetapi_build_realm($searcher, $realm_name);
krumo($build);

```

The krumo output contains a render array for each facet you're trying to access, and all the facet options are available for you to access.

I hope this helps someone struggling with the same issue.
> 1 votes

---
Tags: search
---


# Question
Title: How can I change the node path shown to the user?
How can I change the path part of the node URL from `?q=node/2` into something more meaningsful. I want, for instance, to display it like this: `?q=Services`.

# Answer
What you need is the pathauto module

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

And you may also want to enable clean url to get rid of the **q=** in the url

To change a particular node, go to **admin/config/search/path/add**

Or go to the node and scroll down to url path settings and change it there. Make sure to uncheck generate automatic URL alias
> 0 votes

# Answer
Assuming you're using Drupal 7, to manually set a name for a module, all you need to do is to login as admin and navigate to *Configuration → URL aliases*. There you can create string aliases for nodes, so that `node/2` is aliased to `Services`.

For the nicest URLs, you should also enable Clean URLs on you site.

If you do not want to do this yourself, but instead want want names to be assigned to node paths *automatically* (based on some set of rules), then you can install and enable the PathAuto module.
> 2 votes

---
Tags: nodes
---


# Question
Title: How to jump to a specific page in a multipage Webform?
I have a multipage Webform, and I'm using Webform Bonus Pack to display a summary at the end before the user finally submits the form.

What I'd like to do is provide "edit" links alongside the various sections of the form data so the user can jump to the page containing those fields.

Does anyone know how I can do this or, failing that, can anyone at least throw me a bone and tell me how Webform decides which page to display after a "next/previous" button is pressed on a multipage form?

I thought I'd be cute and use Javascript to change the value of the hidden "details\[page\_num\]" field to be one greater than the target page, then invoke a `click()` on the Previous button, but to no avail; it still goes back to the previous (second to last) page. There is a `$_POST['details']['page_num']` containing the current page number, but it's apparently not used to determine where the Next and Previous buttons take the form.

# Answer
I've just published a webform\_steps module that provides a navigation bar for multi page webforms. It solves the problem by implementing a submit-handler that simulates the next and previous buttons very similar to how you describe it.

The magic has to happen on the PHP side in the `$form_state` array.
> 2 votes

---
Tags: webforms, forms, navigation
---


title: Poll Rules integration

text:
# Question
Title: Poll Rules integration
How can I integrate core poll module with rules?

I found the advpoll module but it is still in dev version and throws errors everywhere.

I am looking to simply trigger a rule after user votes on a poll.

Are there any alternatives to achieve the same functionality?

# Answer
> 2 votes
It turned out to be fairly easy to do through custom module:

**MYMODULE.module**

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'poll_view_voting':
      $form['vote']['#submit'][] = 'MYMODULE_poll_view_voting_submit';
      break;
  }
}

/**
 * Submit handler for poll_view_voting form.
 */
function MYMODULE_poll_view_voting_submit($form, &$form_state) {
  // Invoke our custom rule and pass the loaded node object as an argument.
  rules_invoke_event('MYMODULE_poll_vote', node_load($form['#node']->nid));
}

```

**MYMODULE.rules.inc**

```
/**
 * Implements hook_rules_event_info().
 */
function MYMODULE_rules_event_info() {
  return array(
    'MYMODULE_poll_vote' => array(
      'label' => t('User casts a poll vote'),
      'help' => t('Triggers when users are casting votes on polls.'),
      'group' => t('MYMODULE HUMAN NAME'),
      'variables' => array(
        'poll' => array(
          'type' => 'node',
          'label' => t('Poll node'),
          'description' => t('Voted poll node.'),
        ),
      ),
    ),
  );
}

```

---
Tags: 7, rules, polls
---


# Question
Title: How can I securely expose data through Drupal (via REST or something else)
I'm looking to use Drupal to pull in data through forms etc, probably in the form of content types, and then expose these, probably via REST, to other things. I've had a look at the services module, but I'm concerned about securing this, and am going to be using certificates to do so. Is there anything out there that currently supports this sort of thing, or am I getting into custom made module territory here?

# Answer
> 2 votes
Services has a pluggable architecture for authentication, so if there's nothing that supports certificate authentication, all you need to write yourself is such a plugin.

That is basically responsible for mapping that certificate to a Drupal user and then everything after that will check that this user has permissions to access whatever entity/content it requested.

Drupal Module as web service with SSL looks like a related question but doesn't have any answers.

---
Tags: nodes, security, services
---


title: Add js script to register page

text:
# Question
Title: Add js script to register page
Like the title says really, I'm trying to add a script to my register page, I'm using Zen as my theme, and I've added a script into the .info file, and to just test that it works I have added an `alert()` function, and it runs on just about every page **except** the default register page, and I don't know why, it just doesn't call the script at all.

The longer version is that I have a bespoke Drupal site, not intended for public use, just for specific medical personnel to use for an event we have coming up. What the client has requested is that the user *must* tick a box declaring they are a healthcare professional before they can register. I have added a boolean checkbox to my register form, and set it to mandatory, but obviously Drupal will accept either checked or unchecked, I want to make it so that they have to check the box before they can register (it's just a legal compliance thing)

I wanted to try to do it via Drupals methods only, but my backup was creating a js solution which would set the register button to disabled until the box was checked, except it doesnt seem to work on the register page.

Can this be done?

# Answer
If you make a checkbox required it should force the user to check it (if you have an up to date version of drupal core). See the issue here where that was fixed.

For older versions of drupal there was the checkbox validate module.

As for adding javascript in your info file. That will add it to every page. So either the page it doesn't work on is using a different theme (and therefore a different info file), or there is a javascript error on the page that is preventing your code from running.

Check your page for javascript errors.

There is also the legal module, which allows you to set terms and conditions that the user has to agree to when signing up. The module handles the checkboxes. It might not be right for you but it is another option.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Modify default rendering of a custom content type defined in a module
I am developing a module for importing, editing and exporting DocBook(XML) documents. In this module I define two new content types: docbook and \*docbook\_section\*. I have also defined new fields like: author, *keywords*, etc.

The default rendering of these content types is not quite handsome, so I would like to change and improve it. The classical Drupal way is to copy the template **node.tpl.php** to **node--docbook.tpl.php** and customize it. But this modification is done on the current theme, after the module has been installed. I would like to do the modification inside the module, so that as soon as it is installed it has a decent default look, without having to make any external modifications. Themes should also be able to override this template, in order to customize the look.

It may seem reasonable to place **node--docbook.tpl.php** inside the module, but that way it will not work: the theme/rendering engine will not be able to find and use the template. To solve this problem, I have defined hook\_theme() on the module like this:

```
/**
 * Implements hook_theme().
 */
function docbook_theme($existing, $type, $theme, $path) {
  return array (
    'node__docbook' => array (
      //'variables' => array('view' => NULL,),
      'template' => 'node--docbook' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'docbook'),
      'preprocess functions' => array('template_preprocess_node__docbook'),
    ),
  );
}

```

This time it indeed finds the template **node--docbook.tpl.php** inside the module. Themes can also override the template if they define **node--docbook.tpl.php**. But I have some problems.

First, I call nowhere the function `theme('docbook', $variables)`, so I don't see where I can assign the variables. Another option can be to assign them on the *preprocess* function like this:

```
function template_preprocess_node__docbook(&$variables) {
  $variables['test'] = 'ABC';
}

```

But this doesn't work either, and in fact, it seems that the function `template_preprocess_node__docbook()` is not called at all, although it has been listed on 'preprocess functions' as well (at the definition of `hook_theme()`).

So, I am stuck. Although I have been working with Drupal7 for two years, theme and template processing still seems to me like a huge maze and I am not able to find my way around. Can somebody help me?

# Answer
> 0 votes
This is the way that I solved this problem:

```
/**
 * Implements hook_theme().
 */
function docbook_theme($existing, $type, $theme, $path) {
  return array (
    'node__docbook' => array(
      'template' => 'node--docbook',
    ),
    'node__docbook_section' => array(
      'template' => 'node--docbook-section' ,
    ),
    'field__field_dbw_author' => array(
    ),
  );
}

/**
 * Implements hook_preprocess_HOOK().
 */
function docbook_preprocess_node(&$variables) {
  //krumo($variables);  //debug

  if ($variables['type'] == 'docbook') {
    $variables['variable1'] = 'hello1';
  }

  if ($variables['type'] == 'docbook_section') {
    $variables['variable2'] = 'hello2';
  }
}

/**
 * Implementing theme function theme_HOOK().
 */
function theme_field__field_dbw_author($variables) {
  //krumo($variables);  //debug

  $output = '';

  . . . . . . . . . . . . . . .

  return $output;
}

```

See more details on these commits:

I would expect these solutions to work as well:

```
function docbook_preprocess(&$variables, $hook) {
  if ($hook == 'node__docbook') {
    $variables['my_new_variable'] = 'hello';
  }
}

function docbook_preprocess_node__docbook(&$variables) {
  $variables['my_new_variable'] = 'hello';
}

function template_preprocess_node__docbook(&$variables) {
  $variables['my_new_variable'] = 'hello';
}

```

But somehow they don't work. Either my understanding and expectations are wrong, or there is something wrong on the implementation of Drupal.

---
Tags: theming, nodes
---


# Question
Title: How can I change the labels on a chart created with the Google Chart Tools module?
I'm using both the Chart module and the Google Chart Tools module to create a chart from the data that I'm collecting from registered users.

Here is a sample of my chart:

But how can I change the labels of the X-axis?

And I want the title to appear on the X-axis also, instead of the link. How can I do that?

# Answer
That is very easy. Simply uncheck **link field to original piece of content** of the field you are using.
> 1 votes

---
Tags: 7, charts, google-search-console
---


# Question
Title: Checking Available Update data - AJAX error
I'm having problems with a local site that I imported to Acquia Dev desktop from one of my live sites. Everytime I try to Check for Available Update data, I get an Ajax error

> Error Checking Update Data Please Continue to error page An AJAX HTTP request terminated abnormally. Debugging information follows. Path: /batch?id=676&op=do StatusText: ResponseText: ReadyState: 4

Clicking the error page link, drupal returns me to the available updates page with a message

> An error occurred trying to get available update data.

Any ideas?

Thanks Sharon

# Answer
It turns out the problem was with Cron, It was not running due to some custom php code. Remove the code and everything seems fine now.
> 0 votes

---
Tags: ajax, updating
---


# Question
Title: Process a token from panel context in a ctools content type plugin
I have a ctools content type plugin. It has a simple text field settings form. In there I am putting a token from the panel content e.g. %vn\_subject:vn-subject-facebook-link. I am then rendering this into a template. However, it is just rendering out the token as above without processing it. How can I process the token if possible to retrieve the required field value? Thanks

# Answer
> 3 votes
The magic function is ctools\_context\_keyword\_substitute

The key to getting this working is to make sure that you use the `all contexts` flag in your plugin configuration.

```
$plugin = array(
  'single' => TRUE,
  'title' => t('Instagram'),
  'category' => t('Content'),
  'all contexts' => TRUE,
);

/**
 * Render the custom content type.
 */
function MODULE_PANE_content_type_render($subtype, $conf, $panel_args, $context) {

  ....

  $replaced = ctools_context_keyword_substitute('your_string_with_%keywords', array(), $context);

  ....
}

```

---
Tags: tokens, chaos-tool-suite
---


title: Webform simplenews component styling

text:
# Question
Title: Webform simplenews component styling
I am creating a Newsletter field for just one component to include email only for newsletter subscription, but I need a way to style both the input field and the submit button to be inline, i.e side by side rather than above each other like typical forms.

# Answer
You can make use of the arrange fields module.

> This module lets you drag-and-drop the fields of any CCK content type, Webform, or almost any other form in Drupal into the positions you would like for editing. This makes it super simple to have forms with inline fields, which you can change at any point. Tab indexing is also updated, so no matter how you arrange the fields, the users can still tab through them easily. And, you can now add arbitrary bits of HTML markup-- labels, images, HR's, etc.
> 1 votes

---
Tags: theming, emails
---


# Question
Title: Value or label inside a exposed search form and change input form
I've created a three exposed filters:

* Search
* Choose location
* Choose category

Instead of using a label "Search", in input field I want to have a "enter keywords to search" and when the user clicks on that input the letters will disappear. I've seen this in many websites.

Choose location has a label "Choose location" and in drop down menu the first option is "All". Instead of using label, I want the first option (All) to be "Choose location".

Choose category to be exactly like the location desired method.

I'm using Drupal 7.

# Answer
For adding text to your input field, can be done in one of two ways

```
    function myhook_form_alter(&$form, &$form_state, $form_id){
        if($form_id == "views_exposed_form"){
         dsm($form); // print $form array on the top of the page
          if (isset($form['title'])) {
            $form['title']['#attributes'] = array('placeholder' => array(t('Enter Keywords to search...')));
    }
  }
}

```

Or use Compact form

> Compact Forms presents text fields for selected forms in a more compact fashion using jQuery.
>
> The form item/element fields are overlaid with their respective labels. When the user focuses a field the label fades away nicely, and if the field is left empty the label fades back in again.

**For changing the All to choose location**

```
function your_module_name_form_alter(&$form, $form_state, $form_id) {
      if($form_state['view']->name == 'your_view_name') {
        $form['your_dropdown_name']['#options']['All'] = t('- Choose Location -');
      }
}

```
> 4 votes

---
Tags: views
---


# Question
Title: Override entityreference autocomplete and return entityfieldquery output
I am trying to override an entityreference autocomplete form item, I have managed to override the form, and get the arg passed to a hook\_menu callback. However, I'm struggling with getting the callback to work based on what I type into the form box. Looking in the Entity reference module there is some code in the hook\_autocomplete\_callback that handles the $string argument and looks up matches `$entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator']` \- something like that.

Can anyone assist?

My code:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function wl_event_form_event_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
  // We will get our term id argument from the from build itself.
    $node_id  = $form['#node']->nid;
  // This is the path we will create in hook_menu().
     $new_path = "wl_event/autocomplete/{$node_id}";
  // Maximum number of descrete values (deltas) that are present.
 $max_delta = $form['field_wl_event_acquired_resource']['und']['#max_delta'];
  // Hijack the autocomplete callback for each of our values.
  for($x=0; $x <= $max_delta; $x++) {
    $form['field_wl_event_acquired_resource']['und'][$x]['target_id']['#autocomplete_path']= $new_path;
  }
}

/**
 * Implements hook_menu().
 */
// can be used to do a lookup on a menu path to return json
// probably entity reference autocomplete does a similar thing

//we want to get all of the resources of the user profiles of
//users who are registered on the event

//
function wl_event_menu() {
  $items = array();
  $items['wl_event/autocomplete/%'] = array(
    'title' => t('project call back'),
    'page callback' => 'wl_event_autocomplete_callback',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return $items;
}

function wl_event_autocomplete_callback($arg1, $string = '') {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'resource');
  // ->propertyCondition('nid', '1')
  $results = $query->execute();
  print_r(drupal_json_output($results));
  return drupal_json_output($results);
}

```

# Answer
> 10 votes
EntityReference uses the ctools plugin system to define selection handlers which feed into the autocomplete options. The interface definition is defined in entityreference/plugins/selection/abstract.inc. In that same directory, you will see the two included handlers, Simple and Views. Each of these is defined by two files, one for the class itself, and one with an array to register the plugin with ctools.

To provide your own selection handler, first tell ctools where to look for your plugin by implementing `hook_ctools_plugin_directory`.

```
/**
 * Implements hook_ctools_plugin_directory().
 */
function wl_event_ctools_plugin_directory($module, $plugin) {
  if ($module == 'entityreference') {
    return 'plugins/' . $plugin;
  }
}

```

Then create 2 files in `wl_event/plugins/selection` similar to those in the entityreference. The `.inc` file should define the ctools plugin info, and the `.class.php` file should contain your plugin class. Most likely you'll want to subclass `EntityReference_SelectionHandler_Generic` and just override the appropriate methods.

Lastly, make sure you add the file with your plugin class to the `files[]` array in your modules info file so that the autoloader can find it.

---
Tags: ajax, entities
---


# Question
Title: How to use EntityFieldQuery etc. to return a particular field efficiently?
A taxonomy has a lot of big fields attached, but one of these fields is a short text field called `external_identifier`.

In code, I need to obtain an array mapping `external_identifier`s to `tid`s for a given list of external identifiers.

So in raw SQL this is very efficient:

```
SELECT entity_id, field_external_identifier_value
  FROM field_data_field_external_identifier
 WHERE field_external_identifier_value IN ('a123','b567',...);

```

I understand I should be using EntityFieldQuery, but this only gives me an array of `tid`s, keyed by ...`tid`. Then if I loop those and call entity\_load it will be doing lots of separate lookups and loading a whole load of stuff I don't need. This looks **really inefficient**.

I understand that EntityFieldQuery will only return Ids, so is there a better way?

Or do I just resort to SQL?

# Answer
The safest way to get a field value in Drupal is to load the whole entity using the API - Drupal is a modular system and this allows other modules to interact with the data. There are ways (see Clive's answer) to load the field with the API without having to load the full entity - but this is still much less efficient than a raw SQL query.

The question however is how often you need to run this inefficient code. Presumably you only need to run this code when entities have been modified - so while caching entities is not an option, you could well cache your map and only rebuild it when an entity has been modified (ie. on cache clear).

If your entities are modified very often, then rather then rebuild your map every time, you could use hook\_entity\_update and then edit that entitie's entry in your map - so continuously modify your map.

This approach may or may not be faster than using an SQL query every time you need your map - it depends on how often entities change and how often you generate the map.

That being said, it is extremely unlikely that Drupal 7's core database schema is going to change at this stage - you'd be quite safe using direct SQL queries (in particular if this is your own code as opposed to a module you want to release).
> 4 votes

# Answer
You might be able to get something of a compromise using `EntityFieldQuery` and `field_attach_load()` (not sure if I've understood your problem 100% so can't be totally sure).

I'll leave the specific implementation to your imagination, but suffice to say you can use the `EntityFieldQuery` to query for the pertinent entity IDs, and then use `field_attach_load()` to load the field data, for a single field if necessary.

It avoids the need to load the entities, or any fields other than the one you're looking for. It's still not as efficient as raw SQL query, but is certainly more future-proof.

It would go something like...

```
// Result of the EFQ
$result = $query->execute();

if (!empty($result[$entity_type])) {
  $entities = $result[$entity_type];

  field_attach_load($entity_type, $entities, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

  // Each $entity->$field_id should contain a relevant value if available.
}

```

As I say, might not work in your specific case but it's an interesting method nonetheless.

N.b. you'll probably need to use `field_info_field()` or `field_info_instance()` to get the ID of the field itself, so there'll be another query involved. Still nowhere near as much as a full entity load though.
> 3 votes

# Answer
Querying the database table is not an API. Not using an API means you are on your own and things might not behave/work as expected.

The values in there might or might not be the same as when you use entity\_load(), various load hooks are executed that might affect the data that you actually get in the end.

Yes, entity\_load() is considerably slower, but one way to solve this is to use the entitycache module, which makes loading entities much faster.
> 2 votes

---
Tags: entities, database
---


# Question
Title: Where do you store arbitrary home page data?
There's some welcome heading, text, video that goes on the front page. Currently this is stored in variables but it feels wrong to me because, well, it's a wall of text and variables is loaded on every page. Any module helping here?

# Answer
> 0 votes
We use two different solutions, depending on the situation.

The easiest is to make a custom content type and field it out the way you want. Make a node, and assign it at the home page. If this is your own site, then you can trust yourself to only use it once. If this is for someone else, you either have to trust them, or put some mechanism in place so that they can't reuse this content type elsewhere. Modules like Viewfield, especially combined with Nodequeues can be used to lists of things. The custom content type concept can also be extended to a custom entity type if you are inclined to do so.

The second way is to make a custom Panel page, and then assign it to the home page. You get total flexability here to do just about anything you need. Text can be handled by the custom content pages. Other things, like media, are either handled by custom blocks / custom content pages, or internal-use content types that you Rabbit Hole and exclude from search results with Custom Search. Lists of things can just be handled with normal view content panes.

Of the two, we have been using the custom content type more than we have been using custom panel pages.

# Answer
> 0 votes
If its all editable why not creating a content type "homepage"? There will be only 1 node of this type(so what...)

# Answer
> 0 votes
You can use a custom settings form, the benefits:

1. Easy to build (Using the form API, hook\_menu, hook\_permission)
2. Easy to maintenance (content)- When you need to edit some content you may go to the settings form page and just edit whatever you need.
3. Easy to maintenance and add new features (code) - You can always add a new field (Image, text, embed and so on by using the great Form API .

In my opinion this is the best solution for this kind of need, using homepage content type is an overkill..

Thanks.

---
Tags: 7
---


# Question
Title: Display block based on main content type with view
I have created a view in a block, to display some related information to the current content type being displayed into the block. More precisely, I want to display the block only for book pages.

What I did is to add a contextual filter based on content type. For "WHEN THE FILTER VALUE IS NOT AVAILABLE", I provide a default value for "PHP contextual filter code" as follows

```
$node = node_load(arg(1));
return $node->type;

```

For "WHEN THE FILTER VALUE IS AVAILABLE", I use "Specify validation criteria" for content types with "book page".

I tried this but it didn't work. I think because I am using aliases in the url, it does not work.

What am I missing?

P.S: My final goal is actually to extract the group audience from the current book page and display the admins of that group into the block.

# Answer
In your case you don't need to provide any default value with PHP code.

Remove your contextual filter and add new one: `Content: nid`.

**"WHEN THE FILTER VALUE IS NOT AVAILABLE"**

Provide default value -\> content ID from URL

**"When the filter value IS available or a default is provided"**

Specify validation criteria

Validator -\> Content -\> book
> 1 votes

# Answer
Why are you checking the content type with the view?

If I understood your question, you want to display the view's block only on certain content type ('Book'). A much easier solution will be:

1. Go to Dashboard \>\> Structure \>\> Blocks
2. Find the view's block and go to its configuration
3. Under the 'Content Types' tab add 'Book'

That is it!
> 1 votes

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


title: Drupal block-level form submit URL?

text:
# Question
Title: Drupal block-level form submit URL?
I have a form:

```
function form_search_products($form, &$form_state) {
  $form = array();

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter keywords (ie: Fat free milk)'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add item to my shopping list'
  );

  return $form;
}

```

Simple and its loaded into a block region above product listings via:

```
function products_block_view($delta = '') {
 $block = array();

  switch ($delta) {
    case 'search_form':
    {
      $block['content'] = drupal_get_form('form_search_products');
      break;
    }
  }
  return $block;
}

```

I am trying to figure out how to map a submit handler now as there is no menu...

My current menu looks like this:

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

  $items['products/mycity'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping in MyCity',

    'page callback' => 'html_list_products',
    'access arguments' => array('access products')
  );

  $items['products/autocomplete.json/%'] = array(
    'type' => MENU_CALLBACK,

    'page callback' => 'json_list_products',
    'page arguments' => array(2),
    'access arguments' => array('access products')
  );

  return $items;
}

```

What or how do I add to the menu\_hook above so that I can process form submissions done through the above block code???

Alex

# Answer
> 1 votes
Form submissions aren't dependent on there being a path to view/submit the form at, all you need to do is one of the following:

1. Name the submit function as `FORMNAME_submit()` and Drupal will pick it up automatically
2. Add the handler manually in the form function itself, e.g.

```
$form['#submit'][] = 'my_submit_function';

```

---
Tags: forms
---


# Question
Title: Why is Solr throwing exceptions on unfound text files after insttalling Apache Solr Multilingual config files?
I have used Apache Solr Multilingual to generate Solr config files; however after installing these files Solr throws many exceptions of the form :

`Can't find resource '<text_file_name>_<lang>.txt'`

For example

`Can't find resource ' mapping-ISOLatin1Accent_fr.txt'`

Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?

# Answer
> 0 votes
> Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?

Seems the answer is 'no'. I manually created 6 text files per language in my solr config and solr started without complaint.

Each language needs each of these text files:

```
compoundwords_<lang>.txt
mapping-FoldToASCII_<lang>.txt
mapping-ISOLatin1Accent_<lang>.txt
protwords_<lang>.txt
stopwords_<lang>.txt
synonyms_<lang>.txt

```

where 'lang' is the Drupal language code which can be confirmed by looking over the schema.xml kicked out by Solr Multilingual Module . for example: 'en', 'es', 'de' ...

I copied the contents of each of said files from the Solr Multilingual Module config. forms

---
Tags: i18n-l10n, search
---


# Question
Title: How to set up a trial-based account for users on an ubercart site?
I want to set up a trial based account for an user who will sell his products. After he paid the payment, i will upgrade him to `role seller`.

Until his role is upgraded to `role seller`, i don't want to show `add to cart` button for the added products.

First of all how can i differentiate it to be a trail site for example. 30days until he pays, if not i want the role to be expired. How can i do it. Any suggestions will be helpful?

# Answer
1. Create 2 user roles: Trial Seller and Seller.
2. Create a **Rule**.

The second question is another seperate task.

1. Create a **Rule**:

* Event: "Drupal is initializing"
    * Conditions: User is of role "Trial Seller" AND not "Seller" AND php "(Current\_date\_time - Account\_Created\_Date) \> 30\*24\*60\*60" (to see if the time from the user account date until now is more than 30 days, time in seconds) AND he has paid
    * Action: Remove user role -\> "Trial Seller"

There is also the module Role\_Expire that may help you.
> 2 votes

---
Tags: 7, ubercart, users
---


# Question
Title: How do I remove the Previous and Next links?
The Previous and Next button links are causing accessibility errors and I would like to remove them (don't really need them for what I am using them anyway).

Is there a way to do this?

The error message is the following one:

> This button element does not have a name available to an accessibility API. Valid names are: title attribute, element content.

I have managed to hide the links from being displayed, but the error messages are still there. All I managed to do is get the css to set the display to none. Is there a way to completely remove the links from the code?

# Answer
> 0 votes
On the MANAGE DISPLAY of the content type that has this image edit the formatter for the colorbox image. There set the **Gallery (image grouping) \> No Gallery**.

---
Tags: javascript
---


# Question
Title: Form API-passing on the NID in a hidden field?
So, here's my issue. I have a university course page. I want to display a list of students currently weight listed for the course, and give the option for the student to add their name to the weight list.

I've outputted the current student weight list through a custom template file just fine. I've also made a one button form through a custom module that simply calls a submit function. Then I call that form on my node template. That part works all fine.

Then, all I need for this form to work is the current User's UID (which can be called easily from my form submit function in my module). And the NID that their name should be attached to. Where I'm having difficulty is the NID part. I can't figure out how I can add that to my custom form built through my module with Form API.

Right now, I'm setting a variable and calling that variable in the submit function.The problem there is it will screw up the system if more than one student is looking at different pages and submits it. So there needs to be way that I can set the current NID that the form sits on, then call it through my submit handler.

I've been searching google up and down for this, and I can't figure out how to set a hidden field with the current NID the form is on.

Any help would be greatly appreciated.

Edit: Here is my code currently for reference:

```
function wl_add_form($form_state) {

 $form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Add Name to List'),
  '#submit' => array('wl_add_form_submit_function'),
);

  return $form;
}

//Add me to weight list functions
function wl_add_form_submit_function($form, &$form_state) {

//dpm($form);
  //Handle the student add
  global $user;
  //get the User ID
  $userID = $user->uid;
  //get the NID from the node variable we set in the node-course template:

  $nid= variable_get($wlNID);
  $node = node_load($nid);
  $count = count($node->field_course_weight_student);
  $node->field_course_weight_student[$count]['uid'] = $userID; // another user
  node_save($node);
  drupal_set_message(t('Your name has been added to the weight list'));

}

```

# Answer
Just save the node ID in `$_SESSION`.

Using `variable_set()` has another effect, apart saving a value that is valid for all the users: It clears the cache Drupal uses for the Drupal variables, with the effect they are reloaded from the database the next time Drupal bootstraps. Compare the code used by variable\_set() and variable\_initialize(). (Similar code is executed by Drupal 6.)

```
  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;

```

```
  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

```

As for an example of how to use `$_SESSION` in a form, see node\_filter\_form(), the form builder function that handles the form that allows to filter nodes in admin/content/node.

```
  $session = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
  $filters = node_filters();

  $i = 0;
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__node',
  );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
    if ($type == 'term') {
      // Load term name from DB rather than search and parse options array.
      $value = module_invoke('taxonomy', 'term_load', $value);
      $value = $value->name;
    }
    elseif ($type == 'language') {
      $value = $value == LANGUAGE_NONE ? t('Language neutral') : module_invoke('locale', 'language_name', $value);
    }
    else {
      $value = $filters[$type]['options'][$value];
    }
    $t_args = array(
      '%property' => $filters[$type]['title'],
      '%value' => $value,
    );
    if ($i++) {
      $form['filters']['current'][] = array('#markup' => t('and where %property is %value', $t_args));
    }
    else {
      $form['filters']['current'][] = array('#markup' => t('where %property is %value', $t_args));
    }
    if (in_array($type, array('type', 'language'))) {
      // Remove the option if it is already being filtered on.
      unset($filters[$type]);
    }
  }

  $form['filters']['status'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('clearfix')),
    '#prefix' => ($i ? '<div class="additional-filters">' . t('and where') . '</div>' : ''),
  );
  $form['filters']['status']['filters'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('filters')),
  );
  foreach ($filters as $key => $filter) {
    $form['filters']['status']['filters'][$key] = array(
      '#type' => 'select',
      '#options' => $filter['options'],
      '#title' => $filter['title'],
      '#default_value' => '[any]',
    );
  }

```

Its form submission handler sets `$_SESSION` with the values entered by the user.

```
  // Apply every filter that has a choice selected other than 'any'.
  foreach ($filters as $filter => $options) {
    if (isset($form_state['values'][$filter]) && $form_state['values'][$filter] != '[any]') {
      // Flatten the options array to accommodate hierarchical/nested options.
      $flat_options = form_options_flatten($filters[$filter]['options']);
      // Only accept valid selections offered on the dropdown, block bad input.
      if (isset($flat_options[$form_state['values'][$filter]])) {
        $_SESSION['node_overview_filter'][] = array($filter, $form_state['values'][$filter]);
      }
    }
  }

```
> 2 votes

---
Tags: forms, 6
---


# Question
Title: How to upload a static copy of a pages HTML to S3
I have a need to upload a copy of a rendered output of a URL to Amazon S3 when it is edited and published.

By this I mean if I was to edit /brand-a/page-1 on a site, I would like the full rendered output of that page as seen by an unauthenticated user to be uploaded to /brand-a/page-1 in a S3 bucket. Essentually using Drupal as a content publishing platform offloading all delivery to the end user to Amazon S3.

I am comfortable using the Amazon S3 + AWSSDK + Libraries plugin for handling of media, I have not been able to find a plugin that covers off my requirements highlighted in red in the above diagram.

# Answer
> 1 votes
If you want to speed up the transfer process you could use HTTPRL to send the data to S3 in a non blocking request. You can also use it to do threading.

---
Tags: 7, caching
---


# Question
Title: Requirements for enabling compress and aggregation files
Is there any requirement or module that I need to enable in Apache to properly use the option bandwidth optimization in performance?

Do I need to enable the deflate module or I just need the headers module?

# Answer
> 3 votes
headers module is all you should need

---
Tags: 7, css-js-aggregation
---


# Question
Title: No access to admin page after change my server and domain
I have changed my website to a new domain and server. I can navigate throught my content. However, after login I can't access to admin pages. No error is shown, only blank page.

What I did was upload a new `.htaccess`, delete the cache tables, uncomment on `settings.php` the line "Base URL (optional)". $base\_url (replacing example.com with my site).

I don't know what can I do. Any idea please?

# Answer
I had the same problems and there are the several steps that you should do for solving your problems:

**1**.Add the Error reporting debug ability in settings.php by adding these lines:

```
error_reporting(-1);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

These lines should be comment out after debug or after solving problems.

**2**.Browse the website and see what error information that you will get. If there is error with timeout or memory problem. Please change the memory\_limit or max\_execution\_time if your hosting support to do that.

**3**.If there are some problems with the PHP version(There are some differences between PHP 4 and PHP 5). You will consider to upgrade or not.

**4**. Sometime there are several issues that are related to database or .htaccess. You'll see on the debug information and try to fix one by one
> 2 votes

# Answer
You might need to increase memory\_limit in php.ini . Check if php memory of new server is same as old server.
> 0 votes

---
Tags: debugging
---