title: How to add a Subscription box?

text:
# Question
Title: How to add a Subscription box?
I would like to add a style-able Subscription box which will consist of a Heading, text field and a styled button in form of an image. Upon pressing the submit button I would like the user to be presented with some options in form of checkboxes as well as the option if they would like html or plain text email format.

How would I go about adding this to my drupal 7 site?

# Answer
You can go ahead with Newsletter module. Module page explains features of it-

> * Multiple newsletters lists configurable on existing terms.
> * Plain text or HTML out of the box.
> * Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
> * Centralized administration and configuration on a single page.
> * Users can customize the terms in the list they subscribe to.
> * Custom template per list.
> * Statistics (CTR and Open-Rate).

As I see, it fulfil your requirement.
> 1 votes

# Answer
There are basicly two alternatives:

1. Using the Ctoosl Modal module. This module, included on the ctools project, is the most popular way to popup modal forms on Drupal, with lots of addon modules (like modal\_forms). Here is a nice tutorial.
2. Using a custom module. You may find the following modules helpful:

* popup\_message \- which seems well supported.
    * popup\_announcement \- this is a new module which seems closer to what you search for, with full html support, but with only a few downloads.

With option 2, you should have to create the form and inject it into the popup using the forms API, so here is a form creation tutorial, and a stackexchange discussion about the best form creation method.
> 1 votes

---
Tags: notifications
---


# Question
Title: Is it possible to set Cookie Session ID from a REST Service?
I have overridden Drupal's login process by calling a REST API which returns a 'true' or a 'false' depending on whether the login was successful or not. Once successful, I'm logging the user in by using a particular Drupal user account.

Would it be possible to change Drupal's Session ID to the one specified by the REST API call? Currently the REST API Call is giving me a JSESSIONID cookie and I was wondering if its possible to map this cookie to the one Drupal generates when the user logs in. Reason I need this is because I need keep track of this JSESSIONID to call other API methods related to the logged in user.

# Answer
You cant save off the `JSESSIONID` into the user attributes, eg `data` column, in D6 or D7. You simply do this in your code with:

```
$_SESSION['JSESSIONID'] = /* some value here */;

```

or wherever you call user\_save() in your custom login you can pass `$edit['data'] = array('jsessionid' => 12341234);` from the user\_save documentation:

> $edit: An array of fields and values to save. For example array('name' =\> 'My name'). Key / value pairs added to the $edit\['data'\] will be serialized and saved in the {users.data} column.

it then becomes accessible from a fully loaded `$user` object as simply a field of the user ... `$jsessionid = $user->jsessionid;` and you can use it as needed.
> 0 votes

---
Tags: sessions
---


title: Node and revision id

text:
# Question
Title: Node and revision id
I am working with a company setting up a drupal website. I am responsible for entering our product information into the drupal tables. I am having difficulty getting a straight answer/an answer that makes sense as to what the values for `nid` and `vid` should be in the `drupal_node` and `drupal_node_revision` tables should be. I am being told by our vendor that the values for `nid` and `vid` need to be the same (ie 27 and 27) but that doesn't make sense to me. Shouldn't the `vid` just start at 0 or 1 and increment up from there. Isn't it simply what the node table uses to read the current version from the revision table.

I know very little about drupal so I may be wrong but their answers aren't making sense to me. And as the `nid` is automatically incremented in the table, I have no way of knowing what the `nid` value is until after the insert. So I would have to read the value and run an update statement, which seems really sloppy.

# Answer
> 2 votes
If you begin to add nodes and never edit them, like you would do when migrating data to a new Drupal installation, then the nid and vid would increment at the same pace, and would *happen* to be the same. After first edit though, assuming you have revisioning on, the new vid would be what ever is the next available number for *all* revisions.

---
Tags: nodes
---


# Question
Title: Views: pass link to referenced node to image field
I have a content type "slideshow" with three fields: 1. title 2. image 3. entity reference to nodes of a specific content type.

Then I created a view which I want to display as a slideshow on the frontpage. Its filter is set to the content type "slideshow" and I have three fields there: 1. the entity reference to the nodes (hidden) 2. image 3. title

What I want to achieve is, pass the referenced node from the entity field as a link to the image field so that the image in the slideshow has a link to the node from the entity reference field.

I tried the following:

In 2. image field settings: I checked: Output this field as a link and in the link path I put: \[field\__slideshow\_link\_gallery\] which I got from the replacement patterns below.

The problem is that the image actually has a link but the link is **the name** of the referenced node rather than **the link** to the referenced node. I would need the link not the name.

In the 1. entity reference field in the view I have only three formatters (label, entity id and rendered entity). I used label as a formatter and checked "Link label to the referenced entity. Unfortunately only the name is passed to the image not the link. Any ideas would be greatly appreciated.

# Answer
1. You can select the entity I'd formatter and set the image link to 'node/'\[your\_token\_here\]
2. Use the views image field template (see the views theme information) to wrap it with the link
> 0 votes

---
Tags: views, entities
---


title: Using select lists with radio buttons

text:
# Question
Title: Using select lists with radio buttons
I have a form that has 5 radio buttons. Two of those have optional additional parameters that the user can select. If radio 1 is selected, then only the optional items for that radio would make sense to be populated. Is there a way using the Forms API to accomplish this?

I have the following code. The Optionals Extra2 is the olnly select boxes that are shown. If I change the `$form['mc']['cats']` to `$form['mc']['cats2']` I can get it to display but it's not in the same fieldset as the rest.

```
$form['mc'] = array(
    '#type' => 'fieldset',
    '#title' => t('Membership Categories (select only one)'),
    );

$form['mc']['cats'] = array(
    '#type' => 'fieldset',
    '#title' => FALSE,
    '#prefix' => '<div style="background-color:red;">',
    '#suffix' => '</div>',
    );

$form['mc']['opts'] = array(
    '#type' => 'fieldset',
    '#title' => FALSE,
    );

$membership_cats = array(
    0 => t('Option 1'),
    1 => t('Option 2'),
    2 => t('Option 3'),
    3 => t('Option 4'),
    4 => t('Option 5'));

    $form['mc']['cats']['profile_memberlist']['field_membership_category']['#prefix'] = '<div style="background-color:salmon;float:left;width:50%;">';
    $form['mc']['cats']['profile_memberlist']['field_membership_category']['#suffix'] = '</div>';

    $form['mc']['cats']['profile_memberlist']['field_membership_category']['#type'] = 'radios';
    $form['mc']['cats']['profile_memberlist']['field_membership_category']['#title'] = t('Membership Category');
    $form['mc']['cats']['profile_memberlist']['field_membership_category']['#description'] = t('Please select your membership category.');
    $form['mc']['cats']['profile_memberlist']['field_membership_category']['#options'] = $membership_cats;

$optionals = array(
    0 => t('No Thanks'),
    1 => t('Optional 1'),
    2 => t('Optional 2'));
$optionals2 = array(
    0 => t('No Thanks'),
    1 => t('Optional 3'),
    2 => t('Optional 4'));

$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#type'] = 'select';
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#prefix'] = '<div style="background-color:lime;">';
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#suffix'] = '</div>';
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#title'] = t('Optional Extras');
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#options'] = $optionals;

$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#type'] = 'select';
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#prefix'] = '<div style="background-color:lime;">';
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#suffix'] = '</div>';
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#title'] = t('Optional Extras2');
$form['mc']['cats']['profile_memberlist']['field_optional_extras']['#options'] = $optionals2;

```

# Answer
You should do some research before posting such question here. There are lots of tutorials available for ajax like this one.

Then you have option of example module. look into the code of ajax\_example & extend your form like that.
> -1 votes

---
Tags: 7, forms
---


# Question
Title: How do I populate a webform component with a %_GET variable token?
I have webform 4 enabled. I just created a textfield component and set its default value to %get\[my-key\]. But the token is not working at all. I also tried with %\_get\[my-key\] and \[%get\[my-key\]\] but is not working neither.

As far as I understand Webform 4 in not working anymore with POST variables in favor of GET variables.

How can I get the GET variables?

# Answer
> 1 votes
I use tokens to get keys from the URL. The token for the %get variable would be \[current-page:query:?\], where the ? = the query name in the url. For example, if your url is mysite.com/page?foo=bar, you would use \[current-page:query:foo\] to return "bar".

---
Tags: webforms
---


# Question
Title: Why did ~20k Drupal 7 websites just drop off the map?
I was looking at Drupal statistics and surprised by how a bunch of sites just disappeared from the count. I'm assuming this is due to a change in the code, and not actually reflective of total count. But who knows!? Can anyone here offer any deeper insight?

https://drupal.org/project/usage/drupal

https://drupal.org/project/usage/1960640

# Answer
If you look back through the statistics they fluctuate quite often really.

Looking at stats for May 26th 2013 (642,589 Drupal 7 sites) or June 9th 2013 (666,573 Drupal 7 sites) I'm not actually certain it can be taken to represent sites disappearing so much as people evaluating Drupal or indeed installing and uninstalling new development snapshot instances.

It's also well worth bearing in mind that the accuracy of the statistics is not 100% and sites which don't use the update manager module don't report in at all. (It is, in some circles, common practice to disable this component once a site goes live if it's being updated in a separate development environment).
> 0 votes

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


title: Getting data from submitted form

text:
# Question
Title: Getting data from submitted form
I am trying to get data from a submitted form - as far as I can tell, data is being passed correctly, but I want to look at and manipulate it.

I'm trying to `print_r()` it with no success - because it happens after form submission and it isn't on the previous page.

This is my submit function so far:

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

$form_state['values']['multi_reg_checkbox'];

}

```

The checkboxes are generated on the page `/multiple-registration`, but I have no way of checking my variables once this page is submitted.

Any help would be appreciated

# Answer
> 1 votes
The devel module will help a lot. It provides a `dpm()` function which is similar to `print_r()` but provides you with a nested array of data to look through in Drupal's messages area.

You're correct in that `$form_state['values']` holds the user input, but since the submit handler will return back to the previous page automatically, you're better off doing something like this in your `_validate()` handler (or throwing a `dpm()` in your submit handler if you don't mind that running). This will let you debug things quickly and then submit when you're ready for it:

```
<?php
function my_form($form, &$form_state) {
  // Build out the $form.
}

function my_form_validate(&$form, &$form_state) {
  dpm($form_state['values');
  form_error($form, "Debugging the form.");
}

function my_form_submit(&$form, &$form_state) {
  // Perform your submit functionality here.
}

```

# Answer
> 1 votes
Check your variables by printing them with drupal\_set\_message().

```
function multi_reg_pagecreate_submit($form, &$form_state) {
  drupal_set_message('<pre>' . print_r($form_state['values'], true) . '</pre>');
}

```

Alternatively, you can use debug()

```
debug($form_state['values'], 'Debugging the form', TRUE);

```

# Answer
> 0 votes
I'm not sure of this, and I'm not a FAPI expert by any stretch but something like:

`$form_state['input']` might be useful.

---
Tags: forms
---


title: Show content added by current user

text:
# Question
Title: Show content added by current user
In user permissions i let users with editor role "Access the content overview page". And this page showing them all added content. I can make a view with this user added content, but i want to achieve this with "Find content" page. How can i achieve that? I want users to show only the content they added.

# Answer
I don't believe that's possible with the Find Content page. You may have to resort to making a View to accomplish the task. I've created several views for the same purpose, and actually prefer it as I can create my own admin links (edit, delete, view, publish, etc.) customized to what my goal for the page is.
> 1 votes

---
Tags: users, nodes
---


# Question
Title: How to use views to make queries on the webform (or entityform) results and show in a node?
Do you know how to use the Views module (or any other "query builder") to filter/query the submissions made either by webform or entityform?

# Answer
> 1 votes
The newest version of webform (7.x-4.0-alpha10) allows views to display webform submissions right out of the box. Although you cannot revert to an older version after upgrading to 4.x, so it's important to back up your database. But after you have 4.x installed, you will see an option when you create a new view to show content of type "webform submissions". You can also read up on how to accomplish the task in older versions of webform here: https://drupal.org/node/1658784

---
Tags: views, webforms, entities
---


# Question
Title: Feature stuck on Overridden - "Overrides" column empty, "Default" not
I have a feature which is constantly stuck at overriden, no matter how times I try to revert or re-create it. I have gone through the standard checklist, including uninstalling and reinstalling, and checking the correct includes are present in .info file and .module file.

On the "Review Overrides" panel, however, I have the attached screenshot. Noticed that the default contains an array full of field settings, but the overrides just contains FALSE:

It would seem that my database doesn't contain this info when it should, and refuses to take it from the Feature?

UPDATE:

I checked the .info file and they seemed all in place; however I suspect that the second cause indicated by the accepted answer below could be the problem. There are currently two modules that remain in a persistent "Overidden" state, and they both share: "CTOOLS EXPORT API -\> context:context:3" and "FEATURES\_API -\> api:1". On initial investigation it would seem that these two items are inherent in the feature, although perhaps I could remove the CTOOLS EXPORT API item by removing the ctools dependency? Argh...

# Answer
There's two possible reasons for this that I can think of: one is that the .info file for your feature is out of step with the other files. This can happen when you are creating or updating a feature and you don't wait for the little animated timer gif to stop before clicking on another option. It occasionally happens for other reasons, such if you do a git merge automatically with changes from another developer.

To fix this, you generally need to go through your .info file one item at a time and check it corresponds to the other files, so there are no items in any of those files that are not in the .info.

The other reason is if two features overlap in some way. If you have the same configuration item in two features, one of them will usually fail to revert. You may need to refactor your features to prevent this.
> 3 votes

# Answer
Another cause I encountered: After updating to features 2, for some reason (possibly a git merge) I still had the xxxx.features.field.inc files in addition to field\_base and field\_instance. Removing the field.inc files solved the problem.
> 1 votes

---
Tags: 7, features
---


# Question
Title: Make a directory and link it in a node at node creation
I’m developing a site in Drupal 7 where users view a calendar of events as well as photos taken at those events.

I’ve already created an Event content type, generated several Event nodes, and put those nodes together in a Calendar view.

What I want to do now is add a ‘Photos’ link to Event nodes. Clicking on this link should open a gallery of photos for the given event. For example, imagine a user is viewing an Event node titled ‘Pool Party @ Jan’s House’. The user clicks on the node’s ‘Photos’ link and then sees a photo gallery also titled ‘Pool Party @ Jan’s House’ that displays all and only photos taken at that event.

How do I get the following two actions to happen (automatically) when an Event node is created?

1. Make a directory that will contain photos for the event. (These photos will be uploaded later by users who attend the event.)
2. Include a ‘Photos’ link in the newly created Event node that opens a page display of the directory's files. (See the example I give above.)

I’ve been trying to figure this out using the Media, Rules, and Views modules, but I’m not making much progress.

Thanks in advance for your help.

# Answer
Creating directories on the fly in the actual file system is uncharacteristic in Drupal.

The simplest way of attaching photos to nodes would be having an image field with unlimited number of uploadable images. That would show thumbnails of those related images right there when you go to the node page. This is all in core.

If allowing all users to edit event nodes is not an option, you could create an image node type and connect images to respective events with node references or taxonomy, and then create a view listing those images on the node page (views attachment) or on a separate, gallery page.
> 0 votes

---
Tags: views, rules, media, datetime
---


# Question
Title: Separate classes in include file not loading?
I have a peculiar problem... I'm trying to simplify my module by breaking up a ton of code into classes, and I have all of the classes in a separate include file that I'm registering in my .info file with the files\[\] directive.

However, when I go to use these classes in my module code, PHP dies. It's like they're not being loaded. I thought they were supposed to autoload at first use since I was using files\[\]?

**module.info**

```
name = Module
description = Module description
package = Module Package
core = 7.x

scripts[] = my_module.js
files[] = includes/my_module.class.inc

```

# Answer
The files listed in `files[]` do get autoloaded, but Drupal's registry needs to "find about" about them first. The .info files aren't parsed & processed on every page load, but rather only during specific system operations. Go to the `/admin/config/development/performance` page on your site and clear the cache - this will rebuild the registry and your files should then get loaded as necessary.
> 2 votes

---
Tags: 7, .info
---


# Question
Title: Replacement for Drupal 6's $form_state['post'] in Drupal 7
I have the following code (part of a module):

```
function whm_ui_edit_account_form($form, &$form_state, $account) {

  $res = whm_account_info($account);
  $account_data = $res[0];
  $current_state = array('values' => array(
    'user' => $account_data['user'],
    'domain' => $account_data['domain'],
    'email' => $account_data['email'],
    'plan' => $account_data['plan'],
  ));
  $form_state['values'] = array_merge($current_state['values'], $form_state['post']);

  $form = _whm_ui_account_form($form_state);
  $form['account']['password'] = array(
    '#type' => 'fieldset',
    '#title' => t('Change Password'),
    '#description' => t('Enter values here <b>ONLY</b> if you want to change this account\'s password.'),
    '#collapsible' => TRUE,
    '#collapsed' => empty($form_state['values']['pwd1']) && empty($form_state['values']['pwd2']),
  );
  $form['account']['password']['pwd1'] = $form['account']['pwd1'];
  $form['account']['password']['pwd1']['#required'] = FALSE;
  $form['account']['password']['pwd2'] = $form['account']['pwd2'];
  $form['account']['password']['pwd2']['#required'] = FALSE;
  unset($form['account']['pwd1']);
  unset($form['account']['pwd2']);
  unset($form['account']['email']);
  unset($form['account']['plan']);

  $form['current_user'] = array(
    '#type' => 'hidden',
    '#default_value' => $current_state['values']['user'],
    '#required' => TRUE,
  );
  $form['current_domain'] = array(
    '#type' => 'hidden',
    '#default_value' => $current_state['values']['domain'],
    '#required' => TRUE,
  );
  return $form;
}

```

The $form\_state\['post'\] no longer exists in D7 (I'm porting an old module) and perhaps I'm insanely tired or just out of my depth :-p but I can't find a suitable replacement. The function is essentially looking to merge existing information with the information given in the form before submitting (I think).

Any assistance or if anyone can point me to an alternative to the post value being used previously it would be appreciated.

# Answer
`$form_state['post']` in Drupal 6 contains the values of the `$_POST` global, and a quick look at Drupal 7 shows that when accessing a form via the post method, `$form_state['input']` will contain that same array. Side note: if it is accessed via the get method, this will contain `$_GET`.
> 0 votes

---
Tags: forms
---


# Question
Title: Is there a way to edit views fields in place?
I haven't tried the Editview or editablefields modules for Drupal 6, but neither is available yet for Drupal 7 anyway.

I'd like to provide a way for my users to edit lots of nodes and node fields on one screen, presented preferably to views. I'd rather they don't have to keep following a link (contextual or otherwise) to another edit form.

Any suggestions?

# Answer
Try editablefields-d7; as reported by the project page the module is a Drupal 7 port of editable fields.
The project is a sandbox project, which means it doesn't support releases, yet, and drupal.org doesn't automatically create the archive containing the module code; this means the code should be considered experimental, and you get the code using git, using `git clone http://git.drupal.org/sandbox/damz/1130436.git editablefields_d7` or the link to the snapshot archive.
> 6 votes

# Answer
The drupal community is working hard to make WYSYWYG edit-in-place functionality (using the Aloha project) be built into drupal 8 read about spark initiative. For the meanwhile, people are telling the spark D7 distribution should do it visually (I haven't tried it myself yet), as well as the modules above (non-WYSYWYG).
> 0 votes

# Answer
Recently, there's a new module that's now a project that allows you to edit multiple fields at once:

https://drupal.org/project/editableviews

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
> 0 votes

---
Tags: 7, views
---


# Question
Title: kpr() in my form validation and submit function is not being called
In my form validation and submit functions, `kpr()` is not being called. Is there a better way to check that I'm in those functions? If `kpr()` isn't ideal to output my `$form_state` array, then what is ideal?

# Answer
> 4 votes
Everything that is output with `drupal_set_message()` (the function that `kpr()` uses to output the message) could not be visible from the browser if code redirects the user to another page after `drupal_set_message()` is called and before the page is rendered. After a form is submitted, the users are redirected to a page whose URL is set in `$form_state['redirect']` or `$_GET['destination']`; the latter takes the precedence over the former.
To avoid the users are redirected after the form is submitted, you can:

* Set `$form_state['rebuild']` to `TRUE`
* Set `$form_state['redirect']` to `FALSE`

Setting `$form_state['no_redirect']` to `TRUE` would have the same effect, but form builder functions, form validation handlers, and form submission handlers should never set `$form_state['no_redirect']`.

A preferred method would be calling watchdog(). If you have the Database Logging module enable, then the message output from the module will be visible in admin/reports/dblog.

For debugging messages, you can call `watchdog()` passing `WATCHDOG_DEBUG` as value for the `$severity` parameter.

### References

---
Tags: 7, forms, debugging
---


title: ajax call back function

text:
# Question
Title: ajax call back function
i am using drupal 7

i am trying to add a button within form and successful. now i want to call a function when someone click on that button

here is my code.

```
function clicktell_form_alter(&$form, &$form_state, $form_id) {
    //print_r($form);

    if($form_id=='user_register_form') {
        $form['add_button'] = array(
            '#type' => 'button',
            '#value' => 'Verifynow',
            '#ajax'> array (
                'callback' => '_udr_ajax_handler',
                'progress' => FALSE,
            ),
        );

    }
}

function _udr_ajax_handler($form, &$form_state) {
    echo "hello "; exit;
}

```

But this is not working fine. Does anybody tell me how to solve this Thanks

# Answer
> 1 votes
You missed equal sign '=' near '#ajax'.

---
Tags: 7
---


title: Autosave Not Working

text:
# Question
Title: Autosave Not Working
I wanted to provide a feature to autosave the data while adding the article so that user can restore the content in the event he goes to some other page.

For that I am using Autosave module. I have installed it and set it for my content type. But it is not showing any kind of message that form has been saved. Also I have checked that it is not running in "Stealth Mode", so it must give message that it has been saved.

Is there anything I am missing. I am using drupal 7 and latest version of autosave ie 7.x-2.1

Also it would be better if someone could suggest some other module that helps to accomplish this.

-- Thanks

# Answer
**Autosave** module works fine with a multilingual Drupal site.

So I'm assuming that you are working on a single language Drupal site.

In order to make **Autosave** module work on single language Drupal site, you need to apply this patch file

**Edit:**

The patch file should be for Autosave 7.x-2.x-dev

Check the actual issue
> 1 votes

# Answer
Save Form State can be a good alternative. This module provides a way to autosave data entered in any Drupal form without actually submitting the form, which helps if the user is writing an article or a comment and the browser crashed or the power went down, or even if the window was closed accidently.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Implementing callback function in hook_menu()
In the link given below , **https://drupal.org/node/224333**
So as given in below statement *you do not have to declare the callback path** what does this mean? I have **hook\_menu()** in d6 which is as follows :

```
$items['ort/add/ion'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'ort_add_ion',
    'access arguments' => array('access content'),
    'file' => 'ort.tion.inc',
  );

```

Does the link say that for d7 you do not need page callback or something different?

In Drupal 7, **you do not have to declare the callback path** in hook\_menu(), and the callback function is far simpler.

Drupal 6:

```
<?php
// This function must be pointed to in hook_menu() in D6.
function my_callback_function() {
  // ... Much work to build the form ....

  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);

  $output = drupal_render($form);

  // Final rendering callback.
  print drupal_json(array('status' => TRUE, 'data' => $output));
  exit();
}
?>

```

Drupal 7:

```
<?php
// No path needs be set up to point to the function, and $form and $form_state are provided.
function my_callback_function($form, &$form_state) {
  // Often you would select a portion of the form to match #ajax['wrapper']
  // rather than processing the whole form.
  return $form;  // Either HTML or a render array may be returned.
}
?>

```

# Answer
> 1 votes
The simple answer is it is for ajax items. In drupal 6 you had to declare a path and direct your ahah to it with \['#ahah'\]\['path'\]. In drupal 7 it is handled automatically and you now use \['#ajax'\]\['callback'\] to call the function without having to declare a path.

---
Tags: 7, routes
---


# Question
Title: Creating "view" of "user blogs" specific to a user
On a user "my account" page, I want to create a view block which lists the blogs created by that user only. Is there a way to accomplish this ?

# Answer
There are solution for it by using Contextual Filter in views. Follow this -

* Create a new content view and limit it to the content type you want.
* Uncheck "Create a page" and check "Create a block." Select the format you want.Click "Continue & edit."
* Add a contextual filter for "Content: Author uid.". Do this --

> Under "When the filter value is not available," select "Provide a default value," and select "User ID from URL" from the dropdown. Because blocks don't understand contextual filters very well, the view won't work properly without this default value, and all posts of the given content type will show on all user pages (not just the user's own posts).
>
> Under "When the filter value is available or a default is provided," check "Specify validation criteria" and select "Basic validation" as the validator. Select "Hide view" from the dropdown.

* Save your view.
* Assuming that you created a block display, the block will now be available on the Blocks page. Go there and open it.
* Set your block to display on all user pages (/user/\*) in the correct region. Save the block.
* Your block should now appear on all user pages, showing the content written by each user.

Let me know the result if it works fine :)
> 2 votes

---
Tags: views, users, nodes
---


# Question
Title: Parsing value of a field from content to a webform field
I have a content type named apartments. When i view a content of content type apartments i will give a button for requesting a quote. When clicked on that button it takes to a webform and by default a field value should be filled by that contents title. Please let me know the process of parsing a fields value to a webform field.

# Answer
> 1 votes
Try using the webform node value module

> Fill a Webform field with the value of a node field.

---
Tags: webforms
---


# Question
Title: How to set available/unavailable dates in date webform component?
I have a webform with a **date** component.

Then the visitor is able to select a date in a popup calendar. So far so good.

I need to show available and unavailable dates in the calendar, then visitors only can select an available date. Look my capture:

I'm trying with the availability\_calendars which is a great modules. But I have 2 problems with it:

1) it is a 2 steps process, you choose the date in the calendar and then you are directed to the webform to fill the rest of information (name, phone,...)

2) the calendar allows the visitor to select 2 dates: Arrival and Departure dates. I only need one date.

How can I accomplish this?

# Answer
You may want Date Restrictions module. It restricts allowed values in date fields, and datepicker popup widget, based on several criteria.

The module is still under initial development but may fit your needs. In any case please submit an feature request in the modules' issue queue if there's some missing functionality you find useful.
> 1 votes

---
Tags: datetime
---


# Question
Title: How to get node id in a block_view theme page?
I have added blocks to my custom module. A same block should be displayed in two pages. I have to display the field $node-\>field\_tag\['und'\]\['0'\]\['value'\]; in my block.

```
$nid = explode("/", $_GET['q']);
$node = node_load($nid[1]);

```

I got the node id by this. When it goes to another url it is not loading. So how can I get the nid in the block\_view theme page without using the url?

# Answer
> 2 votes
You want menu\_get\_object() to obtain the node object when visiting a node page.

# Answer
> 0 votes
You can also do this (show a node's field in a block on only two pages) without a custom module. Make a block view showing this field. On the block configuration page make it display only on the two URLs that you want.

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


# Question
Title: Drupal 7 - Destroying the session when the browser closes is not working on Chrome
Is there an issue with destroying the user session using Chrome? I've set this setting in settings.php: ini\_set('session.cookie\_lifetime', 0) but it seems like Chrome ignores it or is it just caching the user session itself.

On IE and FF this works as intended. I've even set Chrome to not save user credentials but to no avail.

Any ideas please?

# Answer
This is not a problem with drupal session. The feature that remembers the opened tabs when the browser is closed is the root of your problem. The feature is named "On startup" "Continue where I left off". Turn that off and you should be fine.
> 1 votes

---
Tags: sessions
---


title: Filter content by group

text:
# Question
Title: Filter content by group
I use Drupal 7 with the Search API, and the Facet API modules.

I want to create a facet that shows all OG groups. When I click on an OG group all its content associated will be draw.

How can I achieve this?

# Answer
> 1 votes
Using the modules you described:

* Create a index containing all the nodes that are group content
* Edit the fields of this index and add a relationship to 'Groups' (at the bottom of the page)
* You will get additional (group)fields available
* Check the one named "Groups » title" and change the type to "string" (instead of default fulltext)
* In the Facet tab, make the facet available, and place the block.

This should do the trick!

---
Tags: organic-groups, search
---


# Question
Title: How to alter the uc_address:city form field?
I have to alter cities form field in checkout page under delivery section. I have to change it from a textfield to a select options dropdown.

* I have managed to do that using a separate template file for checkout page but I am not able to use `#ajax` functionality of form field
* In Drupal 6 it was possible using `hook_form_uc_cart_checkout_form_alter()`, but in Drupal 7 the address fields are rendered in a different way, and I'm not able to alter the address form fields as desired

What are other ways of changing it?

I used `hook_form_alter()` with an `#after_build` callback; I was able to change the field from text field to select option, but the `#ajax` parameter attached to this is not working.

It seems like ajax callbacks are attached with the hooks at an early stage. Is there any way to have the #ajax property working?

# Answer
If you are using Addressfield module you can easily do that extending the module itself.

Look into the **`sites/all/modules/addressfield/plugin/format`** & you will see `address.inc`, where you can extend the list of region or city.

You can look for the example in **`sites/all/modules/addressfield/example/plugin/format`** to better understanding of the the format which module will accept for extending it for your list values.
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: What is the difference between using theme_table() and theme('table', array())?
I am using following code for theming..

```
theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => 'view-all-frame')));

```

is the above format right? Can 'attributes' be written above inside array? Can I use theme\_table() instead of theme()?

```
theme_table(array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => 'view-all-frame')));

```

If they are same then does it affect the execution or anything related to it?

Similarly for **theme('item\_list', array())** and **theme\_item\_list()**;

# Answer
> 5 votes
It's not the same.

`theme()` function is some kind of wrapper for specified theme functions.

It's recommended to use `theme()` function instead of direct calls, so `theme('item_list', array())` is the right way.

# Answer
> -1 votes
I think the function of theme\_table and theme('table',array()) is the same. But the way you call the theme\_table should be simple like that:

```
theme_table($header,$rows,array('class' => 'view-all-frame'));

```

---
Tags: 7, theming
---


title: Using prefix and suffix form api layout

text:
# Question
Title: Using prefix and suffix form api layout
I have created a form, though I'm having an issue with using the prefix and suffix to place items into rows rather than the list they appear as standard.

For example I have these 3 form elements, how would I go from having them appear as standard on a new line, to on the same line. Normally I would just chuck them into a table and place each one in a different column. I have read that I should possibly use floats?

I have tried `'#prefix' => '<div style="float: left; width 200px;">',`

`'#suffix' => '</div><br>' ,` But this seems to affect the navigation on the left and shuffle it down.

```
$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

```

**I cannot answer for 7 hours but here it is:**

The solution was to close the DIV, I had forgotten, which meant the styling was effecting the whole page.

```
     '#prefix' => '<div style="float: left; width 200px;">',
    '#suffix' => '</div><br style="clear: left;" /></div>',
    [Useful link to aligning form elements horizontally][1]

```

# Answer
I think you want to keep it in table. Lets try with putting it in one like this --

```
$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => '<table><tr><td>',
    '#suffix' => '</td>',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => '<td>',
    '#suffix' => '</td>',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => '<td>',
    '#suffix' => '</td></tr></table>',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

```

I haven't tested this code, so please try this & let me know if it works :)
> 0 votes

# Answer
Yes. We can put the form and form elements into table with rows, columns structure. And of course we can use the prefix and suffix attribute to do that. Please follow this instruction from this Drupal 7: theming forms with tables
> 0 votes

---
Tags: forms, theming
---


# Question
Title: Link to anchor on current page with smooth scroll
I have smooth scrolling working (https://drupal.org/project/scroll\_to\_destination\_anchors) and I have linking to anchors working (https://drupal.org/project/menu\_token) but I can't get my desired result of clicking a menu item and then scrolling to the anchor. I only need this to work on the current page - if the anchor is on another page, I am ok with the menu item loading the other page and jumping (not scrolling) to that anchor.

Do you have any idea?

# Answer
> 2 votes
Solved by using the Void Menu module and using the id of the anchor as one of the void options.

For example, my menu item says "`<void2>`" where void2 contains the id of the div `"#aboutus"`.

---
Tags: 7, routes, javascript
---


# Question
Title: how do I add javascript to a specific panel-page
I have created a panel page (i.e using panels). I can add html content to it from the panel itself using add content-\>New custom content. I can also add css classes (add body css classes).

Now I would like to add a jquery button to that panel page. I could add a javascript to my theme but then it would be called on every page load not only this specific panel-page. So I would like to add my javascript through my module.

But how do I programatically check that the current page beeing viewed is that specific page panel? Is there a hook that lets me check that?

Thanks,

baba

# Answer
I have done it using panel nodes which lets me "wrap" a panel in a node. Then I get access to the node using hook\_node\_view

```
function mymodule_node_view($node, $view_mode, $langcode)
{
 if( $node->nid == 49 )  /* 49 is the nid */
  {
   drupal_add_js(drupal_get_path('module', 'mymodule') . '/myJS.js', 'file');
  }
}

```
> 0 votes

# Answer
I'd probably do this in the theme with template\_preprocess\_panels\_pane() - http://drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template\_preprocess\_panels\_pane/7

You can do (make sure you have devel.module installed first)

```
MYTHEME_preprocess_panels_pane(&$vars) {
  dpm($vars);
}

```

and get a full print out of everything that's going on in all your panel panes. With enough digging, you should be able to find a `$vars['_something_']['#attached']['js'] = YOUR_FILE;` to hook into. I think you can do this in a module too, if that's what you want.

EDIT: After actually thinking about it though..

I would probably advise against this and just put it in your theme js. Unless it's an enormous amount of js, you're going to be taking better advantage of Drupal's js aggregation by *not* doing this. If you put the js in your theme, it'll be compiled into the main site js file automatically, whereas if you do something different when only this panel pane is showing, it'll require that an entirely different js file be aggregated and downloaded on pages when it shows.

Assuming this is a performance tweek, I think you might actually be headed in the wrong direction with this one, since browsers should cache this file after the first time it's downloaded.

edit: hook name typo
> 2 votes

# Answer
The theme template for your panel will look like this:

```
panels-pane--[pane type]--[pane subtype].tpl.php

```

and you can change the template for your specific needs, this page explains in much greater detail:

https://drupal.org/node/1678810

don't forget the homepage of the panels3 documentation:

https://drupal.org/node/496278

good place to start for all things panels related. The theming overrides is even linked from there.
> 0 votes

# Answer
Have you looked at the JS Injector module? It basically does exactly what you're looking for; inject javascript onto specific pages. It also allows you to specify where you want the javascript loaded (ie. header or footer). Very handy.

https://drupal.org/project/js\_injector
> 0 votes

---
Tags: javascript, panels, theming
---


# Question
Title: Make Foo and foo to be different free tagging tags in Drupal 6
I need a way to make Foo and foo to work as two different freetagging words in a Drupal 6 taxonomy field, any suggestions for this?

# Answer
> 1 votes
This goes beyond Drupal - your database is using a case-insensitive collation, so all queries are case-insensitive.

Changing the collation would be the way to sort it ("how" is out of scope here but easy to find on Google), but that might produce unwanted results. I'd advise taking a backup beore making any changes, and having a good read up on the whole *collation* concept before going any further.

Another approach might be to alter the individual queries that go into the `txonomy_term_data` table (using `hook_query_alter()`), and set the collation manually (SQL examples in the `COLLATE` docs above). Again, your mileage may vary so take a backup before trying anything.

---
Tags: taxonomy-terms
---


# Question
Title: How to override the menu_tree without affecting the admin menus
I've worked out how to override `theme_menu_tree()` using this code in template.php.

```
function myTheme_menu_tree($variables) {
  return '<nav class="menu">' . $variables['tree'] . '</nav>';
}

```

However, I've noticed that this is affecting other menus as well.

How do I target only non-admin menus?

# Answer
> 3 votes
You should use theme\_menu\_tree\__MENU\_NAME().

# Answer
> 0 votes
### page.tpl.php

```
// for admin menu
<?php print '<ul id="nav-admin" class="menu clearfix">'.menu_tree('navigation').'</ul>';?>

// for primary menu
 <?php print  '<ul id="nav-primary" class="menu clearfix">' . menu_tree('primary-links').'</ul>'; ?>

// for secondary menu
 <?php print  '<ul id="nav-secondary" class="menu clearfix">' . menu_tree('secondary-links').'</ul>'; ?>

```

### template.php

```
function yourthemename_menu_tree($tree) {
  return $tree;
}

```

---
Tags: theming, routes
---


title: Field Validation: 18 Years or Older

text:
# Question
Title: Field Validation: 18 Years or Older
I am using the Field Validation module to validate a date field that will contain a user's birthday. I want to make sure the person is 18 years of age or older. Here are the settings I was thinking of using in my validation rule. Are these correct?

**Column:** value

**Minimum Date:** now - 18 year

# Answer
Depending on your requirements, Field Validation can be a good approach. It's simple to set up, but one potential issue is that if this field is something that the user can edit, they can easily modify their birthday if the form submission is rejected.

Often this is OK, but for my site I needed to actually block users who were under 18, so I did the following. I have a required date field, *birthday*, on the user registration form.

Then, I added a computed field, *age*, to calculate the age based on the value of the date field, *birthday*. For sample PHP, you can see this Stack Overflow answer. This is a way that you can take into account leap years, etc.

Then, I added a rule:

**Event** *After saving a new user account*

**Condition** *Data to compare: Age less than 18*.

**Actions** *Block user*

The advantage of doing it this way is that if a user registers with a birthday under 18, their e-mail address will be blocked from registering again. Of course, this may or may not be necessary for your case, but I'm just putting it out there because other sites may have such a requirement.
> 3 votes

# Answer
Date Restrictions is useful to acomplish this with no coding. Enable date\_restrictions\_minmax submodule, and configure your date field to set a minimum valid date of 18 years.
> 0 votes

---
Tags: entities, datetime
---


title: I want to customze menu_tree output

text:
# Question
Title: I want to customze menu_tree output
I found a code in drupal page in this url http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_tree/6#comment-1073

code is

```
<?php
function phptemplate_menu_tree($tree,$menu_name="") {
     return '<ul class="menu menu-$menu_name ">'. $tree .'</ul>';
}
?>

```

it is written that we can customize every menu by css and also adding $menu\_name.

but even though that I have added this function into my template.php and it is working , $menu\_name variable is always **empty**

really the target that I am following is : I want to modify the css class of the ROOT us base on menu name.

for example for primary links , i want to have this return out put

```
'<ul class="menu menu-primary-links ">'. $tree .'</ul>'

```

or for secondary links i want to have this return output

```
'<ul class="menu menu-secondary-links ">'. $tree .'</ul>'

```

$tree includes all nested li items from the selected menu.

please help me

# Answer
> 1 votes
**page.tpl.php**

for admin menu

```
    <?php print '<ul id="nav-admin" class="menu   clearfix">'.menu_tree($menu_name = 'navigation').'</ul>';?>

//for primary menu
 <?php print  '<ul id="nav-primary" class="menu clearfix">'.menu_tree($menu_name = 'primary-links').'</ul>'; ?>
//for secondary menu
 <?php print  '<ul id="nav-secondary" class="menu clearfix">'.menu_tree($menu_name = 'secondry-links').'</ul>'; ?>

```

**template.php**

> function menu\_tree($tree}{return $tree;}

# Answer
> 0 votes
Try out by calling

```
<?php print theme('links', $primary_links, array('class' =>'menu-primary-links')); ?>

```

to include primary links to the required template file. No need for phptemplate\_menu\_tree function in template.php

---
Tags: 6, routes, theming
---


# Question
Title: How to disable option for users who aren't logged in
I've got custom content-type. On the main page I set teaser display of contents and I decided to show off only several fields there. Next to each content I can notice text "Read more". After entering it, I am redirected to full display of contents (There are show off all fields).

Action, described above can be done by everyone. But, I'd like to allow it only logged in users. How can I disabled it for users who aren't logged in.

# Answer
Use the premium content module

> Restricts access to premium content by role and provides a general API for other modules to help decide if a user has access to premium content.
>
> This is useful on a news or membership site where teasers are available to the general public but the full body is only available to privileged users. Premium nodes appear in listings with full title and teaser available to anyone. If a user does not have adequate privileges, the default behavior is to show a simple message, but you can use Panels or theme overrides to do more custom things.

All you need to do is enable the module, go to the edit page(**admin/structure/types/manage/yourcontenttype**) of the content type you want to make premium, and on the publishing options tab, select premium content
> 2 votes

---
Tags: 7, rules, nodes
---


# Question
Title: Associate a Taxonomy term to user who creates it
I have field **Company Name** which is a term reference to a vocabulary with same name. when user types the field if name already exists, so auto complete showed that or else it will be added as taxonomy term. let us consider "BBB" is the company name he entered.

On next scenario when another user keying in this company name as "BBB" so its already their in the taxonomy so i have to send a mail to the user who created added the term "BBB" first.

I tried using rules module but i couldn't find way to get the user who created the term.Meanwhile i use Profile2 module so writing submit handler is best?

# Answer
> 0 votes
Taxonomy doesnt contain this kind of data. A possible workaround would be- Creation of a custom module that writes data into a custom table. You can use hooks to intercept the addition of the item.

---
Tags: users, taxonomy-terms
---


title: How do I hide title of a node?

text:
# Question
Title: How do I hide title of a node?
I have tried doing this in hook\_node\_view or hook\_node\_view\_alter with no luck:

I have tried things like: `unset( $node->title);` or `$node->title ='';`

note: my node was created using panel nodes

# Answer
> 3 votes
The Exclude Node Title module has that functionality if you'd prefer a non-code solution.

> This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers.

# Answer
> 3 votes
Hope this will help you.

In Drupal 7 , if you dont want any modules then you can use **template preprocess functions** for you requirement.

* template\_preprocess\_page ````
function THEMENAME_preprocess_page(&$vars) {
    if ($vars['is_front']) {//for home page
      $vars['title'] = '';
    }
    elseif (!empty($vars['node']) && in_array($vars['node']->type, array('NODETYPE1', 'NODETYPE2'))) {//for specific node type(NODETYPE1 OR NODETYPE2)
      $vars['title'] = '';
    }
}

````
* You can also use template\_preprocess\_node ````
function YOURTHEME_preprocess_node(&$node) {
      // check for node type
        if(in_array($node['type'], array('NODETYPE1', 'NODETYPE2'))) {//for specific node type(NODETYPE1 OR NODETYPE2)
         $node['title'] = NULL;
      }
}

````

# Answer
> 1 votes
If you use modules display suite or/and page manager (part of ctools), you could have more control of all the fields, including the title.

# Answer
> 0 votes
`$title` is not inside the `$node` variable but independent. You will find it inside **page.tpl.php** rather than **node.tpl.php**, where usually we guess at first.

So if you are trying to hide it then you should better do some action on this one or just hide it from your specific **page.tpl.php**.

---
Tags: nodes
---


# Question
Title: Access CCK Fields on Content Type EntityFieldQuery()
Okay, I've spent two days banging my head against the wall, so I'm finally going out for help...

I have a custom content type "eod\_report" with a CCK field called "rfqs\_received" which stores an integer.

I need to access the value of "rfqs\_received" (previous 5 entries per user), but all I get is a list of the nodes themselves. What I want is an array of the queried field values.

How can I get access to the field values? Any help is MUCH appreciated.

```
    <?php

global $user;
$uid = $user->uid;

$query = new EntityFieldQuery();
$entities = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'eod_report')
  ->propertyCondition('uid', $uid)
  ->propertyCondition('status', 1);

  //->fieldCondition('field_rfqs_received', 'value', '6', '<');

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = node_load_multiple($nids);
$output = node_view_multiple($nodes);

print render($output);
?>

```

The answer below solved it. To clarify, this was a portion of an attempt to create a custom action that would calculate the average of field values for the last five pieces of content created by a user. The action occurs when content is saved/updated and saves values to the current user's profile. It's a bit sloppy, I think, but it works. I'm still learning... Here's the full code of the action:

```
    <?php

global $user;
$uid = $user->uid;

// query the database to get the previous 5 eod_reports
$query = new EntityFieldQuery();
$entities = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'eod_report')
  ->propertyCondition('uid', 50)
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0,5);

$result = $query->execute();

// Collect the $nids of the nodes returned by the query

$nids = array_keys($result['node']);

// Declare an empty array to store the rfq results
$rfqs = array();
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // loop through items, extract rfq values and store to array.
  foreach ($items as $item) {
    // Add to the output array.
   $rfqs[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

// Declare an empty array to store the order results
$orders = array();
foreach ($nodes as $node) {
    // Get the field items
    $oitems = field_get_items('node', $node, 'field_orders_received');

    // Loop through items, extract order values and store to array.
    foreach ($oitems as $oitem) {
    $orders[] = field_view_value('node', $node, 'field_orders_received', $oitem);
    }
}

// Prepare the loop to sum the rfq results

$rfqSum = 0;
$i = 0;
// Loop through the results and collect a sum
while ($i < 5) {
    $rfqSum = $rfqSum + render($rfqs[$i]);
    $i = $i + 1;
}

// Prepare the loop to sum the order results

$orderSum = 0;
$x = 0;
// Loop through the order array to collect sum
while ($x < 5) {
    $orderSum = $orderSum + render($orders[$x]);
    $x = $x + 1;
}

// Print the Sums

print "<h3>RFQ Sum: " . $rfqSum . "</h3>";
print "<h3>Order Sum: " . $orderSum . "</h3>";

// Calculate the average

$rfqAvg = $rfqSum/5;
$orderAvg = $orderSum/5;

// Print the average
print "<h4>RFQ Avg: " . $rfqAvg . "</h4>";
print "<h4>Order Avg: " . $orderAvg . "</h4>";

// collect the current user information and store the calculated value in the user->field

$existing = user_load($uid);
$edit = (array) $existing;
$edit['field_rfq_average']['und'][0]['value'] = $rfqAvg;
$edit['field_order_average']['und'][0]['value'] = $orderAvg;
user_save($existing, $edit);

?>

```

# Answer
`EntityFieldQuery`s are for querying entities, with the option to filter on their field values. They don't have the capacity to return any field data.

What you might be looking for is something like this, using `field_get_items()` and `field_view_value()`

```
...
$output = [];
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // Truncate to the necessary number (your logic will probably change here)
  foreach (array_slice($items, 0, 5) as $item) {
    // Add to the output array.
    $output[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

print render($output);

```
> 0 votes

---
Tags: database
---


# Question
Title: how to prevent node revision update when node is updated?
I noticed that every time a node is updated, a timestamp column in node\_revisions table is also updated for this node. I would like to change this behavior for "forum" content type and disable updating of the revisions table when forum node is edited. I don't use any modules that impact revisions. How do I achieve it (probably via my own custom module?)

**\[Edit\]**

The suggested duplicate solution (*"How to disable the revision feature completely?"* ) is quite a big thing. I don't want to disable revisions functionality so deeply, only in particular "forum" node type case and only prevent timestamp change, nothing else. The reason I need this is that the advanced forum module sorts topics by revision timestamp. There is a question how to change this behavior, but there is no answer, so it may be difficult and I also tried to figure it out myself but was lost - this module uses views handlers etc in code, hard to change anything.

I will try maybe to write a hook `mymodule_node_save` or `mymodule_node_insert` which is called after the revision table update (as visible in node\_save function) and then just reverse this timestamp column back to node creation timestamp.

If it doesn't work then I'll try to deal with the node\_save overwriting.

# Answer
@camcam, have in mind that even when you are not using revisions (keeping separate node revisions for each update you make to your node content), the revisions table will still always have *one record* in the node\_revisions table associated for each record in the node table that it keeps track of.

On the other hand, if you have enabled revisioning, you will have *multiple* entries in your node\_revision table associated with each node, corresponding, not just to the current revision, but all past revisions too.

My suggestion is to make sure you really want to mess with that functionality before you go ahead and do anything - because what you're seeing is actually standard behavior. :-)

If you look at the code in node\_save, you can see that a revision is created or updated in each instance of a node\_save() call.

If this really doesn't work for you, I'd suggest using the hook\_form() function to edit which function is called when your specific node content type is saved, and you can choose not to call the standard node\_save() function (this should only be done if really necessary). The api documentation, along with some code samples in the comments, can be found here: https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_form/7.
> 1 votes

# Answer
I believe you'll have to change the submit handler on the form in question. I had a quick look and don't see anywhere else, but you want to override the standard node\_save() function.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to render alt and title texts of image file entities using a theme function
Out of the box, image file entities have alt and title text fields attached, `field_file_image_alt_text` and `field_file_image_title_text` respectively, that provide the rendered image with an HTML alt and title text.

Today I feel like `Mysite.com` would be a great title for the images on my website, and I could easily programatically populate both text fields with `Mysite.com` upon upload of the image file. However, what if tommorrow I change my mind and instead of `Mysite.com` I want the alt and title text to be `Welcome to Mysite.com`? I would have to edit all file entities and modify both text fields for each.

Is there a way to render the alt and title text through a theming function so that I do not have to actually store the alt and title text within each file entity? I want to be able to modify the alt and title texts of *all* images by just modifying a *single* line of code.

# Answer
> 1 votes
The logic is pretty easy, you can just preprocess `theme_image()`:

```
function MYTHEME_preprocess_image(&$vars) {
  $vars['attributes']['alt'] = 'alt';
  $vars['attributes']['title'] = 'title';
}

```

If you're using any of the standard image display formatters they'll eventually be passed through `theme_image()` so that should work for all fields.

I'd strongly advise you consider **not** doing this though. The point of an alt tag is to describe the image to parties who can't interpret it in its original form (visually impaired people, robots, text only browsers, search engines, etc)

By setting the alt for every image to the same string, you're making your site quite inaccessible to those groups of visitors. And since Google and others assign a reasonable weight to alt text, you won't be doing your SEO any favours either.

---
Tags: theming, media, files
---


# Question
Title: Drupal 7.13 and Services 3.5 XML Payload schema to Update Node?
I have finally got Services up and running and setup an endpoint to nodes but can't work out how to update custom fields from a POST or PUT.

Been trawling through the docs, examples, and tutorials but none seem to offer a simple explanation of the XML payload schema to update custom fields of nodes (Using REST).

Below is an example of what I'm putting into by test client (Using REST console for Chrome plugin)

URL: http://example.com/task/node/65 Encoding: application/x-www-form-urlencoded METHOD: PUT

Payload:-

```
<title>New Title</title>
<body>New Body Content</body>

```

However this doesn't update anything, I just get the following response:-

```
<?xml version="1.0" encoding="utf-8"?>
<result>
    <nid>65</nid>
    <uri>http://example.com/task/node/65</uri>
</result>

```

It seems to create a revision and logs the update, but no fields are updated.

Can anyone advise the schema I need to follow for the payload? Thanks for any help or pointers!

**EDIT:** Thanks to Clive for a key pointer: Sticking ".xml" on the end of the URL seemed to make it update the body field, and then changing the content-type header to application/xml seemed to help as well.

So the following REST client config is now working:-

URL: http://example.com/**service\_endpoint**/node/***nid***.xml

REQUEST METHOD: **PUT**

CONTENT-TYPE: **application/xml**

RAW PAYLOAD:-

```
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <name>user</name>
    <title>Change this owner!</title>
    <body>
        <und is_array="true">
               <item>
                <value>Another owner test</value>
            </item>
        </und>
    </body>
</data>

```

Screenshot to help anyone else using the Chrome REST Console plugin:-

**NOTE**: I removed all security for the service and content type to make testing it easier but wouldn't recommend this on a public server!

# Answer
> 1 votes
See updated EDIT above.

RAW PAYLOAD:-

```
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <name>user</name>
    <title>Change this owner!</title>
    <body>
        <und is_array="true">
               <item>
                <value>Another owner test</value>
            </item>
        </und>
    </body>
</data>

```

---
Tags: 7, services
---


# Question
Title: Node type created by custom module doesn't get updated
I'm working on a custom module that creates a new content type. Recently I added a new field to the content type, but it doesn't get updated. I don't have any nodes of this type and when I disable my module, the content type is deleted. After I enable it again, the content type is back, but with the old setup and without the newly added field. I'm probably overlooking something very basic, but I couldn't figure out what. I cleared the cache and run cron before and after I disabled and enabled my module.

I even tried to give a different name to my content type and fields, but then the content type is not created. I bet it's just some small mistyping or something.

What could be the problem?

Here is the code. I put the field arrays into functions, but I don't think this causes any problem.

```
function simplegal_node_info() {
  return array(
    'simplegal' => array(
      'name' => t('Simple Gallery'),
      'base' => 'simplegal',
      'description' => t('A simple gallery that will display all images from a given directory'),
      'title_label' => t('Title of gallery'),
      'locked' => TRUE,
    ),
  );
}
function simplegal_node_type_insert($content_type) {
  if ($content_type->type == 'simplegal') {
    $body_instance = node_add_body_field($content_type, t('Description'));
    field_update_instance($body_instance);
    foreach (_simplegal_installed_fields() as $field) {
      field_create_field($field);
    }
    foreach (_simplegal_installed_instances() as $instance) {
      $instance['entity_type'] = 'node';
      $instance['bundle'] = 'simplegal';
      field_create_instance($instance);
    }
  }
}

function _simplegal_installed_fields() {
  return array(
    'simplegal_gallery_dir' => array(
      'field_name' => 'simplegal_gallery_dir',
      'cardinality' => 1,
      'type'        => 'text',
      'settings'    => array(
        'max_length' => 60,
      ),
    ),
    'simplegal_thumb_width' => array(
      'field_name' => 'simplegal_thumb_width',
      'cardinality' => 1,
      'type'        => 'text',
      'settings'    => array(
        'max_length' => 10,
      ),
    ),
    'simplegal_thumb_height' => array(
      'field_name' => 'simplegal_thumb_height',
      'cardinality' => 1,
      'type'        => 'text',
      'settings'    => array(
        'max_length' => 10,
      ),
    ),
  );
}
function _simplegal_installed_instances() {
  return array(
    'simplegal_gallery_dir' => array(
      'field_name' => 'simplegal_gallery_dir',
      'label'       => t('The directory of the gallery'),
      'widget'      => array(
        'type'    => 'text_textfield',
      ),
    ),
    'simplegal_thumb_width' => array(
      'field_name' => 'simplegal_thumb_width',
      'label'       => t('Width of thumbnails'),
      'widget'      => array(
        'type'    => 'text_textfield',
      ),
      'default_value' => variable_get('simplegal_thumb_width',120),
    ),
    'simplegal_thumb_height' => array(
      'field_name' => 'simplegal_thumb_height',
      'label'       => t('Height of thumbnails'),
      'widget'      => array(
        'type'    => 'text_textfield',
      ),
      'default_value' => variable_get('simplegal_thumb_height',120),
    ),
  );
}

```

# Answer
> 1 votes
My wild guess is:

From `hook_node_type_insert` documentation:

> Respond to node type creation. This hook is invoked from node\_type\_save() **after the node type is added to the database**.

Because you're not "Uninstalling" the module after you disable it, the content type will be kept, but it will simply be flagged as "Disabled" in the "disabled" column in the `{node_type}` table.

Therefore that hook is not invoked when you re-enable the module, hence the new fields not added.

So what you need to do is after disabling the module, go to the Uninstall tab and uninstall it, or if you're using drush:

`drush dis -y simplegal && drush pm-uninstall -y simplegal`

---
Tags: 7, nodes
---


# Question
Title: Give an individual cron task for each Feeds import
Can I separate different import tasks? I have feeds module installed and it runs multiple import jobs per cron. So I would like to at least order them (give different weights to them).

# Answer
My first thought was to suggest Elysia Cron, but it sounds like Feeds doesn't yet support individual per feed cron jobs.

Alternatively, depending on your needs, you might consider the Feed Import module, which can apparently be made to support per feed cron jobs via Elysia Cron.
> 2 votes

# Answer
You can indeed use Elysia and define a cron job for each of the feed imports like this:

```
/*
 * Feed import managed by Elysia
 */
function MYMODULE_cronapi($op, $job = NULL) {
  $items['fetch_MYFEED_cron'] = array(
    'description' => 'Fetch MYFEED',
    'rule' => '*/10 * * * *', // Every 10 minutes
    'callback' => 'MYMODULE_fetch_MYFEED_cron',
    'arguments' => array(array('MYFEED')),
  );
  return $items;
}
function MYMODULE_fetch_MYFEED_cron($feednames){
  if (function_exists('feeds_source')){
    foreach($feednames as $feedname){
      $source = feeds_source($feedname);
      $source->import();
    }
  }
}

```
> 3 votes

---
Tags: feeds
---


title: Refreshing AJAX Forms in Drupal 7

text:
# Question
Title: Refreshing AJAX Forms in Drupal 7
My dynamic Competition form has two basic parts:

1- Basic Info

* Name
* Size Dropdown

2- Ajax Fields

* Options dropdown based on Size

When I change the value in Size, a new combobox is loaded via AJAX with related values.

Here is part of my form:

```
if ($competition->size == 0)
    {
        $form['country'] = array(
            '#type' => 'select',
            '#title' => t('Country'),
            '#weight' =>3,
            '#required' => FALSE,
            '#zurb_class'=> 'cleared',
            '#default_value' => $competition->country_id,
            '#options' => _ajax_countries_dropdown_options(),
            '#prefix' => '<div id="dropdown-competition-size-replace">',
            '#suffix' => '</div>',
        );
    }
    else if ($competition->size == 1)
    {
        $form['continent'] = array(
            '#type' => 'select',
            '#title' => t('Continent'),
            '#default_value' => $competition->continent_id,
            '#weight' =>2,
            '#required' => FALSE,
            '#options' => _ajax_continents_dropdown_options(),
            '#prefix' => '<div id="dropdown-competition-size-replace">',
            '#suffix' => '</div>',

        );
    }
    else
    {
        $suffix = '<div id="dropdown-competition-size-replace"></div>';
    }

    $form['size'] = array(
        '#type' => 'select',
        '#title' => t('Size'),
        '#default_value' => $competition->size,
        '#weight' =>1,
        '#options' => $options_size,
        '#required' => FALSE,
        '#ajax' => array(
            'callback' => 'ajax_competition_size_dropdown_callback',
            'wrapper' => 'dropdown-competition-size-replace',
            'method' => 'replace',
            'effect' => 'fade',
        ),
        '#suffix' => $suffix,
    );

```

Ajax Callback

```
function ajax_competition_size_dropdown_callback($form, $form_state) {
    $size = $form_state['values']['size'];

    if ($size == 0)
    {
        return array(
            '#name' => 'country',
            '#type' => 'select',
            '#title' => t('Country'),
            '#weight' =>3,
            '#required' => FALSE,
            '#zurb_class'=> 'cleared',
            '#default_value' => $competition->country_id,
            '#options' => _ajax_countries_dropdown_options(),
            '#prefix' => '<div id="dropdown-competition-size-replace">',
            '#suffix' => '</div>',
        );
    }
    else if ($size == 1)
    {
        return array(
            '#name' => 'continent',
            '#type' => 'select',
            '#title' => t('Continent'),
            '#default_value' => $competition->continent_id,
            '#weight' =>2,
            '#required' => FALSE,
            '#options' => _ajax_continents_dropdown_options(),
            '#prefix' => '<div id="dropdown-competition-size-replace">',
            '#suffix' => '</div>',
        );
    }
    else
    {
        return '<div id="dropdown-competition-size-replace"></div>';
    }
}

```

Steps I made so far:

* When I change the first select when editing, the values are not saved.
* Debugging Backend
* The form changes on the front (AJAX), but it does not change on the backend
* Apparently the problem is I am creating the form fields based on size, Drupal will only recognize this fields. So when I change the select and load the second, it won't parsed by Drupal
* I tried to use $form\_state\['rebuild'\] = TRUE; but it didn't fix anything, actually avoided the redirection after submission.

# Answer
The Ajax callback should only return the named FAPI element that is to be replaced. For example:

```
function questionaire_4D_selector_form_ajax_callback($form, $form_state) {
  // If the form has errors we show them in the Preview spot. There's not much
  // else we can do because jQuery is replacing out the specified
  // target element in the #ajax FAPI element.
  if (form_get_errors()) {
    return $form['preview-content-area']['esci-questionaire'];
  }
  return $form['preview-content-area']['esci-questionaire'];
}

```

Your `form_builder` function which build/rebuilds the form should examine the `$form_state` and alter the form as necessary based on the ajax submitted values:

```
/** Our form builder function */
function questionaire_4d_selector_form($form, &$form_state) {
 # for ajax inspection goto /tmp and view file output.
 #dd($form_state);
 #dpm($form_state);

  // This form responds to an AJAX submit button, and also a $_GET argument.
  $form_passed_get_parameter_questionaire_id = $form_state['submitted'] == FALSE &&
          count($form_state['build_info']['args']) &&
          ctype_digit($form_state['build_info']['args'][0]);
  #dpm($form_passed_get_parameter_questionaire_id ? 1 : 0);
  if ($form_passed_get_parameter_questionaire_id) {
    $id = $form_state['build_info']['args'][0];
  } else {
    $id = !empty($form_state['values']['questionaire_id']) ? $form_state['values']['questionaire_id'] : '';
  }
  #dpm($id);
  $form['questionaire_selector'] = array(
    '#type' => 'fieldset',
    '#title' => t('Select 4D Questionaire'),
  );
  $form['questionaire_selector']['access_id'] = array(
    '#type' => 'hidden',
    '#value' => drupal_get_token(QUESTIONAIRE_4D_PREVIEW_AJAX_SECRET_VALUE),
  );
  $form['questionaire_selector']['questionaire_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Questionaire Number'),
    '#default_value' => $id,
    '#element_validate' => array('element_validate_integer_positive'),
    '#size' => 15,
  );
  $form['questionaire_selector']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Preview 4D Questionaire'),
    '#ajax' => array(
      'callback' => 'questionaire_4d_selector_form_ajax_callback',
      'wrapper' => 'questionaire-preview',
      'method' => 'replace',
    ),
  );
  $form['preview-content-area'] = array(
    '#type' => 'fieldset',
  );
  $form['preview-content-area']['esci-questionaire'] = array(
    '#prefix' => '<div id="questionaire-preview">',
    '#suffix' => '</div>',
    '#type' => 'markup',
    '#markup' => '<h3>Your Questionaire Preview will appear here.</h3>',
  );

  // This says if we were given an remote 4D form id of say 23456, load it into the supplied FAPI
  // element.
  if ($form_passed_get_parameter_questionaire_id) {
    $remote_response = retrieve_questionaire_4d_response($id);
    if (strpos($remote_response->data, 'Error',0) === 0) {
      form_set_error('questionaire_selector', "<b>Remote 4D Error</b><br>" . $remote_response->data);
    }
    $form['preview-content-area']['esci-questionaire']['#markup'] = questionaire_4d_selector_build_esci_questionaire_preview($id, $remote_response->data);
  }

  $form['#attached']['css'] = array(
    drupal_get_path('module', 'questionaire_4d_preview') . '/assets/questionaire_4d_preview.css',
  );
  return $form;
}

/* Implements hook_menu() */
function questionaire_4d_preview_menu() {
  $items['admin/config/esci-online/questionaire-4d-preview'] = array(
    'title' => '4D Questionaire Preview',
    'description' => 'View a preview of a remote 4D questionare.',
    'page callback' => 'drupal_get_form',
    // I'm not sure we have to, but explicitly pass in the 4th
    // argument on the URL as the questionairre ID. This is added
    // to build_info of form automatically.
    'page arguments' => array('questionaire_4d_selector_form', 4),
    'type' => MENU_CALLBACK,
    'access arguments' => array('administer esci'),
  );
  return $items;
}

```
> 1 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Where should I define the "drupal_stale_file_threshold" Drupal variable?
I want to delete my CSS and JavaScript files every day. Where do I define the "drupal\_stale\_file\_threshold" variable?

* In the template.php file with `variable_set('drupal_stale_file_threshold', 86400);`
* In the settings.php file with `$conf['drupal_stale_file_threshold'] = 86400;`

# Answer
> 2 votes
Settings.php makes sense if the setting isn't supposed to change.

A module may be useful if the value of the setting is just temporary.

A themes template.php file is absolute **not** the place to put it.

---
Tags: configuration
---


title: Theming Subpages

text:
# Question
Title: Theming Subpages
Back in Drupal 6, if I wanted to create a sub-theme for a bunch of pages, I could make a special pages-subtheme.tpl.php page and this would handle not only the /subtheme page, but also /subtheme/page1, /subtheme/page2, /subtheme/sub-subpage/page3 etc...

With the changes to Drupal 7, I could be wrong, but it looks like I have to do this node by node. And it also looks like I can't use the pathauto paths...

Thus those same 3 nodes which in Drupal 6 were pages-subtheme.tpl.php become in Drupal 7 three distinctly themed pages--node--40.tpl.php, pages--node--57.tpl.php, pages--node--23.tpl.php etc...

I'm hoping I'm wrong about this, which is why I'm asking

# Answer
> 3 votes
Would it help you to create a tpl.php page based on the node itself or by content-type? For example, you'd have your main page.tpl.php, but then for specific content types (subtheme), you'd have a page--content-type.tpl.php or node--type.tpl.php.

If you plan the sitemap and templates carefully beforehand you should be able to avoid creating individual page--node--1.tpl.php, etc.

Check out: https://drupal.org/node/1089656 (Drupal Theme Hook Suggestions)

The hook suggestions normally require a template\_page\_preprocess() function, but once you have it set up you're good to go.

I think you're right about pathauto paths not working for .tpl.php names, but you might be able to write your own preprocess function to accommodate those.

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


title: Use Image Styles with remote images?

text:
# Question
Title: Use Image Styles with remote images?
I have a set of images on a separate host, images are available by a URL. I would like to render one of these using Drupal's image styles, but I note that theme\_image\_style says it won't work with remote images.

Is this possible some other way?

I would like it to use Drupal's caching (so it doesn't fetch the original image every time).

# Answer
There's a module for that.

Imagecache external
> 3 votes

---
Tags: 7, media
---


# Question
Title: Output JSON views_field_view with Services?
I am using Services Views to render JSON for a view that has a views\_field\_view. The JSON output from Services for the views\_field\_view field is currently a rendered HTML view. How can I make views\_field\_view render a JSON version of the output to be included with the parent view's JSON output?

UPDATE:

The content in the sub-view has a Geofield, which is causing problems in a Services display. The view is set as an unformatted list. A Page display looks like this:

```
node_title: Marquette
Geofield: 44.977297200000, -93.270110200000

```

Then if I create a Services display with the same view (same fields), the output looks like this:

```
  stdClass::__set_state(array(
     'node_title' => 'Marquette',
     'nid' => '1335',
  ))

```

In a Services display, anything I try to do with a Geofield just outputs the nid.

# Answer
This was an issue with custom fields in Services Views that has been fixed in the latest dev version.

https://drupal.org/node/1647270
> 1 votes

---
Tags: views, services
---


# Question
Title: PDOException: SQLSTATE[HY000]: General error: 1 too many SQL variables
I keep on running into the following error in my Drupal 7 installation:

```
PDOException: SQLSTATE[HY000]: General error: 1 too many SQL variables:
SELECT menu_links.link_path AS link_path,
       menu_links.mlid AS mlid,
       menu_links.router_path AS router_path,
       menu_links.updated AS updated
FROM {menu_links} menu_links

```

It is followed by hundreds of lines similar to this:

```
:db_condition_placeholder_994, :db_condition_placeholder_995, :db_condition_placeholder_996,

```

and hundreds more similar to this:

```
[:db_condition_placeholder_994] => admin/config/content/panelizer/%/%/list/%/clone
[:db_condition_placeholder_995] => admin/config/content/panelizer/%/%/list/%/delete
[:db_condition_placeholder_996] => admin/config/content/panelizer/%/%/list/%/disable

```

The current error stops at *:db\_condition\_placeholder\_1005* but I have seen *:db\_condition\_placeholder\_1018* in other errors.

If I disable installed modules it goes away but it comes back as I enable them again. It doesn't seem to be caused by any particular module, but more by how many modules are enabled. I thought it might be something to do with the admin\_menu module, but disabling that has no effect.

I have googled this many times in the past 6 months, but never found a solution although I get the impression it has something to do with an SQLite limitation (999 variables in a query).

Down the line I'm quite prepared to dump SQLite and move to PostgreSQL (or MySQL), but for the time being I need to get this to work with SQLite.

Does anyone have an insight? Or even a fix?

Steve

# Answer
> 2 votes
This is a limitation of SQLite: 999 parameters.

I posted it as an issue here and as long as we have no general solution in the db driver to overcome the limitation, i posted in comment #6 a d7 patch for the menu router.

Note that other DBs also have limits, but higher.

# Answer
> 0 votes
I solved this by going back to the root of the problem and migrating to PostgreSQL, which is a story in itself. No

```
PDOException: SQLSTATE[HY000]: General error: 1 too many SQL variables

```

since!

Steve

---
Tags: database
---


title: Categorizing content types

text:
# Question
Title: Categorizing content types
I have a lot of views that need a content type filter which I should select about 20 content types for each of them. Is there any module to categorize content types(not contents)? For example adding a taxonomy term named `news` to content types `news`, `image news`,.. so instead of selecting content types I will add the filter `content typs has tag news`.

# Answer
> 2 votes
This module appears to be built exactly for your use case: https://drupal.org/project/content\_type\_groups

From the readme.txt: "Create a content type group called 'Media' and add the 'book', 'movie', and 'audio' types. You have just created a logical grouping between the content types to show that they are somehow related. ... Now that you have your content type group, you can filter Views by the Media content type group instead of selecting each content type individually."

I haven't used it. I was looking into coding a views filter handler etc., then it occured to me to search for "content type groups" and found this.

# Answer
> 3 votes
You can't add fields to the content type in regular old Drupal.

Also, the thing is that the *view* itself is pulling fields from the actual entities you're trying to list, so even if you manage to somehow add tags/fields that relate to the content type (through a custom or contrib module), your views wouldn't be able to just access those special fields by default. After all, your views are actually pulling entities themselves and accessing *their* fields. You know?

The simplest way to do this, I think, is to *hard-code* which content types you want listed in your views as filters:

In your views' '**Filter Criteria**' section, simply add the filter '**Content: Type**' and select all the content types to include. So, if you wanted a view that applies to 'news' category types, just filter to include all those content types (news, image news, etc). Of course, if you ever add a new content type or want to change your categorization, you'd have to edit your views by hand to match the new way of doing things...

The above is better, in my opinion, then adding a 'content category' vocabulary that is included in each of your content types as a field. Even if a 'category' vocabulary has a default, which allows content editors to create nodes and not have to set a category, the problem is that tagging each node (versus filtering by the content types as above), would make 'switching' your categories or removing/adding categories to your content types harder. If you decide to change them later, what do you do about all the nodes you've created in the meantime that have been tagged a certain way already? :-)

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


# Question
Title: I want the date view filter on current date, not on current time
I have schedule view in my project. I want to show the current day schedule in my view. We have following option in date filter.

"An offset from the current time such as "+1 day" or "-2 hours -30 minutes""

which gives you option for show the schedule from current time. which did not allow you to show the current day result. I used the "Views between dates filter" module but it gives filter on node created date only.

We can override the view by using the "hook\_views\_pre\_build" hook.

Is there any better solution for this?

# Answer
I have a view similar to what you're trying to achieve. You have to install the Date module (https://drupal.org/project/date) and through that module, you'll be able to set the granularity to 'Day' instead of minutes or seconds. Then, just put `+0 day` or `now`
> 2 votes

---
Tags: views, datetime
---


title: Drupal 404 not found with SOME browsers

text:
# Question
Title: Drupal 404 not found with SOME browsers
hello I have a drupal multisite setup, with the same modules and paths enabled ( services with REST endpoints). I have some weird behavior:

on site1 I call a URL and get the HTTP status 401 ( which is normal as the test has the not signed request). I am not signing for the purpose of this test.

on site1 it works no matter which browser I use.

now site2, all is setup, and when I test it from chrome/firefox/IE/safari it all works (rest client, rest console etc...), when I say it works it means that I get the 401 back. BUT when I test with safari mobile, or webview I get a 404. same request, same everything.

here are some log entries:

```
site1.net ###.##.180.109 - - [13/Aug/2013:16:07:01 +0000] "GET /REST/myapp/sendPassReset/oscar4/123 HTTP/1.1" **401** 157 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B141 Safari/8536.25" [smartphones] [0.671] [MISS] [nil]

site2.net ###.##.180.109 - - [13/Aug/2013:16:07:15 +0000] "GET /REST/myapp/sendPassReset/oscar4/123 HTTP/1.1" **404** 5 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B141 Safari/8536.25" [smartphones] [0.219] [-] [nil]

site2.net ###.##.180.109 - - [13/Aug/2013:16:54:36 +0000] "GET /REST/myapp/sendPassReset/oscar4/123 HTTP/1.1" **401** 180 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36" [-] [0.285] [-] [k-xae2qQMbNdjU4VbQoTpoTh1c2gfnvp-8cz7505Ajk;]

```

both sites are served by nginx, and PHP-FPM, with the same configuration. same code base.

any idea as to what can be happening?

# Answer
Finally tracked down the isse to broken/partially updated menu in some templates... they were causing the issue. have not been able to close the issue though.

hard reset of memcached fixed the issue... not nice to do in production site on busy day. we had to look through the whole bootstrap to finally see this.
> 0 votes

---
Tags: services
---


# Question
Title: How do I change the price of a flat rate shipping fee depending on a type of Product?
I am trying to create a different price for shipping of heavy items. I have light and heavy items and they are categorized via taxonomy heavy/light. How do I change the shipping price via Shipping Rules to detect if its a heavy or light item?

# Answer
An alternative to the solution duckx documents is to use a single flat rate and use a rate calculation rule to increase the unit price of the flat rate if the product has heavy products. However, if you need to differentiate in reporting between the number of orders (or total shipping amount) for light vs. heavy, the simplest way is with two separate flat rates.
> 0 votes

# Answer
figured it out .. but not sure if its the best way i think it is. for reference:

1. created a light & heavy shipping flat rate option.
2. added in new conditions matching if its a **heavy** or **light** via taxonomy terms.
3. added in an extra condition for LIGHT shipping to make it disappear by detecting if there is a heavy item in the cart by doing a **negate** on the same above condition.

To make this work you will need https://drupal.org/project/commerce\_rules\_extra

As you need the **Total quantity of selected product comparison** condition to loop through the entire cart and match what you need in accordance to the terms you select.
> 0 votes

---
Tags: 7, rules, commerce
---


# Question
Title: How do I add an expression into a query?
When I use the code below, I get the following error:

> Call to a member function addExpression() on a non-object

```
 $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->execute()
    ->fetchAssoc();
  $query->addExpression('MAX(nid)', 'max_nid');

```

What is wrong with that code?

# Answer
Change the code to the following one.

```
$query = db_select('node', 'n');
$query->fields('n', array('nid'));
$query->addExpression('MAX(nid)', 'max_nid');
$query->execute()->fetchAssoc();

```

The value returned from `fetchAssoc()` is an array. Since you are assigning the value returned from `fetchAssoc()` to `$query`, and then calling `$query->addExpression()`, you rightly get the error. You cannot call a method on something that is not an object (in this case, an array).

If you want to list all the node IDs and set *max\_nid* to the maximum value, you can use the following code.

```
$query = db_select('node', 'n');
$query->fields('n', array('nid','type'));
$query->leftJoin('node', 'n1', 'n1.type = n.type');
$query->addExpression('MAX(n1.nid)', 'max_nid');
$query->groupBy('n.nid');
$result = $query->execute()->fetchAll();

```
> 4 votes

---
Tags: 7, database
---


title: Display view items as thumbnails

text:
# Question
Title: Display view items as thumbnails
I would like to make a view created as a block where every item is displayed as a thumbnail of a cover photo-field of the content type.

I can't find this option in the display options dropdown ... How should I go about it?

# Answer
> 2 votes
In Drupal 7, you just need to use **Image style** as answered by Jack-PL

---
Tags: views
---


title: Get internal path from external URL

text:
# Question
Title: Get internal path from external URL
Is there a way to get Drupal internal path from the external URL? I need to get node id (or any other internal path) from the URL that user specifies in the textfield. External URL in this case is not the URL of current page, it is arbitrary URL that is entered by user.

For example:

Base URL: `http://www.example.com/drupal`

Alias of `node/101`: `foo/bar`

User input: `http://www.example.com/drupal/foo/bar` or `http://www.example.com/drupal/?q=foo/bar`

Expected result: `node/101` or `foo/bar`

The problem explained:

1. `drupal_get_normal_path()` only returns normal path if internal alias is given. In this case internal alias from external URL needs to be extracted but there are no internal Drupal function that would do that directly.
2. If site has Clean URLs enabled, request path in external URL can either be in "q" argument (`?q=foo/bar`) or in URL itself (`/drupal/foo/bar`).

# Answer
I came up with the following code, based on a great @Jimajamma answer.

```
/**
 * Returns internal path, query and fragment from external URL
 */
function get_path_from_url($url, $normal_path = TRUE) {
  global $base_path;
  // Get hostname
  preg_match("/^(https?:\/\/)?([^\/]+)/i", $url, $domain);
  // Format localhost + base_path (http://hostname/drupalbase)
  $base = (isset($domain[0]) ? $domain[0] : '') . $base_path;
  // If $url contains $base, remove the $base part
  if (strpos($url, $base) === 0) {
    $path = str_replace($base, '', $url);
  }
  // $url is presumed to be without $base part (internal path?)
  else {
    $path = $url;
  }
  // Path may contain language prefix. Check if that is the case.
  list($language, $path) = language_url_split_prefix($path, language_list());
  // Parse the path (without $base)
  $result = drupal_parse_url($path);
  // Add language to result
  if (!empty($language)) {
    $result['language'] = $language;
  }
  // Get normal path
  if ($normal_path) {
    $result['path'] = drupal_get_normal_path($result['path']);
  }

  return $result;
}

```

The following function will take both clean URLs and regular URLs (with internal path in `?q=`), http or https protocol.

Any of these URLs will be converted to internal path (or alias) if processed on a host `www.example.com` with site locating in `/drupal/`:

```
$url = 'https://www.example.com/drupal/en/node/b10d6840?foo=bar#xyz';
$url = 'https://www.example.com/drupal/en/node/b10d6840?foo=bar#xyz';
$url = 'http://www.example.com/drupal?q=en/node/b10d6840&foo=bar#xyz';
$url = '?q=en/node/b10d6840&foo=bar#xyz';
$url = 'en/node/b10d6840?foo=bar#xyz';

```

`get_path_from_url($url)` will return:

```
array(
    'path' => 'node/110',
    'query' => array(
        'foo' => 'bar',
    ),
    'fragment' => 'xyz',
    'language' => [language object],
);

```

`get_path_from_url($url, FALSE)` will return aliased path:

```
array(
    'path' => 'node/b10d6840',
    'query' => array(
        'foo' => 'bar',
    ),
    'fragment' => 'xyz',
    'language' => [language object],
);

```
> 2 votes

# Answer
Dull Ax....

```
$path='';
$with_trailing_slash=$base_url . '/';

if (strpos($user_input, $with_trailing_slash)===0) {
  $user_input=str_replace($with_trailing_slash, '', $user_input);
  if (strpos($user_input, '?q=')===0) {
    $path=substr($user_input, 3);
  } else {
    $path=$user_input;
  }
} else {
  // this isn't on the local system so there is no way to figure it out
}

if ($path) {
  $normal=drupal_get_normal_path($path);
}

```
> 2 votes

# Answer
Since I don't know in what context you're going to be using this in, so I'll just point you to the Drupal function which can generate the internal path when given a URL alias: `drupal_get_normal_path`

> drupal\_get\_normal\_path: Given a path alias, return the internal path it represents.
> 1 votes

---
Tags: path-aliases
---


title: Drupal ajax call within form

text:
# Question
Title: Drupal ajax call within form
I am trying to call ajax call within form. here is my code

```
<?php

function clicktell_form_alter(&$form, &$form_state, $form_id) {
    //print_r($form);

    if($form_id=='user_register_form') {

        $form['choice_wrapper']['poll_more'] = array(

            '#type' => 'submit',

            '#value' => t('More choices'),

            '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),

            '#weight' => 1,
            "#executes_submit_callback" => FALSE,

            '#ajax' => array(

                'callback' => 'poll_choice_js',

                'wrapper' => 'poll-choices',

                'method' => 'replace',

                'effect' => 'fade',

            ),);

    }
}

function poll_choice_js($form, $form_state) {
    print_r($form_state);
    return $form['choice_wrapper']['choice'];

}

```

when i click on more choice button it is not calling poll\_choice\_js function. i checked this in firebug but didn't get any result

Thanks

# Answer
Use return

function poll\_choice\_js($form, $form\_state) { return('something'); return $form\['choice\_wrapper'\]\['choice'\];

}
> 0 votes

# Answer
For the **ajax callback** and **hook\_form\_alter()** to function you should **clear the caches** from the performance link. Also you should change the following

```
return $form['choice_wrapper']['poll_more'];

```
> 0 votes

---
Tags: 7
---