# Question
Title: How can I do a cascading Entity Reference data entry or is it even possible?
I am working on a system where we want users to be able to create a Project which will be made up of one or more Project Activities, each Project Activity being constituted of several Sub-Activities.

Each Project Activity can be one of several types, and the Sub-Activities also are typed. This means that when I assign a Project Activity to a Project, I should only assign Sub-Activities of the same corresponding type.

So, I have two fields in the Project content type, one is Project Activity, the other is Sub-Activity (which can have multiple values). Both these fields are Entity References to the corresponding Project Activity and Sub-Activity content types. What I want then, is when I enter the Project and choose Project Activity type A, I should only be able to select Sub-Activities of type A also.

I had thought to do this using the Views selection with a contextual filter, however this only seems to work with a static filter when mine needs to be dynamic.

Does anyone know a way round this, or a different approach which could solve the problem?

# Answer
> 1 votes
I've not used it yet myself. But, if you want an out of the box solution you can try the Hierarchial Select module:

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
>
> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

See the project page for a Demo page.

Depending on how complex your criteria is you could also consider the `#states` Form API of Drupal 7, or a simple jquery Ajax callback on your select tags in the form.

---
Tags: views, entities
---


title: user choice for events

text:
# Question
Title: user choice for events
im creating community event site where i have city and events in that city. i would like to give option for user to select which cities he would like to see the events for. whats the best way to do this? i have created content type of city and events, and using entity referrence to tie events to the city, now im kinda stuck on how do i give a user ability to chose which city/cities he wants to view events for. thanks in advance

# Answer
> 0 votes
You can achieve what you have asked, in the following steps:

1. Create Event content type
2. Create City content type
3. Add field called events in City content type of type Entity Reference (Install and enable the module Entity Reference) - Configure the field to point to Event content type and make it multi-valued
4. Create a View of type page
5. Filter by content type for both ***Event*** and ***City***
6. Create relationship on entity reference field in City content type named events (i.e. A bridge to the Content entity that is referencing Content via field\_events)
7. Select use the relation and make it ***Required*** \- require could be useful
8. Save your view, add another filter as follow
9. Filter on content:title field, select the newly created relationship, operator choose either "Is equal to" or "Contains .." and then choose ***Expose*** filter and then
10. Apply
11. Save the view, navigate to the created page, enter the city name and the filter should show you the events that are referenced in that city, see the screenshots below

Event configuration page

Events in London

Events in Paris

All events

The view export code

```
    $view = new view();
$view->name = 'events_by_city';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'events-by-city';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'events-by-city';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'input_required';
$handler->display->display_options['exposed_form']['options']['text_input_required_format'] = 'filtered_html';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_events_node']['id'] = 'reverse_field_events_node';
$handler->display->display_options['relationships']['reverse_field_events_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_events_node']['field'] = 'reverse_field_events_node';
$handler->display->display_options['relationships']['reverse_field_events_node']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'city' => 'city',
  'event_' => 'event_',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'reverse_field_events_node';
$handler->display->display_options['filters']['title']['operator'] = 'contains';
$handler->display->display_options['filters']['title']['exposed'] = TRUE;
$handler->display->display_options['filters']['title']['expose']['operator_id'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['label'] = 'Type city name to show events taking place';
$handler->display->display_options['filters']['title']['expose']['operator'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['title']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'city' => 'city',
  'event_' => 'event_',
);
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'reverse_field_events_node';
$handler->display->display_options['filters']['title']['exposed'] = TRUE;
$handler->display->display_options['filters']['title']['expose']['operator_id'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['label'] = 'Enter city name to show events';
$handler->display->display_options['filters']['title']['expose']['operator'] = 'title_op';
$handler->display->display_options['filters']['title']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['title']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['block_description'] = 'Events by city';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'events-by-city';

```

You can also find out how to use contextual filters. I guess this tutorial can give you more ideas http://torontowebsitedeveloper.com/drupal-video-tutorials/drupal-7-node-reference-tutorial

# Answer
> 0 votes
I'd say you need the views module.

I haven't used it with entity reference before, but I think you will need to set up a new view that displays events and use the *relationship* settings to link them to your city nodes.

If you don't actually need the cities to be nodes, you could make them a taxonomy instead which is much simpler to create a view for because you can make a field on your event that directly references the taxonomy.

Finally, to 'allow the user to choose' anything you need exposed filters in your view.

---
Tags: nodes
---


# Question
Title: acquia cloud - images in content break, different path local vs cloud/server
On my local dev environment, my images are stored in (relative to server root) /sites/default/files/images/

On the server, acquia cloud implements a virtual directory and the end result is that images are stored relative to root in /files/images

In my content nodes, I'm using root-relative paths for my images. But this means any time I migrate my content between the local environment and the server, all images break.

I don't want to have to take any manual steps to change image paths every time I migrate content (I migrate content "down" from server to lcal periodically so that I am developing against "real" content).

Shouldn't there be some simpler way to configure things so that the root-relative image paths can intelligently choose the correct path based on which environment is being accessed?

# Answer
Implement a directory redirect on your local environment's web server so that any request for /files/\* gets redirected to /sites/default/files/\*

For example in Apache, edit the httpd-vhosts.conf

```
<VirtualHost *>
  ServerName yourservername
  DocumentRoot "pathtoyourdocroot"
  Redirect /files /sites/default/files
</VirtualHost>

```
> 2 votes

---
Tags: media, acquia-cloud
---


title: Add Bootstrap Carousel to Region

text:
# Question
Title: Add Bootstrap Carousel to Region
I am creating a custom front page (using a template page--front.tpl.php).

I've defined a few regions to be used on my front page. In one of these regions I would like to embed a Bootstrap Carousel (that was created with the Bootstrap Carousel module). Can this be done? It appears only `block`s can be added. A Carousel appears to be of type `content`. Perhaps this can be done using Views or a similar module?

The reason for me going this route is for simplicity of updating the carousel. Another maintainer of this website does not have PHP/HTML/CSS skills, so I would like for them to simple update the carousel using the Drupal admin interface, as opposed to updating page--front.tpl.php itself.

# Answer
> 2 votes
I did something similar and used the Views Bootstrap Module. I am not sure if you are using also a Bootstrap Subtheme, but here is what i did:

1. Installed the Bootstrap Theme and created a Subtheme.
2. Installed JQuery Update. (Most recent Bootstrap need JQuery 1.9)
3. Installed Views Bootstrap.
4. Created a Views Block for my Slides. I did it with articles which have an imagegallery field.
5. Added a contextual filter, so for each article a carousel of images can be added in form of a block.
6. In the Views Block under Format i choosed Bootstrap Carousel.

Then i had a Carousel Block to put in any region i want. You can configure your view to serve your personal needs.

---
Tags: 7, blocks, theming
---


title: Drupal 7, no toolbar, strange code

text:
# Question
Title: Drupal 7, no toolbar, strange code
I am new to Drupal. After reading about it and watching some tutorials, I tried to install Drupal 7 on my localhost to see it for myself. But now it is installed, I see no admin toolbar on top of the page. On the place where the toolbar should be I get the following code: $S$DWqdyauf.rdiK9FyIjcO5oZuwyz2HaRQiTO2Ot/5o4YIN8fxcH3u

In the middle of the page it does say 'add more content', so I guess I do have an admin account.

I tried to change the rights via PHPadmin, but sometimes I ended up having no access to the page at all anymore. When I refresh the page I get a different code. It happens in both Chrome and Explore.

What can I do to see a toolbar?

Thank you for your time. Mariska.

# Answer
Sounds like an incomplete or partially failed install. Delete all the tables in the database and try doing a fresh install.

Try performing the install with Drush so you can see in real time if there are any errors when writing to the database (look under "Quick installation with Drush"): https://www.drupal.org/documentation/install/developers

Also make sure you're running PHP 5.3+ and MySQL 5.0.15 or higher with PDO: https://www.drupal.org/requirements
> 1 votes

---
Tags: users, toolbar
---


title: How to update to jQuery v1.11.1?

text:
# Question
Title: How to update to jQuery v1.11.1?
I'm trying to implement a full screen bootstrap carousel base on this tutorial. He mention to use the jQuery version 1.11.1. And I was wondering what is the best way to upgrade to this version. I'm currently using the jquery\_update module but this module does not have the ability to upgrade to jQuery version 1.11.1.

I believe that I can use the CDN by pasting the below code in the my page template.

```
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

```

But I'm looking for the best practice to insert this jQuery version 1.11.1 on my Drupal site ?

In 2012 a similar question was ask "How do I update jQuery to the latest version I can download?" and one of the solution was to use the module \[jQuery Multi\] to have different version of jQuery.

Anyway what it the best method to update jQuery v1.11.1 ?

# Answer
The easy way is to use install jQuery Update module, which gives you the option to use new version of jQuery.

* Download the jQuery Update mobile and extract it into sites/all/modules
* Go to modules and enable the jQuery Update model
* Visit `http://mysite/admin/config/development/jquery_update` to select which version would you like to use

You can also use jQuery Multi module to update the jQuery module, the installation process is same as jQuery Update.
> 3 votes

# Answer
Use the module Jquery Update:

> Upgrades the version of jQuery in Drupal core to a newer version of jQuery.

For 1.11, I believe you will need to use the DEV version, and take a look at this item in the Issue Queue for updating to that version.
> 4 votes

---
Tags: javascript, cdn
---


title: How to prevent deleting a term if used?

text:
# Question
Title: How to prevent deleting a term if used?
Is there any way to prevent deleting a taxonomy term if it used in any node ?

I have a `Taxonomy` that is used in `Field Collection` in my `Content Type` , I want to warn/prevent deletion of any `Term` in that `Taxonomy` if it is used in any node.

I checked `taxonomy_term_confirm_delete` it is where the confirmation message is formed, I read from some posts about using

```
db_query("SELECT COUNT(nid) FROM {taxonomy_index} WHERE tid = :aid", array(':aid' => $tid) )->fetchField()

```

to get the number of nodes a term is used in but this is not working in my case -maybe because the taxonomy is in field collection ?

# Answer
I wrote an article tackling this problem.

In short, you have to use hook\_form\_alter on the form taxonomy\_form\_term and use the function taxonomy\_select\_nodes() to check if a node uses the term in question.

You can just copy the code from the article into your custom module (naming the 'mymodule\_form\_alter' accordingly to your module's name), flush the caches and that should do it.
> 6 votes

# Answer
I think you can use `taxonomy_select_nodes` function to achieve this.

> Return nodes attached to a term across all field instances.

```
taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'))

```

Parameters

**$tid:** The term ID.

**$pager:** Boolean to indicate whether a pager should be used.

**$limit:** Integer. The maximum number of nodes to find. Set to FALSE for no limit.

**$order:** An array of fields and directions.
> 1 votes

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


# Question
Title: How to display all record from database in Drupal?
```
global $user;
$nid = '650';

$query = db_select('field_data_field_batch_reference');
$query->fields('field_data_field_batch_reference', array('field_batch_reference_target_id'));
$query->condition('entity_id', $nid, '=');
$result = $query->execute()->fetchField();
drupal_set_message($result);

```

# Answer
You should use a different method on the query object to get all results.

e.g `fetchCol()` to get an array when querying for a single column value (in this case `field_batch_reference_target_id`):

```
global $user;
$nid = '650';

$query = db_select('field_data_field_batch_reference');
$query->fields('field_data_field_batch_reference', array('field_batch_reference_target_id'));
$query->condition('entity_id', $nid, '=');
$target_ids = $query->execute()->fetchCol();
drupal_set_message('<pre>' . var_export($target_ids, 1) . '</pre>);

```

You could also then load those entities with something like

```
$entities = entity_load_multiple('entity_type', $target_ids);
drupal_set_message('<pre>' . var_export($entities, 1) . '</pre>);

```

Keep in mind that will load all results, so you may want to add a limit to your query instead, e.g:

```
$query->range(0, 25);

```
> 0 votes

# Answer
To fetch all the records from the database, you can also use fetchAll() with your query.

```
$query = db_select('field_data_field_batch_reference',fr);
$query->fields('fr', array('field_batch_reference_target_id'));
$query->condition('entity_id', $nid, '=');
$result = $query->execute()->fetchAll();

```

It will return multiple results to display.

Hope it works for you!
> 0 votes

---
Tags: database
---


title: check if user exists

text:
# Question
Title: check if user exists
I want to check if user exists based on some profile2 field. I have tried the following. Works fine. I want to know if it is proper or not. If it is not proper, is there any other way around?

```
function checkUserExistsByProfile($company_id){

        $query = 'SELECT field_somefield_value
        FROM {field_data_field_somefield} AS fn
        WHERE fn.field_somefield_value  =:rids';
        $result = db_query($query, array(':rids' => array($company_id)));

        $field_value = $result->fetchCol();
        return count($field_value);

    }

```

Please suggest.

**UPDATE:**

I have tried solutions suggested by Mołot, Bulat as follows.

Profile Field name is `field_ngouniqueid`

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
->fieldCondition('field_ngouniqueid', 'value', (int)$company_id, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));

```

But users is an empty array always. But it has a record with value `$company_id`

**Solution:** it should be **$query-\>entityCondition('entity\_type', 'profile2')**

# Answer
> 0 votes
To get the users filtered based on profile2 field, `field_ngouniqueid` is created through **profile2**

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
->fieldCondition('field_ngouniqueid', 'value', (int)$company_id, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));

```

---
Tags: 7, users
---


title: Bootstrap tooltip form inline errors

text:
# Question
Title: Bootstrap tooltip form inline errors
I tried "Inline Form Errors" module but it add errors message content after form element. How to add inline form errors with bootstrap tooltip or popovers directly to inputs and selects? Does somebody do something like this?

# Answer
> 1 votes
Solve this by element pre render callback and ife module.

```
function _custom_bootstrap_pre_render_input($element) {
    $types = array(
        // Core.
        'password',
        'password_confirm',
        'select',
        'textarea',
        'textfield',
        // Elements module.
        'emailfield',
        'numberfield',
        'rangefield',
        'searchfield',
        'telfield',
        'urlfield',
    );
    if (empty($element['#type']) || !(in_array($element['#type'], $types) || ($element['#type'] === 'file' && empty($element['#managed_file']))) || !isset($element['#id'])) {
        return $element;
    }
    $error = ife_errors('get', $element['#id']);
    if (!empty($error)) {
        $element['#attributes']['class'][] = 'error-tooltip';
        $element['#attributes']['data-content'][] = $error;
    }
    return $element;
}

```

---
Tags: forms
---


# Question
Title: How to add form on ubercart checkout complete page?
I have latest Ubercart 7.x-3.6 on Drupal 7.31 installation. I want to add a form on cart/checkout/complete page. which api can I use to add a form on checkout complete page.

EDIT:

Ubercart's core cart checkout complete page contain an order submit message and created order link, right? Now I want to add a form bellowed to the contents of checkout complete page. I think its enough detail.

# Answer
Create a custom module and use hook\_form to create your form.

Then I would do as suggested in this post to add your custom form to the ubercart page you wish to edit, only instead of rendering items, call your new function. Does that make sense?
> 1 votes

---
Tags: ubercart
---


# Question
Title: How to use entity_metadata_wrapper for users particulary in hook_user_presave
For node I can use the entity\_metadata\_wrapper like below

```
function mymodule_node_presave($node) {
  $ewrapper = entity_metadata_wrapper('node', $node);
  $ewrapper->title->set('new title');
}

```

However how can I use the entity\_metadata\_wrapper for users. I want to use entity\_metadata\_wrapper in hook\_user\_presave.

```
function mymodule_user_presave(&$edit, $account, $category) {
  ???
}

```

this variant works for me:

```
function mymodule_user_presave(&$edit, $account, $category) {
  $edit_object = (object) $edit;
  $ewrapper = entity_metadata_wrapper('user', $edit_object);
  $field_telefon = $ewrapper->field_telefon->value();
  $ewrapper->field_telefon->set($field_telefon.'123');
  $edit = (array)$edit_object;
}

```

# Answer
> 1 votes
Try casting $edit as an object:

```
function mymodule_user_presave(&$edit, $account, $category) {
  $ewrapper = entity_metadata_wrapper('user', (object) $edit);
}

```

---
Tags: 7, entities, users
---


# Question
Title: How to remove edit tab after create commerce order
How to remove edit tab after create order for Authenticated User.

# Answer
You should edit the permissions for the user role in question. Doing so will mean they will not have access to edit orders, and only create them if you so choose to.

It might be a little easier to use the secure permissions module to manage the permissions in code.
> 1 votes

# Answer
You might find Tab Tamer useful for that.
> 0 votes

---
Tags: commerce
---


# Question
Title: HybridAuth: How to bypass 'allow access' button
I have installed HybridAuth module to login in LinkedIn. The following is the url through which user can log in from Popop window.

> http://www.mydrupal.com/hybridauth/window/LinkedIn?destination=node/38&destination\_error=node/13

The logged in window gives 'allow access' button each time when open a popup.

**Question:** How to bypass this 'allow access' button after the first attempt? I have already gone through various links but could not get proper idea.

**Screen shot** is as follows.

# Answer
I am also face the same problem, But am using ulgoin module. After login You must first authorize LinkedIn integration to use related features.

In this button available in user edit page. Once you have synchronized your details , in the above message not appear in the second attempt.

Thanks
> 1 votes

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


# Question
Title: add variable to process_page($vars) in form function
Is there an option to change $vars array in form function? I would like to pass some variables to page template in form creation function .. If not, what are other options to influence page.tpl from form?

EDIT: I have a function for form creation and i would like to add page class if some params are sent to this function.

```
function mymodule_test_form($form, &$form_state, $param){
  if ($param == 'special'){
    #add class to page
  }
}

```

thanks!

# Answer
> 0 votes
It seems to me that you are talking about two different things: altering form fields vs. modifying the $variables array in page.tpl.php.

1) When you say "form creation function", what I hear is that you want to change fields in an existing form. For this, you would want to implement hook\_form\_alter(). If you want to learn more about how to structure a form, visit the Form Generation page in the Drupal API.

2) If actually you meant that you want to add or change variables in your `page.tpl.php` file, then you'll want to implement hook\_preprocess\_page().

# Answer
> 0 votes
I think you want add some variable to prepared variables in `page.tpl.php` for this job you should add it in you `template.php` file in your current theme.

create a function start with your theme name ,(as example if I use mytheme , it will be function `mytheme.preprocess_page`) , then add your variables to $variables array ( be sure that it passed by reference in function (&$variables) )

as example

```
function ThemeName_preprocess_page(&$variables) {

$variables['gregab'] = 'Hello,I am new variable :)';
  }

```

//Part of Page.tpl.php Anywhere put this variable

print $gregab;

Then clear the cache (dont forget every time you change the 'tpl\` files clear the caceh)

enjoy!

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


# Question
Title: use different "From" header for different actions when sending emails
So for example, when a user's creating an account, I want to have the sent email use "From: register@example.com" header.

But also, when I will approve his content I want to use the header "From: info@example.com"

Right now, all emails sent are using the same "From" email header provided in the "Site information" settings.

Any ideas on how to achieve this? Thanks

# Answer
> 1 votes
use hook\_mail\_alter function in your custom module and change the from address based on your requirements.

---
Tags: 7, emails
---


title: Creating new template for new page

text:
# Question
Title: Creating new template for new page
In drupal 7, I created a content type called page and set the url to /about. If I check the source code I see

```
<link rel="canonical" href="/website/about">

```

and

```
<link rel="shortlink" href="/website/node/7" />

```

So if I create a new template called page--node--7.tpl.php then it works. But if I create a new template called page--about.tpl.php it wont get picked up.

What am I doing wrong here?

Thanks!

# Answer
I think you have issue with **hook\_suggestions** that we need to configure correctly for a template to work.

Its already answered here

drupal 7 template suggestions based on path alias

Hope it will help!
> 1 votes

# Answer
You aren't doing anything wrong per se Jean.

I am assuming that you created the content type page and then created a node of the type page. To create a template for just the page you just created and not all of the instances of the content type page, using the node ID is a fairly standard solution. If you want to have that template for all instances of the content type page then you would use page--Content\_Type\_MACHINE\_NAME.tpl.php

You also need to add a preprocess function for that to function:

```
function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

I am curious about naming your new content type page since Drupal has a Basic Page content type with the machine name of page already. What is the machine name of your new content type?

If you absolutely must have the template based on the URL then it looks like you need a different preprocess function. I'd think twice about approaching it this way since it is so easy to change the path/alias. You will need to install the path module for this preprocess function to work:

```
<?php
/**
 * implements theme_preprocess_page() function
 */
// drupal7 code
function yourthemename_preprocess_page(&$vars) {
  // create template based on url aliases if path module is enabled
  if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
    if ($alias != $_GET['q']) {
      $template_filename = 'page';
      foreach (explode('/', $alias) as $path_part) {
          // d7 contains two underscore _ after page.
         // During creating tpl file underscore (_) is converted to dash (-)   i.e page--gallery.tpl.php
        $template_filename = $template_filename . '__' . $path_part;        $vars['theme_hook_suggestions'][] = $template_filename; // drupal 7
      }
    }
  }
}
?>

```
> 1 votes

---
Tags: theming, 7
---


# Question
Title: How to add custom email to account user emails?
There are a few email templates in account user emails page: "/admin/config/people/accounts".

How can i add custom emails from my own module? I would like to have&edit all email templates in the same place.

# Answer
This form is defined in core user module, user.admin.inc file:

```
/**
 * Form builder; Configure user settings for this site.
 *
 * @ingroup forms
 * @see system_settings_form()
 */
function user_admin_settings() {

```

Particularly, line 444 starts email template section:

```
$form['email'] = array(
    '#type' => 'vertical_tabs',
  );
  // These email tokens are shared for all settings, so just define
  // the list once to help ensure they stay in sync.
  $email_token_help = t('Available variables are: [site:name], [site:url], [user:name], [user:mail], [site:login-url], [site:url-brief], [user:edit-url], [user:one-time-login-url], [user:cancel-url].');

  $form['email_admin_created'] = array(
    '#type' => 'fieldset',
    '#title' => t('Welcome (new user created by administrator)'),
    '#collapsible' => TRUE,
    '#collapsed' => (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) != USER_REGISTER_ADMINISTRATORS_ONLY),
    '#description' => t('Edit the welcome e-mail messages sent to new member accounts created by an administrator.') . ' ' . $email_token_help,
    '#group' => 'email',
  );
  $form['email_admin_created']['user_mail_register_admin_created_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#default_value' => _user_mail_text('register_admin_created_subject', NULL, array(), FALSE),
    '#maxlength' => 180,
  );

```

As you can see, there is no `foreach`, no external hook call, nothing. Just raw fields hardcoded. The only way is to add your fields using `hook_form_alter()`. Make sure you also add your validators and submit handler to take care of your new fields, because user module will not do it for you.
> 1 votes

---
Tags: emails, users
---


# Question
Title: Invoke custom JS function in AJAX callback?
Is it possible to invoke a custom JS function in an AJAX callback?

```
function MY_MODULE_ajax_callback() {
  // Define a new array to hold our AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX command that replaces the #page text with our own text.
  $ajax_commands[] = [CUSTOM JS FUNCTION]

  // Return our commandS
  return array('#type' => 'ajax','#commands' => $commands);
}

```

# Answer
You can't run an arbitrary script, but if you can wrap your JS functionality in a jQuery plugin you can use `ajax_command_invoke` to get the same effect, e.g.

```
$selector = 'body';
$method = 'myJqueryPlugin';
$args = array('arg1', 'arg2');

$ajax_commands[] = ajax_command_invoke($selector, $method, $args);

```

When that comes out in the front end it'll execute something equivalent to

```
$('body').myJqueryPlugin('arg1', 'arg2');

```
> 6 votes

# Answer
Yes, it is.

Code sample:

```
$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',
);

```

JS Code:

```
(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);

```
> 11 votes

---
Tags: 7, ajax
---


title: Custom Field type was empty in views

text:
# Question
Title: Custom Field type was empty in views
Im build a module, and this module was add a new field type, and all its good, but when i try to use this field in view, its print empty.. no value.., but when I use delta field, its retrieve value ..

look here:

how i can integrate field value with view ..?

this code I used for create field ..

```
// Install New type of field module.install
function custom_anees_location_field_schema($field) {
  $schema = array();
  $schema['columns']['option'] = array(
      'type' => 'varchar',
      'length' => 25,
      'not null' => FALSE
  );
  return $schema;
}
 // mymodule.module
function custom_anees_location_field_info() {
  return array(
    'country_list_location' => array(
      'label' => t('Country Location'),
      'description' => t('Field For spesfic Location content'),
      'settings' => array('max_length' => 255),
      'instance_settings' => array(
        'text_processing' => 0,
      ),
      'default_widget' => 'options_select',
      'default_formatter' => 'states_field_options',
    ),
  );
}

function custom_anees_location_field_widget_info_alter(&$info) {
  $widgets = array(
    'options_select' => array('country_list_location'),
  );
  foreach ($widgets as $widget => $field_types) {
    $info[$widget]['field types'] = array_merge($info[$widget]['field types'], $field_types);
  }
}

function custom_anees_location_element_validate($element, &$form_state) {
  switch ($element['#type']) {
    case 'textfield':
      if ($element['#value'] == '') {
        form_error($element, t('Case Name may not be blank.'));
      }
      break;
    case 'checkboxes':
      if (empty($element['#value'])) {
        form_error($element, t('You must give at least one role access to this state.'));
      }
      break;
  }
}

```

# Answer
You need to let Views know about your custom field in database with `hook_views_data`. Here is an article that explains all about it: http://blog.menhir.be/2008/10/22/expose-database-fields-to-views-in-a-custom-drupal-module/
> 0 votes

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


# Question
Title: image style not applied porgrammatically
I create below function to create image style programmatically

```
function imh_get_image_from_uri($image_uri, $style) {
    $derivative_uri = image_style_path($style, $image_uri);
    $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
    $new_image_url = file_create_url($derivative_uri);
    return theme_image(array('path' => $new_image_url));
}

```

and call in my tpl with

```
 imh_get_image_from_uri($node->field_cast_image['und'][0]['uri'],'215x317');

```

and a example of image created path is

`http://mydomain.com/sites/default/files/styles/215x317/public/Hugh%20Jackman-2.jpg`

I check the images style , as expamle this image image style set to scale `215` * `317`,every thing seems work good but when I see image directly I see the image in this path not resized ( I call my function with another image style but also they are not resize or scale or ....) , The images that use build-in drupal image style work correctly but when I use top function to load image style programmatically the image style action (resize, scale ,... ) not applied, the image create on that path but noting applied on it.

where is problem?

**update** Also I try

```
$build = array(
  '#theme' => 'image_style',
  '#path' => $image_uri,
  '#style_name' => $style,
    );
return render($build);

```

**output** `<img src="http://mydomain.com/sites/default/files/styles/215x317/public/Hugh%20Jackman-2.jpg?itok=PcP0uFjT" width="215" height="317">`

but the problem exists yet, the file in the image path exists but not resized. it seems change it by style ( not resized main image)

# Answer
The solution is

```
  return  theme('image_style',array('style_name' => $style, 'path' => $image_uri));

```

but this not work first because the image style for that file created before , first I should remove it then try this ;)
> 0 votes

# Answer
I had a similar problem. This solved my issue, maybe it can help you out.

```
$image = field_get_items('node', $node, 'field_image');
$image_output = render(field_view_value('node', $node, 'field_image', $image[0],
array('settings' => array('image_style' => 'medium', 'label' => ''))));

print render($image_output);

```
> 0 votes

---
Tags: media
---


# Question
Title: Call Remove Button (File Upload) Programmatically using JavaScript
How can I call the remove button of temporary uploaded file programmatically using JavaScript?

I want to clear the form fields when the condition changes. I've done all the form fields exept the temporary uploaded file.

Can I call the remove function? If yes, Where is it?

# Answer
> 1 votes
Easiest way to do is what @Molo mentioned in his comment.

```
$('#element_id').trigger("click"); OR $('.element_class').trigger("click");
$('#element_id').trigger("mousedown"); OR $('.element_class').trigger("mousedown");

```

Or you could, reset the .html() of the upload element

```
$('#'+id).html($('#'+id).html()); OR  $('.'+class).html($('.'+class).html());

```

JavaScript into Drupal can be done in various ways, you could reference your javaScript file in your theme's info file or you override the drupal\_add\_js function in template.php and add your JavaScript.

For more Information on how to put JavaScript into Drupal see this or this and these (module or module) could also be handy. This article explains how to programmatically submit a form in Drupal.

Here is a good tutorial, how to add your JavaScript to Drupal https://www.drupal.org/node/756722

---
Tags: webforms, entities
---


# Question
Title: Which module is work good with profile2 to show profile complete status?
I am using profile2 module in drupal 7. I want to use percentage to show profile complete status. I already use profile complete percentage module but i am not getting proper result. Please help which module is work with profile2. Thanks

# Answer
> 1 votes
Use this Profile Complete module for Profile completion in Percentage.. I didn't use it. But I think it will help to u...

# Answer
> 0 votes
The Field\_Complete module might also be of help: https://www.drupal.org/node/2049963

Based on this blog post by the author, it should be compatible with Profile2: http://drupal7ish.blogspot.co.uk/2013/09/field-complete-and-profile2.html

---
Tags: 7, users
---


# Question
Title: hook_module_implements_alter() to put hook implementations into separate files - bad practice?
In a number of modules I wrote, I use hook\_module\_implements\_alter() to split up the \*.module file, and to move hook implementations into separate files.

The main reason is that I passionately hate long files. (and yes, this does make me unhappy about a lot of the files in Drupal 7 and contrib)

Examples:

I know there are a few things to consider:

1. It might not work for all hooks. E.g. boot or install, or hooks that are not called via module\_implements().
2. It is important to include the respective file from within the hook\_module\_implements\_alter() implementation, due to the way that module\_implements() works.

Now I heard from a long-time and well-known Drupal developer that this practice is problematic. https://drupal.org/node/2230319 (topic starter, and comments #5 and #11).

Before I start moving functions around, I would like to hear from others whether and why this is bad, both technically and aesthetically.

EDIT: I guess this could be split in two questions:

1. Is it good or bad to split up your \*.module file, so that hook implementations live elsewhere?
2. Is hook\_module\_implements\_alter() reliable enough, or should I rather use `include_once __DIR__ . '/MYMODULE.filename.inc'` directly in the \*.module file? What could possibly go wrong by using hook\_module\_implements\_alter() for this?

# Answer
> 4 votes
I just found the piece of information that was missing.
EDIT: And another one.

# Problem with module\_invoke()

`module_invoke_all()` always calls `module_implements()`, which checks the module include file by checking both `hook_hook_info()` and `hook_module_implements_alter()`.

However, `module_invoke()` only checks `hook_hook_info()` and *not* `hook_module_implements_alter()`.

`module_invoke()` is called e.g. in `_block_render_blocks()` for `hook_block_view()`. This means that `hook_module_implements_alter()` is not a good solution to split a `hook_block_view()` implementation into a separate file.

This has been a problem in Crumbs, see https://www.drupal.org/node/2328535.

For other hooks it generally works ok, but you never know if a specific module wants to use `module_invoke()` instead of `module_invoke_all()`.

# module\_implements() cache polluted in bootstrap.

Another problem is caused by a core issue reported here:
module\_implements\_cache() can be polluted by hook\_boot() implementations calling module\_invoke\_all() directly or indirectly

This applies only to *non-boot modules*, where it can happen that the implementation of `hook_module_implements_alter()` is never discovered.

1. An unexpected chain of events causes `module_implements($hook)` being called from `hook_boot()`.
The `$hook` can be any random hook, it does not need to be related to the module we are working on.
2. This causes `module_implements('module_implements_alter')` to be called.
3. Drupal looks for all implementations of `hook_module_implements_alter()`. At this time, `MODULENAME.module` is not included yet.
Therefore, for the rest of the request, Drupal assumes that the implementation `MODULENAME_module_implements_alter()` does not exist.
4. Later in the request, implementations of other hooks are being discovered, but the implementations by MODULENAME are not being found, because `MODULENAME_module_implements_alter()` is not being executed.

# Alternatives

## require\_once

Alternatives have already been mentioned. Instead of these tricks, one can include the file directly. There may be a tiny performance impact but this is probably overshadowed by a lot of other things in Drupal.

But, instead of using `module_load_include()`, I would suggest a more direct solution:

```
require_once __DIR__ . '/crumbs.block.inc';

```

Or to be PHP 5.2 compatible:

```
require_once dirname(__FILE__) . '/crumbs.block.inc';

```

## Why not module\_load\_include()?

There is generally no need to call `module_load_include()`, it could even be detrimental, if the \*.module file is included from you-dont-know-where (e.g. from `settings.php`), and you don't know if `module_load_include()` is available.

This function is mostly there to help you determine the location of *other* modules. But if you are including *within the same module*, it is generally safer and easier and faster to work with relative file paths and explicit `require_once`.

## Call to helper function

As mentioned by Jimajamma, you can also implement the hook in the main `*.module` file, and then include another file and call a helper function from there. This is done e.g. in Display suite.

This solution is ok, although I think it still clutters the main file, and gives you even more places to look.

And here likewise you can use require\_once instead of `module_load_include()`, if it is within the same module.

# Answer
> 2 votes
Any major project I have worked on has broken things up into manageable and easily assignable pieces; basically ending up like @tenken mentioned here, or to the point where `foo.module` ends up being only includes:

```
<?php

module_load_include('inc', 'foo', 'foo.defines');         // bring in our define()s
module_load_include('inc', 'foo', 'foo.HOOK1');           // bring in our HOOK1 functions
module_load_include('inc', 'foo', 'foo.HOOK2');           // bring in our HOOK2 functions

// ...etc

```

Of course, I have also seen, and used, situations where admin only or otherwise rarely used hooks are included like:

```
function foo_HOOK(/* $args */) {
  module_load_include('inc', 'foo', 'foo.HOOK');
  return _foo_HOOK(/* $args */);  // _foo_hook() is defined in foo.HOOK.inc
}

```

# Answer
> 1 votes
If I try to breakup my .module file across multiple files I tend to do what Features for D7 does for its "included" files which it uses include\_once() for:

```
include_once('MYMODULE.features.inc');

```

For D7 I still use my module's name "function namespacing" for these included files, and private module functions typically are prefixed as "\_MYMODULE\_foo()".

This answer kinda ignores your desired use of Autoloading classes and any OO related patterns you're trying to use within your code (code dependencies, etc).

In your linked issue it sounds like you want to use hook\_module\_implements\_alter() to be a readable index of what files have what functions in your .module file. I think sane 'MYMODULE.PURPOSE.inc' filenaming is enough to clue a developer of the use of that include file within your module.

---
Tags: 7, hooks
---


# Question
Title: drupal 7 - views conditional not working
I have a content type that has an External Link (field type: Link) which is an optional field. So users can either type in a url or not. I've created a View where I want to show the latest 2 content types.

I want to be able to display the nodes where its Title either links to the External Link or the url of the content. I already have Views Conditional enabled but I dont think Im setting it up correctly because the nodes arent using the proper url. The url is "http://localhost.test:8888/\[path\]. The 2nd node is correct though, it has http://yahoo.ca which is the External Link that I used.

If anyone has any clue why the settings arent correct, please let me know why. THanks.

# Answer
> 1 votes
If I correctly understand your point, you would like a view to display two latest nodes of a specific content type. While displaying these nodes the view should check:

1. External link is provided or not

If External link is provided then output that as a field of view, if External link is not provided then output the URL Path of the content.

I can achieve this with just Views without the need of the Conditional one, unless I am misunderstanding your questions. I have the following steps for you to achieve what I stated here,

1. Create a content type with link field and either Pathauto or custom URL supplied
2. Create a view with content type as the one created
3. Choose Field for ***Format Show*** and the select whichever field of the content type you are interested including the ***External Link & Path*** fields
4. Click on the external field link, once opened change the title to ***New Title or whatever fancy***
5. You would need to use the ***NO RESULT BEHAVIOR*** settings of this field
6. In ***NO RESULT BEHAVIOR*** supply the placeholder for PATH which is ***\[path\]*** \- The path should be included among the fields
7. Save and there you go the result, if the node is not having an External link then it will display the path as value of external field, otherwise it preserves the supplied external URL. Screenshot for more detail

Create content types as follow: Configure view as follow Configure the NO RESULT BEHAVIOUR as follow There you go the result of your view, first content types does not have external URL and the second content types does have (don't forget to include the path as one of the fields or you won't be able to access it)

---
Tags: views
---


# Question
Title: Intending to select user role while creating the node to control the node visibility
I have simple requirement.

I have multiple user roles. What I want is that when I create a node, I could select a role of the user which is able to see this node.

Or may be by default all roles are selected and I could deselect them to modify the visibility.

Any module or help?

Best.

# Answer
try one of the following:

Node Access:

> The modules provide roles and user specific security permissions for menus, menu items, nodes, and security integration into the administration and help systems.

nodeaccess:

> Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role.

Content Access:

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
> 0 votes

---
Tags: users
---


# Question
Title: How to have different displays for the same node type using Display Suite?
I use display suite module to manage the display of node types. So far so good.

I know that there is a way to have different display for the same node type. Let's say I have 2 nodes of the basic page node type. Then I'd like to set **2 column stacked** for the first one and **single column** for the second node.

But I don't know hot to do it.

# Answer
If the nodes are the same content type, I don't think Display Suite will be enough by itself. You'll have to use another module such as Views or Panels and configure that to specify which display for which node should be shown when.

FYI, there was a pretty good session introducing the many uses of Display Suite at Drupalcon London 2011, which you can watch online.
> 0 votes

# Answer
You can easily do this with display suite but you need to enable the DS extras module.

First create 2 different view modes using different layouts to cover your specific use case.

Next go to admin/structure/ds/list/extras and enable 'View mode per node'.

Now when you create content you can choose which view mode you would like the content to use.

This is a great way to give your content editors control over layout choice.
> 3 votes

# Answer
A module that extends Display Suite is being written (by clint.beacock) to achieve this (i.e. different displays on a per node basis), although at the time of writing it is not ready for production use:

http://drupal.org/node/1632730
> 2 votes

# Answer
If your choice of the view mode for a node depends on some external condition and / or you have a lot of nodes to switch view modes for and / or the choice of view mode has to change over time, you can use the module Contextual View Modes.

It adds to the "View mode per node" feature of the Display Suite Extras module by allowing you to switch view modes for all nodes of a content type based on Context conditions. It also includes options to override these global settings with other conditions for an individual node.
> 1 votes

# Answer
The answer is definitely to use multiple view modes. View modes are different configurations of field displays per bundle. D7 comes with "default" and "teaser" but you can add more via hook\_entity\_info\_alter() or by using Display Suite to do this through an easy interface.

The next question is how to actually show the user the 2nd view mode – on node/123/view it's going to use 'default'. You can use a different view mode by using Views and selecting the alternative view mode on the node display settings, or you could load the node programmatically and set the view mode there:

```
$node = node_load(123);
$node_view = node_view($node, 'my_custom_view_mode');
return $node_view;

```
> 0 votes

---
Tags: display-suite, entities
---


# Question
Title: How to disable a language while still being able to create content for it
I have a website with already 2 languages. I want to add a 3 one, but I obviously don't want it to be accessible until it is finished. If I disable to language, I can't create content in it anymore.

Anyone has a suggestion?

Thank

# Answer
You could try to use the Hidden Language module.

> This module allows site admins to hide languages from end-users. As opposed to disabling language content editors still can translate content to that language. It's useful if you don't have entire website translated.
> 1 votes

# Answer
when testing new items, elements, modules, etc a general rule of thumb:

* only test on a test(development) server - never test new items on a production server

I would suggest something along these lines:

* If you haven't already, set up a test server on a local machine - there are plenty of resources available to do this depending on your OS
* take a backup of the current production site files and DB
* copy those to your test server so you have a mirror to work with
* make all changes to modules, settings, etc - keep track of the changes you make
* test new settings
* when testing shows you have it the way you want, make the changes you recorded earlier to the production site
* BEFORE DEPLOYING ON PRODUCTION SITE: MAKE ANOTHER BACKUP COPY OF PRODUCTION DB AND FILES
* test on the production site imediately, preferrably putting it into maintenance mode so users can't inadvertantly change things or add content that may be lost - if anything is wrong you can restore the site from the most recent backup
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Adding content type field value to a taxonomy term?
What I'm trying to say at the title is, I have this Select List field that gets its values from a taxonomy called "Thing".

The taxonomy term are (Thing-1,Thing-2,Other). When "Other" is selected a text field called "Specify" will appear. What I'm trying to do is when the user submits the form. Whatever he placed on the "Specify" field will be added as a "Thing" Taxonomy term.

So the terms will be (Thing-1,Thing-2,New Thing,Other).

I might be over explaining this, but I can't find anything on google.

# Answer
> 1 votes
If you are using Select (or Other) module and it does not specifically need to be a taxonomy term, there is an option for exactly this:

> On the field edit page, the "Other value as default value" allows you to select how other will be handled:
>
> * Add the values to the other textfield-\> store the value but don't change the list
> * Append the values to the current list-\> store the value and add to the list attached to the node/user/entity
> * **Append the values to the available options-\> store the value and add the value to the list so that it can be selected on other nodes/users/entities**
> * Ignore the values-\> do not store the value

**EDIT (courtesy of DuaelFr)**

You will need the 7.x-3.x-dev version to be able to use this module on a Taxonomy Reference Widget.

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


# Question
Title: Need help on adding options to $form via select field
I altered the username field in login block into a select field and now I'm trying to filter the usernames by their user roles via another Select Field.

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

    $users = entity_load('user');
    $user_names = array();
    $acc = array("PH","SL");
    $rolePH = array();
    $roleSL = array();
    foreach ($users as $user_id => $user) {
    $user_names[] = $user->name;
      if (in_array('PH', array_values($user->roles))) {
        $rolePH[] = $user->name;
      }
      elseif (in_array('SL', array_values($user->roles))) {
        $roleSL = $user->name;
      }
    }
    $user_arr = array_combine($user_names, $user_names);
    if($form_id=="user_login"){
    $form['roles']['#type'] = "select";
    $form['roles']['#weight'] = -0;
    $form['roles']['#size'] = 'auto';
    $form['roles']['#options'] = $acc;
    $form['roles']['#title'] = t('Role');
    $form['name']['#type'] = "select";
    $form['name']['#options'] = $user_arr;
    $form['name']['#required'] = true;
    $form['name']['#size']= 'auto';
    $form['name']['#title']= t('Organization');

    }
}

```

I'm a bit stuck, as you can see, I already separated users depending on their roles. My problem is how do I set the $form\['name'\] options when a role is selected. Right now I'm just showing all users in the DB.

# Answer
Borrowed From HERE:

```
If you want to do this hardcoded, you might try to use the #ajax property of the Form API

You can reload your second dropdown on change of the value of the first dropdown and change the value while reloading the form.

I made a little example to give you an idea :

$form['number'] = array(
  '#type' => 'select',
  '#title' => t('Select Number'),
  '#options' => array(
      0 => 1,
      1 => 2,
      2 => 3,
  ),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'ajax_replace_dropdown_default_value_callback',
    'wrapper' => 'wrapper-dropdown',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

$default_value = !empty($form_state['values']['number']) ? $form_state['values']['number'] : 0;

$form['open_closed'] = array(
  '#type' => 'select',
  '#title' => t('Open / Closed ?'),
  '#options' => array(
      0 => t('Open'),
      1 => t('Closed'),
      2 => t('Progress'),
  ),
  '#value' => $default_value,
  '#prefix' => '<div id="wrapper-dropdown">',
  '#suffix' => '</div>',
);

function ajax_replace_dropdown_default_value_callback($form, $form_state) {
  return $form['open_closed'];
}

In your case you will have to do it in a hook_form_alter and add the #ajax property to your first dropdown and add prefix and suffix to give the second dropdown the proper value.

You can also check this link about AJAX with the FORM API :

```
> 0 votes

---
Tags: forms
---


# Question
Title: Views and entity reference: How to avoid duplicates?
I have a content type named »essay« with a entity reference field. Now I want to create a view that show all entities that are referenced by all »essays«. To achieve that I created a view that filters all essays, I added a relation ship to the reference field and now I can show any field of the referenced entities as wished.

But: If two or more essays do reference to the same entity, those will be shown twice or more times. Is there a way to avoid those duplicates?

I do not use any fields from the essay to show in the view, but I do filter the essays by a contextual filter. So the distinct option of the query settings does not work. I think, this is because each row of the view represents an distinct essay and than I join the referenced entities. So from the database point of view the rows are distinct. Am I wrong?

This is a trimmed version of my view:

```
$view = new view();
$view->name = 'clone_of_objekte';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Clone of Objekte';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Objekte';
$handler->display->display_options['css_class'] = 'objects margin-large';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'load_more';
$handler->display->display_options['pager']['options']['items_per_page'] = '2';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'grid';
$handler->display->display_options['style_options']['columns'] = '2';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['hide_empty'] = TRUE;
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_object_reference_target_id']['id'] = 'field_object_reference_target_id';
$handler->display->display_options['relationships']['field_object_reference_target_id']['table'] = 'field_data_field_object_reference';
$handler->display->display_options['relationships']['field_object_reference_target_id']['field'] = 'field_object_reference_target_id';
$handler->display->display_options['relationships']['field_object_reference_target_id']['label'] = 'Referenced from field_object_reference';
/* Field: Content: Bilder */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['relationship'] = 'field_object_reference_target_id';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'objects_small',
  'image_link' => 'content',
);
$handler->display->display_options['fields']['field_image']['delta_limit'] = '1';
$handler->display->display_options['fields']['field_image']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_image']['separator'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'essay' => 'essay',
);

/* Display: Objects for parent */
$handler = $view->new_display('block', 'Objects for parent', 'objects_views');
$handler->display->display_options['display_description'] = 'Shows the objects that are related to a list of essays';
$handler->display->display_options['defaults']['query'] = FALSE;
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['query']['options']['pure_distinct'] = TRUE;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Has taxonomy term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_index';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['default_action'] = 'default';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['tid']['default_argument_options']['index'] = '2';
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['tid']['reduce_duplicates'] = TRUE;
$translatables['clone_of_objekte'] = array(
  t('Master'),
  t('Objekte'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Referenced from field_object_reference'),
  t('All'),
  t('Objects for parent'),
  t('Shows the objects that are related to a list of essays'),
);

```

I tried to aggregate the view, but this did not help neither.

# Answer
I think the answer is: It does not work, as the way I tried to do it, is all wrong. What you have to do to get it work is:

1. Don't list the referencing content, but list the referenced content in a view
2. Add than a relation to the »referencing Content«, not the »referenced content«
3. In Advanced » OTHER section click on ›Query setting‹ item and check the ›Distinct‹ check-box.

To summarize: Now the rows can be distinct as you are listing directly the referenced content type and not the referencing one. Hope that helps and save you same hours!
> 2 votes

# Answer
You can try to add distinct to your query,

1. Go and edit your view
2. In Advanced » OTHER section click on "Query setting"
3. Check "Distinct" check-box.
> 0 votes

# Answer
I'm deleting what I wrote because it may not apply but I'd like to note there is a regular filter called Linking FROM or Linking TO. You should see this if you start typing the name of the field that you set to be an entity reference. This combined with a token may exclude some content you may wish to exclude reducing duplicates. I used \[nid\].
> 0 votes

---
Tags: views, entities
---


# Question
Title: Putting multiple Add to cart links / buttons on a page
I'm writing a series of blog posts on my eCommerce site. For example, "10 easy breakfasts for the busy mom/dad". Under each "breakfast idea", I want to put a small block like "Items you'll need". This "items you'll need" will have links to products in our shopping site.

The idea is that if someone likes a blog post or one of the "receipes", they can immediately click on the products below and add them to cart. I don't want them to be taken away from the page they are reading though, because that would be annoying.

They will need some indication that the product was added to cart, so maybe a green tick or "Added!" label will need to show up.

When you get to bottom of the blog post, there should be a block "Products you have in your cart" so that they review and can choose to check out if they want.

I've found these articles & modules:

Creating Drupal Commerce add to cart links ,

Commerce Add to Cart Ajax,

Custom Add to Cart Link

But I'm not sure which is the way to go considering my requirements:

* Curated product links / thumbnails in blocks
* Clicking sends ajax signal to cart to add product
* There is an indication that the product was added "Added!" or a tick or border highlight.
* If the same product is on multiple blocks in the page, when I click one block, it should update on all the blocks.
* Ajax stuff should be robust on mobile devices

I've never done this before, Drupal ajax & custom cart stuff, so I wanted to ask your advice on what to consider before moving ahead. I want to do it in the simplest and most robust way possible. If I can avoid custom code and sandbox code, that would be ideal. Thanks.

# Answer
> 1 votes
jQuery is our friend.

Create a DIV for every product that will perform an ajax request (on click) to a path that will update your cart and then retrieve the cart contents. Ex. /ajax/cart?op=add&pid=idOfProduct

Create a path (hook\_menu) where you will send the add to cart message or other messages that you want to send to the cart (item removal for example).

This path will update the cart to your needs based on the parameters you send it.

The response of the path could be in full HTML for simplicity, with the updated and already rendered cart.

Replace the current cart with the new contents. It's not simple but it will work.

Hope that helps!

---
Tags: commerce, ajax
---


# Question
Title: Javascript works inline in webform but not as standalone
I have a javascript that works if I place it in a mark up in my webform but breaks the form if I make the form a multipage. If I place the script as it's own file and then call it using `drupal_add_js(path_to_theme() .'/scripts/SCRIPT_NAME.js');` in my webform-form-NID.tpl.php nothing hapens.

Here is my script in my markup:

`$(document).ready(function(){
 var ac_config = {
 source: "/example/sites/all/themes/skeletontheme/js/democities.php",
 select: function(event, ui){
 $("#edit-submitted-info-company").val(ui.item.company);
 $("#edit-submitted-info-address").val(ui.item.address);
 $("#edit-submitted-info-address2").val(ui.item.address2);
 $("#edit-submitted-info-city").val(ui.item.city);
 $("#edit-submitted-info-state").val(ui.item.state);
 $("#edit-submitted-info-zip").val(ui.item.zip);
 },
 minLength:1
 };
 $("#edit-submitted-info-company").autocomplete(ac_config);
});`

In the stand alone .js file: `(function($){
 var ac_config = {
 source: "/example/sites/all/themes/skeletontheme/js/democities.php",
 select: function(event, ui){
 $("#edit-submitted-info-company").val(ui.item.company);
 $("#edit-submitted-info-address").val(ui.item.address);
 $("#edit-submitted-info-address2").val(ui.item.address2);
 $("#edit-submitted-info-city").val(ui.item.city);
 $("#edit-submitted-info-state").val(ui.item.state);
 $("#edit-submitted-info-zip").val(ui.item.zip);
 },
 minLength:1
 };
 $("#edit-submitted-info-company").autocomplete(ac_config);
});`

First question is why does the script not work if I add page breaks to my webform.

Second question - why won't the script work the way I have it formatted as it's own .js file.

Thanks for any assistance.

# Answer
I think you can use default druypal behaviors

```
  Drupal.behaviors.mywebform = {
      attach: function (context, settings) {
    var ac_config = {
            source: "/example/sites/all/themes/skeletontheme/js/democities.php",
            select: function(event, ui){
                $("#edit-submitted-info-company").val(ui.item.company);
                            $("#edit-submitted-info-address").val(ui.item.address);
                            $("#edit-submitted-info-address2").val(ui.item.address2);
                            $("#edit-submitted-info-city").val(ui.item.city);
                $("#edit-submitted-info-state").val(ui.item.state);
                $("#edit-submitted-info-zip").val(ui.item.zip);
            },
            minLength:1
        };
        $("#edit-submitted-info-company").autocomplete(ac_config);
        }
    }

```

Hope it will help!
> 0 votes

# Answer
I'm not sure about the answer to your first question - but it might be fixed by this:

Regarding your second question, you need to use a wrapper with your javascript, take a look at 'Working with JavaScript and jQuery', about four screens down, it has a great explanation and gives some good examples.

Specifically, the part about 'JavaScript behaviors / JavaScript on AJAX forms'.
> 0 votes

---
Tags: webforms, javascript
---


# Question
Title: Caching problem. Site only works with cache off
I have this drupal 7 site. I wanted to clone it in order to try some new stuff in it, without working on my localhost. So I did it, following these steps:

## Cloned the database:

```
mysqldump -h localhost -u XX -p XXX > backup.sql
mysql -h localhost -u newXX -p newXX < backup.sql

```

## And then cloned the files and changed their perms:

```
rsync -avHl /home/XX/public_html/* /home/newXX/public_html
chown -R newXX. /home/newXX/public_html/*

```

After that I've updated and changed the **settings file** (to use in the cloned files the new database credentials), and created a **new .htmlaccess** file.

All went well and good. The new site was just like the older site, and both sites were running ok.

**A few days have passed since then.**

But after that the **old** site have all **WSOD** inside every page, except the frontpage.

It was a cache problem, that didn't solved clearing all cache tables, but adding this into my settings file:

```
$conf = array(
'cache' => '0',
'preprocess_css' => '0',
'preprocess_js' => '0',
'block_cache' => '0',
'page_compression' => '0',
);

```

The thing is that I can't have my site without caching, and even after successfully logging in and manually unchecked all cache items under *admin/config/development/performance*, I get the WSOD if I try and remove the $conf array I've manually set at the settings.php file.

Note: I have memcached installed on my server, and this is what I've added in my settings.php file:

```
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'memcache_liga';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

Please note that I've uninstalled memcache module on the cloned site, and deleted that configuration inside the settings file of the cloned site.

**Why is all this happening? And what I may do about this?**

Update: I forgot to mention that I've added to my index.php right after the opening php tag, this:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

And when the error appears (WSOD), the page is still completely blank!

# Answer
> 1 votes
Here is how I do in my local projects, may be it can help you.

I have one main project(local) and four its instances(cloned). Same files, same db structure (I'm using Memcache Storage module).. First time when I've tried to clone and work on them I faced some strange problems, then I found that they were sharing cached data (I was using default memcached instance with 11211 port).. Then I just copied the default memcached.conf file as memcached\_1.conf(memcached\_2.conf,...) and changed their port as 11212,... in them, restarted all memcached instanes`(sudo service memcached restart)`, and specified those ports to to my cloned projects in their settings.php, that solved my problem..

---
Tags: caching
---


# Question
Title: Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!
Every time I use a redirect from an URL alias i receive the foloowing report of:

Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!

Ive tried clearing all the cache and ran cron.

I've tried searching everywhere and can't seem to fix it. Thank you kindly for your support.

# Answer
> 1 votes
This is because you're using the Redirect mudule, this issue has been posted here already.. Installing the latest dev version, and applying this patch should fix it..

---
Tags: views, 7
---


# Question
Title: Issue with attaching an existing file while creating node using RESTWS
I am trying to create a new node using the restws drupal module. My content type has just two fields: title and a file. However, when i send the request with following payload, i get an error. The file which i am referring in the payload is already existing on my drupal server.

URL : CMS\_BASE\_URL/node Method : POST

Payload:

```
<?xml version="1.0" encoding="utf-8"?>
<data>
      <field_my_file>
                <file resource="file" id="24">CMS_BASE_URL/file/24</file>
      </field_my_file>
      <type>filetest</type>
      <title>My 1st file test</title>
      <language>en</language>
      <author resource="user" id="5">
      </author>
</data>

```

Error - 406 Not Acceptable: Invalid data value given. Be sure it matches the required data type and format.

Is there any problem in the way i am sending the payload? If i remove the "file" part from the payload, it is able to create node.Please guide me if this is not correct.

# Answer
> 0 votes
Since the RESTful WS module internally uses the Entity APIs to create the content, the problem here is with the format of the data that are passed. While creating the content programmatically with the Entity API and attaching any files, you need to pass the file parameters in the below format:

```
// omitted rest of the code for brevity
$node->field_image[LANGUAGE_NONE][] = array(
  'fid' => $file->fid,
  'display' => 1,
  'description' => '',
);
node_save( $node );

```

Having said that, the solution to your problem would be the data in the below format:

```
<field_my_file>
    <fid>24</fid>
    <display>1</display>
    <description></description>
</field_my_file>
<type>filetest</type>
<title>My 1st file test</title>
<language>en</language>
<author resource="user" id="5">
</author>

```

And the equivalent JSON would be:

```
{
    "type": "filetest",
    "title": "My 1st file test",
    "language": "en",
    "author": {
        "resource": "user",
        "id": "5"
    },
    "field_my_file": {
        "fid": "24",
        "display": 1, // required to avoid integrity constraints voilation
        "description": "" // you may choose to omit this field
    }
}

```

# Answer
> 0 votes
I tested the following code it works fine. Replace your field machine names and bundle name accordingly. Hope it helps

Here is the XML format to send data

```
<result>
<title>title_of_node</title>
<type>sampleimage</type>
<field_samplefile>
<und is_array="true">
<item>
<fid>18</fid>
<uid>1</uid>
<filename>Drupal.txt</filename>
<uri>public://Drupal.txt</uri>
<filemime>text/plain</filemime>
</item>
</und>
</field_samplefile>
</result>

```

Here is the JSON format

```
{
    "title": "title_of_node",
    "type": "bundle_name",
    "field_samplefile": {
        "und": [{
            "fid": "17",
            "filename": "changes.txt",
            "uri": "public://changes.txt",
            "filemime": "text/plain"
        }]
    }
}

```

---
Tags: 8
---


# Question
Title: How to add another field collection instances on Add Form page load programatically
I have one field collection with unlimited values in Commerce Product Add form.

After performing some action, When user redirects to Add Product form, based on some predefined values in session, I want to display User a Field collection items pre-filled.

If I have 5 predefined values then 5 Field-collection items would be displayed to User and by clicking on save that product would be saved with that field collection item values.

By clicking on 'Add another item', User can add more as well. Above field collection items won't be saved until User clicks on Save form button.

I tried below code but it's not adding new items/instances :

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_product_ui_product_form') {
    if (isset($_SESSION['compatibilityInfo']) && $_SESSION['compatibilityInfo'] != '') {
      $compInfo = $_SESSION['compatibilityInfo'];
      $comp = explode('!c!', $compInfo);
      $cnt = count($comp);

        // Go one level up in the form, to the widgets container.
        $element = drupal_array_get_nested_value($form, array('field_part_details','und'));
        $field_name = $element['#field_name'];
        $langcode = $element['#language'];
        $parents = $element['#field_parents'];
        // Increment the items count.
        $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
        $field_state['items_count'] = $cnt;
        field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);

    }
  }
}

```

# Answer
> 0 votes
I resolved it using below code :

```
$cp = commerce_product_new('product');
foreach($part as $title) {
        $my_collection = entity_create('field_collection_item', array('field_name' => 'field_part_details'));
        $my_collection->setHostEntity('commerce_product', $cp);
        $my_collection->field_year[LANGUAGE_NONE][0]['tid'] = $title->fromYear;
        $my_collection->save();
}

```

# Answer
> 0 votes
I had to do this recently on a product. What I ended up doing is copying the instance of the field collection and then looping through and creating them. If your session variable keys are numerical from 0 on then you dont need the $item\_count. In my case it was not so I could not simply use the foreach($value as $key =\> $val).

```
$my_loop = array(); // Array of items with your default values
$item_count = 0;
$field_collection_clone = $form['field_my_field_collection']['und'][0]; // Clone the field collection form element

//Loop through and create a new instance of the field collection form
foreach($my_loop as $loop){
 $form['field_my_field_collection']['und'][$item_count] = $field_item_base;
 $form['field_my_field_collection']['und'][$item_count]['field_my_field']['und'][0]['value']['#default_value'] = 'my default value';
$item_count++;
}

```

---
Tags: forms
---


title: How to load XML to SWF on each node?

text:
# Question
Title: How to load XML to SWF on each node?
Here is my problem: I have 2 SWF files for a crossword puzzle: first one is for creating puzzles and outputting XML files upon clicking the "Save" button and second SWF is displaying those puzzles to the users by listing and loading those XML files and upon clicking it loads the selected XML file into SWF. This is okay so far here. But I need to use web interface so that a user inside a website sees those XML list on the web page and upon clicking/selecting, the second SWF will load with the related XML file. I need this because I will organize those XML files with some modules inside drupal such as Organic Groups. So each user will see different lists of XML files. For example, I have 2 groups created with my organic groups module inside drupal, each group has a different editor. So those editors will create puzzles and will set them for their groups with Organic groups module.

After some research I think I figured a possible and reasonable way to achieve this with a help of a friend. So, to wrap up things so far;

-I have a puzzle maker swf and a puzzle player swf. -Puzzle maker actually generates some xml files that could be played by Puzzle player(swf). -These xml files are to be stored in Drupal. -The stored xml files behaviour is same as Organic groups behaviour. Where the files belonging to a particular group is accessible to the group members.

So the idea of implementation is here,

1.) A custom page for creating puzzle using Puzzle maker(swf). A "Puzzle Data" content-type to hold the xml files. This node is under organic groups.

2.) The editors creates puzzle (things okay so far here) and the xml file will be downloaded to editor's computer.

3.) Now the editor may upload the xml file and attach it to "Puzzle Data" node.

4.) Now I may create a view to display all the "Puzzle Data" nodes in a Organic Group with Views module.

5.) Now comes the tricky part. The actual node display should be a Puzzle Player(swf) that uses the "xml" file uploaded to the node.

After some research I may achieve this either Creating a custom node template or creating a custom field formatter. So here I need a bit help with the php codes part so that each node will post/sent the attached xml file to puzzle player(swf) attached to the node.

(Btw this 2 step: downloading xml and later uploading it to a node is something unwanted, maybe puzzle maker(swf) can be embedded inside node/add path for Puzzle Data content type and editors may download xml so will upload it again into the field on the same page. )

# Answer
> 0 votes
You would create a new node.tpl.php by copying the existing one from your theme or from the node module (part of core). Rename your copy node--*mycontenttype*.tpl.php and place it in your theme directory (along side your other .tpl files).

Install devel and use dpm() to explore the $content variable. Hide the XML field and extract it's file id (fid) and pass it to file\_load. This should return an object containing your file path, again use dpm() to explore this array and get your file.

https://api.drupal.org/api/drupal/includes%21file.inc/function/file\_load/7

Embed your .swf directly into your new node.tpl.php and pass the XML to it as you would any other Flash argument.

# Answer
> 0 votes
This is how I fixed the issue. Created a custom node--puzzle.tpl.php for my puzzleplay.swf file. This custom node template takes the URL of the xml file that attached to "field\_xml" field inside "puzzle" node-type. Then, this url is send to AS3 with Flashvars so that eachtime there is a node with a xml file attached to field\_xml, puzzleplay.swf loads that specific xml from the url sent with Flashvars.

node--puzzle.tpl.php:

```
 <?php
    $xmlpath = file_create_url($node->field_xml['und']['0']['uri']);
    ?>
    <object
    <param name="AllowScriptAccess" value="always">
    <param name="allowFullScreen" value="true" />
    <param name="quality" value="high" />
    <param name="flashVars" value="xmlPath= <?php echo $xmlpath; ?>" />
    <param name="movie" value="/path/to/puzzleplay.swf" />
    <embed allowScriptAccess="always" flashvars="xmlPath=<?php echo $xmlpath; ?>"src="/path/to/puzzleplay.swf" type="application/x-shockwave-flash" ></embed>
</object>

```

AS3 Code:

```
var XML_URL:String = root.loaderInfo.parameters.xmlPath;
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener("complete", xmlLoaded);

```

---
Tags: nodes, entities, organic-groups
---


# Question
Title: Add background to a div based on a Node's Image Field
I had a request approach me and am blanking on a smooth way to implement this. We have on content type that on occasion will have a background image in a a div. The image will be a washed out background image behind content. The content authors want to add this page by page using an Image Field.

How would you implement this?

I'm assuming I can do this through our custom theme -- perhaps a theme\_preprocess\_page() or theme\_process\_page()?

# Answer
You could try BackgroundField:

> BackgroundField started as an extension of the CCK ImageField that allows a CSS selector and background attributes to be set for a content-type. This is particularly helpful for allowing your node authors to add images to a node that are integrated into the theme of the site. With the inclusion of the Image field in Drupal 7, BackgroundField was rewritten to extend that core functionality.
> 4 votes

# Answer
I created a module to do that: Field Group Background Image

The idea is creating a div wrapper (with Field Group), specifying the image field of your content type as the background image.
> 0 votes

---
Tags: theming
---


# Question
Title: How to use an image styled by ImageCache Actions as background for a node?
I am trying to implement a custom banner with some text written on it.

* I have created a custom content type called banner with 2 fields: an image field and a text field.
* Then I process the image field through ImageCache actions in order to apply a watermark on a photo. (fine till now)

I want to use this image (the output of imagecache\_actions) as a background image of a node, so that I can apply the text on top of it.

So now node is something like the following.

```
<div class="node" >
    <img src="" />
    <div class=text> blabla </div>
</div>

```

I want to change it to the following.

```
<div class="node" style="background: //use processed field by imagecache actions">
    <div class=text> blabla </div>
</div>

```

Seen from a different perspective, if I could dynamically overlay some text on top of the image, then that would also do the trick!

Can you suggest any idea?

# Answer
> 0 votes
I managed to do it. Some general knowledge: When uploading an image for an image field, then we can access our image through

```
/sites/all/themes/MYTHEME/img/MYPIC.jpg

```

(let's assume that in my active theme's directory we have created a folder named "img" and put our images inside it)

Then, ImageCache Actions takes the image from the url and performs it's magic on that image. So comes the question: Where to access the styled-by-ImageCache-Actions image? By using Firebug on an end-result image we see that it's path resembles the following:

```
/sites/default/files/styles/public/files/images/MYPIC.jpg?itok=FEqqXOKA

```

Here is what I did:

* In my active theme's directory I opened my template.php (if it doesn't exist we have to create it and write: `<?php` on the top - and it's good practice to **not** close the php tag in the end)
* I paste this code with explanations (notes: my theme is called: "awesome", the custom image field in my content type has a machine name: "field\_banner\_photo" :

```
// preprocess function is used to prepare variables for node.tpl.php
function awesome_preprocess_node(&$variables) {

  // we check if our node has a field_banner_photo filled with an image. This
  // will immediately exlude content types without this field
  if (!empty($variables['node']->field_banner_photo['und'][0]['uri'])) {

    // we store the image path of our field_banner_photo into $org_img_url
    $org_img_url = $variables['node']->field_banner_photo['und'][0]['uri'];

    // we create $imgcache_url which will be used in node--banner.tpl.php
    // using function image_style_url, the path to the altered (processed by
    // ImageCache Actions) is exposed and stored into $imgcache_url
    $variables['imgcache_url'] = image_style_url("banner", $org_img_url);
  }
}

```
* I create a node--banner.tpl.php in my active theme to specifically target my custom content type with the machine name: 'banner'. I fill it with the contents of /modules/node/node.tpl.php
* In the place of

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?>
clearfix"<?php print $attributes; ?>>

```

I put

```
<div style="background:url('<?php print $imgcache_url; ?>') left top no-repeat;"
id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?>
banner clearfix"<?php print $attributes; ?>>

```
* Then I go to manage display for my custom content type and hide the field\_banner\_photo. So I achieve to just use the image provided - after ImageCache Actions does it's magic on it - applied as a background on the node!

And that's it! Thank you Drupal and ImageCache Actions for these amazing possibilities we have, almost out of the box!

# Answer
> 3 votes
I would create some dynamic CSS on the fly and add it to the head of the document.

```
$styled_image_path = image_style_url('style_name', $image_path);

$css = '
.node {
  background-image: url(' . $styled_image_path . ');
}
';

drupal_add_css($css, array('type' => 'inline'));

```

You can add this to a `hook_preprocess_node()` to check for a specific node before adding to the page.

# Answer
> 0 votes
I don't know the "proper" way to do it now, but the problem was seen by W3C.

There is a draft of CSS Variables processed right now. If they'll kick in, you will be able to write static CSS files like that:

```
background-image: url(var(node-image));

```

Then in your theme code just output:

```
<style>
  :root {
    node-image: <?php echo $image_path;?>
  }
</style>

```

Warning: this technology is experimental now, at the date of posting.

# Answer
> 0 votes
If you use Field Group and Display Suite, check Field Group Background Image module. In your content type *Manage Display* page:

Create a `div (background image)` field group to wrap the whole node, and then select the image field you want to use. It allows specifying an image style too.

---
Tags: theming, media
---


title: Form elements update and deletion in D7

text:
# Question
Title: Form elements update and deletion in D7
I have made a form in D7 using form API,submitted values to that and retrieved entries from database;now what i want is to add a delete link in front of every retrieved row.My retrieval code is:

```
function form_data_menu() {
$items['formdata'] = array(
'title' => 'Form Data',
'page callback' => 'form_data_form',
'access callback' => TRUE,
);
return $items;
}
function form_data_form()
{
 $results = db_query('SELECT * FROM {drupal}');
 $header = array(t('Id'),t('Name'),t('College'),t('Education'),t('Percentage'),t('Application'));
$rows = array();
foreach($results as $result){
$rows[] = array(
$result->id,
 $result->name,
 $result->college,
 $result->education,
$result->percentage,
 $result->application,
);
}
return theme('table',array('header'=>$header,'rows'=>$rows));
}

```

any help will be appreciated. Thank You!!

# Answer
Yes you can easily do it in addition to this code. You need to create another url to delete a record from the database

```
$items['deldata'] = array(
'title' => 'Delete data',
'page callback' => 'form_delete_form',
'page arguments' =>array(1),
'access callback' => TRUE,
);

function form_delete_form($arg){
$query = db_query("delete * from the 'table_name' where 'id' =$arg");
drupal_set_message("Record deleted successfully.");
drupal_goto('formdata');

}

function form_data_form()
{
  global $base_url;
 $results = db_query('SELECT * FROM {drupal}');
 $header = array(t('Id'),t('Name'),t('College'),t('Education'),t('Percentage'),t('Application'), t('Options'));
$rows = array();
foreach($results as $result){
$rows[] = array(
$result->id,
 $result->name,
 $result->college,
 $result->education,
$result->percentage,
 $result->application,
'<a href='.$base_url.'/deldata/'.$result->id.'>Delete</a>',
);
}
return theme('table',array('header'=>$header,'rows'=>$rows));
}

```

Hope it works for you!
> 1 votes

---
Tags: 7, forms
---


title: Regarding Filter HTML input option

text:
# Question
Title: Regarding Filter HTML input option
I want to allow one more tag in Filter html Allowed HTML tags: \<a\> \<em\> \<strong\> \<cite\> \<code\> \<ul\> \<ol\> \<li\> \<dl\> \<dt\> \<dd\> \<blockquote\>.

I want to add \<table\> in this list. How can I edit this and in which hook I can modify this.

Anyone can help me?

# Answer
> 1 votes
You don't need any hook for this. Go to Configuration \> Text formats (path may vary slightly, but it is available in versions 6 to 8) and simply add tags to the list:

---
Tags: 6, input-formats
---