# Question
Title: Getting the entire index of nodes from REST API
I'm looking for a way to get **all** the nodes to be shown on my REST service. When I query the endpoint index `http://server/api/node` it only returns 20 results. Are there any additional parameters I can send along to unset this limit?

I would be really thankful for a quick answer. I have been spending a couple of days now to get the REST service in Drupal to work the way I need it to work.

P.S. I'm on Drupal 7

# Answer
> 7 votes
The index actually sends 20 results per page. I highly recommend you check out the ServicesResourceNodeTests.test file in the services module for a better explaination but basically you can pass the page number you want to get each page of results.

The test file shows how it checks to see if the next page is empty:

```
// The n+1 page should be empty.
    $responseArray = $this->servicesGet($this->endpoint->path . '/node', array('page' => $page_count + 1));
    $this->assertEqual(count($responseArray['body']), 0, t('The n+1 page is empty'));

```

Another (my preferred) option would be to use the Services Views module instead and that way you can get all the nodes in whatever format you wish!

---
Tags: nodes, services, 8
---


# Question
Title: Drupal 7 views - Contextual filter content: Nid content id from url
I am working on a portfolio website where there are a lot of projects on the website.

When you have a project node open I want a view next to it with all the thumbnails of other projects.

The problem is the following: When I have the view setting set to Contextual filter content: Nid content id from url I want the reverse effect to happen. Because now it only shows the same node.

Please forgive my bad english, I hope you can help me!

# Answer
> 15 votes
Let assume that you are using "Content: Nid" exposed filter.

Edit settings of your exposed filter and expand "More" section. If you choose "Exclude" check-box then it will show all nodes except current one.

Please see screenshot - how it used to be.

---
Tags: 7, nodes, views
---


# Question
Title: Drupal 7 Forum - Allow Users to 'hide' their online status
I am desperately trying to find a way for my users to 'hide' their online status from other users. Currently all users online are displayed in the drupal 'who's online' box.

Ideally I would look for a way to create a custom checkbox field (online\_status) and then find a way for the who's online block to check that.

Any ideas, modules or approaches anyone can recommend. My current thinking is to do it via Views and a custom block

thanks

# Answer
You can use hook\_block\_view\_alter to alter the content that is returned by who's online block. Ideally use the same logic that was implemented in user.module user\_block\_view function, delta **who's online** block but with extra validations.

Add a field called Show online status to User Profile. Let's say yes or no.

Read the above field value in the alter function for all users online and filter them before displaying.

Hope it solves !
> 1 votes

---
Tags: views, nodes
---


title: Panel Layout Designer

text:
# Question
Title: Panel Layout Designer
I came across this video showing how to setup custom home page using Panels. I installed the Chaos tool suite, and Panels modules, but I don't see the Layout designer interface anywhere as it is shown in the video.

# Answer
Have a look at Administer › Site building › Pages for the page you are wanting to design.

Click on the Content link in the left column and you should see a button for 'Show Layout Designer'.
> 2 votes

# Answer
I found it - well sort of. In my Main panel menu, once you have created a page and chosen custom layout,under the list of pages, there is a manga custom layout option. This takes you to a page that looks like the layout designer they were talking about.
> 2 votes

---
Tags: 7, panels
---


# Question
Title: Views field: how to add html 'title' attribute to link
In views fields like \[Content: Title\] and \[Content: Taxonomy\] there is the possibility to have the content displayed as link. Is it also possible to equip these link with a html 'title' attribute?

Alternatively, is it possible to equip *all* links on a drupal site with html 'title' attributes?

# Answer
This will add title attributes to most links, depends with some modules though.

```
/**
 * Add title attribute to any link that doesnt have a title already
 */
function YOURTHEME_preprocess_link(&$vars) {
    // If title set and not empty dont do anything
    if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
        return;
    }

    // Use the link text as the title
    $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}

```
> 3 votes

# Answer
There are multiple ways your issue can be addressed. Please find answers below that will resolve some of your questions.

* All Menu Links created using Drupal Core Menu Module i.e using User Interface

You can use Menu Attributes module to add title attribute.

* Links exposed in custom module

You can use l function to create a link with attributes.

* Views fields

You can use rewrite results option to rewrite content and add html as you like with attributes to a tag.

**UPDATED:**

Uncheck the setting in title field settings as shown below.
> 2 votes

---
Tags: views, navigation
---


# Question
Title: How to link to particular content type nodes via custom code
I have a content type called 'xyz'. Under that taxonomy select list that contain a,b,c. I am displaying taxonomy terms and I am able to display terms. I need to give link to content type nodes.here is my code. present it has linked to taxonomy/terms.

```
<li class='level".$level."'>".$bullet."<a href=\"$base_url/?q=taxonomy/term/".$value->tid."/pid/".$pid."\"> $value->name </a></li>

```

# Answer
> 0 votes
Create a view. Add a filter for content type. Then give that page url.

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


# Question
Title: Show forbidden content to non-authorized users when viewed in a Panel(-s Node/-ized Node), not when otherwise?
I'm using Panels Nodes (Similar functionality to Panelized nodes, if you're more familiar with that) to display a bunch of content from sundry content types -- for instance, I have a content type called Front Page Slideshow, within which each node is a slide that is placed as a piece of Panels content (For simplicity sake, let's just call it a Pane) on the front page.

However, I don't want each individual slide node showing up in either internal or external search results, so I've used Content Access to prevent access to the individual nodes comprising the front page panes but allow access to the Panels Node content type.

Alas, doing this hides all of the panes inside of the Panels as well.

**How would one prevent access to specific content types *only* when they're being viewed individually and *not* when they're being viewed via a Panel, `in a way that also hides them from search results?`**

*N.B. I'm talking about types of nodes that can be created with individual Panels configurations -- **NOT** Panels pages. So, I don't have access to things like contexts and selection rules and whathaveyou.*

Thanks!

# Answer
> 1 votes
I do two things.

1. I install Rabbit Hole, and configure those nodes/content types to be inaccessible.
2. I install Custom Search, and configure it to exclude those content types from search results.

IIRC, there is an issue open for Rabbit Hole about excluding nodes/types from search, but I don't think there has been any progress or real discussion on it.

Also take a look at Don't index certain content types for another approach for handling the search results.

---
Tags: panels, nodes, users
---


# Question
Title: Is it a bad idea for a view to specify nodes by node id?
I'm inheriting a project which contains a view that specifies what to include by *node id*. This initially strikes me as a terrible idea, but it could be that in Drupal it's not as brittle as it would be if done in other frameworks that I'm more familiar with.

Is this considered an acceptable practice within the Drupal community? If so, why is this not as dangerous as it sounds to me?

# Answer
It really depends what the View is for to be honest.

Is the node ID ever likely to change? Is it something that can't be done with entity view modes instead?

I've had a couple of occasions where I'm filtering a View on a specific node ID, but it's mainly because it's a use case that doesn't really require the massive overhead of something like Display Suite (and I don't use Panels - for no other reason that I don't really like the markup it produces).

If the node ID is GUARANTEED to stay the same, then it might not be disastrous. However if the node ID is ever likely to change (through content migration for example) then it WILL break. It also means that the client won't be able to fix it themselves unless you show them how to use Views and give them access to the Views UI.
> 1 votes

---
Tags: views
---


# Question
Title: Form API: Persistent values across submits?
Getting started with the form API. None of the examples seem to keep and redisplay the values the user entered. E.g., you have a "name" field. User enters "John" and hits Submit.

If the form data is invalidated for some reason, the name field should still show "John" so he doesn't have to enter it again. Is there a setting to set for persistent values? values vs. default\_values?

Drupal 7 stock install

# Answer
> 1 votes
In the Form API, there are two separate value setters `#default_value` and `#value` where these two make different things happen when you using it
\- `#default_value` set the value of your element when the form is created the first time, and if your form has an error for some reason, does not affect your element
\- `#value` set element value every time the form is rendered, even when the form is created again because of some error

It is not correct to use `#value` for textfields and other input elements, use `#default_value` instead. `#value` is meant only for buttons, submits and other non input elements.
if you use `$form['#value'] = 'Name'` for input elements like textfield the value of that field always would be `Name` even if the user entered some other value for this field.

see Form API Reference

---
Tags: forms
---


# Question
Title: Is there a way to track or record users entered taxonomy?
Is there a way to track, flag, or record a users entered taxonomy even if perhaps they may have changed it (tagging). So basically I am trying to set up a list of all the taxonomy tags a user created. The thing these tags can be changed and manipulated by the user so I am wondering if the originals can still be added to my list after they may have changed to a new tag. For example, a user recording places of employment.

# Answer
> 1 votes
You may want to take a look at the Community Tags project. We have used it on a few sites. From the project page:

> The Module has three main features:
> 1. Stores who tagged what and when.
> 2. Allows for this information to be exposed with views.
> 3. Adds an easy AJAX interface for tagging nodes without going to node/edit.

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


# Question
Title: DBTNG Migrate: SQLite -> PostgreSQL fails because of custom fields
I am trying to migrate a website from a development setup that uses SQLite as a database backend to a production environment, where PostgreSQL is used as a DBMS.

My research so far has led me to the DBTNG Migrator Module, that promises to migrate a Drupal site to/from any database system the abstraction layer supports.

This is the database configuration in my `settings.php`:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal',
      'username' => 'db_user',
      'password' => 'db_pass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'pgsql',
      'prefix' => '',
    ),
  ),
);

$databases['sqlite']['default'] = array (
  'database' => 'sites/default/files/site.ht.sqlite',
  'driver' => 'sqlite',
  'prefix' => '',
);

```

Both databases are correctly being displayed in the DTNG Migration UI. However, when I run a Migration check for SQLite -\> PostgreSQL, I get the following error message:

`field_data_field_custom does not existing in default`

`field_custom` is a custom field I defined in the development site.

Is there way to migrate my complete drupal setup, including custom fields and content types to PostgreSQL, using DBTNG Migrator?

# Answer
To answer my own question:

The migration should be run on an empty database. This way, everything gets replicated successfully.
> 2 votes

---
Tags: migrations, database
---


# Question
Title: How to post to remote url on form submit
We want to silently submit a Drupal6 form to a marketing partner, and redirect the user to page on our site. Is this the correct syntax?

```
function my_form_submit($form, &$form_state) {
  $form_state['action'] = url('http://example.com/?method=cSurveyWebservice.submit&mode=test');
  $form_state['redirect'] = array('campaign/thank-you');
}

```

Certainly it processes and redirects, although I'm not sure how to independently validate if the form is actually posted to the specified URL.

# Answer
You can try something like this

```
$request_url = 'http://your-url.com';
$request_headers = array('Content-Type' => 'application/x-www-form-urlencoded');
$request_method = 'POST';
$request_retry = 2;
// form values you want to post
$form_values= array('apple' => 'red', 'banana' => 'yellow', 'pear' => 'green');
$data = http_build_query($fruits, '', '&');

// Send the request.
$response = drupal_http_request($request_url, $request_headers, $request_method, $data, $request_retry);

if ($response->code == 200) {
  $form_state['redirect'] = array('campaign/thank-you');
}
else {
drupal_set_message(t('There was a problem with your submission. Please try again later.'), 'error');
}

```

I haven't tried it but let me know if it works.
> 2 votes

---
Tags: forms
---


# Question
Title: Change the index structure of fields in a table in database? Wise thing to do?
I'm on Drupal 7. The table index structure of `users` table is shown in the fig below:

As pointed out the table has two unique keys `uid`(also primary) and `name` which is the username of the user of the site. The username is displayed on the top of the user's profile.

* I want the `mail` column to be unique, and make it non-nullable.
* and remove the unique characteristics of `name`;

Because username can be same (my use case) and e-mail id shouldn't repeat.
Is it safe to make the change? If not what precautions do I need to take?

# Answer
> 2 votes
If you are even thinking about doing this I have two big key phrases

* BACKUPS
* DEV SERVER

Here is what you should do

* Install MySQL on a DevServer
* mysqldump the database and load it on the DevServer
* Point your Drupal App at the DevServer and bang on it, and kick the tires

Once you got a good dev environment, now do this on the DevServer

```
SELECT mail,COUNT(1) MailCount FROM users
GROUP BY mail HAVING COUNT(1) > 1;

```

If you get any rows coming back, there are multiple users using the same `mail` value

If nothing comes back, you can proceed as follows:

```
CREATE TABLE users_new LIKE users;
ALTER TABLE users_new DROP INDEX `name`;
ALTER TABLE users_new DROP INDEX `mail`;
ALTER TABLE users_new ADD INDEX `name`;
ALTER TABLE users_new ADD UNIQUE INDEX `mail`;
INSERT INTO users_new SELECT * FROM users;
SELECT COUNT(1) UsersCount FROM users;
SELECT COUNT(1) UsersNewCount FROM users_new;

```

If `UsersCount` = `UsersNewCount`, CONGRATULATIONS, you can continue.

```
ALTER TABLE users RENAME users_old;
ALTER TABLE users_new RENAME users;

```

You drop `users_old` if you are sure you no longer need.

Give it a Try !!!

---
Tags: 7, database
---


# Question
Title: Problem with node revisions and taxonomy terms
I have a content type with a number of fields including a checkbox which allows you to select one or more taxonomy terms. If I create a new version of a node, all the previous taxonomy terms are automatically included in the new node version. I can see this in the database table "field\_revision\_field\_catagories" (catagories is my checkbox field).

If I update the checkbox field with fewer terms checked, Drupal will not remove the existing ones. For example:

Node Version 1 has taxonomy terms 1,3,5 7 checked and 4 corresponding records in the database table.

* I use node\_load() to get Version one from the database.
* I update the node using a Form API form and change the checkbox to select 2 (uncheck 1,3,5,7)
* save the node with node\_save().

The database now has Version 2 with taxonomy records 2,3,5,7. It updated the first record, changing it from 1 to 2. The other 3 records are still there, however and need to be removed for my logic to work.

I guess I can use SQL to delete the records (or just delete them all after node\_load()), but will that create other problems? Is there a Drupal function I can use instead of SQL?

Thanks.

# Answer
> 1 votes
I figured it out. unset() is the answer. Here is my code:

```
        $loop = 0;

    $termarr = $form_state['values']['catagories'];
    // drupal_set_message('Termarray '. print_r($termarr,1) .'');
    foreach ($termarr as $term) {
      if ($term > 0) {
        $node->field_catagories['und'][$loop] = array('tid' => $term);
      } else {
        unset($node->field_catagories['und'][$loop]);
      }
      $loop++;
    }

```

This took way longer than it should have. I wish Drupal had better documentation although trial and error for days does have some benefits... :-(

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


title: how to get the web form results

text:
# Question
Title: how to get the web form results
I need to get the results of the web form as a block to display with the webform.

It seems views has no way.

# Answer
I have been able to get Webform information into Views in the past, but I ended up delving into the database to do so since the integration of Webform and Views is limited to submission ids and edit links, not the specific data that was entered by the user.

I found this tutorial online that might be useful for you. http://archive.org/details/DisplayWebformSubmissionDataInViews
> 2 votes

---
Tags: webforms
---


title: Multilingual "labels" in views fields?

text:
# Question
Title: Multilingual "labels" in views fields?
Is there any way to setup multilingual labels in views' fields.

Let´s say I have the ´title´ field and it shows the label ´My Title:´. Then as my site is bilingual (english-spanish) I need to have that label to ´Mi Titulo´ depending on user language.

How can I solve this? Any module to expand views module?

# Answer
You want to look into Internationalization Views, which allows you to translate labels and such in a view.
> 3 votes

# Answer
All the standard module care about printing title, labels and string and keep them translatable using `t()`.

I think Translation Interface (example.com/admin/build/translate/search) can help you to search strings and define their translations.
> 0 votes

# Answer
If I understand you correctly, what you want is done by the Field Translation module, which is part of the Internationalization (i18n) package. Once enabled, there will be a translate tab when you edit a field (from *manage fields*). You will also have to enable more languages, so they are offered as translation targets.
> 0 votes

# Answer
I used this method which is probably bad practice, but I couldn't find another solution.

With your file manager/FTP go to core language file: Example is for the installed German language \[mysite\]\profiles\standard\translations\drupal-7.0.de.po

Open in a utf-8 reader. You will be able to see a list of all English strings and their German counterparts: Example msgid "Countries" msgstr "Lände"

Add your labels (strings) and their translations and save. \[-all good but this library must now be reread in-\]

Using your web interface go to www.mysite.com/admin/config/regional/language Delete the language you are editing. This will clear the DB of the translations but the edited file will remain untouched. Now select "Add Language" and select your language again. The system will now read-in your updated list.
> -1 votes

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


# Question
Title: Does DRUPAL_CACHE_PER_PAGE count pager pages (i.e. frontpage?page=3)?
I guess my whole question is pretty much in the title... I'm wondering if blocks that use DRUPAL\_CACHE\_PER\_PAGE get cached on pager pages (i.e. mysite.com/frontpage?page=3), or if the pager query is disregarded (so the block would only be cached once for frontpage, frontpage?page=2, frontpage?page=3, etc.)?

# Answer
Yes.

See `drupal_page_get_cache()` in bootstrap.inc:

```
if (drupal_page_is_cacheable()) {
  $cache = cache_get($base_root . request_uri(), 'cache_page');
  if ($cache !== FALSE) {
    $cache_hit = TRUE;
  }
  return $cache;
}

```

`request_uri()` returns the whole path including any GET arguments.
> 5 votes

---
Tags: 7, blocks, caching, paging
---


# Question
Title: Show 'log in' in user menu when not logged in
I'm asking myself, where is the code that hides "My account" & "Log out" in the user menu? Just curious, to learn from that code. Any way to know where to search if you want to know something like this?

I added a "Log in" link to this menu, and I want to hide this when nobody is logged in.

# Answer
When you have something that happens with a link, you need to look in the code for a `hook_menu()`. Then you need to guess which module it is in. In this case, take a look at core User module:

```
function user_menu() {
  $items['user/login'] = array(
    'title' => 'Log in',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

```

Note the `'access callback' => 'user_is_anonymous',` line. This means that you can only do this if you are anonymous (ie, not logged in). This means that you should just be able to make a menu entry with "user/login" as the path, and the link will only show when you are logged out.
> 13 votes

# Answer
You can add a menu link to `user/login`, the access callback of that verifies that it is only shown to anonymous users. Just like `user/logout` is only visible for logged in users.

The definition of these callbacks() are, as mentioned in the other answer, in `user_menu()`
> 16 votes

# Answer
Check the menu definitions in `user_menu()` in user module. The access callback determine, when will the menu item be shown.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How do I assign a role to a user after the user's email is confirmed?
I want to assign a role to a user after the user confirms his/her email.

How do I do this?

# Answer
You'll want to take a look at Rules and LoginToboggan (as per this answer on Drupal Answers).

Rules will allow you to add a "trigger", such as adding a role to a user, and LoginToboggan will provide the "trigger" for when the account is validated.
> 2 votes

# Answer
You can use `hook_user_login(&$edit, $account)` which is called from `user_login_finalize()`.

When $edit parameter is empty is because is called from `user_pass_reset()` menu callback:

```
// user_login_finalize() also updates the login timestamp of the
// user, which invalidates further use of the one-time login link.
user_login_finalize();

```

This example should work:

```
function MYMODULE_user_login(&$edit, $account) {
  if (empty($edit)) {
    // @todo Add role to $account->roles array
  }
}

```
> 0 votes

---
Tags: hooks, emails, users, tokens
---


# Question
Title: How to show message to user when page is in a filtered state?
I have a view with a few exposed filters and it uses ajax. It is set to remember their last selection. Is there any way to ensure that the user is aware the the view still has applied filters? (i.e. Some users may not be ware that the list is still filtered and they need to hit the reset button).

Edit

To further clarify:

The issue is that if the user is not aware that the list is in a filtered state that they should reset it before starting another drill down

Basically I need it to say "Hey you! this list is in a filtered state. You need to hit the reset button before doing another search!"

# Answer
> 3 votes
In views, to remember the user entry, Views uses sessions. It uses different variables for each view. If you print the $\_SESSION variable you can see that.

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-test-page'){ //your exposed form's id

      print_r($_SESSION);
   }
}

```

Now you can see that a structure like below

```
[views] => Array
    (
        [test] => Array
            (
                [default] => Array
                    (
                        [title] => Page
                    )

            )

    )

```

So if you check value exists for this variable, you can perform your task

ie:

```
if ($form['#id'] == 'views-exposed-form-test-page'){
//check is it exists, if so perform your task
 if($_SESSION['views']['test']['default']['title'] != ''){
    // "need to reset";
          //here using jquery or css, show or hide your message
        $script="(function ($) {
                //action to do here
        })(jQuery);";
        drupal_add_js($script,'inline');
 }
}

```

Hope this may helps you

# Answer
> 1 votes
Install Better Exposed Filters and you will have an option in the exposed filters settings to include a reset button (make sure you choose "Better Exposed Filters" in "Exposed form style" first).

# Answer
> 0 votes
This can be acheived by jquery.For example take test case with admin/content/node page.

```
$(document).ready(function(){
  if($('#node-admin-filter #edit-reset').length){
    alert("Hey you! this list is in a filtered state. You need to hit the reset button
 before doing another search!");
  }
});

```

Try this code using firefox console. In your case replace #node-admin-filter with a parent div specific to filter div.

# Answer
> 0 votes
I have used this solution in Drupal 6. It should work in D7:

```
/**
 * Implementation of hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'my-view') {
    // Check view URL arguments or exposed filters
    if (count($view->args) > 0 || count($view->exposed_input) > 0) {
      if ($view->total_rows) {
        drupal_set_message("Hey you! this list is in a filtered state.", 'status');
      }
    }
  }
}

```

---
Tags: 7, views
---


# Question
Title: Store value in file entity field using a form
Apologies in advance, this question probably has an obvious answer.

I am using a custom form with a 'managed\_file' widget named 'image' to upload image files to the public file directory:

```
$image = file_load($form_state['values']['image']);
$image->status = FILE_STATUS_PERMANENT;
file_save($image);
```

I am using File Entity Module to attach to image file entities a caption text field (the machine readable name is 'field\_caption'). On the custom file upload form there is a 'textfield' widget named 'caption' whose submitted value I want to store as the value of the image file entity's 'field\_caption'.

Certainly, Drupal needs to first realize that the uploaded file is in fact an *image* file, as other file entites might not have attached a caption text field. That's why in the code above I first save the file before the code is followed by

```
if (isset($form_state['values']['caption'])) {
$caption = $form_state['values']['caption'];
$image->field_caption[0]['value'] = $caption;
}
file_save($image);
```

However, after submission the caption text field is always left empty.

Did I choose the wrong commands to store a value in field\_caption?

# Answer
I posted this on drupal.org (https://drupal.org/node/1820706) and got an answer that works. I have to replace

```
$image->field_caption[0]['value'] = $caption;
```
with
```
$image->field_caption[LANGUAGE_NONE][0]['value'] = $caption;
```
> 0 votes

---
Tags: forms, files
---


# Question
Title: Group context on pages generated by views
I have two group page

node/%/posts and node/%/activity.

Inside these pages, I have a mini panel which requires group context to display. For some reason, the pages generated by views are not recognized as group context though its a menu tab inside the group. Did anyone had the same issue ?

# Answer
> 0 votes
This has been an issue on the Organics Groups page. Please refer to comment #6 for the solution.

The other way to work around this is to Use page manager to create pages instead of using views. Page manager helps to maintain the context of the group across its pages.

---
Tags: views, organic-groups, 7
---


# Question
Title: A View which displays Posts assigned to a Parent which is followed by current user
A little advice please:

Users "follow" a content type Parent by using the method in this question. There is a content type Posts which has an Entity Reference to the Parent it is assigned to.

How do I go about creating a View which shows all Posts which the current user has "followed"?

I guess this could be done with Views Field View but that seems a little over-kill. There must be a simpler way of doing this, just with Views out-the-box, surely?

## Update

See my answer. Please, *please*, if anybody has a better solution let me know!

# Answer
> 0 votes
Use Views PHP.

In Views

* Format
    + Content
* Filter Criteria
    + Content: Published
    + Content: Type (=Post)
    + Global: PHP (see below for code)

Code for Global: PHP -

```
$flag = flag_get_flag('follow_parent');

$post_nid = $data->nid;

$post = node_load($post_nid);

$field_parent = field_get_items('node',$post,'field_parents');

$parents_followeds = array();

foreach ($field_parents as $field_parent) {
  $parent_nid = $field_parent['target_id'];
  $followed = $flag->is_flagged($parent_nid);
  $parent_followeds[] = $followed;
}

return in_array(TRUE, $parent_followeds) ? FALSE : TRUE;

```

---
Tags: views, entities, flags
---


title: Token for email includes name of field

text:
# Question
Title: Token for email includes name of field
Ok, so I've got this webform sending an email upon correct submission.

I'm trying to format the email so that it can send to a user who submits a form.

This email would say something like "Hi, Name, thanks for submission!"

I am trying to use the following:

```
<p>Hi %email[name]</p>

```

And the email is coming out like this:

Hi

name:

PersonNameHere

Why is this happening? Shouldn't the name come out without the field name?

# Answer
```
<p>Hi, I'm %value[Name]!</p>

```

works perfectly.
> 0 votes

---
Tags: 6, webforms, emails, tokens
---


# Question
Title: Get cart items and check for product of type X
How do I?:

1. Get the current cart in commerce
2. For each item in the cart, check its product type?

I want to do the following:

```
foreach($cart_items as $item){
  if($item[product_type]=='X'){
    //perform a task
  }
}

```

I want to use this in the module code for a custom checkout pane.

# Answer
Well this seems to work!

```
global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);

foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $type = $line_item_wrapper->commerce_product->value()->type;
  if($type=='X'){
    //perform a task
  }
}

```
> 8 votes

---
Tags: 7, commerce
---


# Question
Title: Can I include a list of sub-menu pages in the content of the parent page?
I have a page that is the parent of a series of menu items, e.g. Projects, with some project pages as child items in that menu. I would like this parent page to automatically have the list of children in the content. Is this possible?

I have a block that I created that lists this menu via the Views module...if there is a way to use that, it might be an alternative.

Thanks

# Answer
> 0 votes
By some coincidence, there is an article on how to embed a block in the middle of your node body content on Drupal Planet today.

It seems to me, though, that if you put the block at the top of your content and floated it with css, maybe with a border attribute, the result would perhaps be better than adding content to an arbitrary location inside the content.

---
Tags: 7, views, routes, nodes
---


# Question
Title: Generate a random image on front page each time it is loaded
I'd like to have a random image appear on the front page of my site each time the page is visited. Is there a module set up to do that? Any suggestions as to how to accomplish this?

# Answer
You can use Views slideshow Module to get the same. In the view all you need to make is a random query.
> 1 votes

---
Tags: media
---


title: How to programmatically create a flag?

text:
# Question
Title: How to programmatically create a flag?
How do you programmatically create a flag in drupal 6? I wish to capture this in code so that I can stage flags between different environments. The current stable release of flag does not support features.

# Answer
> 6 votes
Check out the flag API. There are examples for creatig flags, flagging a node and more. Here the example for the flag-creation:

```
$flag = flag_flag::factory_by_content_type('node');

// Absolutely required, will break your site if not added properties.
$flag->name = 'my_flag_name';
$flag->title = 'My Title';

// Properties required by the UI.
$flag->roles = array(2); // An array of role IDs. 2 is for "authenticated users".
$flag->types = array('story', 'page'); // An array of node types.
$flag->flag_short = 'Flag this';
$flag->unflag_short = 'Unflag this';

// Optional properties, defaults are defined for these (and more).
// Use a print_r() or dsm() to see all the available flag properties.
$flag->global = TRUE;
$flag->flag_long = '';
$flag->flag_message = '';
$flag->show_on_form = TRUE;
$flag->show_on_node = TRUE;
$flag->show_on_teaser = TRUE;
$flag->link_type = 'toggle'; // For JS link. Other options: 'normal' and 'confirm'.

// Save the flag.
$flag->save();

```

# Answer
> 2 votes
Nonsenz's answer is great, the only thing missing is that the **roles** are set differently than that.

You set a role for each action - flag and unflag.

```
    $flag->roles = array(
        'flag' => array(3),
        'unflag' => array(3),
    ); // sets up for administrator role only, corresponds to drupal role id in roles table, by the way

```

---
Tags: 6, flags
---


# Question
Title: Is Drupal Commerce ready for the real world?
I'm trying to make a decision between Drupal 6 + Ubercart and Drupal7 + Drupal Commerce... I'd much rather develop in 7 and am excited about Drupal Commerce but, as it is relatively young, have some concerns about its security and stability.

Does anyone have any relevant experience they would be willing to share?

# Answer
The payment gateway is the key. If your chosen payment gateway is available for Drupal Commerce, I would say yes, go ahead and use it.

Even if not, there are compelling reasons to develop or help to develop the payment gateway.

Drupal 7 is much more advanced, and will continue to be relevant for much longer. Drupal 6 will not be supported when Drupal 8 is released. Suppose Drupal 8 is released in 2 years (nobody knows at this stage but it's a reasonable estimate) and your site takes 6 months to launch. A Drupal 6 site would only have a viable life of 18 months. It's something worth considering!

We're building a reasonably complicated Drupal Commerce site right now and the elements like the order system, cart, checkout and things like entity types are all fairly concrete. It's also slick to use, and offers numerous advantages over Ubercart (products do not HAVE to be nodes, opening up new ways of selling things).
> 7 votes

# Answer
We're running a project with Drupal Commerce and it a great base for a store, but I'd say the key decision whether to use it is how comfortable you are with development. Commerce is a well designed e-commerce framework done the "drupal way", but unless you're comfortable with writing some custom modules to fill the in the gaps it's a lot slower getting up and running then UC. If UC has what you need out of the box it's likely the way to go from a time-cost of development point of view. If you're looking for long term longevity and future upgradeable of the project and you're ready to do some custom work then consider commerce.

For our project the store we're making is very customized (you order prints online) so commerce is an excellent framework to build on. But if you need something more simple like a say a clothing store, the current way you make a product in commerce is cumbersome. To create a basic product you need to create all the commerce "products" (EG product variations or SKUs) one at a time, in a commerce product type, and then you relate them to a "product view node". When a shopper sees a single product they see the product node view, which bundles up all the (commerce product) variations. There's logical reasons to do this but its slow to enter the data.

This is a lot more work - make all the variations, and then link them to the product. There's some contrib modules out there to help this but commerce is a fast moving target so you'll see commerce updates break these modules - so that's where your ability to modify / write modules becomes important in deciding what system to use. Commerce will be likely be more challenging to develop in right now - as it's got it's own learning curve, but its nice that basically everything is there is now drupal core stuff : views, fields, etc. So if you need flexible expandability in the long run commerce is great, but if your store is not likely to require future functionality enhancements and UC does what you need out of the box then I'd suggest going that direction
> 5 votes

# Answer
Commerce Kickstart 2 hit its 2nd release candidate yesterday so I would consider it stable to start working with. It is also very actively maintained so I guess there will be lots more bugfixes rolling out over the coming weeks as you start building your site.

I have used it for an upcoming project and it was a major help in boosting development time. It allows as much modification as you like but does include many dependent modules that are difficult to remove as they are part of the core features of kickstart.

Basically, yes, use it but dont install the demo content as you will be stuck trying to remove it.
> 4 votes

# Answer
I have been using Drupal Commerce for several months now. I have not have found many troubles so far. You should take a look of the videos and the documentation commerce guys has and find out if this module will be a good fit for your situation. I love Drupal Commerce. It really helped us to do our solution with the time constrains. I have never tryed ubercart though. I would have loved to have the time to try Ubercart and make a comparison. For my needs, it looked like Drupal Commerce had everything I needed. So, I never give a try to Ubercart.

Here I leave you with some information that helped me out with Drupal Commerce.

1. Drupal Commerce Official Site
2. Commerce Guys video in vimeo
3. developing with Drupal Commerce

I love the integration that it has with Views and there are also modules that help you to extend their features as commerce cart ajax, commerce cart expiration and Commerce Stock. You can customize commerce but don't do it in the core use the best practice of Drupal. I did several customization for my project. I even had to do my own expiration cart because they did not have at that time a cart expiration. I love the way you can also integrate it with Rules. I love the flexibility that this module has given me.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to change the alias for the core forum landing page?
Core forums sets the landings page to /forum. I need this changed to /another-page/forum. I know I can change the forum posts using pathauto, but I need to change the alias for the top-level forum landing page. Thoughts?

# Answer
> 2 votes
Why not just use the core path module:

http://example.com/admin/config/search/path/add

---
Tags: 7, nodes
---


title: Rewrite user edit page url

text:
# Question
Title: Rewrite user edit page url
On my Drupal 7 website, I would like a uri like

```
folder/subfolder/preferences

```

to be an alias for the user edit page

```
user/<uid>/edit

```

for all users. To be precise, when a user navigates to folder/subfolder/preferences, they should be at their own user/"uid"/edit page with the original folder/subfolder/preferences uri in the navigation bar. If necessary, I wouldn't mind if the aliase contained the uid, so I'd be ok with folder/subfolder/preferences/"uid".

It seems like the pathauto won't do what I want, I'm experimenting with sub-path auto but so far no luck. If there's a module that can help me do what I want that would be great, but wouldn't mind to do it through a hook if necessary (I haven't figured out how to do this by hooks either). Thanks for any help.

# Answer
> 2 votes
Please, consider using Extended path aliases or Sub-pathauto.

For breadcrumbs you can use Path Breadcrumbs or Custom breadcrumbs.

You also can set active menu item programmaticaly, but I don't like this way:

```
  // Somewhere in menu callback for 'folder/subfolder/preferences' path.
  global $user;
  if (user_is_logged_in()) {
    $path = 'user/' . $user->uid . '/edit';
    menu_set_active_item($path);
    return menu_execute_active_handler($path, FALSE);
  }

```

Maybe someone can improve this code to be more transparent.

*Tip: you often can find related modules in module description or on the right sidebar on Drupal.org. I found these modules on Pathauto page.*

---
Tags: path-aliases
---


# Question
Title: Importing PDFs into Drupal as content types
I'm new to Drupal and I have a question.

Is there any way to import table data on PDFs into Drupal, creating them as events?

I don't believe there is but I want to double check.

# Answer
> 5 votes
Not an easy task, I guess. Apache Tika is a toolkit to detect and extract metadata and structured text from various documents, PDF included. Is used, for example, by Apache Solr to parse and index PDF (and other) documents.

You may use Apache Tika to parse PDF documents and get the data you want, then create what you need (a Content Type, an Event).

Apache Solr Attachments seems to use Tika to index PDF documents, you can start looking at its code.

---
Tags: files
---


# Question
Title: How can I isolate *content* from *configuration* in the database?
There's no obvious way (that I can see) to isolate a Drupal site's *configuration* (which is of course all in the database) from its *content* (which is of course in the *same* database) when doing any operations on the database.

For instance, it would be very useful to be able to be able to push your configuration changes from your development server to production,

```
drush sql-sync @dev @prod

```

and then push *only your content* back to development from production.

```
drush sql-sync @prod @dev

```

Short of going through the database and making a list of tables for each type of data, and writing your own script to dump and import just those tables (an approach which seems kludgey and error-prone), how can this be done?

***UPDATE***: There doesn't seem to be any way to do exactly what I'm asking how to do. Since both answers were very helpful, however (1st of all because they contain useful information, and secondly because they indirectly confirm that it's not currently possible to do in any practical way) I'm up-voting them and selecting one. I hope that by selecting an answer no one is confused into thinking that what I described is possible. (I've seen such things happen before.)

# Answer
> 6 votes
There are different ways of passing the configuration data between various environments;

1 - Features

> 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.

It can be used in combination with Strongarm .

2 - Configuration Management

> ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.

# Answer
> 2 votes
Good answer from junedkazi.

I know that this isn't much use *right now*, but wanted to point out the config management initiative being worked on for D8.

http://groups.drupal.org/build-systems-change-management/cmi

---
Tags: database, nodes
---


# Question
Title: Continue saving node under some condition
Is there a drupal function can i use to check some condition, if it return true the node will be saved if not it should be return to the creation form.
Thanks.

# Answer
Following on from your comment above:

> i have a float field i want to compare it with another node field

Would the Field Validation module help?

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.
> 2 votes

# Answer
You can use hook\_node\_validate() to check your condition.

> Perform node validation before a node is created or updated.
>
> This hook is invoked from node\_validate(), after a user has has finished editing the node and is previewing or submitting it. It is invoked at the end of all the standard validation steps, and after the type-specific hook\_validate() is invoked.
>
> To indicate a validation error, use form\_set\_error().
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to make [uc_order] token globally available?
In admin/config/people/accounts , I want user password in welcome mail.

Currently it is

```
username: [user:name]
password: Your password

```

I want this

```
username: [user:name]
password: [uc_order:new-password] // this token is already available in order setting page admin/store/settings/checkout

```

Now question is is there anyway to make `uc_order` token available in user account setting page?

# Answer
I think you are going about this the wrong way.

You can make the uc\_order token globally avaialbe, but it would be a bit messy since some users wont have an order and other people have more than one order.

Instead you should use `hook_mail_alter` to actually insert the password from the order. You could search for `[uc_order:new-password]` and if found load the correct order and replace the value with the value from the order.
> 1 votes

---
Tags: 7, users, ubercart, tokens
---


# Question
Title: Changing block templates based on context? moving title in body field in template
Is it possible to change my block template suggestion based on a particular context?

E.g. On certain parent landing pages (I could manually set; because there are only 3 conditions no determinate pattern), I need the block title to go inside the content `<div>`.

I could do a workaround and add the title in the body field. Although, I don't want to modify the block content (to add title in the body area/field) because they maybe used on other taxonomy pages; and the clients will have a hard time managing this (calls asking why is the title shown twice in the block management).

Would or could this be best in terms of most efficient solution achieved by preprocessing?

**Current output on pages** (Default drupal templates in psuedocode):

```
div.block-block-{delta}
  h2.block-title
  div.content

```

**Desired output (on set parent landing pages)**

```
   div.block-block-{delta}
     div.content
       h2.block-title

```

**Desired output (on all other taxonomy pages)**

```
div.block-block-{delta}
  h2.block-title
  div.content

```

**Update:**

These landing pages are just three nodes that the client wants. Theres not really a rhyme or reason to what determines if it is a landing page. I just need to set three node id's to trigger the block template change.

# Answer
You mention the word 'context' in the first line of your question. Take a look at the Context module. I just came from this page

http://www.metachunk.com/blog/context-based-template-suggestions-drupal-7

Edit: elaborating .. here's the context module http://drupal.org/project/context Install it and create a context 'mycontext' for your 3 pages.

Based on this context, provide a template suggestion as mentioned in Topsitemakers' answer. In your themes template.php, it should be something like (not tested)

```
mytheme_preprocess_block($&vars) {
  $context = context_get();
  if(isset($context['context']['mycontext'])) {
    $vars['theme_hook_suggestions'][] = "block__mycontext";
  }
}

```

You can do this more generic as described in the post linked above. Now, your block will render using block--mycontext.tpl.php, if it exists, when shown in the 'mycontext' context.

$2c, \*-pike
> 3 votes

# Answer
Yes, the easiest way is to use `hook_preprocess_block()` function and add your templates to the list in specific contexts.

Example:

```
/**
 * Implements hook_preprocess_block().
 */
function THEME_preprocess_block(&$variables) {
  // Replace 1, 2, 3 with real node IDs
  if (arg(0) == 'node' && in_array(arg(1), array(1, 2, 3)) && !arg(2)) {
    $variables['theme_hook_suggestions'][] = 'block__custom_context';
  }
}

```
> 1 votes

---
Tags: theming
---


title: How to filter views using Ajax

text:
# Question
Title: How to filter views using Ajax
I have an array that I stock in the browser's storage. I retrieve it in Javascript.

I'd like to use those values to display a view. They IDs represent a nid.

I already created a view, took a wildguess and decided to use the contextual filters, allowing me to pass parameters in the URL.

But now, I'm stuck.

Any hints/tips ?

Thank you

# Answer
Don't use Contextual filters in this case, cause they are sent in url - use exposed filter.

Exposed filter will create form, which you can fill in and submit by js-code. Turn on AJAX fro view and filters will also work via AJAX.
> 0 votes

---
Tags: ajax, views
---


# Question
Title: Is comment fields data store in render array?
Is render array contain key-value entries that is generated by node module **only**? or comments fields also included?

# Answer
The render array for a node contains also the content of the comments, which is added by comment\_node\_view(), an implementation of hook\_node\_view(). That hook is invoked from node\_build\_content(), which is called from node\_view().

The Devel module shows the following output for a node render array.

In Drupal 8, node\_view() is a thin wrapper for entity\_view(), which renders the node using entity\_render\_controller().
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: how to show admin/reports/dblog in terminal ( cli )
While developing I really like a dedicated screen with all the drupal log messages. Working on mac or \*nix creating a new terminal window and doing a tail -f on the log file would be really nice. So I can do a tail -f on the apache error.log but I want to show the drupal log that is shown in admin/reports/dblog Where can I find it and or is it possible to let it output to a terminal screen and if so how?

# Answer
> 35 votes
You can use drush to do this:

```
$ drush help | grep watchdog
 watchdog-delete       Delete watchdog messages.
 watchdog-list         Show available message types and severity levels. A
 (wd-list)             prompt will ask for a choice to show watchdog messages.
 watchdog-show         Show watchdog messages.

```

`drush watchdog-show` has too many options to fully show here, but these are the examples:

```
 drush watchdog-show                       Show a listing of most recent 10
                                           messages.
 drush watchdog-show 64                    Show in detail message with id 64.
 drush watchdog-show "cron run succesful"  Show a listing of most recent 10
                                           messages containing the string "cron
                                           run succesful".
 drush watchdog-show --count=46            Show a listing of most recent 46
                                           messages.
 drush watchdog-show --severity=notice     Show a listing of most recent 10
                                           messages with a severity of notice.
 drush watchdog-show --type=php            Show a listing of most recent 10
                                           messages of type php.
 drush watchdog-tail                       Show a listing of most recent 10
                                           messages and continue showing messages
                                           as they are registered in the watchdog.

```

# Answer
> 3 votes
You have to enable the Syslog module, and the log will be available in /var/log/drupal.log. For more information, you can read Syslog: OS-integrated logging.

---
Tags: log-messages
---


title: How to extend TableSort class

text:
# Question
Title: How to extend TableSort class
I have a paged table that extends the TableSort class. The thing is, I would like to add some special parameters to the header links, so I need to extend the TableSort class. The problem is, it is not recognizing my new extended TableSort (MyTableSort) class. This is the code, any help would be greatly appreciated:

```
<?php
// $Id: RadiosDemo.module $
//This module demonstrates the radios default value problem.

class MyTableSort extends TableSort {
/**
* Compose a URL query parameter array for table sorting links.
*
* @return
*   A URL query parameter array that consists of all components of the current
*   page request except for those pertaining to table sorting.
*/
  public function tablesort_get_query_parameters() {
    return drupal_get_query_parameters($_GET, array('q', 'sort', 'order', 'nid'));
  }
}

/**
* Implementation of hook_menu().
*/
function RadiosDemo_menu() {

  // Added a link to navigate to the demo node display page
  $items['RadiosDemo/Problem'] = array(
    'title' => 'Demo of Pager Problem',
    'page callback' => 'RadiosDemo_displaynodes',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Function which will display all the nids in a paged table
 */
function RadiosDemo_displaynodes() {

  $headers = array(
    array('data' => 'nid', 'field' => 'nid', 'sort' => 'ASC'),
    array('data' => 'status', 'field' => 'status'),
    array('data' => 'title', 'field' => 'title'),
  );

  // Select nid from published nodes with 20 pager limit
  $query = db_select('node', 'n')
    ->condition('status', 1)
    ->extend('MyTableSort')
    ->extend('PagerDefault')
    ->orderByHeader($headers)
    ->limit(30)
    ->fields('n', array('nid', 'title', 'status'));

  $results = $query->execute();

  $rows = array();

  foreach ($results as $result) {
    $row = array();
    $row[] = $result->nid;
    $row[] = $result->status;
    $row[] = $result->title;

    $rows[] = $row;
  }

  $html = theme('table', array(
   'header' => $headers,
   'rows' => $rows,
  ));

  $html .= theme('pager', array(
    'parameters' => array(
      'banana' => 'banana'
  )));

  return $html;
}

```

# Answer
> 0 votes
Like any other extender, the TableSort class implements the SelectQueryInterface interface.

Your code doesn't work because tablesort\_get\_query\_parameters() is a Drupal function, not a method defined from `SelectQueryInterface`. To change the behavior of an extender, you need to re-define one of the methods listed in the documentation for SelectQueryInterface.

### References

---
Tags: 7, database
---


# Question
Title: Upload image to commerce product on save?
Currently working with the Commerce module in Drupal 7.

I've hooked the product creation form (using `hook_form_alter()`) to include a custom validation function. I have an image for each product that is generated on the fly and needs to be associated with the relevant product. The name of the image field is 'field\_pchem\_structure\_image.'

I'm able to create and save the image, but I need to make sure it is added to the product when the product is saved. I've tried setting:

`$form_state['values']['field_pchem_structure_image'] = $file;`

However, this does not seem to work. Could someone please explain how to do this?

# Answer
> 1 votes
I ended up solving this by using `hook_field_attach_submit()`.

The basic process was this:

* Save the file using `$file` = `file_save_data()`
* Set a hidden field in `$form_state` to store `$file`
* Ex: `$form_state['hidden_fid_val'] = array(
 '#type' => 'hidden',
 '#value' => $file
 );`
* In `hook_field_attach_submit()` do some basic entity type checking (e.g. `if ($entity_type == '<your_entity_type_here>') { ... }`
* Typecast the file object as an array
* Set the correct entity field to the file array ( `$entity-><entity_field_name>['und'][0] = $file;`)

The file should then populate the correct field after save.

# Answer
> 2 votes
I installed Commerce Customizable Products and created a new line item type. This enabled me to create another product type with an upload field in the add to cart form users can use to upload file to the site. Also use rules obviously to do some more backend stuff, like change file location (that's set with a token uid) to be updated on username change and lots more. Can do lots of fun stuff with media/file entity, but your fix also works, just adding this for the search bot arena ;)

---
Tags: 7, commerce, entities
---


# Question
Title: How to modify taxonomy term path in the page render array?
I'm trying to change the path of a term before it's displayed on a node page. I'm using this preprocess function in template.php:

```
function bartik_preprocess_node(&$variables) {
    $variables['field_photo_topic']['0']['taxonomy_term']->uri['path'] = 'photo/test';
}

```

The path won't change, what am I missing? This is the dpm output:

# Answer
This question makes perfect sense if photo/% and video/% are views. It might be even better to map taxonomy/term/% to topic/%, and then make a single view with a path topic/%/%, where one argument is the content type and the other is the taxonomy term. However, you may also use the paths you suggest by building two views (or two pages in one view), each with its own path.

On to your main question, though. Changing items in the render array is easy, but it can sometimes be hard to figure out what needs to change and when. It is a general problem with render arrays that sometimes there are shadow copies of info that are available for your reference. Changing these copies does not affect the rendering of the page, because they are only copies of the item that is used to build the actual page. The problem with the code in your question is that it was altering a copy of the target link; the master information that you need to change to affect page rendering appears somewhere else in the data structure. You need to adjust the copy that appears inside the 'content' item.

Here is some code that works for a similar content type:

```
function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }
  }
}

```

From here, you can use pathauto to map photos/% to a pleasing URL to your photos + taxonomy term view.
> 9 votes

# Answer
Just found this solution based on hook\_entity\_info\_alter(): http://erikwebb.net/blog/changing-url-all-taxonomy-terms. Basically:

```
function YOUR_MODULE_entity_info_alter(&$entity_info) {
    $entity_info['taxonomy_term']['uri callback'] = 'YOUR_MODULE_taxonomy_term_uri';
}

```

and

```
function YOUR_MODULE_taxonomy_term_uri($term) {
    return array('path' => 'your/custom/path/' . $term->tid);
}

```
> 9 votes

# Answer
Why not create a View to create a block for the terms of a node? You can use a contextual filter to get the terms associated with the node and display those terms. Then using Views you can call the term ID field and the term name field and rewrite the terms to go to your custom URL.

```
<a href="custom/path/[tid]">[term_name]</a>

```
> 2 votes

# Answer
Have you considered Pathauto pattern for taxonomy? Once the module is installed and configured, it also allows you to override individual URLs per term. This would be much more sane system-wise.

Having read your other post, I would suggest that for your content types (photo, video) you enter in Pathauto pattern section:

```
photo/[term:url:path]

video/[term:url:path]

```

then rebuild the patterns for all entities and see if that works. If that does not work, then please specify what exactly - 'cause I'm afraid I might not understand your issue well enough.
> 1 votes

# Answer
First, I don't understand why you would do this, the taxonomy is still going to have this path, your theme is just going to show a wrong path for it if it worked. Have you tried using autopath module or changing the path in the taxonomy form? There you can define an alias for the taxonomoy.

If what you are trying is to change the taxonomy of a node, then change the node. What you are doing now is probably working but being overwritten by some other process. But I think you might want to provide more details, since your question is not very clear.
> -1 votes

---
Tags: 7, taxonomy-terms, theming
---


title: Calculating quiz score for validation

text:
# Question
Title: Calculating quiz score for validation
I'm not using the Quiz module; I am using Webform and Drupal 7.

I have created a quiz that, if passed, assigns the user a new role. Currently, I use validation rules to simply prevent wrong answers from validating; all questions must be answered correctly before the user can proceed.

I need to change this to allow users with a score of 80% or higher to proceed to the next quiz. I know that I can do that with the quiz module. However I also need to be able to show correct answers for missed questions only to users who scored between 80% and 100%. Those scoring below 80% may not see any answer key.

What is the best way to go about this?

# Answer
> 2 votes
I am solving this problem by disabling Quiz and using only Webform, and writing a custom module that does the following:

* use hook\_form\_alter to catch webform submissions
* compare them to fields in an answer key
    + answer keys are of content type 'answer key'
    + they have a node reference field that references a webform
* calculate percent that match
* display a message depending on score
    + if 80% \< x \< 100% display answers
    + if 80% \< x return that the quiz was passed
    + if 80% \> x tell them they failed and redirect them back to the quiz page to re-take the test.

# Answer
> 2 votes
Just an FYI I put together a webform quiz module that works with the formbuilder module. It allows you to put in a percentage that the user needs to pass to finish this quiz as well as putting a correct answer for each form component: http://drupal.org/sandbox/acouch/1817016

---
Tags: 7, webforms, forms
---


# Question
Title: Change "Public file system path" with Amazon S3
I want to keep my media files, all files in the "default/files" folder in the Amazon S3 account. I've opened the "admin/config/media/file-system" page and there is the "Public file system path" field, which by default is set to sites/default/files.

I can't imagine how can I connect my Amazon account with this file system path.

I'm using Drupal 7.

# Answer
> 2 votes
You are looking for the following module: AmazonS3.

# Answer
> 2 votes
Once you've configured your bucket, I believe you need to configure the public path to be something like:

```
s3://public/path

```

as opposed to

```
sites/default/files

```

---
Tags: files
---


# Question
Title: How to modify form fields before validation
I have a custom content type with a lot of fields, and some are required. Under some circustances these required fields can be computed from other fields. I tried to use also hook\_node\_validate, but i have always the error message because the field is empty when the user sends the form. It's not easy to implement a javascript solution, since the algorithm to compute the values is not trivial. Which kind of solution do you suggest to use?

# Answer
> 1 votes
From the documentation:

> Note: Changes made to the $node object within your hook implementation will have no effect. The preferred method to change a node's content is to use `hook_node_presave()` instead. If it is really necessary to change the node at the validate stage, you can use `form_set_value()`.

---
Tags: 7, forms
---


# Question
Title: referenced entity not showing up in the node view page or in any view I create
I have a custom module which defines a custom entity. On a content type, I have an 'Entity reference' field that let's me select a custom entity. The value is saved in the database (I looked directly to the database) but is missing when the node is viewed.

if I dump the `$node` in `hook_node_update($node)` I can see the referenced value is there. But on `hook_node_view($nodes, $types)` the value is gone.

The funny part is that in a view, if I create a relation based on this field, I can see the entity's fields, but not the entity reference field value :))

Other types of entities are displayed correctly though, the problem is only with my custom entity

Any help would be very appreciated :) Thanks

# Answer
Still haven't found an answer so I decided to try the model module. Looks ok now :)

LATER EDIT: eck module seems the best way to work with entities
> 1 votes

# Answer
I just Googled the same issue and was led to this page.

You need to implement an `access callback` in `hook_entity_info()`, else the entity reference field won't load the entity.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How do I specify the custom template for a theme?
Instead of page.tpl.php, How can I use a custom template in theme? I am using the Zen theme.

In Drupal 6, we will specify it in the `theme_preprocess_page()`, using the `$vars['template_files'][]` array. I don't know what to use in Drupal 7.

# Answer
The equivalent in Drupal 7 is `$variables['theme_hook_suggestions']`, which is initialized in template\_preprocess\_page() using the following code:

```
  if ($suggestions = theme_get_suggestions(arg(), 'page')) {
    $variables['theme_hook_suggestions'] = $suggestions;
  }

```

If you want to add suggestions for the template files to use, you should append new suggestions using code similarly to the following one (`$variables` is the parameter passed to the preprocess functions):

```
$variables['theme_hook_suggestions'][] = "page__new_suggestion";

```

You can also add your suggestions before the existing ones, to be sure the template file you are suggesting is used whenever other template files exist.

```
array_unshift($variables['theme_hook_suggestions'], "page__new_suggestion");

```

Clearly if the template file your code suggests doesn't exist, one of the other template files will be used.
It is also suggested to prepend the template filename with the type of the template, in this case with "page\__"; the underscores used in the suggested filename are converted in hyphens before to check if that file exists.
> 6 votes

# Answer
**Drupal 6**

```
<?php
function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
   // If the node type is "blog" the template suggestion will be "page-blog.tpl.php".
   $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}
?>

```

**Drupal 7:**

```
<?php
function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
  // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
   $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }
}
?>

```
> 1 votes

# Answer
Just in case this is useful to anyone else out there that stumbles across this looking for how to specify a custom template **in a custom location** (i.e. not the templates folder) for Drupal 7... this was what I got working:

```
/**
 * Helper function to produce a list of custom templates
 * in my code I have this tied up to some directory listing
 * code using file_scan_directory - but I have simplified here
 */
function _my_module_get_template_array(){
  return array(
    'panels-size2-x1-sliders-x2'
      => '/sites/all/themes/my_theme/custom/panels-size2-x1-sliders-x2.tpl.php',
  );
}

/**
 * Implementation of hook_preprocess_HOOK().
 */
function my_module_preprocess_node( &$vars ){
  if(isset($vars['node']) && arg(2) != 'edit') {
    $node = $vars['node'];
    /// In my setup certain nodes have a field that defines
    /// the template from a widget that derives it's values
    /// from the _my_module_get_template_array function.
    /// You could obviously totally change all the checking
    /// logic that follows. The only important line is the
    /// 'theme_hook_suggestions' array assignment:
    if ( isset($node->field_lp_template) ) {
      if ( ($items = field_get_items( 'node', $node, 'field_lp_template' )) ) {
        /// pull out the template value from my field_lp_template field
        $template = drupal_render(
          field_view_value(
            'node',
            $node,
            'field_lp_template',
            reset($items),
            array('label'=>'hidden')
          )
        );
        if ( $template ) {
          /// we need to translate hyphens for underscores to be inkeeping with D7
          $vars['theme_hook_suggestions'][] = strtr($template,'-','_');
        }
      }
    }
  }
}

/**
 * Implementation of hook_theme().
 *
 * In the following code we define theme information for each possible
 * template - keyed by the template name. Doing this means we can
 * define a full path to our template (which you can not do in
 * theme_hook_suggestions alone). By keeping the theme_hook_suggestions
 * name defined above the same as the key in the $theme array below
 * means that we tie both together and Drupal will use this information
 * if there are no other overriding templates found.
 */
function my_module_theme() {
  $theme = array();
  foreach ( my_module_get_template_array() as $template => $path ) {
    /// we need to translate hyphens for underscores to be inkeeping with D7
    $template = strtr($template,'-','_');
    $theme[$template] = array(
      'render element' => 'node',
      'template' => $path,
    );
  }
  return $theme;
}

```

Anyway, as I said hope it helps... took me several hours of trying lots of other solutions before getting this one.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Error adding one content type. Bundle missing in term references
I've got a problem on a Drupal 7.14 site when trying to add a new node to only one content type.

I get the following error message in the log:

```
EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7389 of /homepages/33/d169792374/htdocs/sites/yourfutureinautomotive.com/includes/common.inc).

```

I've tried the fixes outlined here as well as removing modules one by one and I'm not getting anywhere.

I've even reverted back to 7.8 to make sure I was on the same version as other people who were having the issue.

I'm open to any ideas or troubleshooting hints.

Ta

**EDIT**

As per @mojzis suggestion below I used the Devel dpm function. The following was output:

**EDIT 2**

vid: 14 is the problem. There is no vocab with vid of 14. Trying to hunt down a reference to it anywhere but not having much luck.

# Answer
> 0 votes
OK I'm going to answer this with that's solved the issue for me.

I got a bit desperate and was trying to hack common.inc in the core (may god have mercy on my soul), but after checking things out using the wonderful Devel module I just added in a test taxonomy vocabulary with a VID of 14. I can now add content again which is good, but am none the wiser as to the actual cause of the problem.

Interestingly the vocab as terms added to it when I add a new content of the type that was giving me trouble but they're blank. When I get a bit more time I'll try and troubleshoot this properly but if anyone else has the same issue, this is what solved it for me.

# Answer
> 2 votes
Your issue is most likely related to the Media module, and specifically this issue: 'Missing bundle property on entity of type file error'. In your troubleshooting efforts, did you run across this info? A quick check to confirm if this is the culprit is to follow the step(s) outlined in comment #5.

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


# Question
Title: What do we hook in Drupal 6 for inbound URL rewrites?
Where conditional rewrite is desired, not supported by existing path modules, and where we'd prefer to stay out of .htaccess, where might we hook in Drupal 6?

Along the lines of Drupal 7 `hook_URL_inbound_alter`, I think.

# Answer
> 3 votes
`hook_URL_inbound_alter` was introduced as part of a contributed module in Drupal 6 (URL alter), and was moved to core with Drupal 7.

# Answer
> 0 votes
In Drupal 6, the equivalent of hook\_url\_inbound\_alter() is custom\_url\_rewrite\_inbound() which is not a hook, but a function to put in the settings.php file used by Drupal.

The URL alter module defines that function, and call any implementation of `hook_url_inbound_alter()` defined from other modules, allowing modules to use the same code for Drupal 6, and Drupal 7.

The same is true for custom\_url\_rewrite\_outbound(), and hook\_url\_outbound\_alter().

---
Tags: 6, uri
---


# Question
Title: Which html div classes are relevant when styling Views in Drupal 7 (for CSS)?
Generally, I wish to be able to style Views output on my site, but I am unsure which div classes and classes from other html elements to select in CSS to style.

There are many nested divs with classes and some to me seem like housekeeping/ancillary ones that should not be effected, e.g.:

General advice requested please: in the form of: technique, experiences, guide, tools, books and examples.

I've also considered Semantic Views for this aim, but this appears to be not yet in beta for Drupal 7 (i.e. unstable). Also View Element in Chrome browser or firebug - but not sure how much benefit these would have.

Also considered a mix of answers from:

But would prefer a more general approach and one which doesn't require adjusting theme php code.

# Answer
> 4 votes
I can only speak to my personal experience. I use these classes to style my views primarily:

* `.view-myview .view-content` the main content of the view, encapsulates all rows
* `.view-myview .views-row` this is the row in your view, add a border, some margins, etc.
* `.view-myview .views-field-myfield` a singular field in a view

You also get `views-row-even`, `views-row-odd` and `views-row-first`, `views-row-last`, etc.

The classes can handle all tags, it doesn't matter if they're divs, spans, etc. I did a presentation at DrupalCon SF 2009 which explains a lot of different ways to customize views if you're interested it is here: http://sf2010.drupal.org/conference/sessions/jquery-views-and-view-themeing.html

# Answer
> 1 votes
Actually there's nothing you have to know by heart. Take firebug and point to the thing you want to style (everyhting, not just views). It gives you all the CSS information you need. You can even try new settings right in firebug and copy them to your CSS once you're happy.

If this is not enough install the devel themer module. Similar to firebug it let's you point to anything on your site (not just views) and it tells you which theming function is used and which one you can implement to override the current behaviour.

# Answer
> 0 votes
Try the Fences module, cleans up the markup output by views and therefore makes it easier to style it.

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
>
> Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!

---
Tags: 7, views, theming
---


title: Image Gallery with multiupload

text:
# Question
Title: Image Gallery with multiupload
i have a Drupal 7 site and want to generate a image gallery.

My requirements:

* Multi File Upload
* one folder per Gallery
* only accessible for authenticated user

I tried plup and multiupload\_imagefield\_widget for multi file upload. This works fine except for the one folder per gallery requirement. All files are stored in the same folder.

Do you have any advices on how to achiev this goal?

# Answer
I've got the same problem like Jussi and i tried to set up a system with the himuesgallery module, the upload via ftp works great and you can build a folder system. I tried to integrate the image folders in Drupals Private Dir and the result is that i can't see any picture anymore ... may i configured somehing wrong, but this seems not to be a solution. May a module to restrict access to another folder help.

A long time ago i tried the media module and there was some other problems... See also the Media Issues or the statement of the authors:

> Known Issues
>
> Private files: There are several issues in Media and Drupal core when the private file system is used. While these issue are being investigated and fixed, the use of the File lock module is highly recommended.

So my answer is: No, there is currently no working gallery that reachs your aims.
> 2 votes

# Answer
Media *DEV* \+ Media Browser Plus *DEV* \+ Plupload would get you pretty close I think.

There's no integration with media gallery specifically (that I know of) but you can navigate to `admin/content/media/folder_list` to add/manage your list of folders. Once you've done that you'll be able to sort your uploads into the various folders using the normal media browser.
> 1 votes

---
Tags: 7, files, media
---


# Question
Title: Single site vs Sub-sites vs Multi-site installation + Scalability
I am beginning a new Drupal project that needs to very scalable and I need to determine what the structure should look like based on the current and eventual project needs. I have previously used all separate Drupal sites to accomplish similar goals, but would like to at least consider something a little less maintenance-intensive if it makes sense. Any ideas or advice on how to proceed is much appreciated... thanks.

**Players**:
-Organization A (main organization)
-Organization B
-Organization C
-Organization D
(and there may be more in the future)

**Functions**:
-Main public "front area" of site where all organizations land: orga.site.com
-Access-restricted area for members of Organization A: orga.site.com
-Access-restricted area for members of Organization B: orga.site.com/orgb
-Access-restricted area for members of Organization C: orga.site.com/orbc
-Access-restricted area for members of Organization D: orga.site.com/orgd

Access-restricted areas have similar functions between organizations but not exactly the same, and look and feel (theming) would be different for each organization in the restricted areas.

Additionally, each organization's restricted access area would have sub-areas that are further restricted to a smaller group of people, e.g.:

Organization B:
-Main front: orga.site.com
-Restricted area accessible to all members of Org B: orga.site.com/orgb
-Area restricted to a sub-group in Org B: orga.site.com/orgb/groupa
-Area restricted to a different sub-group in Org B: orga.site.com/orgb/groupb

This type of sub-site differentiation would be typical for each different organization.

Normally when I map a project out like this I have a good handle on how to proceed; in this case my head is still spinning a bit, so any input is helpful.

# Answer
There are many possible ways to build out a site like this. Right off the top, I would recommend against using a multi-site setup. c.f. Drush pm-update and multisite. If you did want to use multiple Drupal sites for this, I would use aliases in your vhost conf file to point /orgb, /orgc etc. to a separate Drupal root.

However, in this particular case I think you would be best off using a single Drupal site with Organic Groups and Organic Groups Theme. Disclaimer: the *latter* module is minimally maintained, and I have not used it personally. If you wanted to support orgb.site.com instead of orga.site.com/orgb, then you could use the Domain Access or Subdomain module instead, although if you use Domain Access you should be aware of the issue Domain Access and Organic Groups. Try a couple of experiments and see how they fit your use case before diving in and doing the whole implementation; you should be able to set up something pleasing fairly easily.
> 1 votes

---
Tags: multi-sites, domain-access, subsites
---


# Question
Title: How to get node id on hook_page_build(&$page)
I wrote a hook like so:

```
function john_page_build(&$page)
{
  $akeys = array_keys($page['content']['system_main']['nodes']);
  print $akeys[0];
}

```

On pages with urls like `http://mysite.com/page/43`, it will print the node id for that page. However, on a page with url like `http://mysite.co/page/43/done?sid=2`, drupal gives a warning saying that `$page['content']['system_main']['nodes']` does not exist.

Is there a consistent way to get the node id WITHOUT parsing the url?

# Answer
> 6 votes
Still comes through the URL indirectly, but this is the easiest way to get it: menu\_get\_object.

```
<?
if ($node = menu_get_object()) {
 $nid = $node->nid;
}
?>

```

Note that if there is a node, it was already loaded by the menu system anyway and this is loaded from the static cache.

Refer this discussion for more detail.

# Answer
> 1 votes
Never use arg() in d7 (by chx)! To get actual node, use `menu_get_object()`, on node pages this will return the complete $node object.

# Answer
> 0 votes
To get nid in your hook from url, you can use arg() function as below

```
function john_page_build(&$page)
{
  $nid = arg(1);
  echo $nid;
}

```

---
Tags: nodes, hooks, uri
---


# Question
Title: Display OR between two fileds in a content type
I have two fields in a content type. one is file upload field. another one is link field. Customer can either upload file or give the url to the field.

so I want to display "(OR)" between these two fields in content type.

How this can be achieved.

# Answer
If you simply want to display "(OR)" between two fields in content type, you can achieve this in form alter

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

    if ($form['#id'] == 'page-node-form'){ //contenttype-node-form

   $form['field_test']['#prefix'] = '<div class="classname"> OR';
       $form['field_test']['#suffix'] = '</div>';
       //where field_test is your file upload field
    }
 }

```
> 1 votes

# Answer
I think you are trying to present your customer two options with radio check box - Upload file or Web Link. Upon selection of one of those fields, you would display the respective field - field upload or link.

If you love custom coding, you can do it with custom module with #ajax attribute on the radio field to alter and rebuild the form.

Check this answer for your reference.
> 0 votes

---
Tags: 7
---


# Question
Title: Create a view of all nodes that have the same value for a specified field as the current node
So I have an event, which has a field called 'field\_location'. I want to create a view on the event page where all other events are listed with the same location. In this case location is a node reference to a node (with content type 'location').

How can I dynamically filter all my event nodes on 'location value of the current event'? I tried this with contextual filters but here it only checks the field you use, in this case 'field\_location', with the content id of the url.

I already tried this but without success.

I get zero results.

# Answer
Use Page manager and panels and add the view as a content pane. Then, pass the node's field's value as an argument to the pane(s) on the panel and you should be good to go.
> 1 votes

# Answer
Try this for you php code instead:

```
$node = menu_get_object();
return $node->field_location['und'][0]['target_id'];

```

Does that work?

There's a similar question with a few answers here too: views and contextual filters with entity reference field. There are also comments in that discussion about approaches that avoid poking around the node object and avoiding the \['und'\]\[0\] business. Check that out too!
> 0 votes

---
Tags: nodes, views
---


title: How to pass form input to ctools modal

text:
# Question
Title: How to pass form input to ctools modal
I have a regular Drupal form that is not in a modal. When the user submits the form, a ctools modal popup opens (as per http://drupal.org/node/1482968).

My question is, what is the best method for passing form input to the modal? So that e.g. if the user enters their name ("Alex") in the form, the modal popup can read, "Welcome Alex!" ?

I am using Drupal 7 and the latest stable release of Ctools. (Also, I've asked this question in the ctools issue queue at http://drupal.org/node/1556856, but haven't had a reply in twenty days.) I've been trying to crack this one for a while, so would be incredibly grateful for any help!

# Answer
> 0 votes
Ended up just grabbing the passed variables from $\_GET.

---
Tags: forms, ajax, chaos-tool-suite, javascript
---


title: Aegir installation issue

text:
# Question
Title: Aegir installation issue
While installing Aegir in a VM, during the hostmaster installation, I got the following error:

```
Do you really want to proceed with the install (y/n): y
PROVISION_SITE_INSTALLED                                             [error]
The external command could not be executed due to an application     [error]
error.
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Unsupported operand types in
/var/aegir/drush/includes/environment.inc, line 916

```

Drush version 4.5

# Answer
> 4 votes
Here is an issue on Drupal Groups: http://groups.drupal.org/node/96639.

Possible solutions:

* Check if your system is Ubuntu (the installation script assumes that it is)
* Remove everything in /var/aegir and run the installation script again.
* Run 'mysql\_secure\_installation' command and finish it successfully. Aegir checks for security flaws during installation and block it if, for example, you have anonymous users enabled in mysql.

---
Tags: aegir
---


# Question
Title: Quick tabs module change title to bottom
I am facing a problem. I have a module called QuickTabs, new to Drupal and confused.

I like to change the position of the title of the quicktabs, instead of top and I would like my buttons or links to be on the bottom. I worked the css but it seems that the render is on the inc.

```
    tile1 title2
---------------------------
    content content

```

Change to:

```
     content content
---------------------------
     title1  title2

```

Any hints of how I can do this? I am using Drupal 7

# Answer
> 4 votes
I would recommend you to start by downloading the excellent devel\_themer module from Drupal.org and install it on your site. It will also require that you install the devel module.

Once you install it and enable it, devel\_themer will tell you what template (\*.tpl.php) is being used. You can then go to that template and alter the order of the HTML elements directly. You will also find devel\_themer to be a great tool for learning Drupal theming.

# Answer
> 3 votes
Add this in your template.php file from your (custom) theme:

```
function trasys_qt_quicktabs(&$variables) {
  $element = $variables['element'];
  $output = '<div '. drupal_attributes($element['#options']['attributes']) .'>';

    $output .= drupal_render($element['container']);

    $output .= drupal_render($element['tabs']);

  $output .= '</div>';
  return $output;
}

```

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


# Question
Title: How to integrate some fields into a node more efficient?
in my node.tpl.php i want to display a custom field (field\_cta) which is part of my page. It is working this way, but it looks so terrible...is there a drupal command to shorten all the array-walk-trough precedure?

```
if (isset($content['body']['#object']->field_cta['und'][0]['value'])){ print $content['body']['#object']->field_cta['und'][0]['value'];}

```

Thanks a lot!

# Answer
if it's Drupal 7, I think this can works.

```
if(isset($content['fieldname'])):

echo render($content['fieldname']);

endif;

```
> 1 votes

---
Tags: nodes
---


# Question
Title: How do I track if a user is logged in on multiple devices and computers?
I have video content behind a paywall and want to make sure that each user is only logged in from one computer, or device at a time. If they are logged in on the computer watching videos, I don't want their friends to use the account to log in and watch videos from a different computer, device or IP address.

How do I enforce this?

# Answer
Check Session Limit module.

> Session Limit allows administrators to limit the number of simultaneous sessions per user.
>
> Max session is configurable, no database tables needed.
>
> By default, a session is created for each browser that a user uses to log in. This module will force the user to log out any extra sessions after they exceed the administrator-defined maximum.
>
> Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.
> 3 votes

---
Tags: payment-gateways
---


# Question
Title: Adding custom Text changes the horizontal alignment in Content type
I have a content type. For two fields I am using horizontal tab item . those two fields Section\_grid\_image and section\_grid\_image\_path are displayed one after another so I have used hook\_form\_alter and added custom CSS.

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

//Load CSS
$form['#attached']['css'][drupal_get_path('module', 'displayor') . '/form.css'] = array();

if ($form['#id'] == 'section-node-form'){ //contenttype-node-form

   $form['field_section_grid_image']['#prefix'] = '<div id="leftcolumn">';
   $form['field_section_grid_image']['#suffix'] = '</div>';
   //where field_test is your file upload field

   $form['field_section_grid_image_path']['#prefix'] = '<div id="rightcolumn"> OR';
   $form['field_section_grid_image_path']['#suffix'] = '</div>';
   //where field_test is your file upload field
 }
}

```

CSS

```
#leftcolumn{
width: 400px;
float: left;
}

#rightcolumn{
 width: 600px;
 margin-left: 200px;
}

#innercolumn{
 width: 500px;
}

```

My alignment is getting like this:

I want the fields and OR to be displayed in a line.

How to do this.

**EDIT: Got the answer.Below CSS did the trick.**

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

//Load CSS
$form['#attached']['css'][drupal_get_path('module', 'displayor') . '/form.css'] = array();

if ($form['#id'] == 'section-node-form'){ //contenttype-node-form

   $form['field_section_grid_image']['#prefix'] = '<div id="leftcolumn">';
   $form['field_section_grid_image']['#suffix'] = '</div>';
   //where field_test is your file upload field

   $form['field_section_grid_image_path']['#prefix'] = '<div id="rightcolumn"><span class="or">(OR)</span>';
   $form['field_section_grid_image_path']['#suffix'] = '</div>';
   //where field_test is your file upload field
 }
}

```

CSS

```
#leftcolumn,
#rightcolumn,
#orseperator
 {
   float: left;
   margin-right: 77px;
   padding: 10px;
 }
 .or
  { left: 382px;
   margin-right: 25px;
   margin-top: 1px;
   position: absolute;
   top: 76px;
  }

```

# Answer
Why dont you just do the following:

```
   $form['field_section_grid_image']['#suffix'] = '</div><div> OR';

   $form['field_section_grid_image_path']['#prefix'] = '</div><div id="rightcolumn">';

```
> 0 votes

---
Tags: 7
---


title: Image Annotations in Drupal 7

text:
# Question
Title: Image Annotations in Drupal 7
What's the best way of creating image annotations in Drupal 7?

Ideally, I would like to re-recreate something like in Concept Feedback, where you can post annotations on an image and then display the annotations as a list below the image, grouped by category.

Image Annotate (view demo here), lets you annotate images. The annotations are also displayed as comments on the node (under the comments section). Unfortunately, it the Drupal 7 version is incomplete and not actively developed. The module also doesn't allow you much control over how comments are displayed and you can only annotate one image per a ndoe.

Photonotes (view demo here) is another similar module (although it only displays annotations on the image). It to is only in development for Drupal 6.

JQMap Highlight works on Drupal 7, only lets you post tooltips on images (as opposed to true annotations).

Does anyone have other suggestions.

Thanks!

# Answer
Imagefield Marker is a new D7 module for image annotations.
> 3 votes

# Answer
If nobody knows a module like that, I think you could start porting Image Annotate to Drupal 7.
> 1 votes

# Answer
Image Annotator seems like a better option, tried Imagefield Marker too but had mixed results.
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to add "browse" button in image in CKE Editor?
I wanted to put "browse" button in image button iframe(pop up).

But I am unable to put it.

How can I change the default behaviour and customize pop up screen in cke editor buttons ?

Thank you...

# Answer
> 0 votes
May be IMCE module will solve your problem !

> IMCE is an image/file uploader and browser that supports personal directories and quota.

# Answer
> 0 votes
I like IMCE too, if using wysiwyg bridge module maybe you can try

---
Tags: wysiwyg
---


# Question
Title: Custom content title not displayed as field
I have created 2 custom content type "project information" and deleted body and added other fields and using "title" field as "project title ". Now I am creating view, when I am adding FIELDS ,not able to find project title field.

# Answer
It should be listed under node title. Changing the title in manage fields for a content type only changes the label for the tittle field. Title is a required field for nodes thus you cannot change it's field name.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Can the Drupal 6 search function also index block content?
I have a site where much of content has been entered into blocks instead of Pages, Articles or Blogs. The blocks have then been enabled to show up on specific pages, creating the desired effect for the site.

However, as content as been added to these blocks, the search feature of Drupal won't find the pages that have that content on it.

Are there any options to adjust the search engine features for something like this? Is there a hook that can be used to customize the search results?

# Answer
No, block content is not searchable by default. Have you tried the Block Search module? Seems that is what you need.

**edit**: After reviewing the module, I now see that the search functionality inside block content is done for only administrators, so that module probably doesn't help.
> 1 votes

---
Tags: blocks, search
---


# Question
Title: Organize files attached to a node into folders
We need to organize files attached to a page into folders (with Drupal 7). They don't necessarily have to be physical folders, virtual folders are fine.

Do you know a module like this, or do we have to implement it our own?

Update: To be more specific: we need the ability to display attached files on the page organized into folders, the underlying filesystem structure is indifferent.

# Answer
> 3 votes
Just make a taxonomy vocabulary to simulate the folder structure. Install File Entity module. It makes fieldable files, so you can attach taxonomy for the file own - with the module Media you can do that during editing the node.

To display files grouped by folders, you can make a view to do that, and use EVA to embed it into the node. In the view you have to make a 'File' based view, just add a relationship to the node, and add a Content Id contextual filter, which use that relationship.

# Answer
> 0 votes
Check out Filefield module.

> Configurable upload paths allow you to save files into per-field or per-user directories. FileField does not need a Drupal 7 version because it has been moved to Drupal Core! To upgrade FileField to Drupal 7, install the Drupal 7 CCK Package and use the Content Migrate to upgrade FileField to Drupal 7.

---
Tags: 7, files
---