# Question
Title: Get the number of followers and following in user relationship
I have created a relationship Followers which can be reciprocated using the user relationship module. Now user A's relationship is something like: Followers(Them to you): User B, User C, User D Followers(You to them): User D

Now i want to create a view which only shows the number of followers and following: Follower: 3
Following: 1

I went about to create the view (Views 3, Drupal7) but was not able to do. Didnt get any filters or relationships regarding this. Also, tried using the Views Cal but am not clear. Would appreciate any help.

Thanks

**Edit:**

Apologies for not being clear.

I created a view of type Users. Then i added a relationship (this is the part where i am not sure if i am correct or not). I tried with all the available relationships pertaining to this such as User relationships:

```
 User relationships: Requestee user
 User relationships: Requestee user is current user
 User relationships: Requester user
 User relationships: Requester user is current user
 User relationships: RTID

```

(i tried individually all of them and various combinations of them as well)

Then under Others i clicked yes for Use Aggregates and when asked for the grouping function ("Group type"), i selected "Count and unchecked the label in the configure field screen, so that it only shows the number.

I also added a filter that the user is logged in. However, it just shows me the number of relationships of different users who have requested the current one.

**Edit 2:**

Found this thread: http://drupal.org/node/809476. However its for Drupal 6..., am trying to implement it for 7. lets see...if you have any pointers i would be grateful...will keep you posted

**Edit 3:**

Based on the above thread i wrote the following code into a custom block.

```
<?php
global $user;
$user_id = $user->uid;
$params = array("requestee_id" => $user_id, 'rtid' => 3);
$count = user_relationships_load($params, array("count" => TRUE));
echo $user_id;
echo $count;
?>

```

I just printed out the user id to check if correct user or not and it prints the correct user. However, count prints 0. Why is that?

**Edit 4:**

I think i am on the right way using http://drupal.org/node/203396. However there are some fixes there. The correct code is:

```
<?php
global $user;
$requests = user_relationships_load($param = array("approved" => 1, "user" => $user->uid), $options = array(), $reset = FALSE);
$requestcount = count($requests);
echo  $requestcount;
?>

```

This displays the total number of approved relationships. Now i want only the followers type relationship number. Looking into that. If anyone has any suggestions would appreciate them. Will keep you all posted

**Edit5:**

And now i am stuck. Whatever i try to do i am only getting the total number of relationships. I just want the number of followers(them to you) in one block and then using that, i hope, i will be able to get number of following(you to them). Would appreciate any help.

Thanks

# Answer
The following function works for me to display the count of friends a user have:

```
function mymodule_user_friends_count ($user) {
  $count = user_relationships_load(
    array("user" => $user->uid, 'approved' => 1, "name"=>'Friend'),
    array('count' => TRUE));
  return $count;
}

```

Notice I only count approved friends and only relationships of type 'Friend'
> 1 votes

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


# Question
Title: How to relate two profile2's profile in one single form?
I'm developing a portal, using Drupal 7, to manage the entrance of people on my building. I'm using Profile2 module and I created two profiles: "Dweller" and "Visitor".

Now my idea is to create a content type "visit" where I could register the visits that a dweller receive but how can I add two fields, one "dweller" and another "visitor" that will list the entities (persons) of each kind of profile?

Any one have a better approach for this requirements? Or any idea how to resolve it?

Tks!

# Answer
If you're trying to display 2 profile on the same registration path you can use Profile2 Registration Path and enter the same URL path in the settings. The 2 profile will be added to each other. You can also set the weight to choose which one come first.
> 0 votes

---
Tags: entities, users
---


# Question
Title: mytheme_preprocess_field is not called on add/edit node
I have added the following function in my theme's template.php to test whether it actually gets called when adding or editing a node, but for some reason it is not!

function mytheme\_preprocess\_field(&$variables, $hook) { die('FINALLY!'); }

I have done everything I could think off, refresh cache (all of them), restart apache, restart server, no matter what I do, it is not called. As soon as I go to the frontpage, it is called.

Can someone give me some pointers where I might look next? Thanks!

# Answer
> 3 votes
I believe the theme functions are called on render (as in view) and not the add/edit pages. If you want to affect the markup of the fields on the add/edit forms you would use a hook\_form\_alter or hook\_form\_FORM\_ID\_alter() and change the render array there.

---
Tags: theming, hooks
---


# Question
Title: Awarding points with Rules for uploading a user picture
Does anyone know how to create a rule that awards points to a user for uploading an image?

# Answer
> 2 votes
Have a look at the "User Points" (https://drupal.org/project/userpoints) module. It has rules integration (among many other modules) so this may be the one you're looking for. It also provides a hook API by the looks of it, so if you need more custom functionality than what it offers by default, you should be able to perform actions from within a custom module.

---
Tags: 7, rules, userpoints
---


# Question
Title: Permission for translating menu items via the menu config screen
I have a multi language Drupal site, Using i18n and the entity translation approach. Translating menu items from an node works well, but not all the menu items are driven by the nodes.

Now as user/1, I have permission to translate any menu item from the menu config screen: /admin/structure/menu/manage/main-menu. I am trying to enable the same permissions for other roles/users. The second role has permissions to administer menu items and translate all entities, but for the life of me I cant figure out why the translate link doesn't show in the menu config screen for the other role. Any pointers would be greatly appreciated!

# Answer
I found the answer. You have to have the following permissions set: *translate interface* and *administer menu items*.
> 0 votes

---
Tags: routes, users, i18n-l10n
---


title: add flag to product display view

text:
# Question
Title: add flag to product display view
I have a product display using facets that I have tried in vain in views to add a flag/unflag link to with views I already built a separate comparison view with the relationship to flag and the ability to unflag but I want to be able to flag products from the facets display (if it's even possible) rather than a second display that looks the same as the facets display except that it uses content linked to the product entity and wont show the facets

Does anyone know if it's even possible to add a flag to a view of type "Product Display"?(Correction: "Product Display" was the name of my search api index being exposed to views)

For now I have this working by exposing the flag link on the product displays themselves which is a pain in the neck to flip back and forth and some users probably aren't going to be able to be techie enough to figure it out

# Answer
I am having the same problem. It seems like there is no way to add 'flag' relationship in view used by facets.. The way I have done this is:

1. I installed the module '**Views PHP**' (https://drupal.org/project/views\_php)
2. Added a '**global PHP**' field in my faceted view.
3. called the function to **create flag link** and printed the link in the global php field: print flag\_create\_link('bookmarks', *$data-\>entity*)

Dont know why, my php view cudn't render $row-\>nid, thus I used $data-\>entity for node id.

*Remember to enable php filter once views php is installed.*

Hope It helps.
> -1 votes

---
Tags: commerce, flags, search
---


# Question
Title: Features : export content types with FieldCollection
When I try to export my content type using Features, it works. But when I import it on another Drupal installation, I've got an exception :

```
Exception : Invalid field name given: **my_field** is not a Field Collection field. in FieldCollectionItemEntity->__construct() (line 119 in **path_to_module**\field_collection\field_collection.module)

```

That's strange, because IT IS a Field Collection, and it worked fine on the first Drupal installation.

Any ideas ?

# Answer
> 1 votes
There are two solution to this problem, the first one is a bug in the module that can be fixed via this patch https://drupal.org/node/1084268

The second solution fixes a problem caused by orphan fields in field\_collection\_item table. First try removing **my\_field** via drupal interface, if it didn't exists try searching your **my\_field** in this table, if it existed , delete it

* NOTE : the solution is dirty one, it worked for but it may have side effects, backup your database before trying it

---
Tags: features, entities
---


title: Omit front page in Bartik theme

text:
# Question
Title: Omit front page in Bartik theme
Hey I am using the Empty Front Page module https://drupal.org/project/empty\_front\_page on a sub-theme(Bartik) but the problem is that when I open my domain I see an empty screen and none of the tabs are open. Can I somehow omit this empty page and direct the user to the home tab of the website meaning www.example.com to example.com/home?

PS: I am new to php and Drupal!

# Answer
I will present a solution for empty front page here with help of views module.

You can create or use a content type which you are not intended to use. Either you can create one or use `article` etc.

Create a views with selecting that content type & set other things such as `no pager` & `0 posts`, so that this views doesn't produce any result.

Give it a name such as `home` & make a page with same name.

Go to your **site configuration** & set this `home` as `front page` path. You are done.
> 0 votes

---
Tags: redirection
---


# Question
Title: How do you set up ubercart to filter/sort by price
I'm new to Ubercart and just set-up a simple shop (Using Drupal 7 and Ubercart 7.x-3). In the default uc\_catalog (table) view you are able to sort by product title.

When going to format -\> table settings, there is an option to allow the title field to be sortable, but there is no such option for price. Is there a solution to allow the products in the table to be sorted by price?

I've tried adding a price to the sort criteria but the sort filter doesn't work.

Any help or pointer would be appreciated.

# Answer
Use Ubercart advanced catalog. Very useful views. Here is a quote about it (from the module's project page):

> ... add custom filters on Ubercart catalog and provide taxonomy, products attributes (select) and CCK (option widget) support.
>
> Filters are fully configurable. Product display is fully configurable with Display suite and Node display.
> 2 votes

# Answer
I use Drupal 7 and uc\_catalog is not upgraded for this edition. So, you can also use a view and sort by price, reference, title, etc... everything you want.
> -1 votes

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


title: "Cannot redeclare i18n_variable_set()"

text:
# Question
Title: "Cannot redeclare i18n_variable_set()"
I have made multilingual site. When we redirect users to another domain, I see the following error:

> \[Sun Feb 02 13:03:40 2014\] \[error\] \[client 192.168.1.80\] PHP Fatal error: Cannot redeclare i18n\_variable\_set() (previously declared in /var/www/html/UNI01JO2012031/sites/all/modules/contrib/i18n/i18n\_variable/i18n\_variable.module:116) in /var/www/html/UNI01JO2012031/sites/all/modules/i18n/i18n.module on line 894

Please note I am not changing any configuration.

# Answer
The issue here appears to be that you have installed the same module in two directories:

```
sites/all/modules/contrib/i18n

```

and

```
sites/all/modules/i18n

```

and drupal is picking them both up. If this is the case, I would disable the module, uninstall it, delete one of the directories above, and then re-enable the module. That should clear this up.

If you can't access your site's admin UI at all, then you will have to go in and remove one of the directories directly; I would suggest removing `sites/all/modules/i18n` as the other directory appears to be being searched first.

ADDITION: From some line number searching, the Drupal 6 version of `i18n.module` declares `i18n_variable_set()` from lines 881 to 894 and the Drupal 7 version doesn't even get that long--ending at line 610. This coupled with the fact that the `i18n_variable` submodule isn't even included with the Drupal 6 version has me thinking you have a sorts of module mish mash going on here.

ADDITION 2:

I just installed the Drupal 7 i18n module on a clean install in:

```
sites/all/modules/i18n

```

and enabled it and the i18n variable module. ALL good.

I then copied the Drupal 6 i18n module's code into:

```
sites/all/modules/contrib/i18n

```

and....

> PHP Fatal error: Cannot redeclare i18n\_variable\_set() (previously declared in /Applications/MAMP/htdocs/d7lrfm/sites/all/modules/i18n/i18n\_variable/i18n\_variable.module:116) in /Applications/MAMP/htdocs/d7lrfm/sites/all/modules/contrib/i18n/i18n.module on line 894

so, I would check to see if the same thing is happening on your site and if so, remove the errant Drupal 6 version. A quick check of the `.info` files will show you what core version of Drupal they are for. (And, oops, yes, here I put the Drupal 6 version in `sites/all/modules/contrib/i18n` and the Drupal 7 one in `sites/all/modules/i18n` which appears to be opposite of what's happening on your site, but I tried to be as similar as possible :)
> 5 votes

---
Tags: i18n-l10n
---


# Question
Title: How to fetch list of published webforms from webform module?
How can I fetch list of published webforms from webform module?

I want to show all published webforms in dropdown to the user, so user can select one of the available forms.

Cheers -Zafar

# Answer
> 3 votes
In Drupal 7 it would be something like:

```
$nodes = node_load_multiple(array(), array(
  'type' => 'webform',
  'status' => 1,
));

```

Have a look at the docs for node\_load\_multiple. You could (and probably should) also use EntityFieldQuery as mentioned in the docs. The given examples assumes that you use the default webform content type.

You could then use the `$nodes` array to build options for a Form API select element:

```
$webforms = array();
foreach ($nodes as $nid => $node) {
  $webforms[$nid] = check_plain($node->title);
}
$form['available_webforms'] = array(
  '#type' => 'select',
  '#title' => t('Webforms'),
  '#options => $webforms,
);

```

---
Tags: 7, webforms
---


# Question
Title: User registration silently fails - how to debug?
On our Drupal 7 site, user registration silently fails. Drupal doesn't even reach the form's validation functions.

What we checked:

* disabling javascript didn't help.
* Removing installed modules related to registration such as : logintoboggan, user\_registrationpassword didn't help.
* Error logs show nothing.
* The user module is of course enabled, people are able to login as usual.

Please advise where to put tests to see where execution is stopped.

Thanks in advance

Amnon

# Answer
> 0 votes
Recommended steps to trace the error:

1. Look at watchdog (which you did)
2. Look at the systems php and apache (or whatever you use) error logs
3. Take a local copy of the site and start digging

You can find your system logs (php and apache) by looking at the php info under "Admin \> Reports \> Status \> PHP".

For local debugging: http://ratatosk.net/drupal/tutorials/debugging-drupal.html

My first point of entry would be the form definition. You could try for example to add an `#after_build` callback that get's called once the form has been fully build, and then check which validation and submit handlers are registered.

In your case I would suppose though, that you don't need to go that far. It's probably pretty basic error that will show of in the system logs.

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


# Question
Title: Create a user via the Installation profile
I am using Installation Profiles to automate the process of installing Drupal 7 websites

I would like to create a user via the installation profile and assign it a username, password and email address, plus give it a role (This will be a special administrative user that I want every website to have).

How can I do this? This is the closest tutorial I can find. However, it requires you to set a username/password and email address manually. I would like to store a default values for all these fields.

# Answer
If you still want a configuration form, then you can build upon the "Client step" and change the `function brochure_client_form_submit($form, &$form_state)` so that it suits your needs (all code is untested):

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

  // Setup the user account array to programatically create a new user.
  $account = array(
    'name' => YOUR_NAME,
    'pass' => YOUR_PASS,
    'mail' => YOUR_MAIL,
    'status' => 1,
    'init' => 'install profile', // Just an example
  );
  $account = user_save(null, $account);
}

```

If you don't need a separate configuration form during install, you can define a "formless" task like this:

```
/**
 * Implements hook_install_tasks().
 */
function mymodule_install_tasks() {
  $tasks['mymodule_setup_admin_account'] = array(
    'display_name' => st('Setup admin account'),
  );
  return $tasks;
}

function mymodule_setup_admin_account() {
  // Setup the user account array to programatically create a new user.
  $account = array(
    'name' => YOUR_NAME,
    'pass' => YOUR_PASS,
    'mail' => YOUR_MAIL,
    'status' => 1,
    'init' => 'install profile', // Just an example
  );
  $account = user_save(null, $account);
}

```

You still have to create the role and add it to the created user. If you have created the role prior to the user creation, then you can also pass it directly to `user_save`:

```
$account = array(
  'name' => YOUR_NAME,
  'pass' => YOUR_PASS,
  'mail' => YOUR_MAIL,
  'status' => 1,
  'init' => 'install profile', // Just an example
  'roles' => array(
    ROLE_ID => ROLE_ID,
  ),
);
$account = user_save(null, $account);

```

More on install profiles: How to Write a Drupal 7 Installation Profile
> 2 votes

---
Tags: installation, installation-profiles
---


# Question
Title: Change the description for username field in user registration
I would like to disable the spaces in the usernames. For that I installed a rules module and i applied a rule. Everything is fine but now the label is still saying : `"Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores."`

How can i change that label ? I looked everywhere and i didn't find a thing.

I am new to drupal. I use drupal 7.

Thanks in advance for you responses.

# Answer
Another couple of options using string translation techniques:

1. Contrib module: String Overrides
2. `settings.php` snippet insert

The string overrides module lets you do the string translation via the UI. Otherwise, you can set the override in settings.php - the search string needs to match exactly.

```
/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 */
$conf['locale_custom_strings_en'][''] = array(
  'Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.' => 'Spaces and punctuation are not allowed except for periods, hyphens, apostrophes, and underscores.',
);

```
> 4 votes

# Answer
The text is in user\_account\_form function https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_account\_form/7

To change it, you can implement a hook\_form\_alter. I believe the text appears on two forms, 'user\_register\_form' and 'user\_profile\_form'. Create a module, put this in it (change mymodule to your module name).

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
    $form['account']['name']['#description'] = t('This will be the new text Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.');
  }
}

```
> 2 votes

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


# Question
Title: How can I programmatically enable permission for anonymous users to view comments on a single node?
How can I programmatically enable permission for anonymous users to view comments on a single node? Comments are open, but by default anonymous users are not allowed to view comments. I would like them to on one single node.

# Answer
> 0 votes
If all you are wanting to do is allow anonymous users to view comments on a single node, you could take the dull ax approach by first allowing all anonymous users to view comments, eg:

and then, in your theme, copying the default `node.tpl.php` to `node--###.tpl.php` where `###` is the `nid` of the node you are wanting your anonymous users to View the comments and then making the following changes:

In `node.tpl.php`, there should be something along these lines near the end of the file:

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

```

This is where the actual comments are displayed. Since this is the template that will be used for every node except the one you want special comment treatment, change this to:

```
<?php if ($logged_in): ?>
  <?php print render($content['comments']); ?>
<?php endif; ?>

```

which will have the effect of displaying the comments only if the user is logged in. And, since the `node--###.tpl.php` doesn't have this newly added `if` surrounding its printing of the comments, it will display the comments for both anonymous and authenticated/logged in users.

Of course, you could also just have modified `node.tpl.php` like this:

```
<?php if ($logged_in || $node->nid==###): ?>
  <?php print render($content['comments']); ?>
<?php endif; ?>

```

and not copied it to `node--###.tpl.php`, but then if you wanted to extend this to another node, you'd have to enter the logic directly in the template, and not just copying `node--###.tpl.php` to `node--######.tpl.php`.

Just remember to flush your caches to let Drupal know about your changes.

# Answer
> 1 votes
There are a couple ways to handle this and it depends on when you want to make the change.

What you'll want to change is $node-\>comment to one of the following:

You could use a hook\_node\_presave() function to change the value prior to saving based on some logic. Or you just need to get access to the node object through other means like node\_load(). Just make sure to save the node if you're loading it up to make the change.

---
Tags: 7, comments
---


# Question
Title: How to easily create a landing page for contents with specific tag
I'm building an intranet portal for a non-profit organization I work in, and currently figuring out how to make it easier for my colleagues to build a landing page that displays all contents tagged with x. For example, if they create a landing page called Jobs, all contents tagged with jobs will be updated on the Jobs page.

Think of it similar to OpenAtrium where you could create a section, then upon creating a content you could choose which section it will get automatically posted to.

Currently this is doable by:

1) Users creating a tag (i.e 'jobs'), then creating a view to pull all contents tagged with jobs. But this means I will have to give them permission to taxonomy, views, and page manager. Plus, the steps and interface are too daunting.

2) Using Panopoly module, I can easily add a 'content list' pane that can choose between different content type. Unfortunately it doesn't have an option to filter by tags. Is there any way to include this?

Is there a better way to do this?

# Answer
> 1 votes
You can still do this easily with view panes. They play very nicely together with panels.

First step is to create the vocabulary you want to use / filter on. Then create a view pane with this vocab as an (exposed) filter. By exposing this filter when a user adds this view pane to a panel, that exposed filter becomes a pane configuration option. You can even expose content type as a filter and the user can choose what content types and terms they want to filter on when they add the pane.

---
Tags: 7, views, chaos-tool-suite, distributions
---


# Question
Title: Can I change the post's created date format?
Can I change the date format without touch the code level? I only have admin access. Tried to search for solution but all of them are code level.

# Answer
> 1 votes
Yes you can. As an admin you can access "Administration » Configuration » Regional and language » Date and time", where you can define date formats and and display types. The latter you can then use in the "Manage display" part of an entities field configuration, or in the view display options of date fields.

*Edit:* If that doesn't work (which it doesn't for default node displays) and adding preprocess code is not an option (as the OP declares), another option is to hide the "created by" output (content type settings) and adding an own date field that you can fully control. This one will not, out of itself, be set to the current date when creating a node. Though, that might be an option in the field settings, have to look.

Anyway, code level change would be trivial, but without touching code, this is one of those Drupal WTF moments.

# Answer
> 1 votes
If you are asking, can you change the Authored on/create time when adding or editing a node, eg, here:

then no, there isn't a way to do it without going in and doing a `form_alter()` or similar.

However, if you mean the submitted date shown on the node, eg, here:

then yes, you can, as it uses the `medium` format and you have some limited options available at `admin/config/regional/date-time`. So, you can change, for example,

to

you'll get

but just realize that every place that Drupal uses the medium date format will now use this new one as well.

---
Tags: 7
---


# Question
Title: Facets are missing post updating Apache Solr Search to 7.x-1.4 version
I just updated Apache Solr Search module to 7.x-1.4 version, and since then the facets are missing in the assigned region.

Facets of all taxonomy terms are missing, the rest of the default facets like content type, etc are appearing on the settings page.

Plus the Taxonomy term fields are missing under Bias settings as well.

I have tried to disable \> Uninstall \> re-install all the Apache solr search and Acquia search modules but Facts are not appearing back on the Apache Solr Settings page.

I have this issue on the production server.

Regards, Anand

# Answer
Updating to latest release solved the issue.
> 0 votes

# Answer
Just wanted to log the answer that is suggested on Drupal.org: https://drupal.org/node/2123683, since this question is the first thing that popped up when I ran into this issue. :0)

Here is the issue: the taxonomy facets are the ones affected by the upgrade, because even though your taxonomy terms are probably hidden in the 'Search index' view mode on your content type's configuration page, apachesolr used to ignore those settings (a bug).

The new update fixes that, which means you need to go back to your content type's manage display page -\> search index tab -\> make sure the taxonomy terms in question are not hidden.

Hope this helps!
> 1 votes

---
Tags: 7, search
---


# Question
Title: Editing the default layout for a content type in Panopoly
I am using the panopoly distribution. What is the easiest and preferred way to edit the default layout for a content type.

I know that I can use panelizer for one page, but where should I go to edit the entire contenttype?

# Answer
> 1 votes
You're looking for the panels (node\_view) page. You should be able to find it at admin/structure/pages and then look for node\_view. Edit that page and add a new variant for your content type.

---
Tags: panels
---


title: how do i link to pdf file in drupal 7

text:
# Question
Title: how do i link to pdf file in drupal 7
I have a content type in which i created flie type field and text type field.I uploaded the pdf file and wrote 'link' to text field. I have copied the link from uploaded file and with the use of ckeditor given the link to the text 'link'. Now when i click to text 'link' then the pdf file get opened. But the problem is if we look at the url it says 'www.example.com/sites/default/files/ADMISSION\_FORM.pdf'. which is not correct and secured i think. it shud be somelike 'www.example.com/node/35/ADMISSION\_FORM.pdf'. Can anyone who knows tell me the fact....??????Thank you!

# Answer
That's not a problem, Drupal stores uploaded files under sites/default/files by default. There's no reason file paths for uploaded files would be similar to the URL of the node they're attached to.

www.example.com/sites/default/files/ADMISSION\_FORM.pdf is the correct path if you haven't changed any of the default settings. I'm not sure why you've mentioned security, as that really doesn't come into it.
> 2 votes

---
Tags: files
---


# Question
Title: How to sort field_info_instances return value by field weight?
I'm using `field_info_instances()` to retrieve the information for all the fields used by a content type, for example calling it as `field_info_instances('node','bundle_name')`.

In the returned array, the fields aren't ordered as I expected. I need to get the fields ordered per weight.

For example, a field weight is 8, in the *Manage fields* list.

>

Despite this, it's shown on the top, in the output from `field_info_instances()`.

>

Is there any possibility to get the fields ordered?

# Answer
> 3 votes
You probably want something like this

```
$info = field_info_instances('node','bundle_name');

uasort($info, function($a, $b) {
  $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;

  if ($a_weight == $b_weight) {
    return 0;
  }

  return ($a_weight < $b_weight) ? -1 : 1;
});

// $info is now sorted by weight.

```

---
Tags: 7, entities
---


# Question
Title: Unresolved dependency error when updating
I Tried updating 2 different sites and both gave error messages saying "Unresolved dependency" missing from different modules.

The pages no longer load on the site saying

> Fatal error: Call to undefined function libraries\_load()

Why am I getting these messages?

# Answer
> 0 votes
Updating core first solved this for me

# Answer
> 0 votes
This is a bit of a guess...

If you're updating modules on a fairly out-of-date site, some of the new versions may now depend on other modules, whereas they didn't when you originally installed them. Either that, or the files have just become missing somehow.

Either way, it looks like you need to download

---
Tags: 7, updating
---


# Question
Title: Is there existing integration between the Salesforce and Location modules?
I'm using the Salesforce module in Drupal 7 and am attempting to create a mapping to one of my content types that contains a Location module field. After looking at both modules, I don't see an existing integration for them.

I tried adding a field mapping for just the street address (the only method available was using a token, so I selected `[node:location:street]`). When I kick off the import of salesforce data, I get the following error:

```
WD Salesforce Pull: Unknown data property [node. Processing failed for entity XXXXXXXXXX
associated with Salesforce Object ID: XXXXXXXXXXXXX

```

I tried other variations of the token, too, including:

`[node:location:street:0]`

`[node:location:street:?]`

Both gave me the same error.

# Answer
> 0 votes
It's difficult to say what's the exact problem, but I think you could have unmapped property in your configuration. So please go to /admin/structure/salesforce/mappings and verify all the objects that have the properly set mappings and the tokens are valid.

If this doesn't help, try the following options:

1. Clear the cache (including memcached).
2. Check watchdog logs for further info.
3. Double check your Salesforce mappings again if you didn't miss anything.
4. Upgrade your Location and Salesforce module to development version just to test.
5. Look for any existing issues.
6. Debug the code using xdebug.
7. Report the issue or bug report on Drupal site against the right module.

You may also try the following related links:

---
Tags: 7, location, crm
---


title: Moving from subdirectory to root

text:
# Question
Title: Moving from subdirectory to root
When I installed Drupal, I put it in a subfolder **/drupal**. Got everything set up and then moved everything into my root folder. When I went to the site I got this error:

```
Failed opening required '/home3/XXXX/public_html/drupal/modules/field/field.crud.inc'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home3/XXXX/public_html/drupal/modules/modules/field/field.module on line 20

```

Then I moved everything back to **/drupal** and still get the same error.

Can anyone tell me where I should be looking for the issue?

I looked in my `settings.php` file and didn't see anything about a directory listing. I looked in `/sites/default/settings.php` and couldn't find anything to do with directories.

Thanks for the help!

# Answer
for show the subdirectory site in the root I followed this guide. I hope it could be usefull for you too ^^
> 0 votes

---
Tags: configuration, wsod
---


# Question
Title: How to check the success of AJAX request for following chunk of code using Drupal.ajax()
The following code makes and AJAX request using Drupal.ajax() function. What I want is to have some kind of callback that will be executed once the request completed, basically the 'success' parameter of usual jQuery AJAX request. Adding `success = function(request, status)` parameter doesn't help either, or maybe I did something wrong ther. So how could I get a success callback to this request?

```
var ajaxSettings = {
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
};
var req = new Drupal.ajax(null, popContClass, ajaxSettings);
$(popContClass).trigger('add_event');

```

# Answer
> 1 votes
Could you provide more information on why the success function didn't work for you or what code you were using for it? This should work exactly like ajax settings in jquery Ajax since its just a passthrough, so your code would be something like this in your js:

```
$.ajax({
    url: eventEditFormUrl + '/nojs',
    selector: popContClass + '>div.content',
    wrapper: popContClass + '>div.content',
    event: 'add_event',
    method: 'html',
    progress: {
        type: 'none',
    },
    speed: 'fast',
    effect: 'fade',
    success: function(){
       $(this).html("woot.");
    }
});

```

# Answer
> 0 votes
In order to call javascript commands that are invoked via Ajax framework commands, Drupal uses a `success` callback (see the code in misc/ajax.js on HEAD of 7.x branch). Therefore if you specify your own `success` callback in settings for `Drupal.ajax`, no Drupal Ajax framwork commands will be executed.

In order to execute a custom code in `success` callback and leave Drupal Ajax framwork workings intact, you need to override the default Drupal Ajax framework's `success` callback with the one that executes both your code and that of Drupal Ajax framework, but you need to create Drupal.ajax object first.

Example:

```
var ajaxSettings = {
    // your settings here
};

// Initiate Drupal.ajax object
var req = new Drupal.ajax(null, element, ajaxSettings);

// Override success callback
req.options.success = function (response, status) {
  // Place your code here
  // your_code_here();

  // Proceed with default "success" callback code from Drupal Ajax framework

  // Sanity check for browser support (object expected).
  // When using iFrame uploads, responses must be returned as a string.
  if (typeof response == 'string') {
    response = $.parseJSON(response);
  }
  return req.success(response, status);
}

// Trigger event here

```

Another (and technically better) option is to call "success" callback code directly using `call()` method. This avoids code repetition.

```
var ajaxSettings = {
    // your settings here
};

// Initiate Drupal.ajax object
var req = new Drupal.ajax(null, element, ajaxSettings);

// Override success callback
req.options.success = function (response, status) {
  // Place your code here
  // your_code_here();

  // Call original method with main functionality
  Drupal.ajax.prototype.success.call(req, response, status);
}

// Trigger event here

```

Credit for the last approach goes to asghar as he described it in related topic on drupal.org.

---
Tags: ajax, javascript
---


# Question
Title: select nodes title start with charachter
I want to have query with `EntityFieldQuery` that return me nodes with title start with `A` or `B` but has not obvious method to use or in property condition, I dont want use `db_select` or `db_query`. in this link not comes `like` but it work ,but If I want use `REGEX` operator it return me error.

```
  $query=new EntityFieldQuery();
        $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'product_display')
        ->propertyCondition('status', 1);
$query->propertyCondition('title', '^(B|A)','REGEX');

```

# Answer
The reason it doesn't work is because there's no `REGEX` operator in MySQL.

You probably meant `REGEXP`, which does work in an `EntityFieldQuery`.
> 2 votes

# Answer
There is no database agnostic support for regex in EntityFieldQuery. The documentation in EntityFieldQuery::propertyConditon lists the available operators. As mentioned by Clive, this list is not complete. Apparently you can use any operator that is supported by your database backend.

As an alternative that should be supported across different database backends, you could build multiple queries using the `STARTS_WITH` operator and then merge the results.

Or you write a custom query using db\_query. Or use db\_select with or-linked conditions.
> 2 votes

---
Tags: entities, database
---


title: Edit date field html

text:
# Question
Title: Edit date field html
I would like to edit the html produced for a field. Is that possible to do this through a hook? I want to convert "date1 - date2" to "date1 to date2".

# Answer
You can override the theme function for the date range date field formatter: theme\_date\_display\_range().

For example, in your theme's template.php file you can add this:

```
/**
 * Override the themeing of a date field date range.
 */
function THEMENAME_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date - !end-date', array(
    '!start-date' => '<span class="date-display-start"' . drupal_attributes($attributes_start) . '>' . $date1 . '</span>',
    '!end-date' => '<span class="date-display-end"' . drupal_attributes($attributes_end) . '>' . $date2 . $timezone . '</span>',
  ));
}

```

Replace THEMENAME with the name of your theme.

Note in the return line the dash. The default is for that to be 'to'.
> 3 votes

---
Tags: datetime
---


# Question
Title: How to create content type programmatically with fields and vertical tabs
I'm creating a module using Drupal7.26 and want to create content type with different type of fields like radio/checkboxes/drupdown and textfields.
I'm following the last comment by Jason Gray in THIS thread and is working pretty well except it is not creating Fieldset, Vertical Tab Group and Vertical Tab when the module is installed.

What I did is:
I have created a custom module to create new Content Type by following SITEPOINT tutorial. And take the fields array by exporting of the node which I created manually using CCK with all fields that I want.
Now all the fields are showing in my newly created node by installing module, except (Fieldset, Vertical Tab Group and Vertical Tab) which I created by enabling Field group module.
**NOTE:** When I export the content type using feature as (test) it gives me 3 files as bellow:
1 - test.features.field\_base.inc (I take fields array from here)
2 - test.features.field\_instance.inc (I take instances array from here)
3 - test.field\_group.inc (it give me the bellow hook) which I'm not sure where/how to use it.I place it in both MYMODULE.install and MYMODULE.module files both didn't work.

```
    function test_field_group_info() {

    }

```

Any ideas would be appreciated.

# Answer
> 4 votes
Wooho :) here is the answer I was missing hook\_ctools\_plugin\_api() in my module

---
Tags: nodes, features, entities
---


title: Calculate redirect hash in drupal 7?

text:
# Question
Title: Calculate redirect hash in drupal 7?
I'm upgrading my site from D6 to D7, and want to move a section of the site to a better spot. That requires about 10000 redirects. (I use redirect module: https://drupal.org/project/redirect ).

With D7, the redirect table includes a hash ("hash - A unique hash based on source, source\_options, and language."). How can I build that, using PHP? I have a textfile with node/# and the old URLs. I can make them into a mysql table.

But while I can do basic PHP, I'm not advanced enough to understand the redirect.module source. The relevant bits are, I understand, lines 399-403:

```
$redirect->source = $path['original']['alias'];
$redirect->redirect = $path['source'];
$redirect->language = $path['original']['language'];
// Check if the redirect exists before saving.
$hash = redirect_hash($redirect);`

```

and lines 1069-1081:

```
function redirect_hash($redirect) {
  $hash = array(
    source' => $redirect->source,
    language' => $redirect->language,
  );
  if (!empty($redirect->source_options['query'])) {
    $hash['source_query'] = $redirect->source_options['query'];
  }
  drupal_alter('redirect_hash', $hash, $redirect);
  redirect_sort_recursive($hash, 'ksort');
  $redirect->hash = drupal_hash_base64(serialize($hash));
  return $redirect->hash;
}

```

Thanks!

# Answer
> 1 votes
Usually there is always a module that can help out.

In your case I recommend Path Redirect Import. It has a bulk import mechanism for redirects via CSV. It supports the Drupal 7 redirect module.

To get the redirects exported from D6 in the right format, check the Path Redirect Export module.

I believe that should do the trick for you.

I hope this helps you.

---
Tags: redirection
---


title: Get filename in webform with Rules

text:
# Question
Title: Get filename in webform with Rules
I need to get just the file name from a file submitted in a Webform.

In actions, I try to execute the following code at a "Show a message on the site" action:

```
$path = "[data:component-value]";/*a REPLACEMENT PATTERN that return http://mysite.com/files/webform/submittedfile.pdf*/
$file = basename($path);/*$file is set to "submittedfile.pdf"*/
echo $file; /*this *should* return submittedfile.pdf*/

```

But *ALWAYS* return http://mysite.com/files/webform/submittedfile.pdf

I've tested ltrim, rtrim, god\_trim\_for\_me and chop. And it always return the full URL.

What am I doing wrong?

# Answer
I have managed to find an answer to my question

What I am doing wrong:

$path need set before.

In the value: \[data:component-value\] Named the variable (ex: link\_from\_hell)

So, the next action you can manipulate the $patch.
> 0 votes

---
Tags: rules, webforms
---


title: How do I do a simple GROUP BY?

text:
# Question
Title: How do I do a simple GROUP BY?
I've got a view which represents a list of redirects. The view has two fields:

1. 'Destination'
2. 'Source'
3. 'Hash' (an indexed has based on the destination)

I'd like to generate a view which lists destinations along with the number of times a visitor has been redirected to that destination. If I were to write the SQL myself, I'd simply do:

```
SELECT destination, count(*) as redirects FROM redirects GROUP BY hash

```

However, no matter what I do I can't get Views to ONLY group by hash. This is what I've done:

1. Enabled aggregation (Advanced \> Aggregation\>
2. Enabled COUNT on the 'source' field.

What happens now is that Views COUNT on the 'source' field, but groups on both the 'destination' AND 'hash' field:

```
SELECT destination, hash, COUNT(source) FROM redirects GROUP BY destination, hash

```

How do I get Views to only GROUP BY the 'hash' field?

# Answer
I am not 100% sure but I would suggest you simply do the following:

* Choose Format = Table
* Then click on the settings for Table
* Change the grouping field to the "hash" field

Then aggregate the results based on the destinations.

However, when you use the redirect module in Drupal 7 there is a field available called "Redirect: Clicks". I wonder if this may help you.

I hope this may helps.
> 1 votes

---
Tags: views
---


title: Can't add column to renamed table

text:
# Question
Title: Can't add column to renamed table
When I first developed this module internally (not on Druple.com) the `module_schema` function created a table with the same name of the module (it was the only table, so it made sense. Short sighted.).

But I now need a 2nd table, so the first table should have a more sensible name. There is also a requirement for an additional field in the original table.

```
 function afd_pce_update_dependencies(){
   // update_7201 needs to run after update_7200.
   $dependencies['mymodule_field_mappings'][7201] = array(
     'mymodule_field_mappings' => 7200,
   );

   return $dependencies;
 }

 function mymodule_update_7200(){
      db_rename_table('mymodule', 'mymodule_field_mappings');
    }

 function mymodule_update_7201(){
   $spec = array(
     'type' => 'varchar',
     'description' => "The fieldset that this mapping belongs to",
     'length' => 15,
     'not null' => FALSE,
   );
   db_add_field('fieldset_type','mymodule_field_mappings',$spec);
 }

```

When I run `update.php` I get the error

```
Update #7201
Failed: DatabaseSchemaObjectDoesNotExistException:
Cannot add field <em class="placeholder">fieldset_type</em>.
<em class="placeholder">mymodule_field_mappings</em>: table doesn't exist.
in DatabaseSchema_mysql->addField() (line 325 of
{filepath}\includes\database\mysql\schema.inc).

```

# Answer
I think your mixing up table names and module names in `hook_update_dependencies()`.

First of all, you don't need `hook_update_dependencies()` to declare dependencies inside your own module. The updates will always be run sequentially, so that `mymodule_update_7200()` will always run before `mymodule_update_7201()`.

Then, if you want to use `hook_update_dependencies()`, you would use it to declare inter-module depenencies like this:

```
function mymodule_update_dependencies(){
  $dependencies['mymodule'][7201] = array(
    'other_module' => 7203,
  );
  return $dependencies;
}

```

Now to your error. Can you check in the system table record for your module what the current schema version is? From the code and the error message I would suppose, that the database is already at schema 7200 (at least officially) but that somehow the renaming has not been done. Is it maybe possible that you have altered the database manually?

**Edit:** You are mixing up the arguments to db\_add\_field. It must be `db_add_field('mymodule_field_mappings', 'fieldset_type', $spec);`
> 1 votes

---
Tags: database, updating
---


title: How to display a form in a panel page?

text:
# Question
Title: How to display a form in a panel page?
My goal is to display a form in a page made with panels. The form will be between content panes.

The single page (made with page manager & panels) will be like below:

1. Content Pane
2. Form
3. Content Pane

How can I achieve that, and display the form in a page made with panels ?

Update 2-4-2014: I found this article and created the following block that doesn't work (I am getting an error when trying to add that to panels). can sombody help make this thing work?

```
<?php
function my_answer_form_block_info() {
    $blocks = array();
     $blocks['my_answer_form'] = array(
            'info' => t('My-Answer-Form'),
            'cache' => DRUPAL_CACHE_GLOBAL,
    );

    return $blocks;
}

function my_answer_form_block_view($delta = '') {
    $block = array();
    switch($delta) {
            case 'my_answer_form':
                    $block['subject'] = t('My Answer Form');
                    $block['content'] = drupal_get_form('answer_node_form');
            break;
    }
     return $block;
}
  ?>

```

Note: Form ID is: "answer\_node\_form"

I am using the Answers Module. The form I want to put on the panel page is the Answer Form, that was created by the Answers Module. Is that a node form or a custom form?

# Answer
If it is node form you could use Form Block. It will create form in block and you could add that in content panes.

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.
> 1 votes

# Answer
If you want a simple form for user submissions I would recommend using webform. With this module you can expose it as a block and add it to a panel page.

If it is a custom form, for generation nodes or entities for example, I would recommend writing your own form with the Drupal Form API and exposing it as a block to put it on your panel page.

A good starting point for writing your own modules is the Drupal examples module. This gives you really good insight into how forms need to be structured and also how to create your own blocks.

I hope this helps you.
> 0 votes

---
Tags: forms, panels, chaos-tool-suite
---


# Question
Title: How to create a translation and get author and post date copied from the original node
When creating translations of news I want them to have the same author and post date as the original node, so that I (or the translator) don't have to copy paste. Anyone know a module or snippet for this?

# Answer
> 2 votes
The **Synchronize translations** module, part of the **Internationalization (i18n) package**, allows you to synchronize fields and other node elements.

After enabling it, have a look at *admin/structure/types/manage/your-content-type* options, in "synchronize translations", and check the boxes *author* and *post date*

# Answer
> 0 votes
If you didn't know about the **Synchronize translations** module like me, you could do a form\_alter() in a custom module that would prefill these, eg, something along these lines:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'article_node_form': // or whatever node type you want this to happen with...

      if (arg(1) == 'add' && !empty($_GET['translation']) && !empty($_GET['target']) && ($source = node_load($_GET['translation'])) && i18n_node_type_enabled($source)) { // this logic pulled from i18n_node_i18n_context_language()
        $form['author']['name']['#default_value'] = $source->name; // just changed $node-> to $source-> in the #description so it matches the new default value
        $form['author']['date']['#description'] = t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => !empty($source->date) ? date_format(date_create($source->date), 'Y-m-d H:i:s O') : format_date($source->created, 'custom', 'Y-m-d H:i:s O'), '%timezone' => !empty($source->date) ? date_format(date_create($source->date), 'O') : format_date($source->created, 'custom', 'O')));
        $form['author']['date']['#default_value'] = format_date($source->created, 'custom', 'Y-m-d H:i:s O'); // CORRECTION (had $source->date... in here originally)
      }

      break;

    // any other $form_id's here

  }

}

```

but I've only done a quick test using admin to see if it works; I am sure permissions would come into play if you or your translators didn't have the right permissions to change the author and/or date. Also, this only works I would imagine on the initial translation, eg, when the "add translation" link is in there and creates the url with the extra \_GET variables.

---
Tags: nodes, i18n-l10n
---


title: AJAX Edit Node and update

text:
# Question
Title: AJAX Edit Node and update
Im reading up on how to add AJAX functionality to nodes and am stuck. Where exactly do I place #ajax in order to make the edit field updae via ajax? Specifically is it an existing php, js, html, css file that handles this? Do I add it to the node or block? I've read that its fairly simple but drupal isn't my native language so i'm still learning.

I've tried using this module ajax\_form\_entitty

but it wont load the newly created node after submission it directs to a blank page. I've been told to point the node to a div and insert the div in the header, but I have no idea how that should look. here is what i've done (which doesn't work)

All help is appreciated

EDIT:

Reading Material I've tried following along with this as one possible way to go about it but have no clue how to implement anything.

# Answer
To answer the question of "where" do you add the AJAX functionality in a node form, the answer is in a form\_alter. That can be done in a custom module or the theme's template.php file. I recommend a module so the functionality remains even if you change your theme.

A great resource is the examples module which is a group of example modules with great comments that assist developers in implementing Drupal functionality. In fact, there's is a submodule called ajax\_example that adds ajax functionality to a a field in a node (exactly what you are looking for!). Here's an excerpt from ajax\_examples\_node\_form\_alter.inc:

```
/**
 * Implements hook_form_FORM_ID_alter() for the node form.
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    )
  );
  $form['container'] = array(
    '#prefix' => '<div id="ajax-example-form-node">',
    '#suffix' => '</div>',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ?
                          $node->ajax_example['example_2'] :
                          $form_state['values']['ajax_example_2'],
    );
  }
}

/**
 * Returns changed part of the form.
 *
 * @return renderable array
 *
 * @see ajax_example_form_node_form_alter()
 */
function ajax_example_form_node_callback($form, $form_state) {
  return $form['container'];
}

```
> 2 votes

---
Tags: ajax
---


# Question
Title: How can a user choose items from a view?
I've 3 types of users:

1. Author
2. Reader
3. Site Admin

**What I've done so far?:**

I've created Content Type named `Book`. `Authors`create account on my site & login & then add the information about the books they authored. I've a View with page-display named `books` which lists all the books.

**What do I need?**

1. `Reader` should be able to pick 'x' no. of books from the this view. The no. of books a `Reader` can pick depends on his level `Voracious Reader`, `Moderate Reader`, `Occasional Reader`.
2. After `Reader` choosing `Book(s)`, `Site Admin` will be see the list of books picked by all Readers.
3. He'll then ship the book to their address (offline) & update the status as "Shipped".
4. of course Readers should be able to see the list of all the books they've chosen along with its status.

**How do I accomplish the rest?**

# Answer
> 2 votes
Use flags module along with the default view it provides.

> Flags may be per-user, meaning that each user can mark an item individually,

You can create two flags one called `Marked` and an other one called `Delivered`. Reader should be able to flag a Book as Marked but only Site Admin should be able to mark a Book as delivered.

If you are looking for more control consider using Workflow and then defining the states `Marked` and `Delivered`. You can set the access levels accordingly for the status change.

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


title: Check for existing node titles

text:
# Question
Title: Check for existing node titles
Is there a way to Add autocomplete to Node Titles?

This way I could display duplicate content to users before they add a new post.

Any suggestions?

# Answer
Used Finder module as separate input box for people to check for existing titles.
> 0 votes

# Answer
Consider using Uniqueness Module

> Uniqueness module provides a way to avoid duplicate content on your site by informing a user about similar or related content during creation of a new post
> 0 votes

---
Tags: ajax
---


# Question
Title: How to trace Drupal 7 Core Logic Using Netbeans with xdebug?
I'd like to understand how Drupal core works by tracing core logic and how functions unfold. I installed Netbeans with xdebugger and started a new project. The project includes drupal installation run on localhost. I read several Netbeans quickstart manuals and began studying core by putting breakpoints. But when I start debugging the project they do not seem to work. Please explain any productive approach for studying drupal 7 core logic using Netbeans with Xdebug?

Thanks!

# Answer
> 4 votes
In my opinion, studying drupal core using netbeans and xdebug is somewhat too overwhelming. Starting in index.php will lead you through the whole bootstrap and other parts which do not need to be studied by someone who is starting to understand drupal. The most important parts to be familiar with are menu system and node system. These two parts are the basic building blocks on which you can build further (entities, taxonomy etc.). To study these, I would recommend the combination of 3 approaches:

I think xdebug comes later into this mix because it is a debugging tool (by definition) and even though jumping from function to function, from module to module can give you some understading of the flow of things, it is usually easier to just check it out in the documentation.

---
Tags: debugging
---


# Question
Title: Drush sql-sync Error: no databse record could found for target @mysite.local
I am attempting to sync a production database to a local environment. When I run something along the lines of:

```
drush sql-sync @mysite.prod @mysite.local --source-dump /path/to/dump --target-dump /path-to-dump --create-db --no-cache -y

```

I get the error:

> Error: no database record could be found for target @mysite.local

However, **drush @mysite.local sql-conf** returns the correct connection information, and **drush @mysite.local sql-cli** connects to the correct database as expected.

Further, **drush @mysite.local status** and **drush @mysite.prod status** return the expected status reports.

Aliases file contents (for institutional reasons, making changes to this file is not ideal):

```
<?php

$aliases['local'] = array(
  'parent' => '@parent',
  'env' => 'local',
  'site' => 'mysite',
  'uri' => 'mysite.com',
  'ssh-options' => '-o StrictHostKeyChecking=no ',
  'sites-subdir' => 'mysite'
);

$aliases['prod'] = array(
  'parent' => '@mysite.local',
  'env' => 'prod',
  'root' => '/var/www/html/mysite.prod/docroot',
  'remote-host' => 'xxxxxx.myhost.com',
  'remote-user' => 'mysite',
  'path-aliases' => array(
    '%drush-script' => '/usr/local/drush5/drush',
  ),
  // #destinations is a custom property
  '#destinations' => array(
    'releases' => "mysite@xxxxxx.myhost.com:mysite.git",
  ),
);

$aliases['stage'] = array(
  'parent' => '@mysite.prod',
  'env' => 'test',
  'root' => '/var/www/html/mysite.test/docroot',
  'remote-host' => 'xxxxxxxx.myhost.com',
);

$aliases['dev'] = array(
  'parent' => '@mysite.stage',
  'env' => 'dev',
  'root' => '/var/www/html/mysite.dev/docroot',
);

?>

```

Debugger output

```
Bootstrap to phase 0. [0 sec, 3.79 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.99 MB] [bootstrap]
Loading drushrc                                                      [bootstrap]
"/var/www/vhosts/docroot/sites/all/drush/drushrc.php" into
"drupal" scope. [0.01 sec, 4 MB]
Include /var/www/vhosts/docroot/sites/all/drush/commands     [notice]
[0.01 sec, 4.02 MB]
Cache HIT cid: 6.2.0-commandfiles-0-xxxxxxxxxxxxxxxxxxxxx     [debug]
[0.01 sec, 4.03 MB]
Bootstrap to phase 0. [0.06 sec, 9.36 MB]                            [bootstrap]
Bootstrap to phase 0. [0.08 sec, 9.36 MB]                            [bootstrap]
Found command: sql-sync (commandfile=sql) [0.08 sec, 9.36 MB]        [bootstrap]
Including /usr/share/pear/drush/commands/sql/sync.sql.inc [0.14 sec, [bootstrap]
9.38 MB]
Calling drush command init function: drush_sql_sync_init [0.14 sec,  [bootstrap]
9.58 MB]
Loaded alias @mysite.local from file                                    [notice]
/var/www/vhosts/docroot/sites/all/drush/aliases/mysite.aliases.drushrc.php
[0.25 sec, 9.6 MB]
Undefined index: root sitealias.inc:1168 [0.25 sec, 9.6 MB]             [notice]
Undefined index: root sitealias.inc:1168 [0.43 sec, 9.62 MB]            [notice]
Loaded alias @mysite.prod from file                                     [notice]
/var/www/vhosts/docroot/sites/all/drush/aliases/mysite.aliases.drushrc.php
[0.49 sec, 9.62 MB]
Loaded alias @mysite.stage from file                                    [notice]
/var/www/vhosts/docroot/sites/all/drush/aliases/mysite.aliases.drushrc.php
[0.56 sec, 9.62 MB]
Loaded alias @mysite.dev from file                                      [notice]
/var/www/vhosts/docroot/sites/all/drush/aliases/mysite.aliases.drushrc.php
[0.63 sec, 9.66 MB]
Undefined index: root sitealias.inc:1168 [0.63 sec, 9.66 MB]            [notice]
Backend invoke: ssh -o StrictHostKeyChecking=no                        [command]
mysite@myhost.com '/usr/local/drush6/drush
--backend=2 --verbose --debug --yes --uri=mysite.com
--root=/var/www/html/mysite.dev/docroot  sql-conf   --all 2>&1' 2>&1
[0.74 sec, 9.68 MB]
ssh -o StrictHostKeyChecking=no                                         [notice]
mysite@myhost.com '/usr/local/drush6/drush
--backend=2 --verbose --debug --yes --uri=mysite.com
--root=/var/www/html/mysite.dev/docroot  sql-conf   --all 2>&1' 2>&1
[0.74 sec, 9.68 MB]
Calling hook drush_sql_sync [3.34 sec, 9.72 MB]                          [debug]
Undefined index: root sitealias.inc:1168 [3.34 sec, 9.73 MB]            [notice]
Error: no database record could be found for target @mysite.local    [error]
[3.34 sec, 9.73 MB]
Returned from hook drush_sql_sync [3.34 sec, 9.73 MB]                    [debug]
Command dispatch complete [3.34 sec, 9.7 MB]                            [notice]
Peak memory usage was 11.99 MB [3.34 sec, 9.7 MB]                       [memory]

```

Any help debugging this would be greatly appreciated.

# Answer
First, an unrelated problem: use `--source-dump=/path/to/dump --target-dump=/path-to-dump`, as Drush options always use the '=' form for specifying values.

As for why sql-sync would fail to find the database record when the corresponding sql-conf works, that's a more difficult question. Show the contents of your alias records, and include output with the --debug flag.

**Update:**

Are both 'local' and 'prod' remote machines? Drush is using ssh to fetch @mysite.local's database record. If that's not correct, try removing the remote-host option from the alias definition. Drush tries to ignore remote-host for the local machine so that you can use the same record on every machine, but it might be getting that wrong.

If your 'local' site is supposed to be remote, it looks like you are using drush5 on the remote machine, and drush6 on the local machine. This is supposed to work, but backend invoke is slightly different between these two versions, and there may be some problem. Try using the same version of Drush on both ends, and see if that helps.
> 2 votes

---
Tags: drush
---


# Question
Title: Display different shipping rate depening on taxonomy terms
I would like to offer a different flat shipping to users depending on what taxonomy terms the product they have in their cart.

If a product tagged with "postage rate 1" I would like to display shipping rate 1. If they have a product tagged with shipping rate 2 I would like to display shipping rate 2. I would also like to if possible make it so that if the cart has items with each of the tags then one item shipping rate would win through (the most expensive one to cover costs I would think)

I have had a go with rules but I cannot figure out how to get the different shipping rates to display on taxonomy terms. I do have the commerce rules extra module installed if that will peform part of the solution

Thank you for looking

# Answer
I needed the exact thing for my webshop. Couldn't find it anywhere so a friend of mine made this module which works great! https://drupal.org/project/commerce\_taxonomy\_conditions

On my site every product has either the taxonomy term 'letter' or 'package' And then with that module you can add an extra condition to your shippingmethods to only use the products which that specific term.

If you are still in need for it then try it out :)
> 1 votes

---
Tags: taxonomy-terms, commerce
---


# Question
Title: Which hook do I use to alter product entity data in a product display?
In Drupal Commerce, which hook do I use to alter product entity data in a product display?\** And it needs to be a hook that fires each time I change an attribute that causes a different product entity to be loaded in the display.

I added a line item to my product type called "Comments". It is a textarea, and it has a field description too. Then, on my product type, I added the following fields:

* Customizable? (On/Off checkbox)
* Custom Field Label
* Custom Field Description

As each product entity is about to be displayed (whether it's the first one shown when the page loads, or I make a drop down selection to change which one shows), I want to check if that product entity is "Customizable". If it is, I want to rename the title of the "Comments" line item with the value stored in "Custom Field Label". And I want to change the Comments field description with the value stored in "Custom Field Description". If the product entity is NOT "Customizable", then I want to hide the field completely (such as by converting the field type from a textarea to a hidden field). This way, the "Comments" line item really only shows for the product entities we want it to, and it can have a custom label and instruction when it does show.

Any help someone can give is greatly appreciated. I am having a lot of trouble even figuring out which hook fires each time a product entity is loaded, either the first time, or when switched via ajax.

# Answer
**hook\_entity\_load** may be the answer that some folks are looking for in situations that differ from mine.

For my specific need, I discovered that everything I needed to accomplish could be done with **hook\_form\_alter**. The form\_state holds the value of the currently selected SKU in **$form\_state\['default\_product'\]-\>sku**. Here is a hook\_form\_alter function I wrote to accomplish my goals:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if(strstr($form_id, 'commerce_cart_add_to_cart_form_')) {

        // Load the current product entity
        $prod = commerce_product_load_by_sku($form_state['default_product']->sku);

        // Check and see if the produt is customizeable or not, and then react
        $customizeable = $prod->field_prod_customizable['und'][0]['value'];
        if(isset($customizeable) && $customizeable == 1) {
            // Grab the custom label and instruction
            $customize_label = $prod->field_prod_customize_label['und'][0]['value'];
            $customize_instruction = $prod->field_prod_customize_instruction['und'][0]['value'];

            // Alter the field to display the custom label and instruction
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#title'] = $customize_label;
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#description'] = $customize_instruction;
        }
        else {
            // If not a customizeable product, then make the field hidden and not required
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#type'] = 'hidden';
            $form['line_item_fields']['field_prod_comments']['und'][0]['value']['#required'] = 0;
        }
    }
}

```

Note that the textarea field I added to my Product line item type is called field\_prod\_comments. The fields I added to my product entity are field\_prod\_customizable, field\_prod\_customize\_label, and field\_prod\_customize\_instruction.
> 0 votes

---
Tags: commerce
---


title: Create Multiple Event Calendars

text:
# Question
Title: Create Multiple Event Calendars
I use the Event Calendar on my site. I have a request to have a separate calendar for each department. Is this possible with in the same site?

If so please share the knowledge.

# Answer
> 0 votes
Pass the department id in the url and then use it as as a contextual filter in the same view.

Check out https://drupal.org/node/1578558

> Contextual filters work similarly to regular filters, but there is one important difference. Instead of setting a filter value manually, the value is fetched from variables sent programmatically to the view.

# Answer
> 0 votes
Is it a personal calendar you need - for each individual or for a group.

For an individual settings are like this (nevermind the entity reference fields). Important fields are highlighted. In this calendar a user can only see his own events

or for a group calendar where only members of the groups can see events - use the settings below.

Nodeone.se do great screencasts if you want to learn about either views or organic groups. Hope this helps.

You also need a groups audience field in your event form.

---
Tags: datetime
---


# Question
Title: Can't get template suggestions to be recognized
I am using D7. I have declared a custom template `facet-item.tpl.php` in a module named `dsfacet`. My code goes as follows:

```
/**
 * Implements hook_theme().
 */
function dsfacet_theme($existing, $type, $theme, $path) {
  return array(
    'facet_item' => array(
      'variables' => array('facet_name' => NULL, 'facet_values' => array()),
      'template' => 'facet-item',
    ),
  );
}

```

This custom template is invoked from another template with the following code:

```
<?php foreach ($facets as $name => $values): ?>
<?php print theme('facet_item', array('facet_name' => $name, 'facet_values' => $values)); ?>
<?php endforeach; ?>

```

Everything works great so far, but I'd like my theme to use more specialized templates based on the facet name.

So here's what I did:

1) I declared a template suggestion based on the facet name:

```
/**
 * Implements template_preprocess_HOOK for facet-item.tpl.php.
 * Adds template suggestions.
 */
function template_preprocess_facet_item(&$variables) {
  $variables['theme_hook_suggestions'][] = 'facet_item__' . $variables['facet_name'];
}

```

2) I changed the theme invocation to take into account the facet name:

```
<?php print theme('facet_item__' . $name, array('facet_name' => $name, 'facet_values' => $values, 'node' => $node)); ?>

```

3) I created some templates based on facet names:

```
facet-item--address.tpl.php
facet-item--phone.tpl.php
...

```

I then cleared the cache but... nothing happens. Only the main template `facet-item.tpl.php` is used. After a few hours spent on this, I'm at my wit's end. Any ideas?

(I've tried hard-coding the facet name everywhere to make sure it wasn't a problem with my variables... I've also tried every possible permutation of singe/double dashes/underscores...)

# Answer
> 3 votes
It took me a bit to figure this out and what I came up with is that the issue appears to be that Drupal's Theme System will only look for dynamic templates if they are in an actual theme, not in with a module.

So, you can do one of two things, the first one obviously being to copy all of your `facet-item` templates into your theme directory and call it a day after clearing caches for Drupal to pick them up.

Or... you could get creative like the Views Module does and create theme registry hooks for each of the template files like so:

```
function dsfacet_theme($existing, $type, $theme, $path) {

  $hooks=array();
  $modulepath = drupal_get_path('module', 'dsfacet');

  $hooks['facet_item']= array(
    'variables' => array('facet_name' => NULL, 'facet_values' => array()),
    'pattern' => 'facet_item__',
    'template' => 'facet-item',
    'path' => $modulepath . '/tpl/facet-items',
  );

  $hooks += drupal_find_theme_templates($hooks, '.tpl.php', $hooks['facet_item']['path']);
  // $hooks += _views_find_module_templates($hooks, $hooks['facet_item']['path']);

  return $hooks;

}

```

which if you have Views installed will actually use Views' `_views_find_module_templates()` function to do all the work for you. (it basically goes through the directory passed to it and looks for template files and creates `$hooks['facet_name__foo']` for each one it finds.) If you don't have or want Views installed, you can just copy it out of `views.module` and include and rename it accordingly in your own module.

ADDITION/CORRECTION: DUH; YOU CAN USE `drupal_find_theme_templates()` just as easily without worry about using/including Views' similiar private implementation.

And now if you have put all your `facet-item` templates under your module in their own directory structure (mostly so the find template function doesn't find any other templates and spin its wheels doing extra work) and cleared caches, you should now see all of your templates.

---
Tags: theming
---


# Question
Title: Trying to print results of Apache Solr Search
I'm trying to print to Drupal message, the indexed items as an object in Drupal.

Here's what I have so far:

```
function resource_library_search_apachesolr_process_results(&$results, DrupalSolrQueryInterface $query){
    drupal_get_message(print_r($results, true));

    }

```

I'm not seeing any results on any of my search pages - am I doing anything wrong? How do I get information on the indexed items as an object?

# Answer
If you want to **print** to the drupal messages, you need to use `drupal_set_message` instead of `drupal_get_message` first.
> 1 votes

---
Tags: 7, search
---


title: node_save does not save body content

text:
# Question
Title: node_save does not save body content
I'm trying to create a node using PHP. The below code works fine until I use any language code other than 'LANGUAGE\_NONE'.

```
$node = new stdClass();
$node->type = 'recipe';
node_object_prepare($node);
$node->uid = 1;
$node->language = LANGUAGE_NONE;
$node->title = $item['title'];
$node->body[$node->language][0]['value']= $item['description'];
$node->body[$node->language][0]['format']= 'plain_text';
node_save($node);

```

If I use "en" instead of "LANGUAGE\_NONE" then the node is created without any field being populated. That is, there is only a title; the body is blank.

Locale module is enabled and i18n is installed and enabled.

What should I do?

# Answer
You also need to set the language of the fields.

```
$node->language = 'en';
$field_langcode = field_language('node', $node, 'body');
$node->body[$field_langcode][0]['value']   = $body_text;
$node->body[$field_langcode][0]['summary'] = text_summary($body_text);
$node->body[$field_langcode][0]['format']  = filter_default_format();

```

See this comment (https://drupal.org/comment/5464106#comment-5464106) for more info.
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: Drupal function field_get_items vs user_load
In Drupal, I want to read a custom field value for a group of users while logged into an admin account. I only need 1 field value from each user, the same field and I do not need this information cached.

When I use `user_load` it requests the user object as I only need one field this is very inefficient.

So I investigated `field_get_items`, but I cannot see how to use this function without first using `user_load`. I have attached my code and **MARKED** the line that is giving me an issue.

1. how can I use `field_get_items` without using `user_load`, if not possible is there a efficient way of doing this? Please don't mention `user_load_multiple`
2. with user\_load does setting , $reset = TRUE prevent Drupal caching the data or does it force a cache reset, get the data from the DB and then re-cache the new data?

Code I use:

```
$user_a = array();  //  This is the array of URIs we need to query
foreach ($user_a AS $uid){
  $account = user_load($uid, $reset = TRUE);  // access the user objects, one at a time
  $fullname[$uid] = $account->field_fullname[LANGUAGE_NONE][0]['value']; // extract value
}

$user_a = array();  //  This is the array of URIs we need to query
foreach ($user_a AS $uid){
  **$account = user_load($uid, $reset = TRUE);**
  $fullname[$uid] = field_get_items('user', $account, 'field_fullname');  // extract array
  foreach ($fullname[$uid] as $item) {
    $fullname[$uid] = $item['value'];  // extract value
  }
}

```

# Answer
> 0 votes
You can uses `field_attach_load()` to load the value of a single field for multiple entities (users are entities). You will need an array of stub entities for your users, which can be build using `entity_create_stub_entity()`. You will also need the field ID of your field, which can found using `field_info_field()` or `field_info_read()`.

After using `field_attach_load()`, you should be able to get the values of the field using `field_get_items()`.

Note the `field_attach_load()` may inject data for other fields into the stub entities, for example if they are read from a cache.

# Answer
> 1 votes
No, You can't use `field_get_items` without the loaded user object. As the entity has to be passed as the second argument as illustrated in documentation.

Any reason why you hate `user_load_multiple`? As `user_load` itself uses `user_load_multiple`.

If you don't want to retrieve that huge amount of arrays. You can consider building your own query to retrieve just the field you want.

---
Tags: 7, entities
---


# Question
Title: Check if a panel page is enabled programmatically?
I need to be able to verify if a panel page (which is just a variant of a ctools page) is enabled or disabled. How would one do this, programmatically? If it is disabled, how would one enable it, programmatically?

# Answer
You can use

`panels_load_display`

Then check the `disabled` flag for page status.
> 1 votes

---
Tags: 7, panels, chaos-tool-suite
---


# Question
Title: Separate drupal view filters from the results
I implemented a search index using Drupal Search API, and then created a view using that search index. In my view I added filters on searchable fields. My search is working very well.

However, my clients want to have the search filter controls in the sidebar and the search results in the main content region. But my filter controls and results are part of a single view. It is possible to separate them?

**Drupal version : 7.26**

# Answer
> 0 votes
I haven't used the Drupal Search API but if you are creating a View with exposed filters, you can have them put in a Block instead of being part of the View. Then you can put that Block anywhere you want. To do this, you go into the Advanced Settings of your View:

and in **Exposed form in block:** select `Yes` instead of the default `No.` Then you can go into the Block UI and place the newly created block wherever you want.

One interesting effect: If you don't restrict this block to the page of the View in the Block UI, it will show up on all pages, and if your users then select any of the filters in it and hit apply, that will take them to the View page and results.

---
Tags: views, search
---


# Question
Title: How to display all nodes by user on his profile page
I want to create a view of "users" `/profiles/<RealName>` which lists selected fields from user content type. I accomplished this. But now, I want the same view to display selected fieds from the nodes created by this user.

I tried to do it by myself, but I'm unable to add relation to desired content type.

**PS:** I'm a newbie so kindly throw some details in your answer.

# Answer
1.Create a view for content of type all
2.Inside the view display node title and all other fields as per your requirement.
3.Add a contextual filter content : author uid
4.While adding that you will have a option for provide a default value
5. select that option and inside that use filter by 'currently logged in user'.
6. Save it by this you will be able to see all the nodes of current logged in user.
7. Inside the path you can enter just any path like '/my-nodes'. and you are done.
8.If you want you can avoid providing default value and switch to manual input by placing the path as '/my-nodes/%' and then just add contextual filter as 'content : author:uid' without default value(depends as per the requirement).
9.For user name you can add a relationship **content author:uid** then
in the contextual filter use **User name** with relationship **author:uid**
> 5 votes

---
Tags: 7, views
---


title: Sorting in Filed Collection Views

text:
# Question
Title: Sorting in Filed Collection Views
I am using Field Collection Views in Drupal and everything works fine, except Sorting. I am able to rearrange the Field Collection items in Edit form using both drag-and-drop also manually using Row weights option.

I would like the the Field Collection View results to be sorted by this Row weight, could you please guide how I could acheive this.

# Answer
> 0 votes
Found a very easy workaround via DraggableViews module and it works just fine.. the step-by-step instructions could be found here..

Custom Sort Drupal Content with the Draggable Views Module

Thanks to the Author - Kronda Adair. :-)

# Answer
> 3 votes
This could be achieved by creating a relationship, and using Delta to sort. Let us say that the field collection field's name in the entity is field\_slides.

Create a relationship with '**Field collection item: Entity with the Slides (field\_slides)**'. Check the box for - Require this relationship

---
Tags: views, entities
---


title: Apply template to a specific page

text:
# Question
Title: Apply template to a specific page
I have a requirement to apply template to a specific page and not to the pages following the same url pattern. For example I have a page with the path /asia. I also have pages with the paths /asia/india, /asia/china etc. I would like to create a template which applies only for /asia and not for other paths. I created the template file page--asia.tpl.php but it is getting applied for /asia/india and /asia/china as well. Is there a way to specifically map the template to this specific path?

# Answer
To overwrite Drupal defalut suggestion, You can make your own suggestion for template.

In your case you have defined a menu called asia for that specific template is required, to implement this use this code

```
 **
 * Implementation of hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$variables){
  if(isset($variables['asia']) && arg(1) == '')
    $variables['theme_hook_suggestions'][] = 'page__asiapage';
}

```

create a tpl file in theme called page--asiapage.tpl.php, it will work.
> 2 votes

# Answer
Follow the below points:

1. Create a file with the name "page--node--nodeid.tpl.php" template.
2. Replace nodeid with the node you want to theme.
3. Clear the performance.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do I build a dynamic query in Drupal 7 equivalent to this SQL query?
I want to make this SQL query into a dynamic drupal query:

```
SELECT name, u.uid, COUNT( n.nid ) AS total_written
FROM users u
LEFT JOIN node n ON n.uid = u.uid
GROUP BY u.uid
ORDER BY total_written DESC

```

I do not know where i should append the COUNT. This is what I tried:

```
$query = db_select('users', 'u');
$query->leftJoin('node', 'n', 'n.uid = u.uid');
$query
  ->fields('u', array('uid', 'name',))
  ->fields('u', array('COUNT(n.nid)', 'total_written')) # Wrong
  ->groupBy('u.uid')
  ->orderBy('total_written', 'DESC');

```

How do I append the COUNT to the dynamic query?

# Answer
```
$query = db_select('users', 'u');
$query->leftJoin('node', 'n', 'n.uid = u.uid');
$query
  ->fields('u', array('uid', 'name',))
  ->groupBy('u.uid')
  ->orderBy('total_written', 'DESC');

// Add the COUNT expression
$query->addExpression('COUNT(n.id)', 'total_written');
$results = $query->execute();

```
> 6 votes

# Answer
You can use Query coder module to convert static query to dynamic query. Here is an excerpt about it from its project page:

> Convert SQL query to Drupal Database abstraction layer code.
> 3 votes

# Answer
Try this one,

```
$query = db_select('users', 'u');
$query->leftJoin('node', 'n', 'n.uid = u.uid');
$query->fields('u', array('uid', 'name',));
$query->addExpression('COUNT(n.id)', 'total_written');
$query->groupBy('u.uid')
  ->orderBy('total_written', 'DESC');

```

More info at - http://drupal.org/node/310075#expressions.
> 2 votes

---
Tags: database
---


# Question
Title: Which image editor can be used within Drupal for creating flowcharts?
I am looking for an image editor within Drupal. Particularly, I need something that will help me create flowcharts and save them directly.

The idea is to avoid using an offline image editor, to make the site more user-friendly.

Any pointers?

# Answer
> 2 votes
Try Image Editor module

> integrates several popular online image editing services into Drupal:

There are integrations with quite a few popular online image editing services.

---
Tags: media
---


# Question
Title: Create a rule based on specific URL being visited
I have set up a rule on my website so that when a content writer creates an article, it sends me an email notification and also the body content of the node so I can review it. Only after I have reviewed it and changed a field on the node to mark it as reviewed will it be published. I often get the email on my smartphone and want a quick way to email back the site so automatically publish the article. Does anyone know what rule would do this for me?

# Answer
Publish content

> Exposes publish/unpublish links to your views, making it easy to streamline workflows for reviewers, editors and publishers.
> 0 votes

---
Tags: rules
---


# Question
Title: How to update url_alias after SELECT FROM url_alias
After a rather clumsy migration by a previous developer, my new client's site has a whole bunch of incorrect paths, which I'd like to update in bulk (nearly 7000 nodes, so I'll not be doing this by hand).

In particular, their forum topics are aliased like "/content/12345" rather than "forum/12345" as desired.

I've pretty much figured out how to do this directly in MySQL, but I've hit a snag - MySQL won't allow me to update a table I've done a select from, at least in this nested query.

Here's my query:

```
UPDATE url_alias SET alias = REPLACE(alias, 'content/', 'forum/') WHERE alias in (SELECT alias FROM url_alias LEFT JOIN node ON CONCAT('node/',node.nid) = url_alias.source WHERE node.type = 'forum');

```

and MySQL says:

```
ERROR 1093 (HY000): You can't specify target table 'url_alias' for update in FROM clause

```

Perhaps I should give up and do this in two stages in PHP...? Or is there in fact a way to do this directly in MySQL?

# Answer
Regarding the query, you can do the query using a temporary table:

```
CREATE TABLE `tmp` ( alias varchar(255));

INSERT INTO tmp (SELECT alias
FROM url_alias LEFT JOIN node
ON CONCAT('node/',node.nid) = url_alias.source
WHERE node.type = 'forum');

UPDATE url_alias
SET alias = REPLACE(alias, 'content/', 'forum/')
WHERE alias in (SELECT alias FROM tmp);

DROP TABLE tmp;

```

But if there are lots of those aliases with all different cases, it's better to follow the following steps:

1. Delete all records from the url\_alias table.

TRUNCATE TABLE url\_alias;
2. Go to your admin interface at yoursite.com/admin/config/search/path/patterns and define the patterns for the needed node types.
3. Go to the 'bulk updates' tab of the URL Aliases definitions (yoursite.com/admin/config/search/path/update\_bulk) and bulk update all content paths.
> 2 votes

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


# Question
Title: Can I use Drupal plugin in managing news?
Can I use the plugin of Drupal twitter feed on managing news? Is there a twitter feed for Managing News? Sorry for this dumb question, as I was new on this content management system.

# Answer
Yes you can use Twitter Feed! with Views & OAuth modules and you have to enable OAuth based access for Twitter, you must register your application with Twitter and add the provided in Twitter setting!
> 1 votes

---
Tags: theming, feeds, social-network
---


title: Edit php code on a webform

text:
# Question
Title: Edit php code on a webform
I need to set an auto response message on a Webform 7.x-3.19. I understand that I need to add a script which is going to do the job. My question is which php file should I edit to do so?

# Answer
> 0 votes
I don't have the exact answer to your question but I can give you some advices to how you can do.

First option, UI way, You can try the "Rules" Module with "Webform Rules" Module. It gives you the ability to do some operations on given context. I don't know that module, but it seems to be the easiest solution.

---

Second option, Dev way, you can manually hook your webform and add php code. You have to implement the "hook\_form\_FORM\_ID\_alter" hook You can retrieve webform form\_id by following this answer of this post. In your hook implementation, add your custom submit function like the following snippet :

```
function YOUR_MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    if(isset($form['#submit'])){
        $form['#submit'][] = 'your_custom_function';
    }
    else{
        $form['#submit'] = array('your_custom_function');
    }
}

```

---

Some usefull links :

---
Tags: webforms
---


# Question
Title: Does not using node_save for updating nodes impact SEO for our site
We changed our node updation process from using node\_save() to manually updating the nodes via db queries.

What dramatic change we have seen is that number of people coming to us via seo has dropped significantly after this change.

Does not using node\_save impacts the SEO in any way for example : 1) It impacts the site map which we are not doing manually. 2) It updates a particular field important for SEO which we are not doing 3) Any thing extra

**EDIT:** On further checking the sitemap we have found that Last Modified date is not getting changed in the xml sitemap for the nodes that are updated using the manual process.

# Answer
> 5 votes
You should never manipulate entities directly in the database - even if you're 100% sure you've covered everything that core needs to do when an entity is saved, any number of contrib modules you have installed could need to process things too. How that affects your site is completely down to what you have installed, and how you have that set up.

One of the bigger problems you'll have is that the correct field/entity caches won't be cleared, leaving your database and front end in a potentially inconsistent state. This could include stale meta tags, page content, etc, etc.

I can't comment specifically on your SEO, but certainly if you bypass the proper way of saving/updating data, you shouldn't be surprised to see all sorts of problems arise.

---
Tags: nodes
---


# Question
Title: Avoid duplicates on a view based on results from another view
I have a node type and two views:

* One displaying the last 3 elements with a field marked as «important».
* Another with 3 random elements, marked as important or not.

I don't want the views to repeat nodes.

Since the "lasts" views should always display the last 3 important elements, I thought about filtering the nodes on the random view, but I don't know how.

I managed to do it for a single node in another context. When viewing a node, choosing «Provide default value» with some PHP code combined with the option «Exclude», I can manage to hide that node from the views.

```
$node = menu_get_object();

if (isset($node->nid)) {
   return $node->nid;
}
else{
  return 0;
}

```

Suppose I can get the nodes shown on the "lasts" views programatically. Then what? This approach will only work to filter out a single node, not the three I'll get from that view.

Any ideas?

# Answer
In the contextual filters, there's an option called «Allow multiple values» just above «Exclude». That option lets you return multiple values separated by commas (and) or mores (or).

So, I just use this code in the «Provide default value» field:

```
$my_view_name = 'videos';
$my_display_name = 'otros_importantes';

$my_view = views_get_view_result($my_view_name, $my_display_name);
if ( $my_view!=null ) {
  foreach($my_view as $view_row){
    $nodos[]=$view_row->nid;
  }
}

if(isset($nodos)){
  return implode(",",$nodos);
}
else{
  return 0;
}

```

And that's all, the nodes shown on that display are ignored.
> 0 votes

---
Tags: views
---


# Question
Title: Wyswig editor not showing to authors in Full HTML mode for Authors
I am using wyswig with tinymce 3.5 for my drupal site. The editor is not working for Authors in FULL HTML mode.it is not showing any action after changing it to plain text or full html.

I have rebuilded permissions also tried Full Html Text format (and wysiwyg) show only for administrator role this solution, cleared cache but its not showing for the authors. Not able to resolve whether it is permission issue or js.

Also this issue is came after i am using book access module. Check image for reference.

# Answer
> 0 votes
The issue is resolved as it is js error. I fixed this issue from this solution(https://drupal.org/comment/6313896#comment-6313896).

As i am using wyswig 7.x-2.1 but the above fix is given for 7.x-2.0 which is applied clearly for my version too. The below fig. shows that the js error.

---
Tags: users, input-formats, wysiwyg
---


# Question
Title: Validation error on back button in Multistep Form
Validation errors with a back button on Multistep form.

I used form alter for this but this is also not working below are my code.

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{ if($form_id=='dataset_node_form')
{
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

```

# Answer
Enable devel module. Then put a dpm to make sure that your code is being called.

```
function mymodule_form_alter(&$form, &$form_state, $form_id){   if($form_id=='dataset_node_form')
{
 dpm($form, 'From my custom module');
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

```

If your message shows up then some other module is overriding your form\_alter. You can implement `hook_module_implements_alter` in your custom module to make sure that the form\_alter of your module is called last.
> 0 votes

---
Tags: forms
---


# Question
Title: Can I change the order in which hook implementation by different modules are called?
In D6, I use a contrib module, but I would like to override a small bit of its behavior. I have a custom module for that, but my implementation of the relevant hook is called before the implementation in the contrib module, and so the contrib module's version "wins".

Is there any way to change it, and force my own hook to be called last?

Here are the specific details:

I would like to remove the default "Anonymous" user name for unregistered users in the comment form. I created a small custom module, tweak\_comment\_form, that implements form\_alter hook and removes the default value from the name field (see the answers to my previous question about that).

However I also use a contrib module called RealName, which also implements form\_alter. RealName does what I want for registered users (replaces user name with "real name"), but re-assigns default value to the name field.

# Answer
> 7 votes
Yes, very simply, you need to set the weight of your module to be heavier. There's a few ways you can do this, but if your module is a contrib module being release back to Drupal.org then the best way is to set it in `hook_install()` with code like:

```
db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULE'");

```

Alternatively you can use the Utility module to set module weights from the module page, however this is only for your personal installation.

# Answer
> 4 votes
Just as additional helpful information in drupal7 you have hook\_module\_implements\_alter.

There you can change hooks of other modules, too, for example move you module to the end/the start.

# Answer
> 1 votes
```
function my_module_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'the_hook_to_change') {
    return;
  }
  $module = 'my_module';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);

  $implementations = $group + $implementations; // If you want your implementation to run first.
  //$implementations = $group + $implementations; If you want your implementation to run last.
}

```

Small Modification based on https://api.drupal.org/comment/48623#comment-48623

---
Tags: 7, hooks
---