# Question
Title: What is the correct workflow for updating a high traffic site?
I launched a site based upon Drupal 7.14 with at least 100 simultaneous users accessing the site at all times.

From the Devel module, I see that every page is generating about 200 to 400 Mysql requests.

First question: Is that a lot with 5 customs blocks per page?

With the full caching system for anonymous user, the site is running smoothly.

I had to make two updates. For that, I put the site in maintenance mode, made my modifications and uploading new files, flushed the cache and put the site live again. The first update did not generate any issues. But the second one, my MySQL server crashed due to a huge amount of simultaneous requests.

So how to avoid the flushing of all pages and updating properly JS, CSS and templates files? What's is the correct workflow? Because after the maintenance, if 10 users request a non-cached page, it's more likely that the server won't be able to handle the load.

Does Drupal automatically regenerate the page cache if a JS, CSS or template associated file has been changed? So, is no flushing needed? The page would be correctly regenerated according to the cache configuration?

Here the server specifications:

> ```
> ProLiant DL360 G5
> CPU Intel Xeon 5133 (dual core) 2GHz
> RAM 2×512Mb DDR2
>
> ```

# Answer
> 1 votes
Drush and command line are for rescue here:

1) To clear cache selectivelly, just run `drush cc` and drush will provide you with different options to select from, so you can clear everything or just theme registry, js/css, views, pages, etc.

2) To regenerate script use this bash script: http://dropbucket.org/node/241. It reads your sitemap.xml and revisits all pages, warming up cache.

3) Additionally, consider using Drush Entity Cache Loader http://drupal.org/project/drush\_ecl, it doesn't generate page cache for you, but warms up content cache, so when authorized user loads the page, nodes and other entities are loaded from cache instead of being generated on the fly.

---
Tags: 7, caching, performance
---


title: JS Javascript into a single node / page

text:
# Question
Title: JS Javascript into a single node / page
I have a form that works fine outside of drupal where it called a script ..../default.js However this does not work inside drupal 6 when i copy the code from ym html/php file.

I have seen this line

```
 drupal_add_js('globals/default.js');

```

Is this all I need to add to get the JS read? I have the php filter in Drupal 6 set to allow pretty much all tags for the administrator.

# Answer
Sounds to me like you're trying to call the `drupal_add_js()` function from within a node edit form (or maybe the body of a form). Instead of that, just change the body's input filter to HTML (or whatever filter you have that allows `<script>` tags) and call the external JavaScript there as you would in any HTML page. You don't need to use PHP for that.

I would add that that probably isn't best practice. Using `drupal_add_js()` is, but you should use `drupal_add_js()` in page templates (e.g., node.tpl.php) or in preprocessor functions (e.g., `hook_preprocess_node()`).

As an aside: be very careful of the PHP input filter, it has major security implications.
> 0 votes

---
Tags: javascript
---


# Question
Title: How do you output taxonomy terms and the fields thats attached to it?
I have the following issue where I want to output a list of taxonomy terms and the fields it contains. I have a list of taxonomy terms as US States and each term has a field called city. How can I display the State and City in Drupal 7 Views 3?

I added the field **All taxonomy terms** and I dont' see any option to display its fields in anyway.

# Answer
> 0 votes
You just need to add these 2 fields to your view (and remove the "all taxonomy terms" field you've already added):

```
 Taxonomy term: Name

 Taxonomy term: City

```

Your precise field names may vary.

I was able to do a test view like this and State and City display OK.

I'm not doing any fancy relationships or anything with the view. If you don't see these fields as options, it may be we have different modules, but I'm also Drupal 7 views 3.

# Answer
> 0 votes
You have to add the **Content: Taxonomy terms on nodes** relationship in your content view. After that you will be able to choose the city field of your state term in the Fields section of the view.

---
Tags: 7, views
---


# Question
Title: How do I detect spam from among published comments?
My spam prevention modules had to be disabled while I was fixing a problem. Meanwhile, I was attacked by numerous spam bots and now have thousands of published spam comments on my site.

Is there a way to detect these comments and unpublish and/or delete them?

I am using drupal 7.

# Answer
> 1 votes
I use a view, that shows me 200 comments at once with their body. So by quickly looking at the list of the comments, I can see which are span and checkmark them to delete.

You can copy this view from the gist here: https://gist.github.com/timonweb/5990901

Make sure you have Views Bulk Operations (https://drupal.org/project/views\_bulk\_operations) module installed, then import the view from the gist and go to: http://yoursite.com/admin/content/comment/moderate.

---
Tags: comments, advertising
---


title: drupal views : display previous nodes

text:
# Question
Title: drupal views : display previous nodes
I am having difficulties to filter data with views. I have made several video lessons on a subject and managed to display on the side of each video all other related videos in a block. However i wish to see displayed in this block all related AND Previous videos.

I created a field called "order" (integer) in my content type, and i wonder how i can add a filter to make sure that the related videos have an "order" value lower than the "order" value of the video being displayed.

I 'd be greateful if anybody could help me with that.

# Answer
It would be best to create a page/block (basically just a different views display) to achieve that.

The constraints that you have i.e. Previous and Related can only find a practical application if your videos belong to the same category.

If I am getting the question right what you are better off doing is creating another block which displays all videos irrespective of the categories.
> 0 votes

---
Tags: views
---


title: Using jQuery Tools

text:
# Question
Title: Using jQuery Tools
I have looked online to see if it is possible to use jQuery Tools 1.2.7 with Drupal 7. I see that there is a defunct project that attempted to use it in Drupal 6 but nothing for Drupal 7. I tried downloading it and including it in the scripts line in the .info file for my module but still not executing. I suspect the issue might be that jQuery Tools expect jQuery 1.7.2 while Drupal 7 uses jQuery 1.5.

The specific feature that I am trying to use is the overlay function. I followed the online documentation but I don't see any overlay. All it does is reloading the same page over again. I was wondering if anyone has used the overlay module with Drupal 7 and has gotten it to work.

# Answer
You're approaching this correctly in trying to add this in your own info file - not every jQuery library needs its own Drupal module and its often more overhead than its worth to try and set one up. If the jQuery tools module is what you need but its not compatible with the current version of Drupal 7, than use jQuery Update module to upgrade your version of jQuery.

If all you need is the overlay and you're not tied to the jQuery Tools implementation, you have a couple of customized Drupal options that should be easy to implement:

* The built-in overlay functionality in Drupal 7.x core (see https://drupal.org/node/1087026 for guidance on how to implement)
* Use one of the specialized overlay libraries - best one I've found is Colorbox, which has a Drupal module with easy to implement solutions (i.e. no hand-coding javascript)
> 1 votes

---
Tags: 7, javascript, modal-dialogs
---


title: Single view to display related nodes

text:
# Question
Title: Single view to display related nodes
I am trying to display related nodes block using a single view for all the taxonomy terms. So that if user click on any node title he/she will see the related nodes based on the node's taxonomy term.

I tried adding contextual filter with taxonomy term by selecting all the vocabularies, but doing this will display nodes from other terms as well.

The reason I am trying to use single view is, I have tabs (Quick tabs) structure on a node page, with related nodes as a Tab. So I cannot create different views for nodes based on terms, and cannot specify different views in quick tabs settings.

# Answer
A slightly different approach which might mean taking out your beloved QuickTabs and replacing it with another 'tab' solution.

WHAT YOU NEED

optional but recommended

HOW TO

1. Install the required modules together with any dependencies.
2. Create your content(I think you have that covered) adding a term reference field to each. Ensure you create the accompanying vocabularies for the particular references.
3. Create a view(Again I think you have this covered). Add an EVA display. Just click on the add display link and add "EVA Field".
4. Make some configurations to the display under "Entity Content Settings". The configuration you probably need is Entity Type: Node, Bundles: Your\_Content\_Type EVA will complain if you do not provide the preceding configuration.
5. Add the contextual filter has\_taxonomy\_term. Under the settings set When the Filter is not available,select provide default value and the option that you need is Taxonomy Term ID from URL.
6. Once that is done head over to your content type's display settings. If you have Display Suite installed there are more options in this section. Even without it we can still build something. The first thing you need to do is to create a fieldgroup.
7. The group that you are creating should be a horizontal tab/vertical tab. Depends on what you want.
8. Create another group which should be a horizontal tab item/vertical tab item depending on your earlier option. Example create two tabs. One for the node and the other for the related nodes.
9. Drag the 'main' node's fields i.e. title,body e.t.c to the horizontal tab item for the node.
10. Drag your EVA Field that you had created earlier (It should be there) under the horizontal tab group item which you meant to represent the related nodes.

That should be the ten steps to glory :-) Just style it then you should have some pretty working tabs in your hands.

If you noticed it is also possible to add other tabs to display a specific field of the content type.

Very long but hope it helps.
> 0 votes

# Answer
You need to create a block view with all content. Then filter content for your specific term by adding a filter-\> content type.

Then add a *Content: Has taxonomy term ID*. On the config of the later. When the form value is not provided in the URL choose *provide default value* -\> Taxonomy term ID from URL.

Enable load default filter from page and load default filter from node. On the latter enable your vocabulary.

Afterward, config the case that the ID is present on the URL. Specify validation criteria by choosing taxonomy term and again chose your vocabulary.

It should work! Check the whole tutorial on http://www.drupalgardens.com/videos/410746
> 1 votes

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


# Question
Title: Can I rewrite a view's query SQL directly?
Can I modify the SQL generated by the Views Query Builder? Views doesn't support subquery out of the box, so I'm just wondering if I can add the final line to my query manually?

Background info: The query I'm trying to perform looks a little like this:

```
select full_name, email, users.uid
from
cloudsponge
inner join
`users` on users.uid = cloudsponge.importer_uid
where cloudsponge.email not in (select mail from users)

```

It's worth pointing out that all tables have millions of rows so performance is also important (I haven't checked this query on a large dataset yet).

# Answer
> 0 votes
OK, I solved this by hacking it. This is NOT the cleanest solution, but I see it as being the cleanest way out. I ended up creating a the query I want with MySQL's CREATE VIEW syntax. I then loaded the MySQL VIEW into Views as a table; this did the trick. It's not pretty, but it's the best solution I could come up with for my purposes.

# Answer
> 0 votes
try hook\_query\_alter. Views queries should pass though this hook allowing you to alter them. https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_query\_alter/7

# Answer
> 0 votes
As you want to make changes in the query generated by Drupal Views, you can take help of creating a 'Views Custom Filter'. I personally have tried it for adding an extra WHERE condition to the Views query. You have some other options available in 'handler' folder in 'Views' module.

You shall be needed these files in your custom module :

YOUR\_MODULE\_NAME.info, YOUR\_MODULE\_NAME.module, YOUR\_MODULE\_NAME.views.inc, HANDLER\_NAME\_YOU\_ADD\_IN\_(YOUR\_MODULE\_NAME.views.inc).inc.

Hope it helps

---
Tags: views, database
---


# Question
Title: How to collect the node ID on a webform?
I have a view showing many products. Each product has its own nid. There is a 'RESERVATION' link in each product as well. When a client clicks on RESERVATION, I want to take him to a form in order for him to provide some more details. Here is my problem, in that form how may I have a hidden field containing the nid of the product on which the client has clicked?

# Answer
> 2 votes
Re-write the reservation link field to include the ID in the URL.

---
Tags: webforms
---


# Question
Title: keywords and description for front-page of drupal 7 site
I managed to set page titles with the "Page Titles" module and keywords and description with the "Meta Tags (Quick)" plugin, however it seems like there is currently no way of having custom keywords/description for the front-page. Does anybody knows of a work around this?

# Answer
Try the Meta tags module

It'll allow you to set keywords and descriptions to your site, and you can override those settings to be different for the front page.
> 1 votes

# Answer
Add the meta tags to a view or a node and set the path of the node or view as the frontpage in the site information configuration
> 0 votes

# Answer
You can use Path-Based Metatags option in Meta tags quick module, enable module and go to front page, you will see Path-Based Metatags option...when you click on the option, you can fill in the fields that you want, you can also set the fields that you want to display (admin/config/search/metatags\_quick)...
> 0 votes

---
Tags: 7, meta-tags
---


# Question
Title: How to show a list of users subscribed to the current node's taxonomy terms
I've been boggling my brain on this for a while now and although I seem to be getting close, so far there is now awesomness kicking in.

Here's what I want:

I have a number of articles (nodes), each with their own list of taxonomy terms I have a number of users, each with a list of interests defined in taxonomy terms I want to generate a list of users subscribed to taxonomy terms of the -current- node

I've tried many different approaches and often had the feeling I got close but, so far, no dice.

The closest I've gotten so far is: view of 'user' relationship: 'User: content authored' (yes,I know, this limits the output to author only but it DOES expose the "(nodes)Content: taxonomy terms on node" relationship, which exposes '(term) Taxonomy term: name of the tax-list' etc..

SO: If someone could point out the general outline of the approach (what view type, what relationships to use) that would get me where I need to be, that would be splendid!

REWARD: A whole lotta love will go to the one who sets me on the right track!

# Answer
> 1 votes
You can set the same vocabulary for users and your content type, so they will be related with the same terms, then you will be able to achieve your goal with these four steps:

**#1**

Create a `View block` with these settings:

**View-\>name:** Related users **Show** -\> taxonomy terms -\> **of type** -\> your vocabulary

**#2**

**Create relationship:** Taxonomy term: User using \[field\_name\]

** field\_name: the name of the field with term reference in users account settings*

**check:** Require this relationship

**#3**

**Add field:** (field\_name) User: Name

** field\_name: the name of the field with term reference in users account settings*

**#4**

**Add contextual filter:** Taxonomy term: Term ID

Configure the contextual settings:

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

**provide default value:** taxonomy term id from URL

**check:** Load default filter from term page

**check:** Load default filter from node page, that's good for related taxonomy blocks

Select your vocabulary

**Check:** Filter to items that share any term

**WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED:**

**Specify validation criteria** -\> basic validation

**Action to take if filter value does not validate** -\> hide view

**MORE:**

**check:** Allow multiple values

---

That's all. If the current node will have a relation with some user or users, then the block with the related users will be displayed.

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


# Question
Title: How to enable users editing their CiviCRM profiles details from their Drupal user page?
I have a new Drupal7 instance with CiviCRM integrated. I have successfully linked CiviCRM contacts (specifically CiviMember members) to users in Drupal with the role of 'member'.

I want members to login and edit their CiviCRM profile. How do I go about doing this?

# Answer
Create a CiviCRM Profile (or reuse one of the existing ones) by going to Administer \>\> Customize Data and Screens \>\> Profiles and set it to be enabled on "View/Edit Drupal User Account". Then the user will be able to edit their details from their Drupal user page.

See this Demo Profile on CiviCRM Demo site and notice that "View/Edit Drupal User Account" is checked. Take a look at this tab on the Drupal user page. The fields in the Profile can be edited.

For more details see: the CiviCRM book section on Profiles.
> 4 votes

---
Tags: civicrm
---


title: Contextual filter on a path alias

text:
# Question
Title: Contextual filter on a path alias
I am trying to create a page view that will display content by Content:Title which is part of the node's URL.

I have 3 content-types: *Movies*, *Books*, and *TV Shows*.

Each content type has a path alias matching the *\[node:content-type:machine-name\]/\[node:title\]/\[current-date:custom:Ymd\]* pattern.

I successfully created a view called movies with a filter on *Movies* that displays all the nodes with www.example.com/movies/ in the URL. If I click on a node in the *Movies* view, it displays the content using the node.tpl.php template file.

I added a contextual filter (*Content: Title*) using Scott Edmonds suggestion.

Contextual Filter for: Content: Title ). When filter is not in URL -\> Provide Default Value -\> Raw Value from URL -\> Path Component=2. Use Path Alias=Checked. Then, When Filter Value is In URL: Specify Validation Criteria= "PHP Code" with the following PHP code: $handler-\>argument = str\_replace("-"," ",$argument); return true; That did the trick. the PHP code converts the dashes to spaces so it can be evaluated correctly.

The result is that when I click on the "Star Trek is Great" post link I am taken to the correct URL, www.example.com/movies/star-trek-great/20130702, but node.tpl.php is the template used instead of views-view--movies.tpl.php.

When I copy the title and paste it into the url, as "www.example.com/movies/Star Trek is Great/20130712" the views template page comes us.

Some where along the way I am missing something. Any help out there?

FYI - I also have simply set the contextual filter on Content:Title with Display all results for the specified field Checked "Override title" and added %1 as the first argument Seleced "lowercase" for the Case PATH Selected "transform spaces to dashes in url"

But nothing worked :(

# Answer
> 1 votes
The issue is the following:

When you go to `www.example.com/movies/star-trek-great/20130702` Drupal sees that this is a path alias to `node/#`, and it displays that node. It won't use Views at all.

When you go to `www.example.com/movies/Star Trek is Great/20130712`, this does not map to any URL, but rather to the View sitting at `www.example.com/movies` with an contextual filter of `Star Trek is Great` (and `20130712` most probably).

You may have some other issues to work out as well:

Pathauto is taking out the `is` (and other small words by default) so there will be a bit of a hard time mapping `star-trek-great` to `Star Trek is Great`.

Also, what happens if you have a title of `Star Trek is Great!!!` that maps to `star-trek-great` as well?

---
Tags: views, path-aliases
---


# Question
Title: How to create an entity reference view that contextually filters based upon current user ID
I'm looking to create a entity reference view that filters based upon a field I've placed on the user profile.

I have two content types (Speakers, and Blog Authors) (Speakers will also be blog authors) that I want to as an available list of authors on a Blog content type, so on creation, the speaker can choose the author profile to link the particular blog to, but filtered by only those listed on a particular user's user account.

I've placed an entity reference field on the user account that is a link from a specific user to a specific piece of content of either the Speakers or Blog authors content type (called blog\_author\_link).

I'm looking to create a view that filters the entity reference field on the blog content type based upon which field is selected in a users profile.

I have a view that successfully lists both content types, but when I attempted to add a relationship from that user account link (blog\_author\_link), and contextually filter based upon Content:nid and set it to pull from the logged in user's id, it doesnt seem to work. (Yes, There are users that have that attribute assigned, and I've passed those arguments and the filter results in no output). I tried to do a uid, but I dont think that is available on the entity reference view type. I'm a bit over my head.

Any Ideas?

EDIT: Ok, so It seems based upon when I start passing random arguments into the preview's contextual filter that it is looking doing exactly what I'm telling it to do, filter based upon the NID, when I need to filter based on the UID, but there is no contextual filter for the UID under Entity Reference Views type... Any one have any idea what I'm talking about?

# Answer
You need to add a relationship to the view. It will either be "node: author" or "content: author" depending on your distro/version (I'm commerce 7, views 3).

Once you've added the relationship, "User: Uid" will be an available option under contextual filters.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Flag module: Do not allow users to flag own content
I am using Flag 7.x-3.0 to enable users to flag file entities. I only want users to be able to flag files that *other* users have uploaded. However, I am missing the checkbox option "allow users to flag own content" that I remember having been a part of earlier versions of Flag module.

Has this feature been removed?

# Answer
This is a specific use-case so it may be better to approach this using the Flag API. Specifically, try hook\_flag\_access and add this to your custom module (or create one). This function takes the following parameters:

```
hook_flag_access($flag, $entity_id, $action, $account)

```

and what you are specifically interested in is the following:

```
$entity_id: The id of the entity in question.

$account: The user on whose behalf to test the flagging action.

```

The $entity\_id will allow you to determine what user id created the entity and the account object will already contain the account of the current user so this function will block flag display if they are the same:

```
function YOUR_MODULE_flag_access($flag, $entity_id, $action, $account) {

  //load data for the entity
  $entity = entity_load($entity_type, array($entity_id));

  // if the account that created the entity is the same as the user attempting to flag it then block access
  if ($entity[$entity_id]->uid == $account->uid) {
    return false;
  }

}

```
> 1 votes

# Answer
That feature is still in there. Edit your flag and you will see it about midway through the settings
> 1 votes

---
Tags: 7, flags
---


title: Import data from csv

text:
# Question
Title: Import data from csv
I am new on Drupal. I have a csv where I want to upload on a drupal site every week.

I tried to follow this tutorial enter link description here but "Data Processor" doesn't show. I have installed all the modules and clear the cache.

Any suggestions?

# Answer
as i read in an issue in feeds that:

> The Data processor was removed from Feeds in 7.x because Alex was unsure of the future of the data module. Seeing as there's a release of data for 7.x, it makes sense to revive it.

but if you need to implement it manually i guess this comment will help.
> 0 votes

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


# Question
Title: Creating child nodes when creating parent
I'm trying to programmatically create child nodes according to a parent node's field value.

When a node is created, a reference to these child nodes is saved in the parent node, although the references should not be editable and visible in the edit form and when the node is viewed.

How can I implement this?

# Answer
> 0 votes
Your main problem here is you won't be able to create a reference to the created node in a form submit as the node id hasn't been created yet. I'm not actually sure at what point it becomes available in the node process either. hook\_node\_save is still too early and it's the last node specific hook you can do this with.

I would skip trying to do this programmatically and use rules and entity reference field. Have your rule fire after a new node is saved. then have it create a new entity (node) and set data value (entity\_reference) to the newly created node. much easier to maintain than code.

---
Tags: nodes
---


# Question
Title: Content type with Multiple fields reference
I am building a website a website which holds date about players and teams. There are two content types Player and Team. I want it to work like this, when we are adding a team we can add and reference multiple players into it. How can this be achieved?

# Answer
> 1 votes
you can achieve this using Entity reference module.

after installing the module, you go to team content type and add a new field "Entity Reference", now you can use Autocomplete widget or Autocomplete (Tagging style).

if you use Autocomplete (Tagging style) you can add multiple player names in the same field separated with commas (like tagging).

or you can use Autocomplete widget with unlimited number of values if you like each player has it own field.

Note: if you want to add player by their names, it is preferred that for player content type use the title of the node as the player name, because by default Entity reference will look for title, or you can use views for using others fields then the title

# Answer
> 1 votes
The simpliest way to do what you like is to use ief module. But i dont sure it works with node reference field type. So you will need to use entity reference as a generic entity reference field.

---
Tags: entities
---


# Question
Title: How do I conditionally override views cache using preview?
I'm attempting to embed a view but need to disable the cache in this instance while leaving it enabled in other instances. I'm attmepting to do this using code but nothing I've tried seems to work. Here is my code so far:

```
  // Get the view and attach the handlers with the build call
  $view_object = views_get_view($view_name);
  $view_object->set_arguments($view_args);
  $view_object->build($view_display);

  // Manually editing the cache here does nothing
  //$view_object->display_handler->options['cache']['type'] = 'none';

  // Override option breaks the view object and the get plugin does nothing.
  $view_object->display_handler->override_option('cache', 'none');

  // Prints tell me that the previous two lines have not actualy changed the cache method.
  dsm($view_object->display_handler, 'display handler');
  dsm($view_object->display_handler->get_plugin('cache'), 'get plugin cache');

  // Returns the cached copy of the view despite changing the option.
  $view_object->execute($view_display);

```

Any views experts out there know how to override this cache option?

# Answer
> 3 votes
ADDITION:

This works:

```
$view=views_get_view('to_c_or_not_to_c'); // or whatever your name of your view is
$view->display['cached']->display_options['cache']=array('type' => 'none'); // 'cached' is the display name of the view that is normally cached but here we are going to set it to none
return $view->preview('cached'); // returns the rendered html of that display (if you need arguments, they can be passed here as an array in a second argument

```

ORIGINAL:

May the great drupal gods strike me down for this answer, but....

```
$view_object->live_preview=TRUE;

```

will cause drupal to ignore any cache()ing that may be set and a very quick look doesn't seem to show much other side effects (other than some query capturing)

# Answer
> 0 votes
```
$handler->display->display_options['cache']['type'] = 'none';

```

---
Tags: views, caching
---


# Question
Title: add and remove preassign role to user on completion of user profile
I have created user through admin. Admin Assign specific role to user. But On first time login we want user to complete user profile and then only it will able to access anything else on site. So I want to remove role from user profile if any of field in user profile is empty. And add Pre-assign role again to user after completion of user profile.

Please help. Thanks in advance

# Answer
> 0 votes
I never did something similar before, but I guess, rules module suits you like nothing else.

First of all you need 2 roles: users who just created and users who filled some profile fields. When admin creates a new user he set first (just created) role.

Then you create a new page view event (in rules core):

1. Create action `load entity by id` using site:current-user token (so you can access user profile fields in condition section);
2. In condition section, Check user role (only for just created);
3. In condition section, create condition for each profile field you wanna check (not empty or something similar);
4. Create action to redirect user to edit profile page.

So, each time when new user will load any site page, he will be redirected to edit profile page until he doesn't fill profile fields.

The second event is after profile save, assign new role "Fills some profile fields". There is no difficult conditions, so I'm sure you can handle this event yourself.

If you need more complex solution, redirect on profile if only user load specific page you can try rules page. If you would like to redirect only once per session, you have to write your own rules condition through rules API or try out this one (never use this before).

I hope this could be helpfull for you, anyway wish you luck to find what you are really looking for.

---
Tags: users
---


# Question
Title: Drupal Album/Photos modules error. Not show photos/image/uid
www.sitename.com/photos/image/697 --\> go... But, not show image and other content and blocks...

Error messages: 1- Unable to generate the derived image located at public://styles/large/public/photos/image\_1/6396455561366990133.jpg.

2- DrupalDefaultEntityController-\>load() array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values!.

3- format\_date() /includes/common.inc dosyasının 2014 line) date\_timezone\_set() expects parameter 1 to be DateTime, boolean given.

Help me please...

# Answer
> -1 votes
The problem was the Photo Information Block being inactive; it has been now fixed.

---
Tags: 7
---


# Question
Title: How to boost relevance of Search API solr with the value of a certain field?
I am using Search API solr on my site. To get better search results I would like to boost the relevance by the value of a certain numeric field. Say, all items have a field A, which is numeric. Now I want to boost the relevance of those itemes by the value of field a, so that, if As value is higher the relevance of the item becomes higher too. I have absolutely no idea how to do this. Maybe with

```
hook_search_api_solr_query_alter()

```

But I did not find documentation how to use it. Please hint me in the right direction.

# Answer
> 2 votes
hook\_apachesolr\_query\_alter($query) alter the query after it's prepared and cached.

As per example given in documentation which I found, you can use this hook in similar way to other query\_alter hook. E.g -

```
function hook_apachesolr_query_alter($query) {
  //Adding one more filter.
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

```

Find the documentation by clicking on the mentioned hook name by me.

**EDITED--**

Sorry for giving example of other hook of apache solr module. You can find documentation of your hook here hook\_search\_api\_solr\_query\_alter().

You can find a small snippet for example of this hook like --

```
function hook_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if ($query->getOption('foobar')) {
    $call_args['params']['foo'] = 'bar';
  }
}

```

Eric has wrote a nice article with example of this hook.

---
Tags: search
---


# Question
Title: Redirecting user links to their profile2 pages
I'm using the profiles2 module for my user profiles. I want to keep the user accounts hidden, and instead, use the profiles for public viewing. I disabled user pictures in users, and added an image field to the profile entity. When users post comments, the links point back to the user account. How can I change that behavior so links point back to that user's profile page? Also, how can I display the profile pics for these comments? Essentially, I'm wanting the normal user functionality to occur with profiles instead of users.

# Answer
> 4 votes
This can be done with a combination of

`hook_preprocess_username` (make links go to profile path)

Something like:

```
function MYTHEME_preprocess_username(&$variables) {
  $account = $variables['account']
  if($profile = profile2_load_by_user($account, 'profile_type')){
    // This gets passed onto theme_username
    $variables['link_path'] = 'user/' . $variables['uid'].'/profile/path';
    // Possibly:
    // $type = $profile->type();
    // $path = profile2_page_get_base_path($type) . '/' . $account->uid
  }
}

```

and then the picture override in

`hook_preprocess_user_picture` (override user picture)

Something like:

```
function MYTHEME_preprocess_user_picture(&$variables) {

  $account = variables['account'];
  if($profile = profile2_load_by_user($account, 'profile_type')){
    // You could use a custom 'display' parameter, e.g image_style
    $image = field_view_field('profile2', $profile, 'field_image');
    $variables['user_picture'] = render($image);
  }

}

```

# Answer
> 2 votes
Drilling down a bit, the picture there is generated inside `comment.tpl.php` by the `user-picture.tpl.php` template, inside of which it relies upon the `$user_picture` variable.

So, the easiest way might be to put something along these lines in your theme's `template.php`...

```
YOURTHEME_preprocess_user_picture(&$variables) {

  $account=$variables['account'];

  $variables['user_picture'] = // whatever you want it to be instead of the default

}

```

...with whatever logic you need based upon the user information passed in via the `$account` variable.

This would also have a possible added benefit of overriding this everywhere a user picture is similarly themed.

---
Tags: 7, users
---


# Question
Title: Why drupal include my code into comment in my TPL
Why drupal include my code into comment in my TPL.

in tpl in my module. Drupal include my php code into comments.

```
<!--?if($form["#Xcoords"]):?-->
<!--?$x=(json_decode($form["#Xcoords"], true));?-->
<!--?endif;?-->

```

So I didn't understand it(((

# Answer
> 2 votes
They are HTML comments, not PHP ones. And HTML comments are outputted. Proper way to comment out your code would be:

```
<?php /* if($form["#Xcoords"]): */ ?>
<?php /* $x=(json_decode($form["#Xcoords"], true)); */ ?>
<?php /* endif; */ ?>

```

---
Tags: theming
---


# Question
Title: How to call confirm_form() directly from another submit function
I would like to call a confirm\_form function for selected items in tableselect. If you select some items, and next you specify a action to perform in select and submit it I want to display confirm\_form(). I wrote some code, but it doesn't display any confirm box.

```
function products_manage_delete_confirm($form, &$form_state) {
    if (!isset($form_state['values']['products'])) {
        return;
    }
    $form['products'] = array('#type' => 'value', '#value' => $form_state['values']['products']);
    $form['#submit'] = array('products_manage_delete_confirm_submit');
    return confirm_form($form,
            t('Are you sure want to delete these products.'),
            'admin/products',
            NULL,
            t('Delete'));
}

function products_manage_delete_confirm_submit($form, &$form_state) {
    foreach ($form_state['values']['products'] as $product_id) {
        delete_product($product_id);
    }

    drupal_set_message(t('The product has been deleted.'));
    watchdog('product', 'The product has been deleted.');

    $form_state['redirect'] = 'admin/products';
}

function products_manage_options_submit($form, &$form_state) {
    if (!isset($form_state['values']['products']) || !count($form_state['values']['products'])) {
        return;
    }

    $operation = $form_state['values']['operation'];
    $form['products'] = array('#type' => 'value', '#value' => $form_state['values']['products']);

    switch ($operation) {
        case 'delete':
            return drupal_get_form('products_manage_delete_confirm');
            break;
    }
}

```

# Answer
Check this link.

You need to create one more menu using hook\_menu(). and in that menu call confirm\_call function.

you can check node(Default) module of Drupal for the same. you can see how user asked for confirmation before deleting any node.
> 0 votes

---
Tags: forms
---


# Question
Title: How to create websites in shared folder using quickstart?
I am using quickstart and I am able to create websites, run all drush commands, etc.

I am running Virtual Box on a Windows7 machine. i have setup a folder to be shared.

My problem: I am not able to create drupal sites (using drush qc --domain=mysite.dev") in that shared folder.

I want to create in that shared folder since I need access to the files from my windows environment also - for backup purposes, etc.

My terminal Output:

```
12:51:05 ~$ cd Desktop/
12:51:12 ~/Desktop$ cd shared
12:51:14 ~/Desktop/shared$ ls
DrupalPro_test.ova
12:51:15 ~/Desktop/shared$ drush qc --domain=neil.dev
                                                                     [ok]
Creating dns config (add neil.dev to /etc/hosts) ...                 [ok]
Command failed: neil.dev already exists...doing nothing              [error]
12:51:30 ~/Desktop/shared$ ls
DrupalPro_test.ova
12:51:36 ~/Desktop/shared$ ls
DrupalPro_test.ova
12:51:37 ~/Desktop/shared$

```

# Answer
> 0 votes
I found my answer on how to control where to store code. Trick was to use "--codepath=..." parameter.

# Controlling where files are to be stored

drush qc --domain=d7tries.dev --codepath=/home/drupalpro/websites/REPOSITORIES/my-drupal-experiments/d7tries.dev --makefile=/home/drupalpro/.drush/d7.make

Help at: https://drupal.org/node/819398

---
Tags: backups, drush
---


# Question
Title: link to create a user relationship type in views
I have user relationship, statuses and views installed. I created a view which shows "users online". I need to add a link to the view, that would allow other users to "create a relationship" with other online users via the view.

The user relationship I created is a one way relationship and there is no need for approval.

Thank you.

# Answer
Hope this will help you,

In Drupal 7, after configuration User relationship

* Create a php field using **views php** module and after enabling, add below code in **OUTPUT CODE** within **PHP tags**.

```
  global $user;
  $opt = '';
  $requestee_id = $row->uid;
  $requester_id = $user->uid;
  if (user_is_logged_in()) {
    if ($requestee_id != $requester_id) {
      //for friend request button
      $relationships = user_relationships_load(array('between' => array($requester_id, $requestee_id)));
      if (empty($relationships)) {
        $opt = l(t('Add Friend') , "relationship/$requestee_id/request/2", array('html' => TRUE, 'absolute' => TRUE, 'query' => array('destination' => 'user/' . $requestee_id), 'attributes' => array('class' => array('ur-link add-friend-btn user_relationships_popup_link'))));
      }
      else {
        foreach ($relationships as $relationship) {
          if ($relationship->approved == 1 && user_relationships_ui_check_access('view', NULL, $relationship)) {
            $opt = t('<span class="already-frnd">Friends</span>');
          }
        }
      }
    }
  }
  print $opt;

```

Note

* 2 is the **default USER relationship**.
* **Requester ID** \- Who requested and **Requestee ID** \- to whome the user is requested.

Make changes as per your requirement.
> 1 votes

---
Tags: views, users
---


# Question
Title: How to theme a menu in drupal 7 with this html
```
  <ul id="nav">
    <li class="active"><a href="index.html"><span>Home<br/><span class="SousTitle">The card of flight</span></span></a></li>
    <li><a href="list_news.html">News<br/><span class="SousTitle">The actual & promo</span></a></li>
    <li><a href="list_compagnie.html">Compagnies<br/><span class="SousTitle">More details</span></a></li>
    <li><a href="list_airport.html">Airports<br/><span class="SousTitle">Prepare your travel</span></a></li>
    <li><a href="forum.html">Forum<br/><span class="SousTitle">The community</span></a></li>
  </ul>

```

# Answer
> 1 votes
Use `theme_menu_tree()` theme function overrides

https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_tree/7

Copy the contents of 'Code' on these pages to your theme's template.php and change the 'theme' in the function names to the name of your theme, for example:

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

```

Make the changes to the HTML tags, save the template.php and clear caches.

Also if you just want to customize HTML for a specific menu, you can name your functions like this: `THEMENAME_menu_tree__MENU_NAME()`

---
Tags: theming
---


# Question
Title: Add template suggestions for location.tpl.php to use a different layout for addresses on specific content types?
I have been trying to figure out a method to override the locations.tpl.php template on a per content type basis, but I can't find any good examples on doing this with module template files rather than core template files. Is there code that could be inserted into template.php so that location--blog.tpl.php could be used in the same way that node--blog.tpl.php can be used? Interested in the location module specifically, but would appreciate pointers for general methods of theming contrib modules.

# Answer
@

**Drupal 7 Template Suggestions**
http://drupal.org/node/1089656

lists template suggestions in core. It references,

***Custom Template Suggestions***

> Custom suggestions beyond the ones listed below can be created. See the page Working with template suggestions. http://drupal.org/node/223440#custom-suggestions

which provides examples for mod'ing template.php so that "All layers from core, modules, theme engines and themes can provide the suggestions."

which may provide a start for you.
> 1 votes

# Answer
You could use the following function.

Paste it in your theme file `template.php`

```
function MY_THEME_NAME_preprocess_location(&$variables) {
    $query = db_select('location_instance', 'n');
    $nid_field = $query->addField('n', 'nid');
    $query->condition('lid', $variables['location']['lid']);
    $result = $query->execute();
    foreach($result as $n){
        $node = node_load($n->nid);
        $variables['theme_hook_suggestions'][] = 'location__node__' . $node->type;
        $variables['theme_hook_suggestions'][] = 'location__node_' . $n->nid;
    }
}

```

Your theme can now detect different templates for the locations original template using this pattern: **location--node--\[type|nodeid\].tpl.php**

For instance, these would be valid template suggestions:

```
location--node--1.tpl.php
location--node--blog.tpl.php

```
> 1 votes

---
Tags: 7, theming
---


title: 2 user registration forms

text:
# Question
Title: 2 user registration forms
I need to show users 2 registration forms. 2 different forms with different fields. 1 form for free registration and 1 form with admin approval registration. how can i achieve that?

# Answer
It seems there is not any module that provides this functionality directly. But certainly you can achieve it using other contributed modules.

1. Profile2

This module allows you to create user profile for the users. You can create profile for the two users like free\_registered user and admin\_approved users, and can add any number of fields on the user profiles.
2. Profile2 Registration Path

This module allows you to set the unique registration path for each profile2 user profile. So after installation you will have two registration forms for each profile2 user profiles. You can access this form from the path specified in Profile2 Registration Path module configuration.

Let me know if any issue occurs. :)
> 1 votes

---
Tags: forms, users
---


# Question
Title: Subdomain creation on each user creation
How to create subdomain for each user creation(seller role)? there is subdomain module as well as domain access module. can any one elaborate how to use sub domain module w.r.t user creation? Thanks in advance.

**Note: My Apache is configured to accept all subdomains**

# Answer
> 2 votes
Although I am not aware with your requirement in detail, I would suggest the Subdomain module, which allows you to achieve this kind of functionality.

> Automatically creates subdomains and places content on them. There are 4 modes:
>
> User: e.g. "Mary" and content at http://mary.example.com
>
> Taxonomy: e.g. "Seattle" and content at http://seattle.example.com
>
> Organic Group: e.g. "MyGroup" and content at http://mygroup.example.com
>
> Content type subdomains: e.g. "News" content at http://news.example.com

The other module is the Domain Access module.

---
Tags: 7, subsites
---


# Question
Title: What's the best way to add an image to a page?
I'm wondering if there's a standard, nice way to add a picture - icons for example - to a page. These images should be static (= non-changing), which means that they don't depend on something else (e.g. the user's gender). Let's say that I would like to create a table with two columns: in the first column comes some random text, a view or whatever and in the second column comes a picture, according to the caracteristics I set before. \[Thus, to be completely clear, the image in the column on the right side is simply chosen by the site editor and doesn't change when the text in the left column is changed.\]

How can I insert such an image? Is there a module that makes this possible? I can't find any... For icons, I now created a content type 'Icon' with field\_image and an image style 'Icon' with 'Image styles'. These ones combined work pretty fine, but it doesn't seem a very clean way to achieve my goal, because I've to create a new content type for each icon. Or is it?

# Answer
I think this depends a little on what you want to achieve. Is it a static set of icons that will never change? If so, you should consider just creating a block containing simple HTML for your images. That way, you can use this block wherever you want, and you can style both the images and the position of the block using CSS.

Strictly speaking, adding `field_image` to a content type implies a relationship between the image and the other content of nodes of that content type. I wouldn't advise creating a whole content type just to hold icon images.

Hope this helps!
> 2 votes

---
Tags: media
---


title: How can I get the group ID of a node?

text:
# Question
Title: How can I get the group ID of a node?
I have this node that belongs to a group, and I want to get the group ID of that node, to print it, something like `$node->nid;` but with the group id.

Is that possible?

# Answer
> 11 votes
The relationship between group content and a group is via a membership relation. Since it is possible for group content to be a member of multiple groups then the following code will retrieve the list of groups:

```
$groups = og_get_entity_groups('node', $node);

```

This is a multidimensional array with the group entity\_types as the key and memberships as the value. Each membership is an array with the membership id as they key and then group's entity id as the value. So to go from a group content node, to all it's group parents you would use ...

```
foreach (og_get_entity_groups('node', $node) as $entity_type => $og_memberships) {
  foreach ($og_memberships as $membership_id => $entity_id) {
    if ($entity_type == 'node') {
      // Assuming we only want to deal with node groups, we can
      // access the group node with...
      $group_node = node_load($entity_id);
    }
  }
}

```

# Answer
> 4 votes
I needed this last night. Did it like this:

```
$node = node_load($nid);
$og_id = current($node->og_groups)

```

$og\_groups contains an array of all the OG that a post is a member of. You could get them all with a foreach. Te key to access them is the nid.

```
$og_groups=array(5=>5, 15=>15);

```

Hope that helps.

# Answer
> 4 votes
The `og(organic groups)` module add `entity refrence` field to content types you want be a `group` or be a `group content`. by default name of field is `og_group_ref` but maybe it change to another name. If you want exactlly find out og field name please see the your content type manage field (lets suppose your considered article content type ) `admin/structure/types/manage/article/fields`.
Pick up group field **MACHINE NAME** (some thing like `og_group_ref`).

Your can something like this :

```
$node=node_load($nid);
$ogId=$node->og_group_ref['und'][0]['target_id'];

```

# Answer
> 2 votes
Find out the gid then try print the whole $node object, something like:

> ```
>   print_r($node);
> ```

Some reason Drupal answers will not display anything in the php tags, but you should wrap the php in pre to make the output more readable.

Try ctrl + F and find where the number is outputted. You can then follow the format of the arrays / objects to print it when $node is available.

---
Tags: organic-groups
---


# Question
Title: Save image from URL to a field from a custom module
With a custom module, I'm trying to create a new node, save an image to a node's image field from URL and save the node as well. However when I'm trying to save the node, this error messages comes up

> Notice: Trying to get property of non-object in file\_field\_presave() (line 220 of /var/www/clients/client1/web20/web/modules/file/file.field.inc).
>
> Notice: Undefined property: stdClass::$uri in file\_save() (line 566 of /var/www/clients/client1/web20/web/includes/file.inc).
>
> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file\_managed} (filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> 1 \[:db\_insert\_placeholder\_2\] =\> 1373886933 ) in drupal\_write\_record() (line 7136 of /var/www/clients/client1/web20/web/includes/common.inc).

This is the code I wrote for saving the image into a folder, saving it into a node field and save the node:

```
      $node = new stdClass();
      $node->type = "flickr_image";
      node_object_prepare($node);

      $node->title    = $photo['title'];
      $node->language = LANGUAGE_NONE;

      $node->uid = 1;

      $url = $image[10]['source']; //URL of the image
      $directory = file_build_uri('flickr_images/');

      $file = system_retrieve_file($url, $directory, TRUE, $replace = FILE_EXISTS_REPLACE);
      file_save($file);

      $node->field_image[LANGUAGE_NONE] = $file;

      if($node = node_submit($node)) {
          node_save($node);
      }

```

What am I doing wrong? I've looked up several similar questions here, but I don't understand what's the problem. The messages only come up when I use node\_save(). When I comment it out, the messages disappear.

# Answer
Hope this will help you,

In Drupal 7, for your requirement I made some changes.

* As system\_retrieve\_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the `file_managed` table if you want it to be managed. ````
$node = new stdClass();
$node->type = "node_type";
node_object_prepare($node);
$node->title    =  'your title here';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$url = 'https://ssl.gstatic.com/gb/images/k1_a31af7ac.png';
//I have used picture folder to store images using image field settings
$file_info = system_retrieve_file($url, 'public://pictures/', TRUE);
if($file_info->fid){
    $node->field_image[LANGUAGE_NONE]['0']['fid'] = $file_info->fid;//assign fid
}
$node->field_test_field[LANGUAGE_NONE]['0']['value'] = 'test';//other fields
if($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('submitted successfully');
}

````

Make changes as per your requirement.
> 11 votes

---
Tags: 7, media
---


# Question
Title: "site map" module and I would like to add the following jQuery line so that the /sitemap page is formatted
I am using "site map" module and I would like to add the following jQuery line so that the `/sitemap` page is formatted:

```
$('#mydiv').columnize({ width: 200 , columns: 3 });

```

The `/sitemap` page is not trapped within either `hook_form_alter` or `hook_page_alter` so how could I add this JQuery line?

# Answer
> 3 votes
The site\_map module has a theme template implementation in the root folder of the module:

> site-map.tpl.php

Easiest and most sustainable way to add this would be to copy this file to your theme templates folder, add your javascript in there and flush caches.

Other quick ways:

* Create a block and add your javascript in there then place this in a region on the path '/sitemap'
* Create your own preprocess\_page module that adds this javascript if the path is /sitemap

---
Tags: javascript
---


# Question
Title: Ajax processed not added on link element
I am stuck on a case where I am trying to ajaxify a link, following the tutorial placed here http://clikfocus.com/blog/simple-ajax-example-drupal-6-and-7.

The problem is that the `.ajax-processed` is not added to the link.

Can you suggest any common pitfalls here?

The weirdest part is that some of the other modules is blocking the functionality. Could it depend on the setting of the view that prints this element?

# Answer
In order to have the AJAX event assigned (and the ajax-processed class added) to a link you need two things:

1. use-ajax class on the anchor tag
2. AJAX library loaded

I'm guessing you're missing item #2, and that can be done in a few different ways:

1. If you're generating a renderable array, use #attached:

$my\_data\['#attached'\]\['library'\] = array( array('system', 'drupal.ajax') );
2. Or you could run this PHP pretty much anywhere prior to the page being rendered:

drupal\_add\_library('system', 'drupal.ajax');
> 3 votes

---
Tags: ajax
---


# Question
Title: Prevent inheritance link color secondary menu
I'm creating a lay-out for my website with Zen in Drupal 7. I want links in the body to be red and bold, so I customized the `normalize.css` file:

```
a:link,a:visited {
  color:#990000;
  font-weight:bold;
  text-decoration:none;
}

a:hover,
a:focus {
  color:#990000;
  font-weight:bold;
  text-decoration:underline;
}

```

I noticed that the links in the secondary menu were affected by this too. This isn't exactly what I want, so I tried to color them white again by changing the navigation.css file:

```
#secondary-menu {
  float: right;
  color: #fff;
  text-decoration: none;
}

```

Unfortunately, this doesn't work, because the color of the secondary menu is apparentely inherited (I discoverd this with Firebug).

How can I fix this problem?

# Answer
Try this:

```
#secondary-menu {
  float: right;
}

#secondary-menu a:link,
#secondary-menu a:visited {
  color: #ffffff;
  text-decoration: none;
}

```

This way, the menu will be placed on the right, and the menu items will be in the right order, not reverse.
> 2 votes

---
Tags: routes, theming
---


title: db_query performance

text:
# Question
Title: db_query performance
This is a more general question about db\_query() performance.

I have this function to create an API resource with Services module, and I need to get about 10 fields belonging to several nodes. Basically I have a list of nids and create an array containing information from their fields. The nodes have a lot more fields than I need so doing node\_load to get the info is really slow, so at the moment I am geting the info using db\_query() calls for each field that I need.

My question is: would it perform better if I only have one db\_query with about 10 inner joins? or should I leave it as 10 separate db\_queries?

I am going to do some performance tests, but I thougt someone might have some insight or explanation on why one would perform better tha. the other.

# Answer
> 2 votes
* Install entitycache \- it will load the nodes quickly from a persistent cache ( e.g memcache, but db ok )
* Use EntityFieldQuery to fetch the relevant nodes.

e.g:

```
  // Get published articles created in last 7 days.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('status', 1)
        ->propertyCondition('created', strtotime('-7 days', REQUEST_TIME), '>');
  $result = $query->execute();
  if(!empty($result['node'])){
    // These will be loaded from entitycache
    $nodes = node_load_multiple(array_keys($result['node']));
    // Process result nodes
    foreach($nodes as $node){
      // Do stuff
    }
  }

```

# Answer
> 0 votes
You don't want to be doing 10 joins on the field tables. If your content base (ie. fields tables) grows to any substantial size, this query will get very, very slow. Doing 10 separate queries isn't ideal, but not the end of the world, either.

Realistically though, doing node\_load() on 10 ids shouldn't be too bad. Nodes are statically cached, so multiple calls to node\_load() with the same id won't result in more queries than necessary, and if the same nodes are already being used for something else on the page, you might as well take advantage of their presence in the static cache.

---
Tags: database, performance
---


# Question
Title: View displays nodes that should be excluded by filter
I'm working on the website for my bicycle shop. I've created a series of views that display the different types of bicycles we have: touring bikes, city bikes, etc. There is also a view that displays all the bikes.

In order to hide display of bikes that have been sold already (i.e. have 0 stock), I have the following filter criteria:

Stock: Level (\>0) OR Stock: Active (No)

(There is the provision that if the stock level is not set to active it's ok for the stock to be zero, because there are some products that we don't track the stock of).

When someone buys a bike, the stock is decreased by 1 (to 0, most often), and the bike should then disappear from the view.

Except that it doesn't.

Eg. The first bike on this page \- if you click on it, it says it's sold, and the stock is set to active, and the stock number is zero.

My question is: why does it still appear in the view? I have cleared the caches, re-created the view... If I create a new view that has no filters except the criteria "Stock level \> 0", the aforementioned bicycle with stock=0 still appears!

Please tell me what I'm doing wrong.

Cheers, Chris

# Answer
Your filter says, "if the stock level is greater than 0 (1,2,3,4...) OR stock is not active, don't show the product". You want it to say, "if the stock is equal to 0 ( or \<=0 ) OR stock is not active, don't show the product“. In other words: `Stock: Level (=0) OR Stock: Active (No)`

On second thought, if you're not filtering out, you would want `Stock: Level (>0) OR Stock: Active (Yes)` to show all bikes that are active, and have more than 0 in stock.
> 0 votes

---
Tags: views
---


# Question
Title: In Drupal 7 Commerce 1.x - is there a way to include the price into the dropdown product select box?
Currently the price is outside of the select box on product display's. Is there a way to include the price in the select box itself?

**Example:**

**$5 - Basic Repair - Scratched Disc Recovery**

instead of whats below.

# Answer
Include the price in the product title itself in same way which you want to show in select box.

There are other way, in that you will have fetch the product id of the product reference field in `template.php` & load full product to get price. Then prepare title again at theme lavel..

For better understanding of what I am talking about, you can see my answer for a question here, where I have explained how to prepare title of node again which include taxonomy. You also have to do something similar like that..

But I will suggest you to follow the first solution of mine means - Include price with title of the product.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: MigrateSQLMap how to instantiate if table has no primary key
Guys how do you instantiate this MigrateSQLMap if my destination table has no primary key?

here's my code:

```
 $table_name = 'taxonomy_index';
    $this->map = new MigrateSQLMap($this->machineName,
      array('id' => array(
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
             )
           ),
        MigrateDestinationTable::getKeySchema()
      );

```

im trying to import to the taxonomy\_index table in drupal which we know has no primary key.

how to make this possible?

# Answer
> 1 votes
To migrate content into Drupal taxonomy terms, use the MigrateDestinationTerm class, not MigrateDestinationTable. Here is example code

```
    $this->map = new MigrateSQLMap(
      $this->machineName,
      array(
        'term_id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Term ID',
        ),
      ),
      MigrateDestinationTerm::getKeySchema()
    );

```

---
Tags: migrations
---


# Question
Title: Trying to migrate user data into multi value term reference field
FYI: I'm using the module Migrate 7.x-2.5

I'm trying to migrate users from a custom built PHP website, backed by a mysql database, into Drupal.

Each user can have multiple statutes assigned to him. In the source database I have a table 'users' with a column 'stat\_id'.

```
+---------+---------+
| user_id | stat_id |
+---------+---------+
|       1 | ;2;     |
|       2 | ;26;    |
|       3 | ;3;     |
|       4 | ;27;28; |
|       5 | ;19;2;  |
+---------+---------+

```

The name of the statutes is stored in the table 'users\_statuut'.

```
+---------+----------------------------+
| stat_id | statuut_nl                 |
+---------+----------------------------+
|       1 | Doctoraatsstudent          |
|       2 | Postdoctoraal onderzoeker  |
|       3 | Administratieve medewerker |
|       6 | Diensthoofd                |
|       7 | Laborant                   |
+---------+----------------------------+

```

In Drupal I created a term vocabulary 'statutes' with the names of all the statutes. And I added a term reference field to the user profile that can select multiple values from this vocabulary.

What I can't figure out is how to migrate the data from the source table into Drupal. I've already managed to migrate simple fields like username, email, password,... so that's working, but I have no idea how to get the statutes into the term reference field.

Any help is really appreciated.

# Answer
> 0 votes
Use a callback with a separator to transform the source value to the destination value. For example:

```
  $this->addFieldMapping('statuut_nl', 'stat_id')
   ->separator(';')
   ->callbacks(array($this, 'computeValue'));

  protected function computeValue($value) {
    $allowed_values = array(
      2 => 'Postdoctoraal onderzoeker',
      ...
    );

    return ($allowed_values[$value]);
  }

```

---
Tags: 7, migrations, taxonomy-terms
---


# Question
Title: Custom story-node-form.tpl.php not working
I have created a custom node add form for `story` content type. Though this appears as expected but do not working.
Problem is when i click on the `Submit` button then this form just redirect me again in `node/add/story` path instead creating the story page!
Here is what i have did (Here i have used bartik theme):

> **template.php**

```
    function bartik_theme() {
    return array(
    'story_node_form' => array(
    'arguments' => array('form' => NULL),
    'template' => 'story-node-form',
    'render element' => 'form',
    ),
    );

```

> **story-node-form.tpl.php**

```
<div class='story-form'>
<div><?php print drupal_render($form['title']); ?></div>
<div><?php print drupal_render($form['body']); ?></div>
<div><?php print drupal_render($form['actions']); ?></div>
<div><?php print drupal_render($form['additional_settings']); ?></div>
<div><?php print drupal_render($form['actions']); ?></div>
</div>

```

Now if i click on the Submit button then this story creating form just redirect me again in `node/add/story` path instead creating the story page! What i am missing here? Thanks

# Answer
> 0 votes
I have solved this by doing `<?php print kpr($form); ?>` and put all the hidden input fields in the form like token, form\_id etc that worked!

---
Tags: 7, theming
---


# Question
Title: What happens when you delete a field from an existing Content Type?
When you delete a field from an existing Content Type, does the mysql field also get deleted or is it still there except it's simply not used? This is whether or not the content type already has data.

# Answer
> 1 votes
When you delete any of the field of the content type then all the log of that field from the database is deleted.

eg. Suppose we create a **field** named **test** in the **content type A** then it creates 2 tables in the database ie **field\_data\_test** and **field\_revision\_test**.

So when you **delete the field test** then both the tables are also deleted from the database.

# Answer
> 0 votes
This article explains that if you delete a field that's unique to 1 content type then it's deleted from the database. However if this field is being shared by at least 1 more content type then the field database table remains however the data of field is removed (the data corresponding to the content type that the field is being removed from).

> If the field you delete is unique to a content type, then the field is gone from the database (that includes it's data). If you delete a shared field from, the field is removed from that content type along with the data unique to the contenty type.

---
Tags: 7, entities, database
---


# Question
Title: Displaying Empty Option in Multiselect box
This might be a really trivial question but it is driving me nuts. I have looked at similar posts but they all address a single-select drop-down box. What I need is to get the '-None-' to show up in a multi-select box. For some reason, despite verifying my code a million times, it is not showing up. Hope someone can point out what I am doing wrong.

```
$form['add']['add_drop_down'] = array(
  '#type' => 'select',
  '#title' => t('Select all that apply'),
  '#options' => $options,
  '#multiple' => TRUE,
  '#required' => FALSE,
  '#empty_option' => '-None-'
);

```

Basically, this only shows the options in $options in the select box and doesn't add the '-None-' as the first item. It works fine if I change it to a regular single-select. The moment I turn #multiple to TRUE, the '-None-' disappears. I have tried a number of different ways, but with no luck. Hope someone can help. Thanks.

# Answer
That behaviour is by design; from the docs for `form_process_select()`:

> // A non-#multiple select needs special handling to prevent user agents from
> // preselecting the first option without intention. **#multiple select lists do<br>// not get an empty option, as it would not make sense, user interface-wise**.

(emphasis mine).

If you want to override that behaviour you can probably implement `hook_element_info_alter()` and provide your own process function which does things differently to the core one. e.g.

```
function MYMODULE_element_info_alter(&$type) {
  $type['select']['#process'] = array('MYMODULE_form_process_select', 'ajax_process_form'),
}

function MYMODULE_form_process_select($element) {
  // Duplicate code from form_process_sleect() and change what you need.
}

```
> 2 votes

---
Tags: forms
---


title: Embed vimeo video into the body field

text:
# Question
Title: Embed vimeo video into the body field
How do I embed a vimeo video into the body field. The iframe is being removed in my input format. How do I add it?

# Answer
The input formats can be configured at `/admin/settings/filters/list` so that you can add the `<iframe>` tag as an allowed tag to the input format that you are using.

Though, I think for security purposes, you may want to allow tags other than `<iframe>`. One option it so use Vimeo's 'old' embed code (the link would be just above the box where you copy the code from). The old embed code uses the `<embed>` and `<object>` tags, which you'll likely still have to add to the filter's allowed HTML tag list.
> 4 votes

# Answer
Many possibilities:

1. Change your input format to include `<iframe>`, it's in `admin/settings/filters/1/configure` for the "Filtered HTML" format
2. If you're the one posting and you're admin, you may use the "PHP" format, not very recommended (don't forget to enable the PHP filter module)
3. As Laxman13 suggests, use Embedded Media Field but I would personnaly use the Media: Vimeo module and put the video in a CCK field which could be more usefull when you want to build a views with these videos.
> 2 votes

# Answer
You can use Embedded Media Field module.
> 2 votes

# Answer
Have you tried changing the input filter that is being used on the textarea?

You could also use Embedded Media Field module along with the sub-module **Embedded Inline Media**. However, all this seems to do is add another input filter to be used to automatically display an embedded video.
> 1 votes

# Answer
You need to refresh the browser page after you submit the node edit form.

Webkit browsers will not show embedded media directly after submit. This is a side effect of a security feature. http://code.google.com/p/chromium/issues/detail?id=98787
> 0 votes

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


title: Accessing user input

text:
# Question
Title: Accessing user input
My question is basically how to access values that the user entered in previous forms. For example, I am using drupal commerce and as the user sees a product, fills some text field values and clicks add to cart and then finishes the checkout. At the end of the checkout how can i access programatically the values that he entered in the first stage of the process?

One way I think it might work, is to add a submit handler in the original product form that "grabs" the values when he clicks add to cart and then save them to a session. Is this the correct way ? Is there any other way like querying the db or something?

I do not want to display to the user anything, I just want to work "behind the scenes".For Example after the checkout is complete, I want to call the hooK\_commerce\_checkout\_complete and by using the values that he entered in the first place modify and save a pdf (I know how to crate the pdf with the tcpdf lib what i do not know is how to call the values as i said earlier).

If this were Java the values would correspond to an instance variable and i would have access through the corresponding get method. Surely there must be something equivalent for this in php/drupal.

I would appreciate any advice or links to the proper documentation on how to do that.

PS I am most interested on accessing commerce line items and the value of their fields but i should probably start with the easy ones first!

Thanks in advance

# Answer
PHP isn't Java...there's no concept of 'instance variables' in this context, and no automatic persistence of such vars across page requests.

Drupal Commerce persists information about the order, order lines, products, etc to the database during the checkout process, and then re-loads the relevant entity when it needs it (which is the standard workflow).

In `hook_commerce_checkout_complete()` you already have access to the `$order` entity, so there's no need to load it yourself. I'd advise using an `entity_metadata_wrapper()` to access the order; to get the order lines, for example, you'd use something like:

```
function MYMODULE_commerce_checkout_complete($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    // Do something with $line_item_wrapper.
    $field_val = $line_item_wrapper->field_something->value();
  }
}

```
> 1 votes

---
Tags: commerce, entities, sessions
---


# Question
Title: What is the difference between watchdog Location and watchdog Referrer in dblog messages
What is the difference between watchdog Location and watchdog Referrer in dblog messages?

An easy example to see the difference would be nice, for example on the node creation/edit they are the same.In which case these two URLs will be different?

# Answer
> 4 votes
The 'Location' is the URL a user/process was visiting when the watchdog entry was invoked.

The 'Referrer' is the URL that referred the user to the 'Location' URL.

So if a person goes directly from a link on http://www.google.com to http://yoursite.com/, and visiting that URL on your site generates a watchdog record, the 'Location' will be '/', and the 'Referrer' will be 'http://www.google.com'.

---
Tags: 7, log-messages
---


# Question
Title: Node count published, unpublished and total
I have been on this for a while, considering my low php knowledge. Anyway I would like a view that lists users with total number of articles created, total number of those articles that are published and total number of those articles that are not published per user. I have looked around for an answer to this and the closest I get is node view count which does not do what I need.

# Answer
In my opinion this is not as simple as it sounds although it should be considering the capabilities of Drupal.

I'll provide you with my solution (Drupal 7) which i implemented once in a site:

Create a users view in which you should do the following (in that order):

* Remove any default Sort Criteria and don't add anything in that section
* Add a field of "User: name"
* Add a "User: Content authored" relationship
* Add a filter "Content: Type" = Article
* Add filter "Content: Published" = Yes
* Add a contextual filter of "User: uid"
* Activate aggregation
* Set aggregation settings of user name field to "Count"

Now when you type the uid of a user in the "Preview with contextual filter" field of the view you will get the number of published articles that particular user has created.

Clone that view and (in the cloned view) change the Content:Published filter to No from yes. Now you have a 2nd view that gives you the number of unpublished articles for every user.

Last install and enable Views Field View module and create the following users view (in that order):

* Add a field of "User: Uid" and exclude it from display
* Add a field of "User: name"
* Add a global view field. In the window that pops up choose the 1st view you created and the display you want from the "Views Settings" section (master display can be chosen if you like) and finally (and most importantly) in the "Contextual Filters field" use the \[!uid\] token (replacement patterns: \[!uid\] == User: Uid (raw)).
* In the exact same way add a another global view field to "pull" the 2nd cloned view in this current view.
* Recommendation: style the view as a table for trial reasons then theme as you like.
* Also be careful to always have both global view fields after the user uid field in the Fields listing.

So this final view will present all the users of the site and next to each user the respective number of published and unpublished articles they have created. If you need the total number of articles then create an extra view without any Content: published filters and use it accordingly.
> 1 votes

---
Tags: nodes
---


# Question
Title: How I get notified every time their is an *new* update and not every day for the sames updates?
The update module can send you email when a new release is available for a module you installed. The problem is I get a email everyday. Some security update are very minor and unreachable for an attacker, I don't want to update the website and so I don't want future notification about this update.

I would like to be notified every time their is an *new* update, not every day for the sames updates.

# Answer
> 0 votes
I can use hook\_mail\_alter to cancel the sending of the mail. I can simply store a md5 of the mail's body every time the mail is send and compare it with the "new" email, if it's the same I don't send it.

---
Tags: updating, security, users
---


title: How to get work the hook_form?

text:
# Question
Title: How to get work the hook_form?
I try to hook the node form by hook\_form(), but I can't modify the base form. I try to do this like below

```
function products_form($node, &$form_state) {
  $type = node_type_get_type($node);

  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE,
    '#weight' => -5,
  );
  return $form;
}

```

What's is wrong? My module name is 'products'.

# Answer
`hook_form()` is only meant to be used by a module that provide content type:

> This hook, **implemented by node modules**, is called to retrieve the form that is displayed to create or edit a node. This form is displayed at path node/add/\[node type\] or node/\[node ID\]/edit.

Emphasis mine.

It provides the form, and does not do alterations.

If you want *to modify base form* created by another module, you need `hook_form_alter()`:

> Perform alterations before a form is rendered.
>
> One popular use of this hook is to **add form elements to the node form**. When altering a node form, the node object can be accessed at $form\['#node'\].

Again, emphasis mine.
> 1 votes

---
Tags: hooks
---


# Question
Title: Any way to have one back office to administrate multipe sites in drupal?
I have two websites in one instance of drupal and I want to administrate this websites in one back office, any ideas ?

Thank you.

# Answer
> 2 votes
Seems you are looking for Domain Access module:

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:
>
> * example.com
> * one.example.com
> * two.example.com
> * my.example.com
> * thisexample.com \<-- can use any domain string
> * example.com:3000 \<-- treats non-standard ports as unique

---
Tags: multi-sites
---


title: Hiding error messages: sql query

text:
# Question
Title: Hiding error messages: sql query
I have a site running on Drupal. There is a production site, publicly seen online and a development version on a private machine.

When migrating from a devel to a production server I'd like to disable the display of error messages. This could be done in Home » Administration » Configuration » Development (D7). However I'd like to automate that; put a proper SQL query in my migration script (that packs, transfers and 'installs' the page on a production server)

Can anyone help me with that? Thanks!

# Answer
> 3 votes
That setting is stored in the `variable` table as a serialised PHP string (in the "error\_level" var) - I wouldn't advise updating that table manually with SQL (although obviously you can if you need to).

Far better would be to install Drush, and use `vset` as part of your deployment process instead:

```
drush vset error_level '2'

```

The available options are:

* 0 =\> None
* 1 =\> Errors and warnings
* 2 =\> All messages

---
Tags: database
---


title: Symfony2 authentication

text:
# Question
Title: Symfony2 authentication
I am currently developing a website using the framework Symfony2. I am nearly at the end of its development, and just the "security" part is missing (authentication and authorization). What I would like is to use Symfony2 core bundle to authorize the user but I want to use my Drupal database to get the authentication of the user.

I have previously used the module Services 3 with a REST server to get the user information and to authorize him/she to go on my website (which was flat php coded). Now, I want to make something robust and secure, so here my question, do you know a method for getting the authentication from the Drupal website and then authorize the user via Symfony core bundle?

Here are my 2 thoughts about it:

-\> Fetch the user data ($username & $password) using the REST server and a query made in my custom UserProvider (Symfony Doc) and then leave Symfony makes the authentication using the Drupal's password encoder. But here the problem is that when you fetch the user data using the REST server, you get everything but the password.

-\> Get access to the Drupal database using Doctrine as usual in my application and fetch the user & pass from it. Then use the Drupal's password encoder to check this result.

To conclude, I am really far to be an expert on this kind of stuff, so I would really appreciate your help.

# Answer
You can use a custom User Provider in Symonfy and then use the Service Module from Drupal to login via a REST interface
> 0 votes

---
Tags: 7, users
---


title: JavaScript for Drupal Edit Overlay

text:
# Question
Title: JavaScript for Drupal Edit Overlay
I have written some JavaScript that I want to only run on the Edit page. We are using Drupal 7.8 and in our setup the edit page opens as an overlay. How do I get this javascript to run when the edit overlay page opens up and only then?

Thanks! Jon

# Answer
Regardless of whether the page opens in an overlay or not, the following should work. Suppose you have a node type called "Basic Page", and the machine name of the content type is "page". The node edit forms take the form of: `MACHINENAME_node_form`. So for "page" content type our form id is: `page_node_form`. The hook we're using is `hook_form_FORM_ID_alter`. The following code placed in a custom module should attach the JS file (replace instances of word `hook` with the module name, and `/path/to/file.js` with the path to the javascript file relative to the custom module directory):

```
function hook_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  // Attach a JS file
  $form['#attached']['js'][] = drupal_get_path('module', 'hook') . '/path/to/file.js';
}

```

For reference: Form API #attached
> 0 votes

---
Tags: javascript, modal-dialogs
---


title: Main menu alias links

text:
# Question
Title: Main menu alias links
my current menu links are generated but those are not the alias urls as follows:

```
theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('class' => array('nav nav-pills'))));

```

I would like that the menu generated is with alias urls instead the 'content/name-of-node'. How do you generated menu with alias path links? Is there function i can get only array of links for the main manu, so i can parse out the html myself? Thank You for help

p.s. This is Drupal 7.

# Answer
Thank You Chris...the menu\_load\_links() was exactly what i was looking for. Here is my custom main menu array that i later parse in html teplates as needed:

```
$mainMenuArray = menu_load_links('main-menu');
$finalMainMenu = array();
foreach($mainMenuArray as $key=>$menuItem){
    $finalMainMenu[$key]['active'] = false;
    $linkPath = $menuItem['link_path'];
    $linkPathAlias = drupal_get_path_alias($linkPath);
    $currentId = $vars['node']->nid;
    if(drupal_get_path_alias("node/$currentId") == $linkPathAlias)$finalMainMenu[$key]['active'] = true;
    $finalMainMenu[$key]['url'] = $linkPathAlias;
    $finalMainMenu[$key]['title'] = $menuItem['link_title'];
}
$vars['mainMenu'] = $finalMainMenu;

```

I have this in template.php hook 'theme\_preprocess\_page' where the $vars\['node'\] is used to determine what is the current node loaded. I hope it useful for someone. Thank you Chris for answering my question.
> 0 votes

---
Tags: theming
---


# Question
Title: How to prevent result from being displayed when user selects search/apply
I created a "view" on my site with 3 exposed filters (One for "name", the other for "occupation" and the last for "location") to allow users search/filter for other users on my site.

On page load, no results are displayed. However, if I simply select search/apply (without inputting any search string), it displays results.

Please, how can i resolve this?

Thanks.

# Answer
If you go to advanced settings of the view, you can set the exposed form settings to input required.

Another option if you are making use of the Better Exposed Filters, there's a patch for it which adds 'input required' option/functionality,
> 1 votes

# Answer
In D7, if we make the exposed filters be 'Required', we can avoide displaying default result list. But it will require you to set some default value for the exposed filter(s) out of the options 'Is equal to, Is not equal to, Regular expression etc'. Possibly the below post will help you :

How to combine views exposed filter with search?

Keep the exposed filter(s) as not Required.

Here, you need to also check for a condition in your code that (considering all the exposed filters are mandatory be set to some value, as you have expected) the url parameter(s) have values, I mean it should have a format like 'http://sitename.com/test\_path?title=test\_title' (Not like 'http://sitename.com/test\_path?title=').

Hope it helps
> 0 votes

---
Tags: views
---


title: Drill into computed field entity data

text:
# Question
Title: Drill into computed field entity data
I am using Drupal 7. I installed the computed field module and have a computed field in a content type. I need to be able to access the actual name of a node reference field that is in the same content type so i can then work with the data in the computed field. Currently I can only get the number of the node reference field using this in the computed code (php) field:

```
    $entity_field[0]['value'] = array_pop(field_get_items($entity_type, $entity, 'field_charity_reference'));

```

I need to be able to access a 'drill' into the the node reference to get the rendered title, which is a human readable name.

When using views and custom php I can use `dpm($data);` to explore the data and use this to work out I can access the rendered title by using:

```
    $data->field_field_charity_reference[0]['rendered']['#title']

```

Since originally posting this question I have found i can use `dpm(field_get_items($entity_type, $entity, 'field_charity_reference'));` in the 'Display Code (PHP)' input in the computed field to give a devel printout of the field I wish to access data from.

I would like to know how to drill into the results returned by `field_get_items($entity_type, $entity, 'field_charity_reference')` in order to output the name of the node reference field. Thanks

# Answer
> 2 votes
Procedurally:

```
if ($field_items = field_get_items('node', $node, 'field_charity_reference')) {
  $referenced_node = node_load($field_items[0]['target_id']);
  $title = $referenced_node->title;
}

```

Or OO'ly with the Entity API module:

```
$node_wrapper = entity_metadata_wrapper('node', $node);
$title = $node_wrapper->field_charity_reference->value()->title;

```

If you go the OO route this post will probably come in handy

# Answer
> 0 votes
If you only wish to display the data you can add the following code to the Display Code (PHP) field of the computed value:

```
     $getdata = field_get_items($entity_type, $entity, 'field_charity_reference');
     $drilldata = $getdata[0]['node'];

     $display_output = $drilldata->title;

```

It is worth noting that I got unexpected results / errors when trying to work in the Computed Code (PHP) field of the computed value. It seems that above code will not actually store your data, so it can be used by views etc. I suspect to actually store the values you need to use the Computed Code (PHP) field.

Please also note that it did trying to use `$drilldata = $getdata[0]['node']['title'];` gave the warning 'Fatal error: Cannot use object of type stdClass as array'. Only drilling as far as the node and then getting the title in the last line worked for me.

---
Tags: 7, entities
---


title: Change links titles of PDF uploads

text:
# Question
Title: Change links titles of PDF uploads
I have been trying to find a sensible solution to this problem with no success so far.

I have a site running Drupal 7 – and have built a basic content type which allows content admins to upload their own PDF documents using a file field. The content admins now what to be able to rename the PDF title that appears in the download link to whatever they want, but I can’t find a workable solution to achieve this. I have tried File (Field) Paths, but it was a disaster – full of bugs.

Is there a module out there somewhere that can allow what should be simple functionality?

# Answer
The file module has that built right in. Edit the settings for your file field, and find this bit:

Save that, and go back to your node edit form where you will see:

With both the included field formatters you should see the contents of the 'Description' field for the link text of each file.
> 3 votes

---
Tags: 7, files
---


# Question
Title: What is the difference between ctools_export_crud_load() and ctools_export_load_object()?
What is the difference between `ctools_export_crud_load()`, `ctools_export_crud_load_all()`, and `ctools_export_load_object()`?

In which cases should I use a function instead of the other two?

# Answer
`ctools_export_crud_load()`:

> Load a single exportable object.

`ctools_export_crud_load_all()`:

> Load all exportable objects of a given type.

`ctools_export_load_object()`:

> Load some number of exportable objects.

The first two are just shortcut functions to `ctools_export_load_object()` (with a bit of setup logic) `ctools_export_load_object()` is a more complicated function that can filter the required exportables by various criteria. The main point of interest as I can see it is that the first two accept a `$reset` parameter to reset the exportable(s)'s caches, whereas `ctools_export_load_object()` doesn't accept that parameter.

Basically, I'd say if the exportables you need to load can't be queried by using `ctools_export_crud_load()` or `ctools_export_crud_load_all()`, then use `ctools_export_load_object()`. Otherwise use one of the former functions, as they handle some of the necessary setup for you.
> 0 votes

---
Tags: chaos-tool-suite
---


title: Bartik's code - manage logo and favicon

text:
# Question
Title: Bartik's code - manage logo and favicon
I want upload an image for my theme, like the logo or favicon with bartik (or other theme). Where's the code for doing that with bartik ? (it's not in bartik/theme-settings)

In fact, i want this features : The user choose his background like the logo

Thanks.

# Answer
> 1 votes
If you just want to show the logo or the screenshot of the theme in your drupal site, just replace your own images with the logo.png or screenshot.png in yoursite/themes/bartik/, remember you have to name them 'logo.png' or 'screenshot.png' exactly.

Not sure if this is what you want. Good luck.

---
Tags: theming
---


# Question
Title: Unserialize error in Drupal Commons 3 for unathenticated pages
I've having the darnedest time finding a solution to the following error that is seen on my login screen to Drupal Commons 3 running on Drupal 7.22.

**Notice: unserialize(): Error at offset 52 of 77 bytes in registration\_entity\_settings() (line 863 of /var/www/html/profiles/commons/modules/contrib/registration/registration.module).**

We are additionally using FBOauth. Outside of that this is a new install.

To try to disect the issue a bit more I added the following right above the `unserialize` call.

```
 859     if ($result) {
 860         print '<pre>';
 861         print_r($result);
 862         print '</pre>';
 863         $result['settings'] = unserialize($result['settings']);
 864     }
 865   }

```

This dumps what is in $result\['settings'\]. I thought perhaps a value was incorrectly serialized in the first place, but I cannot see what the issue might be. The output dump...

```
Array
(
    [entity_id] => 5
    [entity_type] => node
    [capacity] => 0
    [status] => 1
    [send_reminder] => 0
    [reminder_date] =>
    [reminder_template] =>
    [open] =>
    [close] =>
    [settings] => a:2:{s:12:"from_address";s:17:"admin@example.com";s:22:"multiple_slots";i:0;}
)

```

This error disappears once I'm logged in. This is a sandbox/development box.

# Answer
Since this was a development server, I just blew away the current install and database. This hasn't occurred since a reinstall of Commons 3.
> 0 votes

---
Tags: 7
---


# Question
Title: Rule to delete other node of same type before saving content
I have designed one content type which can be created by registered users via "Form Block" Module. I am now trying to create a rule which will allow each user to only have one existing node of that content type. If they decide to create a node of that content type again, the previous node should be deleted.

I'm having trouble with the rule that would accomplish this. There are no errors, but nothing appears to be being deleted.

**Event** =

```
Before saving content

```

**Conditions =**

```
Content is of type (Parameter: Content: [node], Content types: NeuroTrans pt1)

Data comparison (Parameter: Data to compare: [node:author:uid], Data value: [site:current-user:uid])

```

**Action** =

```
Delete entity (Parameter: Entity: [node])

```

Here's an export of the rule that I have created:

```
{ "rules_delete_previous_neuro_pt1" : {
"LABEL" : "Delete current user\u0027s previous NeuroTrans pt1",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_presave" ],
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "neurotrans_pt1" : "neurotrans_pt1" } }
    }
  },
  { "data_is" : { "data" : [ "node:author:uid" ], "value" : [ "site:current-user:uid" ] } }
],
"DO" : [ { "entity_delete" : { "data" : [ "node" ] } } ]

```

} }

\**Using the "code" entry mode for this post doesn't appear to preserve the formatting quite perfectly.

Any guidance would be much appreciated. Thanks!!

# Answer
> 1 votes
Daniel,

What I think is happening is that you're trying to delete the actual node that the user is about to save (it hasn't been saved yet)!

It doesn't look like you're finding the user's PREVIOUS node to delete first, you're just trying to work with the current one. :-)

Of course - since this current node hasn't even been saved yet (your event is prior to saving), there is nothing to be deleted.

The rule will have to be more complicated, with your finding an existing node by the current user first...

Hope this helps.

# Answer
> 1 votes
I have solved my problem. I found my answer in THIS HELPFUL VIDEO. In addition to what I described above, only two other components were required to be added to the "actions" section of my rule. The actions section should look like:

Actions:

**Fetch entity by property** : Parameter: Entity type: Node, Property: Content type, Value: \[node:type\] Provides variables: Fetched entity (entity\_fetched)

**Loop** : Parameter: List: \[entity-fetched\] List item: Current list item (list\_item)

--(added to loop)--**Delete entity** : Parameter: Entity: \[entity-fetched:0\]

---
Tags: rules
---