# Question
Title: Creating Nodes and Referenced Nodes at Same Time
I have a situation where I would like to be able to create nodes and referenced nodes at the same time. Are there any solutions for this that work well for this?

To clarify what I am talking about, consider the following situation (*highly* simplified for the sake of explanation):

There is a content-type **Class** that has a node referenced field, **Student**. I would like to have users be able to create **Class** nodes and **Student** nodes at the same time. I would also like them to be able to use the normal node reference auto-complete to pick a **Student** who happens to already exist.

Ideally, I would like all of this to work from a single page, and also work within the confines of the Drupal permission system so I can have various roles and various permissions.

Yes, I know that in this case **Student** would be best served as a user (rather than a node), but **Class** and **Student** are just to illustrate the situation. The real scenario really does need node references.

There is a similar question to this, Creating referenced nodes together with parent node, but I am specifically interested in Drupal 7 solutions only.

EDIT:

Not just looking for existing modules, but also head starts for custom code.

# Answer
I use References dialog, which puts a small "+" on existing reference fields allowing the user to create a new **student** directly from the **class** node edit form.
> 4 votes

# Answer
For a couple different sites now, I've done this using a ctools modal, and here's the basic outline of how I've implemented it (very simply):

* Create a custom page callback in your module's hook\_menu() that displays a basic node form for the node you want to reference (for a 'student' node, just have a name field and maybe a graduating year field). On that form, in your submit callback, save the node using node\_save(), and store the node ID (which should be at $node-\>nid after you pass a new node object to node\_save()) in the form's `$form_state['storage']['student_id']`.
* Alter the master/Class node form using hook\_form\_alter(). You need to do a few things here:

First, you need to add in the ctools modal javascript and functionality so ctools knows what to do with your special link:

```
// Add in ctools modal js and functionality.
ctools_include('modal');
ctools_modal_add_js();

```

Second, you need to add a link to the page callback you created in step 1 in hook menu, and with that link, add the class 'ctools-use-modal'. So, for example:

```
// Add link to custom student form callback with ctools modal.
$form['add_student_link'] = array(
  '#markup' => l(t('Add Student'), 'mymodule/add-student', array('attributes' => array('class' => array('ctools-use-modal')))
);

```
* In your custom page callback, you need to do a few things to make it work with or without JavaScript, and with ctools' form functions.

Here's an example callback:

```
<?php
function mymodule_student_form_callback($js = FALSE) {
  // Make sure $js (set by ctools) is TRUE/loaded.
  if ($js) {
    // Add in ctools modal form stuff.
    ctools_include('modal');
    ctools_include('ajax');
    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Create a Student'),
    );

    $output = ctools_modal_form_wrapper('mymodule_create_student_form', $form_state);
  }
  else {
    return 'Javascript must be enabled for this feature to work.';
    // Or, if we wanted to load the form normally...
    // return drupal_get_form('mymodule_create_student_form');
  }

  // If the form is executed, dismiss the form and reload the page.
  if ($form_state['executed']) {
    $commands = array();

    // Close the frame.
    $commands[] = ctools_modal_command_dismiss();

    // Use one of the ajax framework commands to place the returned
    // student node nid into the proper form value, placholder div, etc.
    // See: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax_commands/7
    $commands[] = ajax_command_append('#student-id-placeholder', $form_state['storage']['student_id']);

    $output = $commands;
  }

  // Render the output.
  print ajax_render($output);
  exit();
}
?>

```
* In `mymodule_create_student_form($form, $form_state)`, build your form like you normally would, and then in the `mymodule_create_student_form_submit(form, &$form_state)` (submit) function, set the value of the NID of the newly created student node in `$form_state['storage']['student_id']`. This is how you'll get ctools/AJAX to pass back the new nid to your original Class form.
* In my situation, I was using the modal to spit back some markup to the original page, so I passed the markup into a placeholder div using `ajax_command_append()`, then I had some jQuery on the original page monitoring the placeholder div, and when it found content in it, it would move the HTML into the proper place elsewhere on the node form. In your case, you'll need to populate a single or multi-value node reference field, which may be a little more complex. I haven't needed to do that yet... so I don't have more advice to offer for that part of the equation.
> 8 votes

# Answer
An option might be to add node support to the Inline Entity Form module.

EDIT: Inline Entity Form has node support nowadays.
> 4 votes

# Answer
Following modules can be used in Drupal 7:

1. https://drupal.org/project/noderefcreate
2. https://drupal.org/project/nodeconnect
3. https://drupal.org/project/entityconnect
4. https://drupal.org/project/inline\_entity\_form

Noderefcreate only create new node if it does not exist by using autocomplete wizard. Nodeconnect and entityconnect provide add/edit button at node reference, if autocomplete wizard is used. Nodeconnect only provide it for node reference whereas entityconnect provide it for node reference, entity reference, term reference and user reference.

Inline\_entity\_form provides two extra widget for entity reference (only).
> 2 votes

# Answer
If this is really similar to the School scenario and your Students can join multiple Classes I would use:

* 3 content types: **Student** *(\*-1)* **Attendance** *(1-\*)* **Class**
* Form Block to enter Student data directly in a block;
* Views Field to display a view with a list of Students attending a Class;

This would also require using Token, filtering the view depending on the Class nid and setting up a default value for the Attendance node reference field as the current Class nid.

Eventually you could map your Student content type to User with a user reference.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to change the database drupal forms send to
It's super easy using php and SQL but how do you change the default database drupal 6 saves posted data in the forms? To an external database?

# Answer
> 6 votes
I would try reading through How to connect to multiple databases within Drupal (notably, the Drupal 6 section towards the end.

Basically, in your `settings.php` file, convert the `$db_url` to an array, and add the secondary database:

e.g.

```
$db_url = 'mysql://drupal:drupal@localhost/drupal';

```

becomes

```
$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';
$db_url['db2'] = 'mysql://user:pass@localhost/db2';

```

Then create a submit handler that either compliments or overrides an existing form submit handler and use `db_set_active` to connect to the secondary database, save the data, and then switch back.

e.g.

```
function MYMODULE_MY_EXTRA_SUBMIT_HANDLER($form, &$form_state){
  // Switch to db2
  db_set_active('db2');

  // Do all your form processing and database transactions

  // Connect back to default Drupal database
  // *Note* If your primary db is keyed with "default", then you don't need to
  // pass an argument to db_set_active().
  db_set_active('default');
}

```

---
Tags: forms, database
---


# Question
Title: How to stop Privatemsg showing user role in 'To' field
With the module Privatemsg (v7.x-1.3) the 'To' field will show the username and then their role in brackets when composing a new message with the user id passed in the url:

```
/messages/new/567

```

I've searched the code but cannot seem to find where the role is being added so that I can disable it. Does anyone know?

# Answer
> 1 votes
Inside the privatemsg module, in `hook_menu` search for `$items['messages/autocomplete']` this is where the menu defines the auto complete path.

Search for `privatemsg_autocomplete` function where the output is defined.

**UPDATE:**

To remove just the role, here is a patch for that. Here is a thread on drupal that shows how this has progressed https://drupal.org/node/1852746

# Answer
> 0 votes
I've found what I was looking for in the file 'privatemsg.theme.inc' within this function:

```
function theme_privatemsg_username($variables) {
  $recipient = $variables['recipient'];
  $options = $variables['options'];
  if (!isset($recipient->uid)) {
    $recipient->uid = $recipient->recipient;
  }
  if (!empty($options['plain'])) {
    $name = check_plain(format_username($recipient));
    if (!empty($options['unique'])) {
      $name .= ' [user]';
    }
    return $name;
  }
  else {
    return theme('username', array('account' => $recipient));
  }
}

```

I've just commented out the lines below which mean it won't add the text ' \[user\]' after the name of a user.

```
    // if (!empty($options['unique'])) {
    //   $name .= ' [user]';
    // }

```

As I'm also using the sub module 'Privatemsg roles' I've edited the file 'privatemsg\_roles.module' and within this function:

```
function theme_privatemsg_roles_format($variables) {
  $role = $variables['recipient'];
  $options = $variables['options'];
  if (!empty($options['plain'])) {
    $name = $role->name;
    if (!empty($options['unique'])) {
      $name .= ' [role]';
    }
    return $name;
  }
  return t('%role (role)', array('%role' => $role->name));
}

```

Commented out the lines below to make sure a role is always marked as such.

```
// if (!empty($options['unique'])) {
  $name .= ' [role]';
// }

```

---
Tags: privatemsg
---


# Question
Title: Drupal does rewrite url but can't load css/themes
I have an url rewriting issue with my drupal 7

I'm trying to rewrite for example `index.php?q=categorie&categorie=laars` to `categorie/laars.html`

So I downloaded the default drupal 7 .htaccess file from https://code.google.com/p/drupalgooglecode/source/browse/trunk/.htaccess

Then in the section

```
# Various rewrite rules.
<IfModule mod_rewrite.c>
</IfModule>

```

I added:

```
RewriteRule ^categorie/([^/]*)\.html$ index.php?q=categorie&categorie=$1 [L]

```

Above the default (I also tried below but that didn't rewrite the url):

```
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

But it doesn't seem to work. When the rewrite rule is added, my site's layout is all messed up. As if the themes/css is not loaded anymore. The url does rewrite as I want, but it looks like drupal doesn't know where the theme files are. What may be the cause of this?

Thanks! Stece

UPDATE: is it possible that url-rewriting of .htaccess conflicts with the drupal clean-url's module? Because theming that doesn't load, feels like something is conflicting. Not sure...

UPDATE2: also tried using a custom module with the hook\_url\_inbound\_alter, but that's not working with me either (https://stackoverflow.com/questions/17176589/drupal-hook-url-inbound-alter-not-altering-my-url). That question is on stackoverflow, for some reason I hoped to get a quicker solution their.

# Answer
> 2 votes
Maybe I am missing something, but you shouldn't need the .htaccess rewrite.

It is likely that the 'conflict' is it rewriting the path to your styles. View the source and check what happens when you try to navigate to your css etc.

To achieve this effect all you should need to do (unless I am missing something) is to enable clean URLs, this will remove the `index.php?q=`.

Then to add `.html` go to `admin/config/search/path/patterns` (with pathauto installed) and add `.html` after `[node:title]` or `[term:name]`, whichever you are using.

So your patterns would look like:
`[node:title].html`
and
`[term:name].html`

# Answer
> 0 votes
This assumes your site is located at `http://www.example.com`:

```
RewriteCond %{QUERY_STRING} ^(q)=(categorie)&(categorie)=(.+)$ [NC]
RewriteRule ^$ http://www\.example\.com/%3/%4\.html${pages:%1¦NULL}? [L]

```

Hope that helps... :)

# Answer
> 0 votes
> As if the themes/css is not loaded anymore.

Are the styles loading? Check the resources in DevTools/Firebug to see the URL request and make sure it isn't returning 404. Knowing the bad request path(s) would help to answer your question better...

This is a shot in the dark, but check to make sure static styles are defined in your .info & dynamic styles are called using `drupal_get_path()` from template.php

Clean URLs + PathAuto is definitely the easiest solution to add the .html extension- this post explains how pretty well.

---
Tags: 7, .htaccess, uri
---


# Question
Title: Update order status with administrator comment
I need a way to be able to allow an admin user post an order comment when they update the order status that the owner of the order would then get posted on their order. This would both be viewable from the owner of the order, when the owner of the order was logged in under their order history view of that particular order, but would at the same time, get an email with these update comments. Ubercart 2 did this quite well. I imagine Drupal Commerce is capable, but how?

# Answer
> 0 votes
In Commerce this is not provided as a part of core. It is provided by the Commerce Message module. In addition to that, the Commerce Backoffice module provides an improved view that allows you to view a summary of an order (and send a message) directly from the order view.

Both are included in Commerce Kickstart, in case you want a quick demo.

---
Tags: 7, commerce, comments
---


# Question
Title: How can I debug why user_save() is being called twice?
I have a site with a large number of modules (100+) installed and I have an issue with my rules firing twice, which appears to be caused by `user_save()` being called twice. (I was able to confirm this by adding a `dpm($account)` in `user_save()`, which is printed to the screen twice on my dev site when I log in as an authenticated user and update that user's profile.

Now I'd like to find which contrib module is caused `user_save()` to be called twice (of course this assumes it is a contrib module). I'm not a developer so I'm getting stuck. I have Netbeans set up with Xdebug and I set a breakpoint on `user_save()`. Then I started the debugger and logged in and updated a user account, but when I look at the call stack I see the following:

> /mysite/modules/user/user.module.include\_once:424 /mysite/includes/bootstrap.inc.drupal\_load:1126
> /mysite/sites/all/modules/contrib/devel/devel.module.devel\_boot:616
> /mysite/includes/module.inc.call\_user\_func\_array:833
> /mysite/includes/module.inc.module\_invoke:833 /mysite/includes/bootstrap.inc.bootstrap\_invoke\_all:1097
> /mysite/includes/bootstrap.inc.\_drupal\_bootstrap\_page\_header:2454 /mysite/includes/bootstrap.inc.drupal\_bootstrap:2214
> /mysite/index.php.{main}:20

And then when `user_save()` is called again (in the same page load) I see exactly the same output. If it is a contrib module that is causing `user_save()` to be called twice, how can I find out which one it is?

# Answer
It turned out Rules was the culprit. I didn't realized that using the *Set a data value* action could cause user\_save() to be called twice.
> 1 votes

# Answer
Try turning off devel. That shouldn't be calling anything that calls user save.
> 0 votes

---
Tags: debugging
---


title: Capture search term?

text:
# Question
Title: Capture search term?
Is there a function that captures search parameters? Specifically I just need the search term as a variable to compare against certain node taxonomies to add a custom filter on the search template.

I want to capture the search term without going through any Solr API. Is this possible?

# Answer
> 1 votes
Typically searching with the default search box results in a url that looks like this:

```
/search/node/[search term]

```

So you can capture that search term (in your custom module presumably) with a line like this:

```
$path = explode('/', $_GET['q'], 3);

// Make sure the path you got has three components and begins with 'search'
if(count($path) == 3 && $path[0]=="search") {
   // Get component #3 (index starts at 0)
   drupal_set_message("Here are my search terms: " . $path[2]);
}

```

---
Tags: search
---


title: can you view a view in a table?

text:
# Question
Title: can you view a view in a table?
I loaded a db to see settings of a view but can't access the site so wondering if I can view it via mysql?

OR can you reset the username and pass for admin in mysql?

# Answer
Can you access the command line? If so, try to use Drush (the drupal shell command-line interface) to export the view settings.

If you use Drupal 6, this is possible once you install the Drush Views module so it won't help you since you can't access the site.

But if you use Drupal 7, you can use this patch.
> 1 votes

# Answer
you can set the admin account's email in mysql and then have it email you for a password reset.

you should also be able to copy the hashed password value of a known password in to the admin user's password and then login.
> 0 votes

---
Tags: views, database
---


# Question
Title: Help! Updated PHP and Cache/ Std Import Problems
I recently moved my site to a new host and got it all working then tried to set up a development replica site in a subdirectory but did something wrong. When I tried to log into my test site it logged into my main site. I also updated my PHP from 5.3.21 to 5.4 around the same time. I now have some errors on my site that I can't seem to work out. and I have lost one of my blog pages I have written too. Since I have downgraded PHP on my server to 5.3.26 (it said 5.3.21 had deprecated) I have restored my database to a previous backup (before the errors) and I have completely deleted the test site I created. Yet still my errors continue.

I can't update my database through drupal, or run cron or flush my caches. And when I try to rebuild my registry I get an out of memory error at 30mb but my limit is right up at 600mb and this is working for my site generally.

The errors:

> Fatal error: Call to undefined method stdClass::import() in /home/mysite/sites/all/modules/rules/includes/rules.core.inc on line 128,
>
> Notice: unserialize() \[function.unserialize\]: Error at offset 229255 of 851457 bytes in DrupalDatabaseCache-\>prepareItem() (line 434 of /home//public\_html/includes/cache.inc). Notice: unserialize() \[function.unserialize\]: Error at offset 152479 of 183944 bytes in DrupalDatabaseCache-\>prepareItem() (line 434 of /home//public\_html/includes/cache.inc). Warning: Invalid argument supplied for foreach() in rules\_filter\_array() (line 901 of /home//public\_html/sites/all/modules/rules/rules.module). Notice: unserialize() \[function.unserialize\]: Error at offset 229255 of 851457 bytes in DrupalDatabaseCache-\>prepareItem() (line 434 of /home//public\_html/includes/cache.inc). Notice: unserialize() \[function.unserialize\]: Error at offset 152479 of 183944 bytes in DrupalDatabaseCache-\>prepareItem() (line 434 of /home//public\_html/includes/cache.inc). Notice: unserialize() \[function.unserialize\]: Error at offset 7654 of 8836 bytes in DrupalDatabaseCache-\>prepareItem() (line 434 of /home//public\_html/includes/cache.inc). Warning: Invalid argument supplied for foreach() in field\_attach\_load() (line 660 of /home//public\_html/modules/field/field.attach.inc).

If anyone help me I would really appreciate it! I am starting to think I might need to rebuild completely but I really hope not.

# Answer
You made 2 big mistakes:

1. You made 2 changes at once.
2. You paid for hostings without overlap.

Now, set up virtual machine reflecting your old hosting. Restore your site from backup you made prior your experiments. Put it in maintenance mode. Clear all caches. Now that's what you want to pack for migration. Exclude data from cache\_\* tables and `/sites/*/files/css` & `sites/*/files/js` directories.

Erase files and database from your new production site, and upload the one with no cache. That should do it.
> 4 votes

---
Tags: entities
---


# Question
Title: How to display entity properties using hook_entity_view_alter? Help with syntax
I'm creating an entity in code using the eck. I've added both properties and fields to my custom entity. That is working great, except I can't figure out how to display certain entity properties when hook\_entity\_view is being called?

I have this in a custom module -

```
function mycustommodule_entity_view_alter($build, $type){
  if ($type == 'mycustomentity'){

  }

}

```

It's suppose to take a render array, but there is no $entity-\>content and I've tried various things to add a very simple render array #markup =\> 'somemarketup'; to $build, but I have not been successfully. Given that my property is named something like 'myproperty' and is just a text property (from eck) can someone help me with the syntax for adding it to the entity display using hook\_entity\_view\_alter?

# Answer
> 4 votes
# Accessing the entity

`hook_entity_view_alter` does not have an `$entity` parameter. This is a problem that has been addressed in Drupal 8 (see https://drupal.org/node/1618140).

In the mean time you can't be certain that the entity is available, because it depends on the function that invokes `hook_entity_view_alter` in the first place. Anyone can invoke `hook_entity_view_alter`, any may (or may not) provide you with the entity in the build array.

The EntityApiController from the entity module (which is not core, but is a requirement for eck) adds a '#entity' field to the build array which contains the entity. My feeling is that it should be safe in most cases to rely on this, but you can't be 100% sure that it will be there.

Here is an example, assuming a required field 'field\_mycustomfield' which has a 'value' property (eg. simple text field):

```
function mycustommodule_entity_view_alter(&$build, $type){
  if ($type == 'mycustomentity' && isset($build['#entity'])){
    $value = field_get_items($type, $entity, 'field_mycustomfield');
    $build[] = array(
      '#type' => 'markup',
      '#markup' => "My custom value: " . check_plain($value[0]['value']
    );
  }
}

```

# Adding values to the build array

You have a small mistake in your code: to be able to modify the `$build` parameter, you must take that parameter by reference (as showed on the documentation for hook\_entity\_view\_alter). Look at my example above and notice the **&** before `$build`.

---
Tags: 7, entities
---


# Question
Title: How to output the label of a field in a template?
I am overriding the node template for a custom content type, say `node-custom.tpl.php`. The content type have some fields that I want to show in columns like this :

```
|Label1|Data1|
|Label2|Data2|
|Label3|Data3|
|Label4|Data4|

```

If I use `render($content['field_custom_data'])` both the data and the label are drawn. I know how to hide the label from the render using the content type display configuration but I need a solution for the label. The site is multilanguage if that matters.

# Answer
> 0 votes
This code will print all labels .

```
     $entity_type = 'node';
     $bundle_name = 'CUSTOM'; //machine name of your content type

  foreach ($node as $key => $value) {

        $field_name = $key;

        $info = field_info_instance($entity_type, $field_name, $bundle_name);

        $label = $info['label'];

        print $label;
        print "<br>";
   }

```

You can modify it according to your need.

---
Tags: entities, theming
---


# Question
Title: How do I prevent a user from re-using the same password within a certain period of time?
How do I prevent a user from re-using the same password within a certain period of time?

I have configured a number of password restriction modules {Password policy, Generate Password and Flood control} which I have configured to do things like "Password must not match any of the user's previous 10 passwords" but I can't configure them to prevent the same password from being reused within a certain period of time like a year.

I am using Drupal 7.

# Answer
You are looking to alter Password policy module:

> A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.
>
> Current constraints include:
>
> * History constraint (checks hashed password against a collection of users previous hashed passwords looking for recent duplicates)

Now, all you need is to take this constrain and make a copy based on time, not number. Should be pretty easy, real difference is in one `WHERE` condition.

If module provides hooks, make it in your custom module. If it does not, provide a patch with your constrain.
> 8 votes

---
Tags: users
---


# Question
Title: Leveraging field_get_items variable in a custom field template
I can use a template preprocess function for node to simply get the alt tag of an image field image using the venerable `field_get_items` as such:

```
function MYTHEME_preprocess_node(&$vars, $hook) {
// Global node.
  $node = $vars['node'];

 $field_image_items = field_get_items('node', $node, 'field_image');
  // Load individual data from 'field_image'.
    $vars['alt_caption'] = $field_image_items[0]['alt'];
}

```

Then in `node.tpl.php`, I can render the alt tag of the image from the variable we created above as:

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

```

... and that works great.

However, I'd like to customize the template for the image itself so when I create a `field--field_image.tpl.php` template, sure enough the image renders fine but if I add the `$alt_caption` variable, that does not render. I'm guessing this will simply not work or there is an extra step I need to do for the variable to render in this new template.

# Answer
You need TEMPLATE\_preprocess\_field() function at `template.php`

You can use this preprocess function in same way as you are doing for `NODE`. Like -

```
function MYTHEME_preprocess_field(&$vars) {
  if ($node = menu_get_object()){
    $node = $vars['node'];
    $field_image_items = field_get_items('node', $node, 'field_image');
    $vars['alt_caption'] = $field_image_items[0]['alt'];
  }
}

```

Then go to your TPL made for your particular field and print it where ever you like just like you have mentioned --

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

```

And it will work like charm!! I have implemented like this several times.

But yeah...don't forget to clear your cache after this implementation.
> 1 votes

# Answer
As I was having issues with this working in teaser mode, another way to do this is to forgo the preprocess function altogether and render this in your custom image field template using the #item var that's already available:

```
 <?php if ($item['#item']['alt']): ?>
    <figcaption><?php print $item['#item']['alt']; ?></figcaption>
 <?php endif; ?>

```

This will render a nice HTML5 caption under the image based on your alt tag. What's interesting about this is that the default `field.tpl.php` template in D7 does not give `item` as a possible variable. Inspiration for this method here.
> 0 votes

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


# Question
Title: SearchApiException: Unknown or invalid item type node
I was working on site, when I got this error:

> WD php: SearchApiException: Unknown or invalid item type node. in
> \[error\] search\_api\_get\_datasource\_controller() (line 1396 of /var/www/luken/shop/sites/all/modules/search\_api/search\_api.module). SearchApiException: Unknown or invalid item type node. w search\_api\_get\_datasource\_controller() (linia 1396 z /var/www/luken/shop/sites/all/modules/search\_api/search\_api.module). Drush command terminated abnormally due to an unrecoverable error.
> \[error\]

Site is telling me about "Unexpected error", the above error I'm getting thanks to the Drush. Last thing that I did, was:

1. Removing one Product Display content type (I'm using Commerce),
2. Changing indexed fields in Search API,
3. Clearing the cache - after that, site was down.

I even don't know where to start with fixing this. I was trying to disable Search API module with Drush, but it appeared that I can't, because I'm getting above error all the time. I can access to /admin/modules but still I cannot disable Search API, because of unexpected error.

What can I do to fix this?

**Added:** I deleted my search index, now I was able to disable Search API, but error still appears when entering the site. I checked log, there is an error:

> EntityMetadataWrapperException: Unknown data property commerce\_product. w EntityStructureWrapper-\>getPropertyInfo() (linia 339 z /var/www/luken/shop/sites/all/modules/entity/includes/entity.wrapper.inc).

# Answer
> 1 votes
I managed to fix the site with the help of Commerce Repair:

> This module is designed to repair missing fields from various commerce entities. After installing, visit the menu item that does the repair, admin-\>store-\>config-\>Repair Commerce Fields (admin/commerce/config/repair). Once you've done that you can uninstall the module.

---
Tags: commerce, search
---


title: How can I do Test Driven Development?

text:
# Question
Title: How can I do Test Driven Development?
* What are the tools used for TDD in Drupal?
* What does your commit/test/deploy workflow look like? Do you use Phing, PHPUnderControl, Hudson for managing this workflow?
* In which way does unit testing make your code more reliable?
* Do you need a separate, expensive, stand-alone unit test server, or can you do it from a laptop?

I know that Robert wrote an excellent technical post on An Introduction to Unit Testing in Drupal; I am more interested in covering the workflow and configuration part. Currently I have a development machine, staging and production server. Both production and stage sites run on a 300MB RAM/300MHz CPU Dreamhost VPS.

# Answer
In the ruby world, TDD is facilitated by tools built into the framework. Factory Girl, Mocha, rSpec and others allow developers to create easily and dynamically tests that address the test cases needed.

I've been frustrated as well by the lack to TDD tools in Drupal. My biggest issue with them is the amount of time it takes to run a single test. Development cycles can't be slowed down by individual tests taking 60-90 seconds each iteration. Full test suites would run into the multiple hour timeframe, if you bother to write the tests at all.

I suspect it has to do with copying a full db everytime a test is run, but that's not likely to change in the near future from what I can tell, especially if you need to use DrupalWebTestCase to do so.

I'm hacking together a solution using Phactory and phpunit, which bootstraps Drupal manually. Obviously running into some issues and haven't finished it, but it's getting there.

Fortunately most of my work is at the backend layer, so I can stay at the DRUPAL\_BOOTSTRAP\_DATABASE level. But I'm running in to more situations where I'll need the full stack.

In the end, TDD in Drupal is not well supported, so you can write your own to make it work outside of the drupal test framework, or endure the poor performance.

-- UPDATE --

I have successfully setup a full Drupal integration with Phactory, and am now running my tests via phpunit instead of the Drupal Web Test Case. So it's possible.

I'll hopefully get to a point where I can release it and it can get incorporated into the Phactory doc.

-- UPDATE 2 --

Doc on how I setup Phactory is at https://github.com/trimbletodd/phactory.
> 9 votes

# Answer
Since Mark's blog is offline, I'll mention some of the tools his team has implemented:

Functional testing: Selenium
Unit testing: Simpletest
Build server: Jenkins
Performance benchmarking: XDebug + Cachegrind

In the two years since I asked this question I've seen some additional tools gain popularity to the TDD scene. Nowadays when you speak of Test Driven Development (in a Drupal context, of course) there's two sides to the same coin — front-end testing, and back-end testing.

Here are two presentations that stand out from the latest Drupalcon Portland 2013 representing this matter:

Development, By The Numbers, backend testing.
Automated testing with Jasmine and PhantomJS, frontend testing.

The first presentation is not related to unit or functional testing (strictly speaking), it's more about tools to measure code quality. Nevertheless, I feel it's somewhat related to the topic.
> 13 votes

# Answer
The only thing that I'm aware of is that for contributed modules, you can enable automated testing of commits *and* patches in the issue queue, see http://drupal.org/node/689990. It is still somewhat unstable, especially if you have dependencies.

Most projects are probably more doing something along the lines of bug driven development, which basically comes down to writing a test first when a bug was found and then fix it. If at all ;)

From my personal experience, TDD is rather hard in Drupal, because you often don't write (only) unit tests with Simpletest but integration tests, where you view pages and submit forms. So it can be rather hard to write good tests in advance. But maybe I'm just not used to doing that :)
> 5 votes

---
Tags: testing
---


# Question
Title: How to set Rules event for "Content is viewed" from excluding Teaser view?
I set up a Rule that will execute during the "Content is viewed" Event and the action was to show a system message.

It worked and was triggered when I viewed the node. However, when I went to the home page, it was triggered N times, where N is the number of nodes on the /node page.

How do I stop this from happening? The Rule should only fall through on content full view, and exclude the teaser view.

# Answer
In your rule add a data comparison called "view-mode" and set it to "Full content".
> 12 votes

# Answer
This might be inefficient but this is what I did:

Added a condition - Data comparison site:current-page:path == node/\[node:nid\]

This is to make sure that it is showing up on the actual full /node/nid page and not as a teaser view.
> 0 votes

---
Tags: rules, nodes
---


# Question
Title: drush status not showing correct setting from alias file
I'm trying to get drush to work with my test environment, which is actually using a separate database.

so here's my alias in aliases.drushrc.php:

```
 $aliases['local'] = array(
   'root' => '/my/drupal/root',
   'uri'  => 'http://localhost',
 );

 $aliases['test'] = array(
   'parent' => '@local',
   'databases' => array (
     'default' =>
     array (
       'default' =>
       array (
         'database' => 'test_db',
         'username' => 'test_user',
         'password' => 'test_pwd',
         'host' => 'localhost',
         'port' => '',
         'driver' => 'mysql',
         'prefix' => '',
       ),
     ),
   ),
 );

```

When I look at the `drush site-alias @local` and `drush site-alias @test` the config is read correctly.

When I run `drush @test status` it gives me the default status. Notice that the username and db are the default, not my test details.

```
 $ drush @test status
  Drupal version                  :  7.14
  Site URI                        :  http://localhost
  Database driver                 :  mysql
  Database hostname               :  localhost
  Database username               :  default_user
  Database name                   :  default_db
  Database                        :  Connected
  Drupal bootstrap                :  Successful
  Drupal user                     :  Anonymous
  Default theme                   :  sporttracks
  Administration theme            :  seven
  PHP configuration               :  /private/etc/php.ini
  Drush version                   :  5.8
  Drush configuration             :
  Drush alias files               :  /my/home/dir/.drush/aliases.drushrc.php
  Drupal root                     :  /my/drupal/root
  Site path                       :  sites/default
  File directory path             :  sites/default/files
  Temporary file directory path   :  /tmp

```

So the question is: why is the alias not being read?

# Answer
This is not supported by Drush, as explained in this issue: https://drupal.org/node/1335626

In brief, the database information stored in an alias file is only used for Drush commands such as sql-sync, sql-cli and so on; a Drush alias will never affect the way that Drupal is bootstrapped. Therefore, Drush core-status will always show you the database info from settings.php, which is where Drupal reads it from.

If you want to force a different database configuration for a given alias, it would be best to use Drupal's multisite feature, and make another settings.php in a sites/test folder. Then, just specify 'test' as the uri for your alternate alias. Should work like a charm. I always prefer to give my local test installations a completely separate copy of the Drupal + contrib code base too, though, in case I want to fiddle with the code on test without interfering with my other local copy's behavior. Using the multisite feature is fine if this is not a concern for you, though.
> 3 votes

---
Tags: 7, drush, testing
---


title: Extra Space Below Footer in Drupal 7

text:
# Question
Title: Extra Space Below Footer in Drupal 7
I'm currently in the process of updating our current site from Drupal 6 to Drupal 7. Between the designer guy and myself, we have been banging our heads trying to figure out where the extra large chunk of space below our footer is coming from. We have added two new regions and three blocks below our main content and when enabling the blocks, the space appears. We have tried everything we can think of. Any help would be greatly appreciated. Thank you.

The site URL is http://prosifland.webhost.uits.arizona.edu/

# Answer
> -1 votes
This looks more like a css issue than a drupal issue. I am not sure if you are looking for some drupal hooks to solve this problem. But adding this css will solve the issue.

```
 .region-links-region{
      overflow: hidden;
  }

```

If this does not work, you can try `overflow: hidden !important;`

---
Tags: theming
---


# Question
Title: Is there a module that creates an input filter to convert text to the ASCII character-set?
I have a textarea on a content type that needs to be converted ASCII character-set. Is there an available module that adds a input filter for this? This field needs to be fed to another platform with this formatting.

# Answer
> 2 votes
If you have the Transliteration module installed, you can create your own filter.

Go to `/admin/config/content/formats` and click on *Add text format* at the top. One of the options is *Convert all characters to US-ASCII*. Set the roles you want to allow use of the format and save.

---
Tags: input-formats
---


# Question
Title: un-escaped _server variable in settings.php - bad idea right?
I recently started working for a new company hosting drupal sites that is using a switch statement within the settings.php for multiple environments. I am accustomed to using multi-site and am exploring the feasibility of having configurations like this.

What concerns me is the lack of any sanitation or escaping of the variable and using it in its raw form. Is this a terrible idea or is it fine if we start sanitizing the 'http\_host' variable?

Code:

```
    switch ($_SERVER['HTTP_HOST']) {

    //Live Settings
    case (preg_match('/^www\.domain\.com$/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : !$_SERVER ['HTTP_HOST']) :
    case (preg_match('/^web001\.domain\.domroot\.com$/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : !$_SERVER['HTTP_HOST']) :
    case (preg_match('/^web002\.domain\.domroot\.com$/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : !$_SERVER['HTTP_HOST']) :
    //Include file that contains sensitive db string
    include_once 'sites/default/settings.live.php';
    break;

    ...

     }

```

# Answer
* D7 ? No need to do this!

First, talking about what you are doing, if it's for a Drupal 7 site, you do not need to do this in the first place. Read the `sites/example.sites.php` for multisite settings.

* `$_SERVER['HTTP_HOST']` is almost safe.

See this great answer about how much secure `$_SERVER` variables are.

* There is no point of sanitizing *it* either.

From Drupal.org post Writing Secure code,

> Whether you are writing a PHP snippet or an entire module, it is important to keep your code secure. Use check functions on output to prevent cross site scripting attacks
>
> No piece of user-submitted content should ever be placed as-is into HTML.

But you are not outputting anything or populating any variable so you do not need to sanitize any **output** here.
> 4 votes

---
Tags: security, configuration
---


# Question
Title: Altering widget produces error, "Class name must be a valid object or a string"
I'm using hook\_field\_widget\_properties\_alter to successfully set the widget type of some fields to 'options\_select', but when trying to set others to entityreference\_autocomplete, I get the error, "Class name must be a valid object or a string in mysite\includes\common.inc". Here's the code:

```
/*implementation of hook form alter*/
function mymodule_overrides_field_widget_properties_alter(&$widget, $context){
  // set widget type to options_select for field_expertisetags and og_group_ref
     $widget['module'] = 'entityreference';
     $widget['type'] = 'entityreference_autocomplete_tags';
}

```

Any thoughts as to the cause?

# Answer
> 1 votes
I discovered that the target field was of a type that required different settings. I solved it by entering this:

```
$widget['active'] = '1';
$widget['#access'] = '1';
$widget['module'] = 'taxonomy';
$widget['type'] = 'taxonomy_autocomplete';
$widget['settings']['autocomplete_path'] = 'taxonomy/autocomplete';
$widget['settings']['size'] = '60';

```

I also realized you can go to the content type, select a field type and the underlying html for that dropdown will reveal the field type module value, and the settings under the widget dropdown will reveal the 'type' value you need to use. Hope that helps someone.

---
Tags: 7, entities
---


# Question
Title: Alter user_pass_reset for one time login D7
I don't like the one time login process; sending the users directly to their user edit page is not what I want. I want to force the users to insert a new password.

I have created a module that doesn't work; obviously I'm not affecting the submit action and is not taking the newly inserted username to the user object.

```
// Let's try to add a form in the user pass reset form for password requests.
function xxx_login_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_pass_reset') {
    $form['#account'] = $GLOBALS['user'];
    $form['loginsetup'] = array(
      '#title' => t('Login setup'),
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE
    );
    $form['loginsetup']['account']['name'] = array(
      '#type' => 'textfield',
      '#size' => 25,
      '#title' => t('Username'),
      '#required' => TRUE
    );

    $form['loginsetup']['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#title' => 'Please enter your new password',
      '#required' => TRUE,
    );

    $form['message']['#markup'] = FALSE;
    $form['help']['#markup'] = FALSE;
    $form['actions']['submit']['#value'] = 'Enter';
    //  $form['#validate'][] = 'xxx_login_user_pass_validate';
    $form['#submit'][] = 'xxx_login_user_pass_submit';
  }

  return $form;
}

// We'll check if the user did not leave a username.

// function xxx_login_user_pass_validate($form, &$form_state) {
//   if (empty($form_state['values']['name'])) {
//     form_set_error('name', t('You must select a username.'));
//   }
// }

// We should send the new values to the user object.

 function xxx_login_user_pass_submit($form, &$form_state) {
   // Set up the edit array to pass to user_save().
   $edit = array(
     'pass' => $form_state['values']['pass'],
     'name' => $form_state['values']['name']
   );

   // Save the account with the new password and name
   user_save($form['#account'], $edit);

   // Inform the user.
   drupal_set_message(t('Your login details have been stored. Welcome to example.com!'));
}

```

The validate function is now commented, but it does not affect the module; with or without it, it still does not work.

# Answer
> 2 votes
This is a bit of a SNAFU as user\_password\_reset doesn't have a hook associated with it. Why that is, I fail to see.

However, you can always use this little trick in hook\_user\_login to determine when users log in with a reset link by checking the emptiness of the $edit parameter as the only time it will be empty will be when the user didn't submit a form to log in = when they were automatically logged in.

```
function mymodule_user_login(&$edit, $account){
  if(!$edit){ // only for automatic pwd resets
    // do your thing, redirect to a password change form with drupal_goto or whatever you need.
  }
}

```

The implementation of forcing the user set a new password is another question altogether. We do it with a modal window that shows a simple custom form, but there are plenty of ways to do it. Unfortunately the easiest one is sending the user to their user edit form like the password reset functionality automatically does, but there's absolutely no reason why you couldn't just do whatever at that point as the user is logged in and good to go.

# Answer
> 0 votes
You can intercept the password reset with a `hook_form_user_pass_reset_alter` function.

When the user clicks the button to login, they can be taken to your alternative page.

Something like this works:

e.g:

```
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function MY_MODULE_form_user_pass_reset_alter(&$form, &$form_state, $form_id) {

  $uid = $form_state['build_info']['args'][0];
  $timestamp = $form_state['build_info']['args'][1];
  $hashed_pass = $form_state['build_info']['args'][2];

  // Go to our user/[uid]/edit/password page for resetting password
  $url = url("user/reset/$uid/$timestamp/$hashed_pass/login", array(
    'query' => array(
      'destination' => "user/$uid/edit/password"
    )
  ));

  $form['#action'] = $url;

}

```

---
Tags: users, forms
---


# Question
Title: Mark location on Gmap without Click on gmap
I am using Location + Gmap module. When creating a content user have to mark location on gmap. I want to to mark location on gmap automatically when user enter the values in location.

I enabled Geocoding for `India` and tried after set `Google Maps Geocoding Accuracy` to `Premise`, `Country Level` etc. but it is not marking on Gmap

I tried this documentation, But map is only displaying if I manually mark on gmap. I am using a Location CCK Field.

# Answer
Solved this using `hook_node_api`

```
if ($op == 'presave') {
    $geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
    $latitude = $output->results[0]->geometry->location->lat;
    $longitude = $output->results[0]->geometry->location->lng;
    $node->field_event_location[0]['latitude'] = $latitude;
    $node->field_event_location[0]['longitude'] = $longitude;
    $node->field_event_location[0]['locpick']['user_latitude'] = $latitude;
    $node->field_event_location[0]['locpick']['user_longitude'] = $longitude;
    node_save($node);
}

```
> 0 votes

# Answer
The location module already geolocates automatically. Go to `admin/config/content/location/geocoding` and make sure you have chosen a geolocation service for the counties you need.
> 0 votes

# Answer
Instead try this modules it have the option same like your requirement. See the below screenshot and also easy to configure.

Geofield Gmap allow to use a google map v3 map to **input a location**.

A **quick text input + geocode** allow you to specify an address.

You can drag and drop the marker to narrow the position.

Geofield Gmap require geofield.

Geofield is a module for storing geographic data in Drupal 7. It supports all geo-types (points, lines, polygons, multitypes etc.)
> 0 votes

---
Tags: 6, location, google-maps
---


# Question
Title: What is the best way to preprocess fields with Display Suite
I'm using Display Suite with Drupal Commerce, and I need to pre-process some fields in my product display. I need to change some values based on some conditions, and need to wrap a few fields in some markup. Should I write a hook to pre-process and change the values, and use a template to wrap the fields in markup? If so, which template file would I use, because DS comes with a few templates.

# Answer
> 7 votes
You can customize your field at theme level by using TEMPLATE\_preprocess\_field() function at `template.php`

You can get get some field value by `node` object or by fetching `field` values itself. You can do something like this to get fields value by node object --

```
function MYTHEME_preprocess_field(&$vars) { //Replace your theme name MYTHEME here.
  if ($node = menu_get_object()){
    if($node->type == 'PRODUCT_DISPLAY'){//Use your product display name here.
      $vars['node'] = $node;
      $product_id = $node->FIELD_PRODUCT_REFERENCE[LANGUAGE_NONE][0]['product_id'];//Use your product ref field name here.
      $product = commerce_product_load($product_id);
      $manufacturer = $product->FIELD_PRODUCT_MANUFACTURER[LANGUAGE_NONE][0]['value'];//Use your field name of product type here.
      $final_body_label = "Description by ".$manufacturer;

      //Set body label for node from here itself.
      $node->content['body']['#label_display'] = $final_body_label;

      //Or set a variable to use it further.
      $$vars['manufacturer_description'] = $final_body_label;
  }
}

```

Further you can use your default template for node or page if it fulfils what you want or you can make separate `TPL` for fields too, which will be named like `field--field_image.tpl.php`, where `field_image` is field name of your content or product.

You will get default `field.tpl` in $`base_path/modules/field/theme`.

---
Tags: 7, commerce, theming, display-suite
---


# Question
Title: How to get the parent comments (in a custom module)?
I'm writing a module that uses flag to handle notifications, and one of the options is to be notified of replies to a given comment.

I can implement without problem `hook_comment_publish($comment)`, but I want to get all of its parent comments so that I can pick up the users that flagged them.

So, how can I retrieve all the parent comments of a given comment (if any)? I noticed that in taxonomy there is a `taxonomy_get_parents($tid)` but I can't find anything similar for threatened comments.

# Answer
> 0 votes
This code does the trick:

```
  $threads = explode('.', $comment->thread);
  $thread = "";
  $pnids = array();
  for($i=0;$i<(count($threads)-1);$i++){
        $thread .= $threads[$i];
        $local_thread = $thread."/";
        $result = db_query('SELECT c.cid FROM {comment} c WHERE c.nid = :nid AND c.thread = :thread AND c.status = :status',
        array(':nid' => $comment->nid, ':thread' => $local_thread, ':status'=>'1'));
        foreach ($result as $record) {
            $pnids[] = $record->cid;
        }
        $thread .= ".";
  }

```

However this code produces 1 DB query for each parent. I don't know if it is feasible/better to include all the :thread in a single query with OR.

---
Tags: hooks, comments
---


# Question
Title: How to solve “This version is not compatible with Drupal 7.x and should be replaced” error?
Similar to but the solution doesn't work: How to solve "This version is not compatible with Drupal 7.x and should be replaced" error?

I've followed everything I can find but a basic custom theme in sites/all/themes is not working at all. Here is my .info:

```
name = Custom
description = Custom custom theme built with Stark
package = Core
version = 7.1
core = 7.x

regions[content] = Content
regions[main_nav] = Navigation
regions[sub_nav] = Sub Nav
regions[landing_large] = Front Large Box
regions[landing_ads] = Landing Ads
regions[landing_ad_bottom] = Landing Ad Bottom
regions[landing_books] = Landing Books
regions[home_first] = Home first
regions[home_second] = Home second
regions[home_third] = Home third
regions[search_box] = Search Box
regions[search_ad_box] = Search Ad Box
regions[content_first] = Content First
regions[content_second] = Content Second
regions[content_authors] = Content Third
regions[content_blogs] = Content Fourth
regions[sidebar_right] = Sidebar Right
regions[footer_first] = Footer First
regions[footer_second] = Footer Second
regions[footer_third] = Footer Third
regions[footer_fourth] = Footer Fourth
regions[copyright] = Copyright
regions[shopping_cart] = Shopping Cart

stylesheets[all][] = css/layout.css

```

I've tried with and without Package, it clearly has defined the version, the core version, the content region...what is it? I copied the .info file from a theme that works perfectly and this is the .info of that other theme verbatim.

# Answer
> 4 votes
Your custom theme is surely not a part of Core package, so remove that line first. Second, you mentioned that the theme is built based on Stark but you didn't define it in the info file, so add this line :

`base theme = stark`

Third, usage of version is discouraged in Drupal 7, so delete this line as well.

---
Tags: theming, .info
---


# Question
Title: How to Get Custom Field Label Translation
I'm using Internationalization module and in my custom entity type, I have my custom field. Since this entity is going to be usable for all enabled languages, I have added translation to my custom field's label.

In node.tpl.php file in my custom template, I am calling this field values like this:

```
$field = field_info_instance('node', 'field_custom', 'custom_entity');

```

And I render the field's label like this:

```
echo t($field['label']);

```

However, even though I've added translation for the label, it remains same string for all languages. I'm surely missing something here, how can I implement this?

Thanks in advance.

# Answer
> 0 votes
OK, here's how I solved the problem.

Internatinalization module renders the content according to translated strings before `node.tpl.php` gets rendered. Thus, the `$content` variable in `node.tpl.php` contains the latest version of rendered page.

Since I was **not** using the `<?php print render($content); ?>` because I was creating a custom template, I have used the field properties inside this `$content` variable. And they contain the translated versions of labels.

Here's how you can get a translated label of a custom field:

```
echo $content['custom_field']['#title'];

```

P.S. If you want to get a field property from `$content` variable, you must set that field to visible in content type's manage display section.

# Answer
> 0 votes
You cannot use variables in t() function, it accepts only strings and placeholders with an array.

The i18n module has Field Translation module shipped with it, be sure you have enabled it as well.

There is also a good information on the following link about getting title fields translated as well.

Drupal 7 – Translate the title field label of content types

---
Tags: entities, i18n-l10n
---


# Question
Title: How can I update user data whenever a user account is saved in PHP?
I need to do some processing (calculate a zodiac sign) on some user data after an account is saved. (When saving a user account, I want to use a custom module to re-compute a field and save the new value.)

I have a function `MYMODULE_calculate_zodiac()` which returns the term ID of the user's zodiac sign. I have used `dpm()` to confirm that the correct value is calculated.

Here is the function in my custom module:

```
function MYMODULE_user_update(&$edit, $account, $category) {
  global $user;
  $user = user_load($account->uid);

  $zodiac_sign = MYMODULE_calculate_zodiac($account);
  $edit['field_zodiac']['und'][0]['tid'] = $zodiac_sign;

  user_save($account, $edit);
}

```

However, when I save a user account with this code, my site just hangs and the user is not saved (error: *Fatal error: Maximum execution time of 240 seconds exceeded*). What am I doing wrong?

# Answer
> 7 votes
The problem there is you're creating an endless loop.

`user_save` calls `hook_user_update`, your `hook_user_update` calls `user_save`.... you get the picture.

A better approach would be to use

hook\_user\_presave

to add the field, then you don't need to worry about saving the account, as the user module will do that for you after the field is added.

The downside is, the uid isn't available in presave (for new accounts), though for a zodiac sign, I assume that's not required.

---
Tags: hooks
---


# Question
Title: dpm() in hook_init shows twice on the page
In my custom module, I use a `hook_init()` with a `dpm`-function.

```
function mymodule_init() {
    dpm('check');
}

```

but for some reason, my page shows 2 times 'check' on the page... Is this default Drupal behavior? And if so, what are the reason for this behavior?

# Answer
hook\_init runs once per-page request, for non-cached pages.

See \_drupal\_bootstrap\_full

```
module_invoke_all('init');

```

I guess what's perhaps happening in your case is an additional ajax request is bootstrapping Drupal and triggering an additional `hook_init` call.
> 4 votes

---
Tags: 7, hooks
---


# Question
Title: How to filter with all outputs when using Rewrite results option in Views
In my view using the "Rewrite Result" option, I combined two fields "first name" and "Surname" to display as one field with label "Full name".

I then added an exposed filter to allow users search through the Full names.

My challenge is that it only filters using the surname and not both. How do I get users to be able to filter using both first name and surname.

Thanks.

# Answer
To filter on both the Firstname and Lastname, when you want to add a filter, select **Global: Combine fields filter,** and then click add. The next step tells you to select the fields to filter. Select your firstname and Lastname field
> 3 votes

---
Tags: views
---


title: Adding dynamic markup to menu items

text:
# Question
Title: Adding dynamic markup to menu items
In Drupal 7, how can I add additional dynamic markup to a menu item? As an example, I'm trying to show the number of nodes 'needing attention' to the right of link in my primary navigation as noted in the attached graphic.

It seems like a theme function would be appropriate here, but I'm struggling to find which hook I should be implementing.

# Answer
> 4 votes
Hope this will help you,

* As answered theme\_menu\_link OR theme\_menu\_tree wil help you to do this. If you go through the above links you can get an idea to change the html of required menu item.

On page load:

* for example im using **theme\_menu\_link** in template.php refer this code. Node count will be update on every page load, if any changes.
* I have updated l() for you requirement. For example I have used a simple function , modify the function as per your requirement.

```
$output = l($element['#title'] . '<span class="'.strtolower(strip_tags(str_replace(" ", "_", $element['#title']))).'_node_count">'.get_node_count($parms).'</span>', $element['#href'], array('html'=>TRUE));

function get_node_count($parms){
    //you code goes here for get node count
    return $node_cnt;
    }

```

If you don't want on page load, it can also be done using **ajax callback**, but not preferable to make ajax callback again and again.

* If you want to do refer ajax callback, then the only change has to be done in the l(). Add the unique menu id, which is used to show the node count for the corresponding menu id.

```
$output = l($element['#title'] . '<span id="'.strtolower(strip_tags(str_replace(" ", "_", $element['#title']))).'_node_count"></span>', $element['#href'], array('html'=>TRUE));

```

+ On sucessfull ajax callback you have to update the node count for each menu. using
    `...
    success: function(data) {
    // Change node count
    $('#menu_title__node_count').html(data);
    }`
    + You will get the class for each node count, you can style as required. And also you can add a common class for common style, based on your requirement.

# Answer
> 1 votes
To alter the menu item markup, you can use:

Note: there are actually functions available for specific menus there too:

> **Targeted overrides (suggestions) available for theme\_menu\_link() and theme\_menu\_tree()**
>
> In addition to other changes to menu rendering, a Drupal 7 theme can implement a `THEMENAME_menu_tree__MENU_NAME()` and/or `THEMENAME_menu_link__MENU_NAME()` function to override `theme_menu_tree()`/`theme_menu_link()` for a specific menu. For example, `THEMENAME_menu_link__management()` would override `theme_menu_link()` for links within the "Management" menu. This is similar to how "`node--article.tpl.php`" overrides "`node.tpl.php`".

Source: https://drupal.org/node/254940#theme-suggestions-for-menus

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


# Question
Title: trailing slash added unwillingly and page not found
There is a url that links to a view that is a page. When clicking the link to that view, a trailing slash gets added and the the page returns 'page not found' nothing about the site gets loaded, just this string as if it said die('page not found') first thing on load. It wouldn't matter if I would manually type the correct url, the trailing slash would be added as well and return the same page not found string.

The only module I could find was global redirect. This module has checkbox in its settings that says 'Deslash'. I tried unchecking - save and checking - save again, but no help.

# Answer
> 0 votes
There was a folder in drupal installation folder with the exact same name as the path, which added the slash at the end

---
Tags: 7, uri
---


# Question
Title: Populating the $variables['classes-array'] in preprocess_html function
It seems most likely that the following code is not working due to bad php but I just can't understand why. If I var\_dump `$variables['classes']` it returns that it is an array with the classes listed in it beautifully.

I debugged the `$item` and returns very nicely what I want as well. Then why don't these things get added to my `$variables['classes-array'];`?

```
    <?php

function mytheme_preprocess_html(&$variables) {
    dsm($variables);
    $path = url($_GET['q']);
    dsm(var_dump($variables['classes_array']));
    $path_items = explode('/', $path);
    foreach ($path_items as $item) {
        array_push($variables['classes_array'], $item);
    }
}

```

also tried `array_push($variables['classes_array'][], $item);`

# Answer
> 0 votes
The problem was solved by putting the debug code *after* the change of values have taken place in the code.

---
Tags: theming
---


title: Slideshow for images in one node

text:
# Question
Title: Slideshow for images in one node
I am having an image field which takes unlimited number of images in the content type. now I need to create a slideshow (using views slideshow possibly) for those images in one node. any ideas how can I do this?

# Answer
There's a Field slideshow module that is probably easier to configure than Views slideshow when all your images are in a single field.

Views slideshow offers more flexibility in that you can source your images from essentially anywhere, but that doesn't seem to be useful in your situation.
> 1 votes

---
Tags: media, views
---


# Question
Title: How to exclude a field when a search is done?
I just enable the **Search Form** (provide by the search module) block to allow the visitor to make searches.

When a search is done the entered word is searched in all field of the nodes.

Can I exclude a field?

Let's say the content type has the fields: **title**, **body** and **provider**.

Then when a search is done I need to exclude the field **provider** from the search.

I have the custom\_search module enabled but I see no way to exclude fields.

# Answer
> 2 votes
Default Search is not customizable. Consider using one of more advanced solutions:

* Search API with client module that will suit your needs.
* Finder with proper views configuration.

---
Tags: search
---


# Question
Title: How to display data collected in a form on a page templated in module's tpl file?
I'm new in the use of Drupal and I have some troubles with the module I'm writing. This module generates a form that writes datas in some tables. It works fine, the datas are correctly writen in the database.

My module.module file contains the following functions :

function myform\_xml\_menu()

function myform\_xml\_form($form, &$form\_state)

function myform\_xml\_form\_submit($form, &$form\_state)

**The big question is : how to display the submitted datas ?**

I've already tryed writing a second module called "Display" :

```
<?php

function display_menu(){
$items['display'] = array(
    'title' => 'Display',
    'page callback' => 'display_contents',
    'access callback' => TRUE
);

return $items;
}

function display_contents(){

$query = db_select('form_xml', 'f');
$result = $query
        ->fields('f')
        ->execute()
        ->fetchAll();

$output = '<table><th>Id</th><th>Name</th><th>Description</th></tr>';

foreach($result as $key){
    $output .= '<tr>';
    $output .= '<td>'.$key->id.'</td>';
    $output .= '<td>'.$key->name.'</td>';
    $output .= '<td>'.$key->description.'</td>';
    $output .= '</tr>';
}
$output .= '</table>';

return $output;
}

```

It adds a menu item and display my results correctly too. But I feel making it wrong or unproperly... I've read many docs speaking about displaying module's results in **blocks** or **pages**.

How can I embed my results in a Drupal page in order to be able to manage its display using a .tpl file ?

# Answer
> 2 votes
You need to use hook\_theme in your module to manage content in tpl file.

Example,

Creating template file using the hook\_theme function

```
    /**
    * Implements hook_theme
   */

    function example_theme(){
      return array(
        'exampletheme' => array(
            'template' => 'exampletheme',
        'arguments' => array('example_array' => NULL),
          ),
      );
    }

```

Now, we can use "exampletheme" theme to display content. Below is the page callback function for the menu item.

```
 function example_callback(){

  $array = array(1,2,3);

  return theme('exampletheme',  $array);
}

```

Now, you need to create "exampletheme.tpl.php" file and you can render the "example\_array" in the tpl file.

---
Tags: 7, forms, theming
---


# Question
Title: How can we create configurable product in ubercart?
I am creating an e-commerce website using ubercart and Drupal 7. I have created attribute size and color for the product from the "Administration » Store » Products" and assigned to product.

I have also used search api and facet api module to generate facet search. I have created a views page to display product listing of search index product and showing facet block in that page.

Now, the problem is that I want to display product attribute as filter in the above product listing page. I have searched on google but did not find any solution for that.

Can any one suggest me?

Thanks in advance for your help.

# Answer
If I had this problem,

1. I would have created taxonomy terms corresponding to the attributes
2. The taxonomy terms can be used as search filters, rather than hacking the uc\_attributes.

or

1. If views is used to display the products, then add filters in the views as product attributes.
2. The taxonomy terms can also be used in views to filter the products.
> 0 votes

---
Tags: 7, ubercart, search
---


# Question
Title: Add multiple fields in +Add more button causes problem in sequence
I am implementing a form and in that form it requires that two form element should be coming under one Add more button, so user can add any number of fields.

Here is the code which i am using to create a form.

```
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  $form['description'] = array(
    '#markup' => '<div>' . t('This example shows an add-more and a remove-last button. The <a href="!ajax">AJAX version</a> does it without page reloads; the <a href="!multistep">non-js version</a> is the same code but simulates a non-javascript environment, showing it with page reloads.',
      array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
    . '</div>',
  );

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
  );
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['names_fieldset']['surname'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('SurName'),
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('ajax_example_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  if ($no_js_use) {
    // Remove the #ajax from the above, so ajax.js won't be loaded.
    if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
      unset($form['names_fieldset']['remove_name']['#ajax']);
    }
    unset($form['names_fieldset']['add_name']['#ajax']);
  }

  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function ajax_example_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function ajax_example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

```

The above code is taken from the example module with little modification. In this code i have added one more text field called **surname** with **name** textfield.

Now when i access form it gives me the form fields as shown in the image given below. Before clicking on Add more button:

Now when i click on the Add more button two fields are added as shown in the below image.

Here you can notice that there are two continuous **Name** and then two continuous **Surname** fields.

But actually i want to show these fields like in group. So the first group of name and surname and then second group of name and surname field.

How can i achieve as per the above snapshot ?

# Answer
> 5 votes
The answer is - you really shouldn't try. The logic behind your form now shows one person with two Names and two SurNames. What you want, I bet, is two persons with one Name and one SurName each. So just group Name and SurName in `fieldset` and you're good.

If you insist on not doing it, read further. You use `$form['names_fieldset']['name'][$i]` and `$form['names_fieldset']['surname'][$i]`. It means `$form['names_fieldset']['name']` is created before `$form['names_fieldset']['surname']`, so everything you put in it will be together and before surname. Just swap indexes and make them look like this: `$form['names_fieldset'][$i]['name']`, `$form['names_fieldset'][$i]['surname']` and you'll be good. Of course `$form['names_fieldset'][$i]` can be a fieldset by itself, so we are back to first paragraph.

---
Tags: forms, ajax
---


# Question
Title: Which tables are safe to omit from sql-sync?
I sync my database with `drush sql-sync @dev @live` and the other way round. Can I omit the following tables safely, like in my `drushrc.php` from `sql-sync`?

```
$options['structure-tables'] = array(
   'common' => array(
     'cache', 'cache_filter', 'cache_menu', 'cache_page',
     'cache_admin_menu' 'cache_block', 'cache_coder',
     'cache_content', 'cache_form', 'cache_hierarchical_select',
     'cache_location', 'cache_update',
     'cache_views', 'cache_views_data',
     'ctools_css_cache', 'ctools_object_cache',
     'history', 'sessions', 'watchdog'
   ),
);

```

Additionally I wanted to exclude **variable\_cache** and **views\_object\_cache** if that is safe.

Is that a good practice? Is there a list of tables somewhere on drupal.org for all modules?

# Answer
If you update to the latest dev version of Drush, you will find the following definition in examples/example.drushrc.php:

```
# $options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');

```

The wildcard syntax is very useful, as with it, it is no longer necessary to make a comprehensive list of all cache tables used by all of your contrib modules. Note that you must use the latest version of Drush pulled from git; the 8.x-6.x-dev from 18 June does not have wildcard support.
> 2 votes

---
Tags: theming, drush
---


# Question
Title: How to hide empty 'Content Zone' div in Omega?
I'm using Omega and I have "Force this zone to be rendered" unchecked in the Content Zone settings, and "Force this region to be rendered" unchecked in the Regions settings.

Any idea what would force this zone to be rendered even if there's no content? The zone is outputting this:

```
<div id="zone-content" class="zone zone-content clearfix container-24">

```

# Answer
> 0 votes
Probably because you have the debug placeholders blocks activated? There is a checkbox "Enable the debugging (placeholder) blocks" in Appereance \> subtheme \> settings \> debugging tab.

The zones are rendered even if empty.
I suggest you try with this option turned off.

---
Tags: theming
---


# Question
Title: How to specify default options in a checkbox field using Field API
I am trying to add a checkbox field to user entities using the FIELD API (in function MYMODULE\_install() )

I can create the field, but I can't pre-load it with the desired default values.

Where my code is wrong ?

```
$default_notification_field_name = "field_notification_defaults";
if(!field_info_field($default_notification_field_name))   { // check if the field already exists.

    field_create_field(
        array(
            'field_name' => $default_notification_field_name,
            'cardinality' => FIELD_CARDINALITY_UNLIMITED,
            'type' => 'list_text',
            'settings' => array(
                'allowed_values' => array(
                    'group' => t('Groups to which you subscribe'),
                    'content' => t('Authored content'),
                    'comment' => t('Replies to your comments')
                )
            ),
        )
    );

    field_create_instance(
        array(
            'field_name' => $default_notification_field_name,
            'entity_type' => 'user',
            'bundle' => 'user',
            'label' => t('Default settings for notifications'),
            'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
            'required' => FALSE,
            'widget' => array(
                'type' => 'options_buttons',
            ),
            'default_value' => array('content','comment')
        )
    );
}

```

# Answer
Try this for your instance creation:

```
field_create_instance(
  array(
    'field_name' => $default_notification_field_name,
    'entity_type' => 'user',
    'bundle' => 'user',
    'label' => t('Default settings for notifications'),
    'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
    'required' => FALSE,
    'widget' => array(
      'type' => 'options_buttons',
    ),
    'default_value' => array(
      0 => array(
        'value' => 'comment',
      ),
      1 => array(
        'value' => 'content',
      ),
    ),
  ));

```

To assist you in knowing the array structure, try this:

1. Install the devel module
2. Go to the page /devel/php on your site
3. Run this code to see all field information on your site:

```
// Show all fields.
dpm(field_info_fields());
// Show all field instances.
dpm(field_info_instances());

```
> 6 votes

---
Tags: 7, entities
---


# Question
Title: how to get backtrace information for php errors in drush
I want to get backtrace information for php errors in drush.

Tried out the following patch - http://drupal.org/node/1158322#comment-6249880. Its shows the backtrace info as message(while using browser), but I'm not getting these messages in drush

# Answer
This should be posted as a Feature Request in the Drush issue queue. I started that off for you here: http://drupal.org/node/1804600
> 2 votes

# Answer
You can do it the old-school way:

drush\_log(print\_r(debug\_backtrace()), 'error')
> 1 votes

---
Tags: 7, drush
---


# Question
Title: php and html tag problem when customizing menu items
I was trying to print the menu item description under the menu name.

I add this into the menu.inc under bootstrap theme, where the function bootstrap\_menu\_link(array $variables) is:

```
if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $element['#title'] .="<br> " . $element['#localized_options']['attributes']['title'];
  }

```

my interface then showed something like `product<br>LED Drivers` as the menu item - the `<br>` tag is printed out directly. I looked at the source code, that area shows: `<br>` , so I then tried using `<br>` in the php string, but the source code showed `&lt;br&gt;` this time. How can I correctly insert html tag into $element\['#title'\]?

# Answer
> 3 votes
You could check if where the call to the l() function is created (in the function mentioned: **bootstrap\_menu\_link**), the third parameter contains the following element in the array:

```
'html' => TRUE

```

This tells drupal to output the title of the link as html and not run it trough check\_plain().

Also, I would create a custom theme based on the bootstrap theme and add my customization there.

---
Tags: routes
---


# Question
Title: Letting users login with facebook to an existing account
My client wants to add FaceBook integration into an existing site. I've successfully setup fboauth and openid\_selector. New accounts can login without an issue. However, we liked to let an exiting user authorize a login from Facebook to their account.

I can see how to do this using `openid_selector`'s `http://yoursite.com//user/xxx/openid`. Might there be a way to duplicate this for FaceBook authentication?

**Update:** I found this node https://drupal.org/node/1624374. It seems that if a user is already logged into Drupal and then clicks the FB connect button, FBOauth will link the accounts. Though I'd prefer to have something like this managed through an interface like `openid_selector` (pictured in this post).

# Answer
> 2 votes
Configuring OpenID for each services is so painful. I have also gone through the same process when I had to enable FB, Gmail & Twitter login at my website, but anyhow it was giving me problem even if I configured with the supported modules oauth & connector.

At last I found another module named HYBRIDAUTH & it worked so fine. Configuration is easy & there is no need of any other addon module with this. Best part is, it's free, otherwise most of the module of this kind are from some paid service provider..

Try this & I hope you will find all the services which you require along with facebook.

---
Tags: users, authentication-authorization, social-network
---


# Question
Title: How to control the order in which the markup for fields appears in the outputted html source for content?
Is it possible to control (as in change) the order in which the fields appear in the html markup?

On admin page for a content type `admin/structure/types/manage/<content type>/fields` and in the Manage Fields tab, the fields can be dragged and re-ordered in the list.

However, looking at the outputted html source, the order does not change according to the order in this list. Is it supposed to? (I'd like to think it does).

I also looked at field\_weight to control the order of the output but it unclear in what the author(s) of this module mean by 'weight'. Trying this module didn't appear to change the order in the resultant html source.

# Answer
You can change tho order these fields are displayed from Manage Display `(admin/structure/types/manage/CONTENT TYPE/display)`. Edit the weight there and the fields should be displayed in the selected order on the node view page.

**Edit**: In the fields screen `(admin/structure/types/manage/CONTENT TYPE/fields)` the weight is used for displaying the form fields in the edit/add content type form.
> 5 votes

---
Tags: 7, entities
---


# Question
Title: Is there a common method to password protect registration pages?
The site I am working on requires that affiliates register on the site. I've created a profile type for affiliates with corresponding permissions and a registration page. I'd like to give access to this and the site's main registration pages without having to deal with all the spam account registration attempts. Is there a standard way of allowing only users that you want to register to have access to registration pages?

# Answer
Well, till they register/login, you can't actually say who they are.

I will suggest a CAPTCHA in the registration form. If you want to restrict it more, then you can search for email white listing modules. https://drupal.org/sandbox/amrit\_b/1768342 This is something I wrote few months back. This is still in dev. In case you don't find anything else, you can try this one.
> 0 votes

---
Tags: users
---


# Question
Title: Clean URLs not working, I can't log in to Admin Panel
I just moved my drupal website to another host. But I am unable to login as `mysite.com/user`. It gives me a `404 not found` error which means clean urls are not working afaik.

So, I checked PHP configuration with `phpinfo();` and there is `"mod_rewrite"` visible in `"loaded modules"` section.

Anyway, I wanted to disable clean urls, however if I try to login as `mysite.com/?q=user`, it redirects to `mysite.com/user` and it is giving `404 not found` error again.

So I kinda have no way to login to my website to update URL aliases. I have renamed my `.htaccess` file to disable it, result did not change.

I have updated this line:

```
  RewriteRule ^ index.php [L]

```

to this line:

```
  # RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

Still, nothing changes. Since I can't control the web server, all I have is FTP and MySQL. Any ideas?

# Answer
You can add this line to your settings.php file and it would allow you to login

```
$conf = array( 'clean_url' => 0,);

```

Another method is to find the .htaccess file in D7 root, and open it, find the `"# RewriteBase /drupal"` in codes, delete the `"#"`, change the "drupal" to your file's name: my file is "blog", "RewriteBase /blog" - the end change to this.
> 3 votes

# Answer
Why you not try first to disable the clean urls from site using something like

```
$conf = array(
   'clean_url' => 0,
);

```

in settings.php, or maybe searching in the database with phpmyadmin the variable clean\_url. Also, take a look to this post https://drupal.org/node/256410
> 2 votes

---
Tags: .htaccess, uri
---


# Question
Title: How to change the alias for the core forum landing page for drupal 6?
Core forums sets the landings page to `/forum`. I need this changed to `/some-other-name`.the forum posts can be changed using pathauto, but I need to change the alias for the top-level forum landing page. I have tried playing with url aliases but can't find anything to solve my purpose. I googled and found this exctly same question on drupal stackexchange, but I need to do it for drupal-6. Please help. Edit: im also using advanced-forum module

# Answer
> 1 votes
As Jimajamma commented, the answer was really simple.. just go to `admin/build/path/add` and in the existing system path I entered forum and in the path alias I entered `/some-other-name` and it worked, and btw if you need it for drupal 7, the go to `admin/config/path/add`.

---
Tags: 6, path-aliases, nodes
---


# Question
Title: How to use pjax module for batrik theme content?
I am trying to use pjax module for content part reloading without refreshing a page but i following the instruction form pjax read me part but not worked. How to configure the module for batrik theme content part. please help me.

# Answer
> 0 votes
It seems that the module is not maintained and importantly the module is still in unstable state.

So you shouldn't be relying on this module, unless you're ready to make it stable.

You can check the alternatives here,

How to use URL-based AJAX in Drupal 7 to serve all pages?

But AFAIK there is no module available as of now with the same feature.

---
Tags: 7, ajax, nodes
---


# Question
Title: User approval needed to reference (entity reference) their profile (profile2)
Here is the use case:

1. User registers, and creates "Employee Profile" (using profile2)
2. Admin user creates node of type Location
3. Location node references (using entity reference) user's "Employee Profile," and then displays all the employees at a location (using the Views module, and EVA)

It is all complete, but users whose profile is being referenced needs to give permission before their profile is displayed in the Location node.

# Answer
In order to achieve this, at a large scale, is to create a field on the user profile (example "Allow your profile to be displayed on Locations?" Yes or No).

Using views, filter profiles by field with value equal to yes.
> 0 votes

---
Tags: users, entities
---


# Question
Title: How to make a child entity automaticially reference back to parent entity when created using inline entity form?
Here is the example:

'Parent' Content Type = Author

* field1: Name
* field2: Age
* field3: Picture
* field4: Entity Reference to Books (inline entity form widget)

'Child' Content Type = Books

* field1: Title
* field2: Description
* field3: Entity Reference to Author using prepopulate (need help)

Author has entity reference to Books using Inline Entity Form. So when creating an "Author", we can add "Books" they have written inline.

When a user visits an individual "Book" page, I want a field that links back to the "Author" who wrote it. How can I create this link automatically when creating a "Book" inline?

I assume I have to create a Book field3 that is an Entity Reference to Author that uses prepopulate. But I have not been able to configure this correctly to get it working as wanted. Any ideas?

# Answer
> 2 votes
This has been acheived using Rules:

Export of Rule:

```
{
        "rules_ifs_backlink_populator" : {
        "LABEL" : "IFS backlink populator",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "REQUIRES" : [ "rules" ],
        "ON" : [ "node_insert", "node_update" ],
        "IF" : [
          { "node_is_of_type" : {
              "node" : [ "node" ],
              "type" : { "value" : {
                  "auction" : "auction",
                  "estate_sale" : "estate_sale",
                  "garage_sale" : "garage_sale"
                }
              }
            }
          }
        ],
        "DO" : [
          { "LOOP" : {
              "USING" : { "list" : [ "node:field-ifs-add" ] },
              "ITEM" : { "list_item" : "Current list item" },
              "DO" : [
                { "component_rules_create_entity_reference_back_link_" : { "child_param" : [ "list-item" ], "parent_param" : [ "node" ] } }
              ]
            }
          }
        ]
      }
    }

```

Export of Component:

```
{ "rules_create_entity_reference_back_link_" : {
    "LABEL" : "create entity reference back link ",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "child_param" : { "label" : "Child Parameter", "type" : "node" },
      "parent_param" : { "label" : "Parent Parameter", "type" : "node" }
    },
    "IF" : [
      { "AND" : [
          { "node_is_of_type" : { "node" : [ "child-param" ], "type" : { "value" : { "ifs" : "ifs" } } } },
          { "entity_has_field" : { "entity" : [ "child-param" ], "field" : "field_auction_ref" } },
          { "data_is_empty" : { "data" : [ "child-param:field-auction-ref" ] } }
        ]
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "child-param:field-auction-ref" ],
          "value" : [ "parent-param" ]
        }
      }
    ]
  }
}

```

---
Tags: entities
---


title: Views and Lightbox 2

text:
# Question
Title: Views and Lightbox 2
I have created a view. The view contains a title. The title currently links to the node.

I have Lightbox 2 installed.

To get the node to load in the lightbox I have to add more information to the link see below:

```
<a href="/path?format=simple" rel="lightframe[|width:800px; height:600px; scrolling: auto;]">click here to see node content</a>

```

URL paramenters Format = simple makes only the content of the node load in the lightbox window.

My question is how do I add the additional information (`?format=simple & rel="lightframe[|width:800px; height:600px; scrolling: auto;]"`) to the view title link

I am using Drupal 7

# Answer
> 1 votes
1. In your title field deselect **"Link this field to the original piece of content"**
2. select **"Rewrite the output of this field"**
3. add two fields **"Content:path"** **"Global:Custom text"** and hide them from display by selecting **"Exclude from display "**
4. In the Global:Custom text field select Rewrite the output of this field and enter **lightframe\[|width:800px; height:600px; scrolling: auto;\]**
5. Go inside your title field again. Look under **"Replacement patterns"** for **\[view\_node\]** and build up your link. Make sure the two fields Content:path and Global:Custom text are arranged before your title field or else you wont be able to use them.

Your link should look something like:

```
<a href=[path]?format=simple rel=[nothing]>[title]</a>

```

# Answer
> 0 votes
I used your method above after many hours of searching and it worked perfect.. but instead of using a 'title' field, i'm using an image thumbnail that i want to open in a lightbox with a larger image and the rest of the fields\[node\].. works great. only issue is.. when i logged out as administrator.. and you click on the thumbnail, lightbox opens, but it's blank white.. can't figure out for the life of me why. permissions are set as should be..nothing weird.. any idea?

my rewrite looks like this for the one photo field: \[field\_your\_photo\_1\] everything works great when logged in as admin, it's just empty white box when logged out..

ALTHOUGH... i must state, that when i don't use the rewrite text above....and i'm logged out, the image opens fine in lightbox (just missing node content) so it makes be wonder if some strange permission that annon users can't see the rewrite text. what do you think?

---
Tags: views, uri, javascript
---


# Question
Title: REST Service - 500 Internal Server Error
I has been trying to set up a drupal *REST Server* in my computer (a clean drupal 6 installation). Unfortunately, I could not configure it. When I send a *POST message* (WITHOUT parameters);

`ht.p://localhst/drupal/?q=note/note/retrieve` or `ht.p://localhst/drupal/?q=note/user/login`, it replies *500 Internal Server Error*.

I used this example (I copied and pasted the example to sites/all/modules) https://drupal.org/node/783460.

It is a drupal 6.28 in a Debian with Apache2. It has not configured clean URLs!

I am using the module Services (6.x-3.4-rc1) and Rest Server (6.x-2.0-beta3).

I checked the `/var/log/apache2/error.log`

> \[Sun Jun 23 17:11:24.136866 2013\] \[:error\] \[pid 2957\] \[client ::1:48424\] PHP
>
> Fatal error: Call to undefined function services\_resource\_uri\_formatter() in /var/www/drupal/sites/all/modules/rest\_server/includes/RESTServer.inc on line 15

I have another doubt, how is it possible to test these services easily? These error messages for me are not intuitive. I was using drush with watchdog but I didn't give more information.

Regards.

# Answer
> 1 votes
The problem was when I used the drush tool. It downloaded and installed the Services module, and the Rest Server module (another no necessary module).

This error was describing this conflict between modules;

> \[Sun Jun 23 17:11:24.136866 2013\] \[:error\] \[pid 2957\] \[client::1:48424\] PHP
>
> Fatal error: Call to undefined function services\_resource\_uri\_formatter() in /var/www/drupal/sites/all/modules/rest\_server/includes/RESTServer.inc on line 15

I disabled the Rest Server and restarted the *HTTP server*.

---
Tags: services, 8
---


# Question
Title: autocomplete on a multi value - custom field
I have a field organizations on the user profile(the field can accept multiple values). I would like to add a autocomplete to this field. My code for this is

```
<?php
/**
 * Implementation of hook_menu()
 */
function org_ac_menu() {
  $items = array();
  $items['org_ac/autocomplete'] = array(
    'page callback' => 'org_ac_autocomplete',
    'access callback' => TRUE,
    'access arguments' => array('access dbpedia autocomplete'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_form_alter()
 */
function org_ac_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    //$form['field_organization']['#autocomplete_path'] = 'org_ac/autocomplete';
    $form['field_organization']['und'][0]['value']['#autocomplete_path'] = 'org_ac/autocomplete'; **/* This works but only on the first input field! */**
  }
}

/**
 * Check for possibilities in dbpedia
 */
function org_ac_autocomplete($string = '') {
  $found = array();

  $url = 'http://lookup.dbpedia.org/api/search.asmx/PrefixSearch?QueryString='.urlencode($string).'&MaxHits=5';
  $result = file_get_contents($url);
  $data = simplexml_load_string($result);

  foreach($data->Result as $res_temp)
  {
      $found[check_plain($res_temp->Label)] = check_plain($res_temp->Label);
  }

  drupal_json_output($found);
}

```

The code works when I reference this element on the form, -\>

```
$form['field_organization']['und'][0]['value']['#autocomplete_path'] = 'org_ac/autocomplete';

```

But since it can accept multiple values, the autocomplete doesn't work on the remaining elements -\>`$form['field_organization']['und'][1] & $form['field_organization']['und'][2]['value']['value']`

How can I make it work on all the input elements for the organization field ?

Thanks

# Answer
> 2 votes
If you modify your hook\_form\_alter to loop through the $delta of field\_organization it should work for you on multiples...

```
/**
 * Implementation of hook_form_alter()
 */
function org_ac_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    foreach($form['field_organization'][LANGUAGE_NONE] as $delta => $field) {
      if(is_array($field) && is_numeric($delta)) {
        $form['field_organization'][LANGUAGE_NONE][$delta]['value']['#autocomplete_path'] = 'org_ac/autocomplete';
      }
    }
  }
}

```

---
Tags: 7, users, ajax
---


# Question
Title: How to skip first row in a dynamic query?
I've not yet found the right way to use **-\>range($offset,$limit)** in a dynamic query to skip first result, but without limiting the resultset (LIMIT clause).

The only workaround I've found is to use an high value for LIMIT, for example:

```
->range(1,99999999);

```

(see my comment in Drupal API documentation: https://api.drupal.org/comment/49938#comment-49938)

What's the right sintax?

# Answer
You could do something like this:

```
// Begin query build
$query = db_select('node');
$query->fields('node', array('nid', 'title'));
$query->condition('type', 'article');
$query->condition('uid', 1);

// Get total count for query
$count = $query->countQuery()->execute()->fetchField();

// Execute range query
$start = 1;
$query->range($start, ($count - $start));
$result = $query->execute();

```
> 2 votes

---
Tags: 7, database
---