# Question
Title: Block visibility based on the content type
I have created a block for showing author details for every individual author; the article's authors can be identified by the 'Author' field. Now I want to match the author block with the particular author's content.

For example, I have an author called 'vividvilla', and I have created a block for 'vividvilla'. How do I show this block for articles where 'vividvilla' is the author?

I know it can be done with PHP code in blocks, but I am not sure about the code.

# Answer
> 8 votes
I would use the `menu_get_object()` function to determine whether or not the block visibility check is being executed on a full node page, then check the field value on the node from there.

**EDIT**

The other edits were getting a bit long so I've deleted them. I've just set up a site quickly to test this and the following steps have worked for me (this is Drupal 7):

* Created a content type called Author Profile (machine name `author_profile`)
* Added a node reference field from the Article content type to the Author Profile
* Created an Author Profile node with a title of "vividvilla"
* Created an Article node linked to the Author Profile node above
* Enabled the core PHP Filter module
* Created a block called Author Details with some dummy content in the body, choosing "Pages on which this PHP code returns TRUE (experts only)" for the block visibility settings.
* Entered the PHP code below

```
<?php

$node = menu_get_object();

// Check we're on a 'full' node page.
if ($node && isset($node->nid)) {
  // Check the node is of the right type
  if ($node->type != 'article') {
    return FALSE;
  }

  // Load the author node based on the node reference field value.
  $author_node = node_load($node->field_blog_authors[$node->language][0]['nid']);

  // Check the title of that node
  if ($author_node->title == 'vividvilla') {
    return TRUE;
  }
}

// Default is to not show the block
return FALSE;

?>

```

The block only shows on an article page that is linked to an Author Profile with the title of "vividvilla" which I'm pretty sure is what you're trying to.

On the off-chance you're using Drupal 6 just change the `$author_node =` line to:

```
$author_node = node_load($node->field_blog_authors[0]['nid']);

```

# Answer
> 7 votes
the most easy way to do it i think is using Views.

In views you can add conditions and get arguments from the url and you can easy set a condition to display the author when you are seeing a node who belongs this author

# Answer
> 7 votes
First of all, I would like to address

> I know it can be done with PHP code in blocks, but I am not sure about the code.

Please avoid inputting code through the UI in this fashion. Use of the eval() is a large source of problems, including security issues. Just see the big warning in php's own docs. I strongly suggest finding a different approach.

That said, this is easily done with Panels and the Page manager. Please note though, that using both Panels and the Page manager requires quite a bit of understanding for both of them. They are powerful tools, and as such a bit complex.

1. Install the Chaos tool suite (ctools) and Panels modules.
2. Enable the Page Manager and Panels.
3. Enable the node template
4. Create a variant of type "Panel", add to it a selection rule on the content type that has been authored.
5. Add a relationship of the type that corresponds to the link between the authored content, and it's author.
6. Place the authored content in one location, and the authors "content" in another.
7. Save

Page manager will now automatically derive the author from every displayed piece of content, and render what ever information you have on the authors where you place it.

Video series on using the two modules: Learn Page Manager!.

# Answer
> 6 votes
If each post has a Node Reference field pointing at the author, then create a View which displays the author for a particular post, by adding an argument to the view and selecting the author field as the argument.

Create a Block display for that View. Blocks don't have URLs, so can't directly get arguments, but the way around this is to click the argument in the display editing pane and specify an 'Action to take if argument is not present'. One option is 'Provide Default Argument', and you can select 'Node ID from URL'.

Then just arrange for the block to be included on the relevant pages - I tend to do this simply by URL.

This question is actually very similar:

How to show a view of content types on another content type

And my response there has a lot more detail!

# Answer
> 5 votes
If you insist in having blocks created with admin/structure/block/add (this means that you are using "semi-static" blocks), I would recommend do it this way:

1. install the block reference module http://drupal.org/project/blockreference
2. replace your author field with a block reference field on your content type
3. edit your node and select the correct block in you block reference field

Now you have 2 options to display the block:

1. use the field UI to configure and display the block in the node body;
2. use the field UI to hide the field in the body and then edit your template file and add the following code where you want your block to be displayed:

```
print theme('blockreference_item_simple', array('item' => field_get_items('node', $node, 'field_your-field-name-here', $node->language)));

```

# Answer
> 4 votes
You can do this without any custom code just using Taxonomy, and the Context module.

Create a taxonomy vocabulary called Authors for instance, and add a term to the list for each author.

For your author's field on the articles, set that as a Term Reference field, and input the appropriate author taxonomy term into there.

With the Context module, you can create a context which has a specific block (select the author's block) to be displayed only when a specific Taxonomy term is present for the currently active node.

# Answer
> 4 votes
I will not answer directly to your question since there are plenty of responses with custom code and various modules that you can use in order to achieve the functionality that you want.

My answer will focus on the method that you chose to use. From what I've read, your approach can be summarized as follows:

1) You have x authors in your website

2) You created x number of blocks (one for each author)

3) You are trying to "associate" each block with nodes, based on the author of the node. So, for example, the first block will only appear if the author is "John Doe", the second block ... , the x-th block will only appear if the author is "Jane Doe".

(please correct me if I'm wrong and you are not using the methodology that I described above)

In my opinion, there are some facts about this specific approach that you should know:

1. Conceptually, the custom blocks that you are creating share a lot of common "properties". For example, all blocks describe an author and present information about the specific author.
2. You may have only 5 (or 2, or 3) authors right now, but in the future more authors may be added. How will you add the extra authors? You will have to create new custom blocks, **copy and paste** the PHP code and change the information in the block to match the new author (an old programming teacher of mine used to say: when you are copying and pasting large chunks of your code, there is something wrong with your code). Not to mention that your blocks administration page will become a nightmare to manage.
3. Even if you are absolutely sure that you will not have to add more authors in the future, are you sure that you will not want to change the information in each block? For example, if you want to remove the "Occupation" field from the block and add an "IM" field, how will you do it? Go to every block, for every author and remove and add new fields.
4. When you'll need to change anything related to the blocks, how sure can you be that you'll remember how the PHP code works in each block?
5. What if you want to give someone else permission to change the author's information? Perhaps, the authors would like to add their own information (e.g. add their own bio). Will you give them access to a block with PHP code?

---

**\- My approach would be significantly different:**

1. New content type: Authors. You add fields that you want to display (like: picture, bio, email, website etc)
2. Create a new node for each author. Add the corresponding information for each author (or even give access to other users to do it).
3. Associate the "Author" field in your existing content type with the new content type ("Authors") using References if you are in Drupal 7 or Node Reference which is a part of the CCK if you are in Drupal 6.
4. Create a block via Views to display the information from the new content type's nodes.

P.S: I intentionally did not include the details on how to setup Views or the References module for 2 reasons: (a) I do not know which version of Drupal you are using and (b) I understand that the chances of changing your whole approach are slim. However, if you decide to follow my method, let me know and I'll edit my post to add some more details.

---
Tags: blocks
---


title: How do I apply a patch file?

text:
# Question
Title: How do I apply a patch file?
I downloaded a patch file from mailhandler module and need to apply the changes in order to fix the problem of pop3 accounts not deleting emails after download (import). How do I install it?

# Answer
> 21 votes
Here are a few links that may help you learn more about patching:

# Answer
> 7 votes
There's a description in every module under the tab version control. Scroll down to the title "Applying a patch" to find a description about applying patches with git.

---
Tags: version-control
---


# Question
Title: How to add text or description in a form without writing a module?
In my fictitious content type form, I have this select/radio question:
`"Do you want the pie ingredients?"
yes|Yes
no|No`

If the user selects "Yes", then a block of text needs to show up
`2 spoons of sugar
1 cup of milk
4 cups of flour
etc...`

How do I do this without writing a module? Why can't I create a custom field of type label/text? I am already using the conditional fields module so I can make the visibility/hidden fields happen, but it only applies to a field. Is there a way to inject/embed my text into the form?

As far as I know, there is no way to create custom text within a form unless I write my own module, which I would rather not do!

# Answer
You are on the right track:

1. Create a new field in your content type of type "`Long Text`", call it something like `Ingredients Text` ("`ingredients_text`") for the machine name -- the text that will be within this field can change per node as you like.
2. Then, go to your `Dependencies tab` in this content type.
3. Click "`Add new dependency`" and choose your newly created Textfield as the "`Dependent`". Choose your select / radio button as the "`Dependee`". (Leave the other two settings as is.)
4. Click "Add Dependency"
5. You are in a new screen, take the defaults
6. For Node View setting of the edit screen, try "`Hide the dependent if the dependee is not viewable by the user and the dependency is not triggered`".
7. Now when you the user is in the node, he can choose the radio button and the new text field will appear!

You will need to play with the settings but this does work, I just set this up on a site for a client. Note, the options in step 6 may vary depending on your particular setup.
> 2 votes

# Answer
I would create two fields on the content type: the "Do you want the pie ingredients?" boolean field and a field containing the block of text.

I'm assuming from the question the block of text is going to be the same each time, if so you can add the text as the field's default value. This has the added bonus of allowing the user to edit the text displayed if needed.
> 1 votes

# Answer
It's tricky, but it is possible to create a template for your content type's form. It should be using your actual `page.tpl.php` code.

ex : `page--node--add--contenttype`.

Then, you can add the desired elements and move them around/toggle them with jQuery. However, if your form is complex, you will need to control it's rendering instead of using only `render($page['content'])`.

This method does not involve any modules but you need to understand (or learn) how forms are rendered in templates.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Can you force users to put all new content in at least one Organic Group?
In Drupal 6, I would like to make sure users always add their Group content nodes to at least one Organic Group. I have a module that enforces a maximum number of groups, but I don't think it does a minimum.

The site is entirely groups-based and I don't really want people posting outside of a group.

I could certainly write a module for this if one does not exist, or it might be as simple as a form\_alter() function.

# Answer
> 1 votes
In admin/og/og search the "Audience required" setting, and change it from *optional* to *required*, if you don't need it for administer accounts also.

---
Tags: organic-groups, forms
---


title: Is PathAuto module a memory hog?

text:
# Question
Title: Is PathAuto module a memory hog?
I'm probably going to need to use the PathAuto module for a current project. While using it in development, as admin, the site slowdown during changes is insane.

Is PathAuto a big memory sink, and are there ways to mitigate this?

# Answer
It depends greatly on which version of Core you are using. The main memory issue is with Token module for Drupal 6, when given a node will generate all possible tokens for that node, regardless of the tokens that will actually be replaced. This means that expensive tokens that need to load or render other objects, etc, in addition with the sheer amount of tokens generated causes the issues.

With Drupal 7, the improved token API only generates tokens that you actually use and greatly improves performance and memory usage. In normal use, Pathauto really only matters when an item is being saved but does not affect "normal" page views.
> 18 votes

# Answer
One issue that we stumbled upon in Drupal 7 is when you have a many nodes which would get the same path alias. Because what then happens is that the first one gets $alias, the second one tries $alias, sees that this one is already reserved and uses $alias-1. The third one tries $alias, then $alias-1 and then uses $alias-2. And so on. That's not pathauto's problem, though and it's not really a bug as you should either clean up your crappy data (we had 600k imported print articles with hundreds of equal titles.. like "weather" ;)) or choose a better pattern for your alias (e.g, include the date). This can also seriously slow down a data import if you have pathauto enabled.

Another issue is that the token browser explodes if you have many fields which can completely break any page that lists a token browser, especially the pathauto config site which has multiple of those.

Apart from those related issues, I haven't seen any direct performance issues caused by Pathauto. If you think you do, what you really should do is profile your site with Xhprof to see what's actually using the cpu/memory.
> 9 votes

---
Tags: 7, path-aliases
---


title: Form Submit Issue

text:
# Question
Title: Form Submit Issue
Below is my form submit statement for my site. I know that the query works by it self however it does not seem to be setting the variable correctly. Does anybody see why this would not work, or am I going about this the wrong way? Basically my module uploads a file and then on submit this function query's the DB for the upload path and needs to set that value to be a drupal variable. Any Ideas?

```
function background_audio_form_submit($form, $form_state) {
$result = db_query("SELECT uri
                   FROM `file_managed`
                   WHERE `filemime` = 'audio/mpeg'
                   LIMIT 1");

return $result;

variable_set('background_audio_upload_path', $result-->uri);

}

```

# Answer
A couple of things:

* You're returning the `$result` variable from the function before calling `variable_set` so that bit of code will never run.
* You have a slight syntax error in your variable set code, `$result-->uri` (you should change it to: `$result->uri`)

This code should work:

```
function background_audio_form_submit($form, $form_state) {
  $result = db_query("SELECT uri
               FROM `file_managed`
               WHERE `filemime` = 'audio/mpeg'
               LIMIT 1");

  variable_set('background_audio_upload_path', $result->uri);
}

```

The return from a form submit function is never used in Drupal so there's no need to perform the `return` at all.

**EDIT**

Just one other thing, if you're uploading the file in a custom form using a `managed_file` element then you'll have the file ID of the uploaded file available in your submit function. You could then use `file_load()` to get the file object and URI without having to use a custom query. Assuming your element is defined as `$form['audio_file']` the following should work:

```
function background_audio_form_submit($form, $form_state) {
  $fid = $form_state['values']['audio_file'];

  $file = file_load($fid);

  variable_set('background_audio_upload_path', $file->uri);
}

```
> 2 votes

---
Tags: forms
---


# Question
Title: Make insert module add uploaded images to media library automatically
I'm trying to get adding images to work smoothly (more like how wordpress handles it) I have added WYSIWYG+CKeditor, Insert, Media, Resize Filter (which I can't yet get working).

Right now the main issue is I can insert things from the media library that are already there. But when I'm at the bottom of a post adding an image, I want all added images to go to the media library (especially to make cleaning up unused/replaced images easier for the content editor).

Is there a simple way to set up this behaviour?

# Answer
> 3 votes
Instead of using the Insert module, use the Media module's WYSIWYG integration. This adds a button to the WYSIWYG toolbar which allows you to choose an item from the Media library. You can also upload a new media item which adds it to the library and selects it to be inserted into the WYSIWYG editor. The link above explains how to set it up. Make sure you follow all the steps. You have to enabled this functionality in both the WYSIWYG profile and the text format to get it working properly.

Also, check out this great video on Media for some more information.

---
Tags: 7, wysiwyg, media
---


# Question
Title: Trigger an action at a specific time using Trigger and Rules
I would like to run an action once a specific `$_SESSION` variable is set. In both Trigger and Rules, I do not find a description on how to do something like that. Can anybody help me, or at least hint at a website explaining this?

I am looking for an easy way to initiate a call at a specific time (think of as a Drupal alarm clock); my idea was to put the time in a `$_SESSION` variable and fire the alarm clock once `$_SESSION['alarm'] == strtotime("now")`.

In case that this should just not be possible: I would also be happy with a trigger that fires whenever I go on a certain page.

# Answer
Why are you interested in the $\_SESSION variable? What is the bigger action you are trying to accomplish?

The easiest way to fire any event when a user visits a page in Drupal is too use hook\_menu and create a custom callback.

If you are trying to fire an action at a specific time you can setup a cron job to go off at the time you desire. Drupal 7 core has a built in cron mechanism you can tell to go off at certain time increments /admin/config/system/cron . If you don't have access to your server to setup a cron job and want it to go off at a specific time once a day (ala an alarm clock) you can use one of these modules Advanced Cron Modules

In order to respond to a cron job you can use hook\_cron or using a cron trigger at "/admin/structure/trigger/system"

---
> 1 votes

---
Tags: 7, rules
---


title: File Upload form issue

text:
# Question
Title: File Upload form issue
I have been working on this code and I am having some errors, and I was wondering if anybody can find errors in this code... I have posted my error below it...

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

$form['background_audio_file']['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('File'),
  '#description' => t('Allowed extensions: mp3'),
  '#upload_location' => 'public://MP3/',
  '#default_value' => variable_get('background_audio_file'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg mp3'),
  ),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save Changes'),
);

  return $form;
}

function background_audio_form_submit($form, $form_state) {

 // The file is automatically uploaded and saved in the default
 // validation process so you just need to load the file object at this point,
 // mark that you want to keep it, and save it again.
 // The file ID is contained in the $form_state['values'] array
 $file = file_load($form_state['values']['background_audio_file']);
 $file->status = FILE_STATUS_PERMANENT;
 file_save($file);

 $fid = $form_state['values']['background_audio_file'];

 $fileid = file_load($fid);

 variable_set('background_audio_upload_path', $fileid->uri);

}

```

> ```
> Notice: Undefined index: background_audio_file in background_audio_form_submit() (line 107 of /Users/jtharpe/Overflow_Dev/sites/all/modules/background_audio/background_audio.module).
> Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 178 of /Users/jtharpe/Overflow_Dev/includes/entity.inc).
> Notice: Undefined property: stdClass::$uri in file_save() (line 573 of /Users/jtharpe/Overflow_Dev/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] => 1329961119 ) in drupal_write_record() (line 6975 of /Users/jtharpe/Overflow_Dev/includes/common.inc).
>
> ```

# Answer
> 2 votes
In your `$form` FAPI usage you called the file key `file`, a child element of the parent container `background_audio_file`. In your `_submit()` function you are not looking for `file`.

Do a Devel `dpm($form_state['values'])` or a `print_r($form_state['values'])` and you will see the key `file` with your content. Besides that your code looks ok.

---
Tags: forms
---


# Question
Title: Holistic Design Critique for a Volunteer Matching Service
I'm a new Drupal developer, and I made an initial implementation of a project, but some of the things that I'm doing probably aren't the best solutions, so I was hoping to get some critiques of my design. What the site will do and how I'm doing it is below.

The motivation:

I'm making a volunteer matching service in Drupal 7. Specifically, community representatives from nonprofits can point our service to their issue tracker (ie, GitHub), we'll turn their issues into nodes, they can organize those nodes, and volunteers can sign up to work on some of those issues. Also, those volunteers will belong to an organization with a Corporate Social Responsibility (CSR) representative, and the CSR representative can administer their volunteers (email them, modify the tasks that they signed up for, etc).

The implementation:

Community managers are a user type. I use profiles2 and fields to give them an issue\_tracker\_url that they can store in their profile. I implement hook\_menu to add a link to their profile that they can click to grab issues from the issue tracker based on their specified issue\_tracker\_url. The function that pulls stuff down from the issue tracker is the callback in hook\_menu.

"Issue" is a custom node type that has some fields like the issue's id within the issue tracker so that we don't get duplicate nodes if the nonprofit pulls issues multiple times.

Each community manager can have several projects. Each project can have smaller sub-components. The issues from the issue trackers all belong to a given sub-component. The community manager should be able to manage which issues are in each component, which components are in each project, and which projects are in their organization. Allowing them to create nodes of each type and organize everything in a book would work, but it seems like a kludge. Taxonomies seem like they might be a more elegant solution, but I wasn't sure how to get one set up for what I'm looking for or how to let the community managers manage their own organization's taxonomy.

The volunteers also need to be able to view using this hierarchy. That is, they should be able to see a list of all organizations (all community managers). An organization page should have a list of all projects; a project page should have a list of all sub-components; a sub-component page should have a list of all issues pulled from the issue tracker that were organized into that component. I have tried using a view with filtering, but I haven't found a way to do that so that it will automatically generate pages based on the hierarchy described above.

I haven't yet figured out how to set it up such that the CSR representatives can manage volunteers from their company.

All of this should be easy to setup in case we want to have multiple instances of this service. Thus, the manual setup stuff involved in setting up the views and fields should be automated. Could I use the features module to automate this?

I have tried to do as much of this as possible using existing modules for the sake of maintainability, but if any of the functionality that I'm describing doesn't exist well in an existing module, I'm perfectly comfortable programming it myself.

Thanks for reading through my lengthy description and for your critique!

# Answer
This type of question is very difficult to respond to. It is very broad and potential responders do not know enough about the details to make sense of the best strategies to use in structuring it. I suggest that you continue expanding the story you have begun here including flow diagrams for how the user would enter, organize and use the information. Since Drupal is basically a big database management system, think about the database structure that would make sense to hold the information.

You will contain most information in content types with associated fields to categorize the content. Fields are often associated with taxonomies which add the benefit of creating organizational hierarchies. They provide a simple way for users to enter and categorize their information effectively and uniformly. You can also organize taxonomies into hierarchical menus (Taxonomy Menus) so they can quickly access information they require.

**Views** is basically a UI for SQL queries, so you will use that to retrieve and organize information to meet the users needs. For instance Views can be set to respond to taxonomy menus to arrange complex collections of content.

The easiest and most flexible way to arrange your information on a page is to use **Panels** and **Page Manager**(Ctools). They allow you to intercept any URL request and arrange the content in multiple ways depending upon the context at the time it is called. For instance, you can alter the content on a page and rearrange how it is displayed based upon the permission level of a user. By adding Panels Everywhere, I have managed to practically totally bypass the theming system and the complex styling spaghetti it can produce and simplify my style sheets and gain better control of what is displayed.

Features is a great module for exporting parts of a site to other sites. It is complicated and not perfect, so I would recommend getting one site solved first and deal with features later if you can.

I have had some problems with Profile2 and do not believe it is ready for prime time yet (it is a fairly new module). Most basic profile information can be easily handled by adding fields to the users entity.

Pathauto will allow you to create aliases for the URL which is very nice for creating user friendly URL descriptions, but bear in mind that views contextual filters do not work with aliases well and cause cause you grief.

You will continue to learn about and pick up on other modules that meet certain needs, but I recommend you start conservative and master the few I have bolded in this answer first. Each of these modules is complex and will require study to master. As you encounter specific questions as \k them and you will probably get more useful answers.

Good Luck.
> 0 votes

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


# Question
Title: Ensure a given module (set) is enabled on a dev site
Configuring dev-site specific settings is easy using the `$conf` array in `settings.php`

Sometimes I need to also disable (securepages) or enable (devel) certain modules on a dev site, but I don't know of an analogous method for doing this via `settings.php`

One hack which seems tempting is to define, say, `menu_init()` in settings.php (\*gasp), and make that function check that the required modules are enabled using module\_exists().

\[\* Yes, all manner of things might asplode if menu.module defined that function. OMG,ETC.\]

So I'm wondering if people have done similar things to make sure their dev site is correctly configured, and if so, what. Is this the Poor Dev's Pantheon?

# Answer
(It was me who wrote the instructions for the `hook_init()` hack at http://drupal.org/node/206368.)

Recent module-level ways of supporting this workflow are underway at the Environment module, and the Production check & Production monitor.

I feel they will rapidly become too bulky: Do you really need to enable a module to ensure another module is turned off? But, at least they may be able to provide a few conventions for us, like putting the list in local.settings.php or equivalent. I hide per-instance configs in in my site\_aliases.drushrc, which is my alternative to local.settings.php

I'm not going for another script you have to call, unless it's part of a fully automated workflow.
> 5 votes

---
Tags: 7, staging
---


# Question
Title: How to set Target points to the User group?
* There is a User Groups in our site (i used `og`)
* Point system for posting nodes (for this i used `userpoints,userpoints_contrib,userpoints_nc`)

Since its working fine, Now i need to set target points to the groups, so that the users of that particular groups needs to get the target points. They need to get the alert message like

> You have earned XX points, you need to get YY points to finish your target

How to do this? Is there any modules for this requirement? guide me...

# Answer
> 3 votes
You'll probably have to use the Rules module to make it happen.

Maybe create some kind of custom field (integer) to store the value of your target points value. ie. target points field = 100 points

Now, you can create a Rule to activate on the event "user awarded points", so that every time a user gets points, that rule is run.

Next, have that rule activate a different rule component, which is designed to compare the user's current points total with the value in the target points field. (So, every time somebody is awarded points, the system will check to see if they have met their target.)

You can set a condition such that, if the current point value is "less than" the target value, run an action "display a message" with some text saying you need XX more points till you finish your target.

(You may need an additional step to run a calculation on the points needed, but I think you get the idea of what you need to do with my example.)

---
Tags: 6, organic-groups, userpoints
---


title: Show drupal login on page load

text:
# Question
Title: Show drupal login on page load
I want to display the login form in a popup when a user is not logged in (meaning Anonymous).

I read this tutorial, but when I try nothing happens, so I think maybe it's because I am on Drupal 7? How is jQuery called in Drupal 7?

# Answer
It would be a good idea to see this podcast.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Add text after input field with form api (field-suffix)
I'm creating a form with a textfield. After the input field I'd like to have some text. Like this:

```
Label *
|________| some text
Field description

```

The code I use is:

```
$form['a_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('A Label'),
    '#size' => 10,
    '#maxlength' => 15,
    '#description' => t('A Field description'),
    '#required' => TRUE,
);

```

Is there a way do add "some text" after the input field in this way? Do I have do output the HTML code manually via #markup? Is there some way to do this via form alter? Or a theming function?

# Answer
You can use the `#field_suffix` property for exactly that:

> Text or code that is placed directly after a textfield. This can be used to add a unit to a textfield.

For example:

```
$form['a_textfield'] = array(
  '#type' => 'textfield',
  '#title' => t('A Label'),
  '#size' => 10,
  '#maxlength' => 15,
  '#description' => t('A Field description'),
  '#required' => TRUE,
  '#field_suffix' => 'Suffix'
);

```
> 22 votes

---
Tags: 7, forms
---


# Question
Title: Change the order of a sort criteria in views to a custom hierarchy
I have a content type called `Technique` that contains a title field, a description field, and a node reference called "belt level" referencing a content type called `Curriculum level`. The content in `Curriculum level` are as follows:

* Yellow belt
* Orange belt
* Blue belt
* Brown belt
* Red belt
* Black belt

I have created an Integer field in the `Curriculum level` content type called `level int`. I have set "yellow" to 1, "orange" to 2, "blue" to 3, "brown" to 4, "red" to 5, and "black" to 6. Now I have a view of `techniques`, in which I want the sort criteria to display results based on the `level int` field value of the content that the node reference field (called "belt level") in the technique was referencing. The problem I am running into is that I have no way of connecting the two. If I use the `belt level` field to try to set the sort criteria, I can only sort it alphabetically based on the title. How can I sort it based on the `level int` field instead?

# Answer
Add a relationship `Content: belt level` (or whatever your node reference field is called) to the view.

Then add a new sort, choose `Content: level int` (or whatever the integer field is called) and under 'relationship' choose the one you just added.

That should do it.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to get the user entered input value to do calculation?
I am developing bank loan application in drupal 7. In my first page there is a option to enter the `loan amount` then --\> `Search` the available loan. In a second page(form) i need to display the available `loan offers, interest, etc`... based on the **user entered value in page-1**. Now i need to get the user entered value on page-2 and have to check with DB(Database) and then needs to display the results. Help me to get out the solution.

# Answer
Store the loan amount in session when user submit the form1, and when rendering the form take that session value and display a suggestion field.

The code will be like below,

```
function form1_submit($form, &$form_state) {
  $_SESSION['loan_search_amount_field_value'] = $form_state['values']['loan_search_amount_field_name'];
}

function form2() {
  $form = array();
  $loan_amount = $_SESSION['loan_search_amount_field_value'];
  //db_query using $loan_amount
  //$db_result_array = db_query();
  $form['load_options'] = array(
    '#description' => t('Loan options'),
    '#type' => 'select',
    '#title' => t('Field type'),
    '#options' => $db_result_array,
    '#size' => 2,
  );
  return $form;
}

```
> 2 votes

---
Tags: 7, search
---


title: Add content to the front page in module

text:
# Question
Title: Add content to the front page in module
I made a module, that outputs the data when the user opens a page /courses

```
function courses_menu()
{
  $items['courses'] = array(
    'title'            => t('Courses'),
    'page callback'    => 'courses_output',
    'access arguments' => array('access content'),
  );
}

function courses_output()
{
  return "some HTML";
}

```

How can I add this data to the main page below the node contents?

# Answer
> 1 votes
I would either implement a block or if you are using panels create a content pane.

# Answer
> -1 votes
You could just add a call to your function in your page-front.tpl.php :

`print courses_output();`

It's not the standard way : you should use a preprocess function etc. but it's straightforward.

---
Tags: 7
---


title: Allowed Values in Drupal

text:
# Question
Title: Allowed Values in Drupal
I am using Drupal-6. I Created CCK Field with Select Box with content type name as list\_porducts.

i am fetching products from external url . Here is my code

```
$key=array();
$flowervalue=array();
for($i=2;$i<=150; $i++) {
        $url="http://testurl.com/test/node/".$i.".jsonp";
        $timeout=0;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $data = curl_exec($ch);
        $jdata=json_decode($data);

            if($jdata->type=='product') {
                $key[]=$jdata->nid;
                $flowervalue[]=$jdata->title." ".$jdata->field_petals_code[0]->value;

            }

}
$res=array_combine($key, $flowervalue);
return $res;

```

which is running properly. Now Problem is this is Quite slow. and i guess it is running for all page load.

Any Idea how to do this.

Thanks

# Answer
> 1 votes
Store the result into a session like below

```
function get_all_products() {
  $prod = get_products();
}

function get_products($reset = FALSE) {
  $res = $_SESSION['products'];
  if(empty($res) || $reset) {
    $key=array();
    $flowervalue=array();
    for($i=2;$i<=150; $i++) {
            $url="http://testurl.com/test/node/".$i.".jsonp";
            $timeout=0;
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $data = curl_exec($ch);
            $jdata=json_decode($data);

                if($jdata->type=='product') {
                    $key[]=$jdata->nid;
                    $flowervalue[]=$jdata->title." ".$jdata->field_petals_code[0]->value;

                }

    }
    $res=array_combine($key, $flowervalue);
    $_SESSION['products'] = $res;
  }
  return $res;
}

```

Else if you want cache the $url="http://testurl.com/test/node/".$i.".jsonp" enable the page caching in drupal.

---
Tags: 7, entities
---


# Question
Title: Is there a module/solution for allowing users to block each other on an SNS site?
Is there a module or solution that allows users to block each other on a social networking site? For example, if a user blocks another they will no longer see that user's profile or any content posted by that user.

I imagine one could do something like this with the flag module, but it seems like it might get extraordinarily complicated...

# Answer
> 0 votes
Take a look at the Ignore User module. From the project page:

> This module allows a user to "ignore" content from other users that they do not wish to view. Node and comment content from an ignored user is hidden from view on a page. A message is displayed above the hidden block of content with a link to the user's "ignore list" and a link to toggle display of the ignored user's block of content in that node or comment.

Not sure if it will handle blocking a profile view or not, but it should block content.

---
Tags: users
---


# Question
Title: Populating a node reference field using PHP in Rules
I have a rule which is triggered when a node is flagged. Currently, the rule loads some content (1) that has been referenced by a field on the flagged content. I have set the rule to create a new piece of content (2) and would like a node reference field on this new piece of content to reference content (1). I know there is a way to do this with PHP but am not sure of it...

Got one more...

I'm now trying to use rules to populate a select list field on a new piece of content. I need the value of the field to be the same as a piece of referenced content that's available to rules. Usually I would use tokens but as its a select list field there is nowhere for me to insert a token. I'm thinking some PHP would do the job, but I don't know where to start.

# Answer
> 2 votes
This should actually be pretty simple:

1. Create your rule for the event "A node has been flagged, under "NAME OF YOUR FLAG" and name your rule
2. Add an action of "Add new content" and click "Next"
3. Choose what you want the auto-created content's title to be (w/ or w/out tokens) and select what content type you want created and click "Save"
4. Add another action of "Populate a field", for the arguments configurations choose "new content type of CONTENT TYPE YOU CREATED" and for field, choose your node reference field and click "Continue"
5. Again on arguments change to "new content type of CONTENT TYPE YOU CREATED"
6. Open the fieldset titled: "Advanced: Specify the fields value with PHP code" and enter:

`return array(0 => array('nid' => $node->field_NAMEOFYOURFIELD[0]['nid']));`

**Note:** You can find the field names by going to admin/content/types and click "Manage Fields" on the content type you want OR you can do a `print_r($node);` on a node of that content type to see the node object structure

Now when you view your rule, you should see something like:

and whenever you use that flag, a new node will be created having the same reference as the node you flagged.

---
Tags: rules, nodes
---


title: User reference and Views 3 and Panels 3

text:
# Question
Title: User reference and Views 3 and Panels 3
i have the follow installation:

* Drupal 7.12
* Views 3
* Panels 3

I have an content type with the follow fields:

* User name (textfield)
* Job Function (textfield)
* User reference (Reference Field)

I filled the content type with: Username: Test Job function: CEO, user reference: demo

I have 3 users at mom, admin, demo and normal

What I'm trying to do is when I change the User reference field on this content type to other user like, admin or normal:

It will update on the views page or panels page the nodes that this user has created

I have setup a View and put on the Contextual Filters: Author ID and pressed Apply (all display)

Then I created a panel page and Add a Content, selected Views and selected this view I created, then I have an option there called Author ID, and a select list that has this field called User Reference, I selected it and update and saved the panel

But when I visit the panel page, it does not show anything

The question is how can I do this that I'm trying to do?

# Answer
There are several things you can do to make your site work with Drupal a little better.

First, it is a bit unclear how you are using your user reference field. When I add the labels Admin and normal it sounds a bit like you are duplicating The users functionality already built-in. Go to admin/people and look at the definition of roles and permissions. It will allow you to define categories of users and assign them access to specific categories of content and activities on the site.

Next. Define your view to achieve what you want, ignoring the panel. 'Taming the Beast' at nodeone.se demonstrates doing exactly what you are looking to do. I recommend watching the entire series to understand exactly how Views works. Note that applying contextual filters can be a little tricky. I recommend you do not use path aliases when using them.

Only after you have your view displaying should you add the additional complexity of placing it in a panel. Once again, nodeone has an excellent series for understanding how panels works. Panels works closely with Page Manager and the videos show them working together.
> 0 votes

---
Tags: users, panels, views
---


title: Drupal cross server workflow

text:
# Question
Title: Drupal cross server workflow
I have my test server installed locally with MAMP and so far everything is going fine but one concern I am having is how will I deploy my server remotely once I want to have a live server. Is there an easy workflow to export all your content, fields and views so that I can move them to a remote server using ftp maybe? How does this type of workflow normally work?

# Answer
> 13 votes
Here are some links to some articles which might be helpful. I've been compiling them myself, to help figure out how to tackle the same issue you're having.

**Exploring Deployment Methods**

**Moving Configuration out of the Database with Features**

**Using Git with Drupal** (http://github.com)

**Useful Contrib Modules**

# Answer
> 2 votes
To move exportable items I use the Features module. Drush is also very useful for dev to live migrations.

> **Features \- From Module Description**
>
> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.
>
> **Drush \- From Module Description**
>
> Drush is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt.

# Answer
> 1 votes
The links provided by @David Csonka are great! I would echo that the Drupal "problem" is making sure to draw the line between content and configuration for deployability (as Drupal by default puts configuration in the DB and the goal is to get config. into **version-able** files as best possible - use git!). Personally, this has been greatly helped by the features.module and accompanying modules that "export" their configuration so that features can read that configuration (some noteworth great examples are views.module and strongarm.module)

We currently live the "Dev-\>Stage-\>Prod" lifecycle at AllPlayers.com - we have talked about it at conferences: http://vimeo.com/33678298

I've also always liked the DevSeed explanation of the direction of features in general (as they're the originators of the module); particularly putting the site-builder in the mindset of building and reusing "packaged" "recipes" on the Drupal "framework".

---
Tags: workflows
---


# Question
Title: Upload a flash based banner as easy as image
Is there a way to add a field that can process a Flash file just like an image and print that file for what it is, just like an image, in a node or whatever?

# Answer
> 2 votes
Use the Media module for your requirement.

---
Tags: 7, forms, files
---


# Question
Title: What is causing this duplicated node issue?
I have the following error: When I create a new node from the new data of my external database (inserting a new row in the external database), the new node is duplicated (but it doesn't have type, language, user); this causes the following error:

> Invalid argument supplied for foreach() en /path/web/my\_proyect/sites/all/modules/cck/content.module on line 1284.

With my other module, I first extract all the rows of my external database, and convert them in nodes.

I don't know why; I debugged my code, but I don't understand that it is causing the problem.

This is the code of my module.

```
/* Implement of Hook_cron */
function node_db_extension_cron(){
  inspectAddHoteles();
  drupal_flush_all_caches();
}

function getHotelFromDrupal() {
  $type = '[my_type]';
  $query_nid = "SELECT count(nid) count FROM node WHERE type LIKE '%s'";
  $result_start = db_query($query_nid, $type);
  $cantidad = 0;

  while ($row = db_fetch_object($result_start)) {
      $cantidad = (int) ($row->count);
  }

  return $cantidad;
}

function getHotelFromExternal() {
  db_set_active('external');

  $result = db_query("SELECT count(id) count FROM [my_table]");
  $cantidad = 0;

  while ($row = db_fetch_object($result)) {
      $cantidad = (int) ($row->count);
  }

  db_set_active('default');

  return $cantidad;
}

function inspectAddHoteles() {
  global $user;

  $cantd_actual_hotel = getHotelFromDrupal();
  $cantd_final_hotel = getHotelFromExternal();

  /* With the count of nid of drupal and id of db external, i verify if exist new rows  because the count of nid of content and id of rows of my db externa should be equals if don't exists new rows on my db external */

  if ($cantd_actual_hotel < $cantd_final_hotel) {
    db_set_active('external');

    $cant_add = $cantd_final_hotel - $cantd_actual_hotel;
    $query = "SELECT * FROM [my_table] ORDER BY id DESC LIMIT %d";
    $additional = db_query($query, $cant_add);

    db_set_active('default');

    while ($row = db_fetch_object($additional)) {
      $node = new stdClass();
      $node->uid = $user->uid;
      $node->type = 'my_type';
      $node->title = $row->title;
      $node->body = $row->body;
      $node->created = time();
      $node->changed = $node->created;
      $node->promote = 0;
      $node->sticky = 0;
      $node->format = 2;
      $node->status = 1;
      $node->language = 'es';
      //All field of my content type

      $nodo_1 = node_submit($node);
      node_save($nodo_1);
    }
  }
}

```

# Answer
> 1 votes
The function `node_submit()` contains the `node_save()` function. So you call it twice.

---
Tags: nodes
---


# Question
Title: How do you change the css of node editing forms?
This ought to be really simple -- all I want to do is increase the font size of the textfields in the standard node editing form (node/123/edit). This should be a trivial tweak of a stylesheet, and I've just spent the last hour adding different bits of css to my standard theme style sheet, with no effect. Nothing is affecting the style of the fields and I can't even see (via browser Inspect Element) what stylesheet is setting the font size.

Has this changed in Drupal 7? I'm clearly missing something; can anyone offer advice?

# Answer
Arggh -- finally found it. I'm running a modified version version of Bartik for my site theme, and Seven came along as the admin/overlay theme. I can put changes into /themes/seven/style.css, and they work. It all makes sense now, I guess. Thanks for the pointers.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: Do contrib modules have to be set to expose settings variables to Strongarm?
I'd like to push everything into Features for the sake of versioning and migration of my site configuration.

Does a contrib module have to be purposefully set up to expose its configuration variables to Strongarm?

# Answer
Looking at strongarm\_vars\_load I can see that it loads all variables in the variables table using ctools\_export\_load\_object regardless of any special consideration (other than variables already controlled via strongarm in features).

When I've used it in the past I've never had to specifically define the variables for strongarm to use.
> 2 votes

---
Tags: 7
---


# Question
Title: Migrate user-data from a non-drupal site
I have to migrate 9000 users (name, address, email, tel, photo...) from a non-drupal-site into a new drupal7-site.

How can I programmatically mimic the registration process and push the data in corresponding fields? And is there a way to change the original password, stored as a MD5-hash, to the drupal7-format while processing the data?

Thanks!

# Answer
> 5 votes
Take a look at the Migrate module. From the project page:

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, and comments is included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using Drush commands.

# Answer
> 1 votes
I have used migrate the last 2 weeks, it's probably the most robust way to import lots of data and do data manipulation during import.

The problem is that it doesn't have a nice UI, you have to setup the migration in code. The included examples are great, but if you are not comfortable with PHP code you might want to try out feeds module instead.

# Answer
> 0 votes
If your data is in another MySQL table you can write a simple "SELECT" statement in MySQL Workbench like so:

```
SELECT
  a.`name` as `name`,
  a.`password` as `pass`,
  a.`email` as `mail`,
  .....
  1 as `status`,
FROM
  my_old_users_table a

```

The first value in the select is the field in your old table, and the value after the word "as" is the corresponding field in the drupal users table.

For default values, just select a literal value: `'default@email.com' as mail`

You then export that resultset as "SQL Insert statements" and then dump them into your users table.

I've never done this with Drupal tables before and I don't know the implications (effects on other tables), but I've done this previously to import masses of data from an ASP website into Wordpress posts table and it seems to work well.

Hope this helps, good luck

---
Tags: users, migrations
---


# Question
Title: How can I override with my module the existing commerce_file_field_access function?
I am trying to alter the way commerce\_file module shows the product file in the Product display. Actually it is shown to all users owning sort of administrative permissions (such as administer commerce\_file or administer commerce\_field type). Its format is:

label: file.pdf

This code is driven by the

```
commerce_file_field_access($op, $field, $entity_type, $entity = NULL, $account = NULL)

```

function in commerce\_file module itself, it seems.

I would like with my\_module to override this behavior to make the file visible to users that doesn't own those permissions but that have already bought the digital product and had license granted for that, but really don't know how to. (I already succeeded in disabling the add to chart button)

I am able to define if the user/buyer already bought it, but just cannot override the module access conditions to apply my rules. I already tried defining another function like `my_module_field_access()`, but it doesn't seem to work...

**How is it possible to override the** `hook_field_access()` **function already defined in commerce\_file module**?

As an alternative I was minding to replicate/copy that field and render it again without that access control, just in the defined conditions I define in my module. To do that I tried with a `my_module_preprocess_node()` function, but didn't succeeded. The new `$vars['elements']` is not rendered ...

I hope have been sufficiently clear. really any advice (on the best approach & way) would be very welcome. Wasted so many hours on this ... yet. Thanks so much

# Answer
> 1 votes
hook\_field\_access() implementations are invoked by field\_access() using the following code:

```
  foreach (module_implements('field_access') as $module) {
    $function = $module . '_field_access';
    $access = $function($op, $field, $entity_type, $entity, $account);
    if ($access === FALSE) {
      return FALSE;
    }
  }

```

The hook is not invoked for the module implementing that field, but for any module implementing the hook.

If you want to override what done by `commerce_file_field_access()`, you just implement `hook_field_access()` in your own module.
As `field_access()` immediately returns `FALSE` when a `hook_field_access()` implementation returns `FALSE`, you can only override what returned from `commerce_file_field_access()` if your hook is executed before `commerce_file_field_access()`. This means that your module, when it is installed, should alter the weight associated with it, and assign it a lower value than the value assigned to the Commerce File module. The following is an example of `hook_install()` implementation for achieving that; it is similar to the code executed in block\_install().

```
function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => -5))
    ->condition('name', 'mymodule')
    ->execute();
}

```

The same can be done in hook\_update\_N().

Any value lower than 5 actually works, as the Commerce File module uses the following code:

```
/**
 * Implements hook_install().
 */
function commerce_file_install() {
  // Make module weight heavier than field module
  db_query("UPDATE {system} SET weight = 5 WHERE name = 'commerce_file'");
}

```

The alternative of changing the weight of your module, which would influence when every hook in your module is executed, is to alter the order used for that specific hook implementations, using code similar to the following one.

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'field_access') {
    // Move mymodule_field_access() to the top of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}

```

---
Tags: hooks, commerce
---


# Question
Title: Linking content type nodes with each other
I have two content types that I want to link each other. I checked node references, but node references only allows me to link to others when creating a node of that content type. What If I wanted to link two nodes of content types that are already created?

Please let me know if it is possible in Drupal-6.

Thanks

# Answer
> 1 votes
You can actually "link" nodes at any time, you just have to *edit* the node to add the reference.

If you want to add multiple references, you have to specify this when you set up the node reference field in your content type. In the configuration page of the node reference field, choose how many references you want to allow (1-10, or unlimited).

For a user to add a reference that did not create the node, make sure the correct permissions are set in admin/user/permissions for the given user role. (ie "edit any EXAMPLE content")

---
Tags: 6, nodes
---


# Question
Title: What is causing the unusual output when trying to create charts in Drupal 7 using the pChart library?
I have been trying to display graphs to users in my Drupal 7 website, by using the PHP library pChart (which comes with a lot of documentation also). Using the libraries module, I have successfully enabled the pChart library.

Then I tried a basic example that came with the downloaded pChart library. Below is the code that I added in a node with the PHP filter enabled,

```
<?php
$name = "pChart2.1.3";
if ($path = libraries_get_path($name)) {
include($path.'/class/pData.class.php');
include($path.'/class/pDraw.class.php');
include($path.'/class/pImage.class.php');
}
/* Create your dataset object */
$myData = new pData();

/* Add data in your dataset */
$myData->addPoints(array(1,3,4,3,5));

/* Create a pChart object and associate your dataset */
$myPicture = new pImage(700,230,$myData);

/* Choose a nice font */
$myPicture->setFontProperties(array("FontName"=>$path.'/fonts/Forgotte.ttf',"FontSize"=>11));

/* Define the boundaries of the graph area */
$myPicture->setGraphArea(60,40,670,190);

/* Draw the scale, keep everything automatic */
$myPicture->drawScale();

/* Draw the scale, keep everything automatic */
$myPicture->drawSplineChart();

/* Render the picture (choose the best way) */
$myPicture->autoOutput("pictures/example.basic.png");
?>

```

However, with no errors, warnings or notices, I only get the below unusual output:

**My Question**: So what is this and what am I doing wrong?

# Answer
The output you are seeing is simply the PNG file that is being outputs it would be a text file. That is because Drupal already sets the "Content-type" header to "text/html; charset=utf-8," while the method you are calling is setting it to "image/png."

```
   function stroke($BrowserExpire=FALSE)
    {
     if ( $this->TransparentBackground ) {imagealphablending($this->Picture,false); imagesavealpha($this->Picture,true); }

     if ( $BrowserExpire )
      {
       header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
       header("Cache-Control: no-cache");
       header("Pragma: no-cache");
      }

     header('Content-type: image/png');
     imagepng($this->Picture);
    }

   /* Automatic output method based on the calling interface */
   function autoOutput($FileName="output.png")
    {
     if (php_sapi_name() == "cli")
      $this->Render($FileName);
     else
      $this->Stroke();
    }

```

What you could do is:

* Use pChart to create a file containing the chart you want to show
* Output a `<img>` tag that references the created file

If `imagepng()` used the PHP stream wrappers (which is true for file\_get\_contents()), the following code would work.

```
/* Render the picture (choose the best way) */
$uri = file_create_filename('example.basic.png', file_build_uri('pictures'));
$myPicture->Render($uri);
echo('<img src="' . file_create_url($uri) . '" />');

```

In this case, the code is slightly more complex.

```
/* Render the picture (choose the best way) */
$uri = file_create_filename('example.basic.png', file_build_uri('pictures'));
$instance = file_stream_wrapper_get_instance_by_uri($uri);
if ($filename = $instance->realpath()) {
  $myPicture->Render($filename);
  echo('<img src="' . file_create_url($uri) . '" />');
}

```

I wrote a conditional statement around `$filename = $instance->realpath()` because DrupalLocalStreamWrapper::getLocalPath(), the method called by DrupalLocalStreamWrapper::realpath(), can return `FALSE` when it cannot determinate the real path.

file\_create\_filename() is a function that returns a unique filename; in the case there is already a file with the name passed as argument, the function adds a number at the end of the filename, checking every time the file doesn't exist already. If "example.basic.png" is the name of an existing file, the function will try with "example.basic\_0.png"; if there is already a file using that filename, it will try with "example.basic\_1.png"; the loop is continued until the function find a filename that is not already used.

In the case you need to the filename to a function, as in this case, try first the `file_create_filename($filename, file_build_uri($directory))` approach, when you are not sure the function to which you are passing the filename is using PHP stream wrappers; only in the case it doesn't, you should use file\_stream\_wrapper\_get\_instance\_by\_uri() as in the second snippet.
> 2 votes

---
Tags: 7, charts
---


# Question
Title: Why are cck fields included in body when getting a node?
I have a content type that has several CCK fields: date, session number, session type, sold out, and homepage eligibility. The values of the fields are in no way stored in the body of the node as far as the database is concerned; here's the contents of the body field from one node in the node\_revisions table:

```
<p>The word “insight” is one of the most misunderstood and misused words in the marketing world today, but it is also one of the most important. As consumers become more fragmented and individualized, they will increasingly look for brands that represent some aspect of who they are. Brands will have to understand their target from an insights perspective. It will no longer be sufficient to settle for target generalizations.</p>
<p>In this seminar participants will take his/her knowledge and application of insights to an entirely new level. This seminar will teach attendees how to:</p>
<ul>
  <li>Identify real insights and distinguish them from generalizations, significantly improving the quality of an organization’s insights.</li>
  <li>“Craft” (rather than just articulate) an insight so it is evocative, breathing life into creative briefs/documents so they inspire.</li>
  <li><div>Connect a shopper insight to a corresponding consumer insight (insight connectivity): How does the life of the shopper outside of the store (the consumer’s life) effect what they do in the store (the shopper’s life)?</div></li>
</ul>

```

When I use the $content variable in a node template, though, the values of the CCK fields are printing as well. I did a `print_r($node)` to see what was happening, and this is what I get (some elements stripped out for brevity):

```
stdClass Object (
  [nid] => 383
  [status] => 1
  [created] => 1323794850
  [vid] => 383
  [title] => Advanced Consumer and Shopper Insights
  [body] =>

The word “insight” is one of the most misunderstood and misused words in the marketing world today, but it is also one of the most important. As consumers become more fragmented and individualized, they will increasingly look for brands that represent some aspect of who they are. Brands will have to understand their target from an insights perspective. It will no longer be sufficient to settle for target generalizations.

In this seminar participants will take his/her knowledge and application of insights to an entirely new level. This seminar will teach attendees how to:

    Identify real insights and distinguish them from generalizations, significantly improving the quality of an organization’s insights.
    “Craft” (rather than just articulate) an insight so it is evocative, breathing life into creative briefs/documents so they inspire.
    Connect a shopper insight to a corresponding consumer insight (insight connectivity): How does the life of the shopper outside of the store (the consumer’s life) effect what they do in the store (the shopper’s life)?

Date and Time:
April 16, 2012
Session Number:
S1
Session Type:
Advanced Learning Session
Sold Out:
Open
Homepage Eligibilty:
Yes)

```

The last chunk of the body element (starting with Date and Time) are all CCK field names and values. Why are they included as part of the body? And what can I do if I don't want them displaying?

# Answer
> 2 votes
CCK fields, by default, are rendered into `$content`. The order depends on their order on the **Manage Fields** tab.

To not do this, edit the content type, and goto the **Display Fields** (or goto /admin/content/node-type/my-content-type/display).

Then set the fields/labels as **Hidden** or **Excluded**. I am spacing on the exact difference (too long since I set this up in Drupal 6), but I normally just use **Hidden**.

---
Tags: 6, nodes, entities
---


title: Field inside of a Field

text:
# Question
Title: Field inside of a Field
I need to put a field (field\_names) inside of the body of the node.

I read that you could do something like:

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

```

The above code does not work for me, and just does nothing. Do I need to declare some variable beforehand, or do something else to make the field display? (yes I do have PHP enabled)

# Answer
What I suggest you do is use Token filter instead of depending on PHP in fields. Tokens look like \[node:field\_names\], and can help you achieve putting one field value inside another.

The php module depends on bad judgement for a reason, so I will skip trying to help you hurt yourself.
> 1 votes

---
Tags: entities, nodes
---


title: Create Relationship In Views

text:
# Question
Title: Create Relationship In Views
I have three content types that have a text field called PID. How do I tell views there is a relationship between these content types?

# Answer
Here are two ways to set up a relationship, depending upon how it is to be applied to content.

1. It is not clear how you are suing the PID field, so I will ignore it. You could create a field with a name like 'relate' and you could enter a term there that identifies a name for a relationship that various content types would share. You would then set up a **View** to filter for that field with the specific term you want and Views will retrieve all the content that shares that term. Further filtering could narrow the selection further if you desire.
2. You could use a module such as **Relation** to define a type of relationship and link pairs of content eg. a 'friends' relationship could be used to link two users in a specific type of relationship.
> 1 votes

---
Tags: views
---


# Question
Title: How to show a list of users based on taxonomy?
I want show a list of users by selecting taxonomy. and also I wanted to add taxonomy field in users profile/registration form and I did this with profile\_taxonomy module.

Suppose I have different taxonomy like "Technology","Eduaction","Stocks" then by clicking on any of this I want the list of users who had selected the same taxonomy. I can get the list by visiting user profile and then by clicking on taxonomy i can get the same list. but i want to make seperate page for it where the list of taxonomy vocabulary is shown. Please suggest solution. I am extremely new to Drupal and also I am not a PHP programmer. I am using Drupal 6

# Answer
> 1 votes
First a little clarification of term meanings. Taxonomy is a module that manages groups of terms gathered in Vocabularies. You have probably created a vocabulary with the terms you listed in it.

To make your list you will use Views. I am using D7 and V3, so I cannot give you a button by button instructions, but they are similar.

1. Add a new view.
2. Define the settings for fields and add a field for the User:name. To do this in D7 you must add a relationship to the content author to expose the User Name field. I don't think this is needed in D6.
3. Delete the node title field.
4. Set the path to a unique URL such as `Group-Type/%/users`.
5. Create an argument to filter the URL input '%' by a taxonomy term ID based upon the vocabulary you are using for the selection terms.

When you enter a URL such as Group-type/stocks/users, The view should be used to generate a list of Users with that term.

A cautionary thought: I have not used D6 version of Views so I don't know its idiosyncrasies. You may have to use the term id (tid) for 'stocks' since Drupal has changed a URL from an alias to a tid by the time the URL is passed to the argument section of the module.

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


title: Change menu item class attribute

text:
# Question
Title: Change menu item class attribute
How can one change drupal's default CSS classes? They are set in drupal's core and I don't find if there is any hook to change the #attribute entry of a menu item.

CSS classes are already set before the theme\_menu\_link hook call, the classes of defined in menu.inc. Is there a hook to alter these values ?

# Answer
> 2 votes
If you want to this by theming, try implementing `hook_preprocess_menu_link(&$variables)` in your theme's template.php.

```
function MY_THEME_NAME_preprocess_menu_link(&$variables) {
  // the class array is here
  $variables['element']['#attributes']['class'];
}

```

# Answer
> 4 votes
If it's just menu links you're after you can give Menu Attributes a whirl.

---
Tags: 7, theming
---


# Question
Title: CSS-tags added using Display suite on products disappears
Using Display Suite to format output of entity product from Drupal Commerce. HTML- and CSS-tags added by "Expert" formatting tend to disappear when products are viewed using display-nodes. In this case its a image-field with n-number of images that I'm trying to display in a horizontal row instead of stack them vertical. I'm using fancybox as display widget and want to change the behaivor with "float: left; position: relative;". Drupal 7.

The dialog for entering the extra tags are displayed both in product-type view and node-type view when administer fields. It does not matter if I do the formatting at product-type-level or node-type.

When adding the same formatting with a non commerce node-type it works as I suppose it should.

Are there a better way to accomplish horizontal rows with thumnails and displaying full size-pictures using fanzybox when presenting commerce products?

I have been using lightbox2, but it seems to be a bug when combining it with Drupal Commerce.

# Answer
I am not trying to do any grid nor gallery, but have had success with Colorbox. http://drupal.org/node/1230232 for info on enabling it.
> 0 votes

---
Tags: commerce
---


# Question
Title: What drupal function do I use to rename files when saving nodes programatically?
Normally when saving a node with the content type form, uploading a file will automatically rename it if the file name is already in the database.

I am creating nodes programatically. Everything works fine, except if the file name is in the database it fails as this is, of course, a unique field.

What function does Drupal use to check if the name already exists and chanages it accordingly? I could write one, but as drupal already seems to handle this perfectly, I dont see a reason to reinvent the wheel. Here is my code for the file saves.

```
$file = new stdClass();
$file->filename = basename($local_path);
$file->filepath = $local_path;
$file->uri = $local_path;
$file->filemime = $mime;
$file->filesize = filesize($local_path);

$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$images[] = array(
'fid' => $file->fid,
'alt' => $page_data['title'],
'title' => $page_data['title']
);

```

# Answer
> 3 votes
Drupal uses the `file_create_filename()` function to do that, you can call it like this:

```
$basename = drupal_basename($local_path);
$directory = drupal_dirname($local_path);
$local_path = file_create_filename($basename, $directory);

$file = new stdClass();
$file->filename = drupal_basename($local_path);
$file->filepath = $local_path;
// etc...

```

---
Tags: 7, nodes
---


# Question
Title: How to restrict JS applied to a block only to block visible pages?
I am using Drupal 6. I have added the javascript to my block using hook\_theme as shown below.

```
function theme_custom($text) {

        drupal_add_js(drupal_get_path('module', 'mymodule').'/sample.js');
        $output =  t($text);
        return $output;
}

```

I am using `$(document).ready(function() { ... });` in my sample.js. I want this js to be loaded only on the pages where the block is set to be visible, but drupal loads this js on all the pages. This makes my script to run on all the pages, increasing the load to the server on every page load. So, how to restrict this js to be loaded only where the block is visible? Any help is much appreciated.

# Answer
> 1 votes
Using hook\_block you can show the js wherever the block renders.

```
function hook_block($op = 'list', $delta = 0) {
   $block['content'] =
   switch($op){
     case 'view':
      switch ($delta) {
        case 'header_block'://block name
        //here you add that js
          drupal_add_js(drupal_get_path('module', 'mymodule').'/sample.js');
          $block['content'] = theme('header_theme');
          break;
      }
      break;
   }
}

```

# Answer
> 1 votes
If this apply css to individual blocks / nodes become a frequent requirment take a look at code per node, we have found it very useful for our knowledge system when we sometimes rely on custom code for advanced jquery data tables or charts etc.

---
Tags: 6, javascript
---


title: How do I use Webform fields in a view?

text:
# Question
Title: How do I use Webform fields in a view?
I use the Webform module to get user information, and I want to use some Webform fields in a view; for example, I want to show only some of the fields (e.g. name and e-mail), and expose a filter for the user's email.

How do I create it?

# Answer
From Webform vs. CCK (or D7 Field module):

> Webform submissions are not nodes. This means that you can't use Views with submissions, ...
> 2 votes

# Answer
You could use Webform MySQL Views.

> The Webform MySQL Views module builds flattened, read-only MySQL views of Webform submission data. These views may be useful when you need to access this data from an external application in an automated fashion without exporting, importing, or the use of a web-based API.
> 1 votes

# Answer
Submissions with Webform are not nodes; they are not nativly available to views. In order to do so you will need another contrib module. The best bet seems to be the data module right now. NodeOne released details on how you can get submission info in views in this blog post; however it is not very elegant.
> 1 votes

---
Tags: 6, views, webforms
---


# Question
Title: Flag the inappropriate content and not allowing people to add a content?
I have added a content type called "share", I have given the user permissions for this content type, meaning he can add the content and he can share to any one..

If any user feels that the content is inappropriate, he can flag the content accordingly. If a piece of content is flagged 3 times, the content is automatically unpublished.. I have done this using the Rules module...

But here what I want is if a user's content is unpublished as "inappropriate", the next time he should not be able to post any content but he can still access the site.

How can I accomplish this?

# Answer
> 3 votes
I would look into using rules again.

You are going to need a way of identifying users who should not be able to post. Set a rule to apply a flag to the users account once one of their nodes has been flagged 3 times.

Then use this flag in another rule as an IF to only apply it to said user, then maybe either redirect the users who access node/add pages to a page with a custom warning message or try another form of disabling the node creation. Please see below

> Event:
> Content going to be saved / Accessing a page
>
> Conditions:
> User is flagged with "suspended user"
>
> Actions:
> Page Redirect
> Show a message on the site

EDIT: Am I correct in assuming you are wanting users to flag a node inappropriate? You should be able to use something like the rule you have already created to do so, just also flag the node author when you flag the content...

---
Tags: 7, rules, flags
---


# Question
Title: Set another page.tpl.php if a parameter is set
i want to use another page.tpl.php file, if die fb parameter is set. The File is located in my theme folder and has the name "page-fb.tpl.php"

My Function in template.php

```
function THEMENAME_preprocess_page(&$vars) {
/** Facebook Output */
    if ( isset($_GET['fb']) && $_GET['fb'] == 1 ) {
        $vars['template_file'][] = 'page-fb';
    }
}

```

The function is called, but the new page-fb.tpl.php is not loaded. I'm doing all of this on Drupal 7.

Any advices?

# Answer
Rename `page-fb.tpl.php` to `page--fb.tpl.php` and then modify your code to use `$vars['theme_hook_suggestions'][] = 'page__fb';` instead of what you got currently. For further information you can check out the Drupal 7 Template Suggestions page.
> 2 votes

# Answer
Here you made a mistake!

```
$vars['template_file'][] = 'page-fb';

```

The above line should be like below.

```
$vars['template_files'][] = 'page-fb';

```
> 1 votes

---
Tags: theming, 7
---


# Question
Title: Is There a way to search non drupal solr index?
I have a huge solr index. I'd like to build my UI within a Drupal site. I tested the apachesolr module but it only focuses on a Drupal node. Does anyone have a similar project?

# Answer
> 2 votes
The Sarnia module is the only solution I'm aware of. It leverages the Search API, but unlike the other SOLR modules, it is designed to expose the content of any index rather than index Drupal content. It also has some pretty decent documentation, here.

However, I'm having trouble getting it to actually work properly. Latest dev version is not working for me, at least at the moment.

\[UPDATED\] Most of my troubles arose because my SOLR index does not use the standard handler names, and so some manual configuration was required (hacking service.inc). Once done, it certainly works, although it does not cope with grouping/collapsing results, and I'm not sure how to expose facets.

# Answer
> -1 votes
Check out search\_api. It allows you to use multiple search indexes (of which solr is one). In Drupal 7, you can search on any entity type (users, taxonomy terms, nodes, etc) and can even limit your search to particular node types. Used in conjunction with Facet API, you can create custom facets, too.

---
Tags: search
---


# Question
Title: Commerce programatically Create Order with Customer Profile
I am using this method to create order successfully, how do I add a customer profile with all the country/address etc to this order?

There does not seem to be any reference to customer profiles in commerce\_order\_save. I had a peek into the commerce\_order database table and it also must be hidden in data.

```
function create_order_with_products($product_ids, $uid) {
    $order = commerce_order_new($uid, 'pending');

    // Save the order so its ID is assigned.
    commerce_order_save($order);

    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

    //add products to order by ids array
    foreach ( $product_ids as $product_id ){
        $product = commerce_product_load($product_id);

        // Create a line item with quantity 1 and this product.
        $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

        // Save the line item to get its ID.
        commerce_line_item_save($line_item);

        // Add the line item to the order using the wrapper.
        $order_wrapper->commerce_line_items[] = $line_item;
    }

  // Save the order.
  commerce_order_save($order);

//somehow attach the profile to the order????
$profile = commerce_customer_profile_load(exampleID);

//How do I use this wrapper maybe?
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$wrapper->{????????} = $profile;

      return $order;
    }

  // Ensure the attached line items are associated with the order if they do not
  // have an order_id set yet.
  foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->order_id->value() == 0) {
      $line_item_wrapper->order_id = $order->order_id;
      $line_item_wrapper->save();
    }
  }

```

# Answer
After running a debug on the $order object in the commerce\_order.controller.inc save method it was simple to work out the right format for the data. But this is probably not best practice but is useful for generating a bunch of orders.

```
function create_order_with_products ( $product_ids , $uid, $profile_id ) {
    $order = commerce_order_new ( $uid , 'pending' );

    // Save the order so its ID is assigned.
    commerce_order_save ( $order );

    $order_wrapper = entity_metadata_wrapper ( 'commerce_order' , $order );

    //add products to order by ids array
    foreach ( $product_ids as $product_id ) {
        $product = commerce_product_load ( $product_id );

        // Create a line item with quantity 1 and this product.
        $line_item = commerce_product_line_item_new ( $product , 1 , $order->order_id );

        // Save the line item to get its ID.
        commerce_line_item_save ( $line_item );

        // Add the line item to the order using the wrapper.
        $order_wrapper->commerce_line_items[ ] = $line_item;
    }

    //create the right array for the save controller
    $profile_object = array (
        'und' => array ( array ( 'profile_id' => $profile_id , ) , ) , );

    $order->commerce_customer_billing = $profile_object;

    // Save the order.
    commerce_order_save ( $order );

    return $order;
}

```
> 4 votes

# Answer
I generally find if something isn't documented, the best way to work out how to do it is by looking at someone else's code! Here's how a customer profile is added to an order in the commerce\_customer module:

```
/**
 * Checkout pane callback: submits a customer profile edit form.
 */
function commerce_customer_profile_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  $profile = $form_state['values'][$checkout_pane['pane_id']]['customer_profile'];

  // Ensure the profile is active.
  $profile->status = TRUE;

  // Set the profile's uid if it's being created at this time.
  if (empty($profile->profile_id)) {
    $profile->uid = $order->uid;
  }

  // Notify field widgets.
  field_attach_submit('commerce_customer_profile', $profile, $form[$checkout_pane['pane_id']], $form_state);

  // Save the profile.
  commerce_customer_profile_save($profile);

  // Store the profile ID for the related field as specified on the settings form.
  $wrapper = entity_metadata_wrapper('commerce_order', $order);

  if ($field_name = variable_get('commerce_' . $checkout_pane['pane_id'] . '_field', '')) {
    $wrapper->{$field_name} = $profile;
  }
  else {
    // Or make the association in the order's data array if no field was found.
    $order->data['profiles'][$checkout_pane['pane_id']] = $profile->profile_id;
  }
}

```

That's assuming you have the order profile ready to go. I won't go on posting a load of code on how to do that, however you should be able to find an implementation somewhere.
> 0 votes

---
Tags: entities, commerce
---


# Question
Title: Custom page with panels in two languages
I created two pages with panels in Drupal 7; they have different names and different languages, but only one can be active as home page.

# Answer
> 2 votes
You can only have one page as the front page, which I assume is what you want. The way to do this, is using a "Selection rule" on language, and two variants, not two pages.

See Learn Page manager for a deeper introduction to Page manager.

---
Tags: panels, i18n-l10n
---


# Question
Title: How to use the gmap module withouth a API key?
I use gmap module to show maps in a website. This module require an API key from google maps. But today I found this page http://code.google.com/intl/es-ES/apis/maps/signup.html when I try to generate a new API key which says:

> The API keys generated by this page are no longer available.

**But the gmap module still require it:**

# Answer
> 4 votes
As suggested in the issue someone opened for the GMap project page, head to this page and follow the steps to obtain a key (Google account required).

---
Tags: google-maps
---


title: Create this type of view in drupal7

text:
# Question
Title: Create this type of view in drupal7
I am using latest drupal 7 and views. I have created a vocabulary and i have created terms under it. Each term has 2 levels sub terms under it. Using views i wanted to create a drop down of all the base level terms and when select the base level terms from drop down all the sub level terms must be listed .. is this possible in views??

# Answer
I'm waiting for this one, too. Conditional Fields module. But it's not yet available in D7.
> 1 votes

# Answer
You can try the Hierarchical Select module.

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

---
Tags: 7, views
---


# Question
Title: is there anything like $view_mode in user-profile.tpl.php
in node.tpl.php you have variable $view\_mode, is there anythings like that in user-profile.tpl.php? user is bundle like node, and you can define different view modes for it.

# Answer
> 1 votes
I don't believe there is. There *should* be, and if I had to guess I'd say there *will* be in D8. Large parts of the entity api simply didn't get implemented in D7, and nodes were probably just considered a higher priority.

I believe the Profile2 modules work by extending the user entity, it may provide you with what you want. Otherwise my suggestion is Panels, which can control the user view via something called "Selection rules", instead of view modes.

---
Tags: 7, theming, users
---


title: Views arguments from URL

text:
# Question
Title: Views arguments from URL
how to get the arguments from the URL and store it for further processing in views drupal 7.I am passing a token from a webform to a view through custom redirect URL.Later i need that value for some calculations.I need some help on how to do this.

# Answer
It depends on the environment you want to use your parameters into. If in code, URL arguments are always available through arg($x), with `$x` being the zero based position of the argument in the URL.

If the context is Views, then bobmct's answer seems relevant.
> 1 votes

# Answer
I've done this for Drupal 6.

In Views 2, I've had to define where in the URL the parameter(s) would be located positionally (e.g. blah/view\_name/%/%) where the % represent parameters 1 and 2 respectively; then, in my next view (which was either another display or attached view within the same view file) I defined the arguments in the argument section and then they could be referenced as %1, or %2 respectively.
> 1 votes

---
Tags: views, webforms
---


# Question
Title: Drupal 6 site not sending password reset emails
The password reset emails for a Drupal 6 site I'm working on aren't getting to our users' inboxes. The emails aren't being blocked by spam filters, and according to the site logs at admin/reports/dblog the emails are being sent. How can I go about debugging this?

# Answer
Are other kinds of mails correctly sent, or are ALL mails from the senong site discarded ?

If other mails are sent from the same server/site, then something's wrong with the Drupal installation.

If they're not and the sending server's logs are indicating a correct sending, then I'd check the destination server logs to see what's happening here. Sometimes mails got discarded for voodoo reasons, like blacklisting (which is not the same as spam detection) etc.
> 1 votes

---
Tags: users
---


# Question
Title: show images for taxonomy terms in referenced node
D7 question. I need to have a "clients" taxonomy with an image extra field on each term (the client's logo). Then I have a "project" content type. Projects belong to specific clients, ie the project content type has a term reference field to the client taxonomy.

When I click on a "project", I want to see the clients logo and not (only) the term name. This seems possible by following these instructions http://drupal.org/node/1224916, but this article is misleading: it suggests having an entity-reference field on the project content type instead of a term-reference. The problem with that approach is that when you connect a term and content by an entitity field, these two are not connected as far as taxonomy is concerned. So you lose all taxonomy functionality.

# Answer
> 1 votes
I beleive you can achieve this with the normal "Term reference" field, and a custom template file: `field--field_my_custom_field.tpl.php` in your theme folder which renders the image. You can access the value of your custom field through `$items[$key]['#options']['entity']->field_my_custom_field` where `$key` is the array index (if you have more than 1 value for this field, first item is index `0`, second is `1` etc, usually you should just loop through the $items like `foreach($items as $item)` and then you can do `$item['#options']['entity']->field_my_custom_field`)

You may need to have a `field.tpl.php` (copy from *root*/modules/field/theme then duplicate it and rename the duplicate into `field--field_my_custom_field.tpl.php`) in your theme folder in order for it to work (or templates folder inside your theme folder, basically same folder as your custom `field--field_my_custom_field.tpl.php`) (*Not 100% sure, but this was the case in Drupal 6*)

API documentation for field.tpl.php

This may also come in handy: taxonomy-term.tpl.php

Sorry for unsure answer with a lot of unknowns, just trying to help :)

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


title: Inserting Taxonomy Images into nodes

text:
# Question
Title: Inserting Taxonomy Images into nodes
In Drupal 7 i have added a new taxonomy vocabulary, then added a new field (image field) into this vocabulary and terms with image (logo). In the content type i've added a new field (term reference). But in the node i can see only title of the taxonomy term. How i can insert imagefield into the node from taxonomy terms?

# Answer
I've done something similar by using a template for the taxonomy term based on template suggestions. Personally I prefer writing theming functions though, and example for how to do this for a taxonomy field can be found in template.php of the default Bartik theme that comes with Drupal. Look for `bartik_field__taxonomy_term_reference` and here is the api documentation for theme\_field().

You will need to install the devel module, which will give you a dump of the node object when you are viewing a node.

You will need to either theme the entire node with specific care taken to render the taxonomy how you want from the node object, alternatively you could just theme the actual term reference field (What I first mentioned and the best way imo.) These are instructions on using the devel module.

With that you will be able to dump the array or object relating to the taxonomy term and then create a template or function theming the field to your liking, as far as I know all the information is available there it's just getting it out of the object/array can be time consuming when you are doing it for the first time.

Overall the Drupal Theming Guide covers the finer details in a lot more detail than what can be kept to a reasonable answer here.
> 1 votes

# Answer
Following this Is it posible to use custom formater to display custom field of taxonomy term helped me a lot
> 0 votes

---
Tags: 7, entities, taxonomy-terms
---


# Question
Title: Adding CCK fields to Simplenews email newsletter
I am designing a newsletter using Simplenews, however I need to add a couple of additional CCK fields to each node included in the newsletter. Seeing as the template file the email newsletter uses (simplenews-newsletter-body.tpl.php) simply uses a $body variable to output content, where would I instruct simplenews to add my additional CCK fields to each of the nodes I am sending?

# Answer
> 1 votes
Try this - it's pretty in deoth on what files and variables you can use with simplenews and cck in Drupal 6: http://drupal.org/node/268404

---
Tags: 6, entities, emails
---


title: Table form element

text:
# Question
Title: Table form element
Is there a way in the Form API to have a form element display in a table (think like a list of fees) where one of the rows value could be changed with AJAX from another form element?

For example, if the default 'Subscription fee' is $10, and I select a different 'Subscription Plan' method, when I click the option, how do I change that fee row to $20 or whatever the amount may be?

I am trying to utilize the #ajax framework as much as possible with the Form API but I am not seeing how this is easily achievable.

The way I have rendered the form is to assemble the header and rows, then output a form Item element with theme('table') as its #markup, but I am getting an HTML string instead of an actual data array to manipulate (which is its intent, but I need something to manipulate with JS/PHP).

# Answer
> 1 votes
You might want to take a look at this blog entry that reproduces exactly (what it sounds like) you are trying to do: http://www.computerminds.co.uk/articles/make-link-use-ajax-drupal-7-its-easy

If you post your code it would be easier to troubleshoot.

You might also want to take a look at the code from the ajax\_example module in the examples module.

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


# Question
Title: Is there a module that changes "node" links to "alias" links?
I use global redirect, pathauto and redirect modules.

Everything is fine, except one situation: I couldn't find the anwser, maybe it is very easy problem.. I can give links to nodes by using "link" "redirection" modules. I creating new field with the type of Link. When i select links from the lists, i can link to any node by using "fields".

But i want to give links to nodes in "body" of "node". When i write

```
<a href="/node/12">click here</a>

```

In node content, the links is written with "node" word. But i want to see this link in page with its alias, like this:

```
<a href="/content/aliasOfNode12">click here</a>

```

Is it possible? Thank you for help.

# Answer
The Freelinking module allows you to add tokens in text fields

Just install. The syntax is `[[nid:5]]` if you want an aliased link to node/5
> 2 votes

# Answer
Other than using a `process` to rewrite the URLs, I don't know how to fix this after the fact.

In the future, though, the Linkit module integrates with WYSIWYGs and use filters to add URLs, which then get properly updated to the alias.
> 3 votes

---
Tags: path-aliases
---