# Question
Title: How do I render a field value including its format?
I'm reading a field value and its format from the database. How would I render that value with the format?

# Answer
> 38 votes
While you could spend a lot of time dissecting how the Field API works, you really should be using the Field API directly to render field content instead of querying the database yourself. There's a lot of encapsulation and abstraction added to fields that will awaken the Old Gods if bypassed.

Using the Field API, if you want the whole formatted field, complete with label and all values, you want to use `field_view_field()`:

```
$nid = 1;
$node = node_load($nid);
$output = field_view_field('node', $node, 'field_foo');

// $output is a render array, so it needs to be rendered first
print render($output);

```

If you just want to display the formatted value of one item in a field, you need to use `field_view_value()`, which is a little more involved:

```
// Must load field content for entity before using field_view_value()
$fields = field_get_items('node', $node, 'field_foo');

// $index corresponds to the value you want to render. First value = 0.
$index = 0;
$output = field_view_value('node', $node, 'field_foo', $fields[$index]);

print render($output);

```

If you want to use a formatter other than the default specified for the field instance, pass it using the `$display` parameter in either `field_view_field()` or `field_view_value()`:

```
$display = array('type' => 'my_formatter');
$output = field_view_field('node', $node, 'field_foo', $display);

```

# Answer
> 0 votes
by checking api, i think you are look for this. ( I haven't tested the code anyway )

```
$the_field = field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL);

// render the field
drupal_render($the_field);

```

update: duplicate answer, may just delete me. other answer posted while I am writing this answer.

# Answer
> 0 votes
If you use module Custom Formatters don't forget to add prefix 'custom\_formatters\_' before your formatter's mashine name like this:

```
$display = array('type' => 'custom_formatters_my_formatter');

```

# Answer
> 0 votes
Looks like you can also edit the template file to adjust how this is output semantically:

1) Set up a custom date fomat and give a machine name like "short\_date\_only" or whatever. 2) Configure the display options for a content type to use that format 3) Override the field template to something like field--field\_date\_custom-content\_type.tpl

---
Tags: 7
---


# Question
Title: Views help from Advanced Help isn't being displayed or I can't find it
**It turns out that I actually hadn't installed Advanced Help on this Drupal setup and was only using regular 'Help'**

I'm using Views 7.x-3.5 (API version 3) and Drupal 7.17

I installed Advanced Help (some time ago now) and cleared all caches

When I go to /admin/help I see a list of the following...

```
Help topics

Help is available on the following items:

Administration menu
Advanced User Management
Block
CKEditor
Color
Comment
Content Access
Contextual links
Dashboard
Database logging

Date
Field
Field SQL storage
Field UI
File
Filter
Help
Image
List
Menu

Menu Block
Node
Number
Options
Path
Pathauto
RDF
Rules
Rules Forms Support
Search

System
Taxonomy
Text
ThemeKey
Token
Trigger
User
Webform

```

The following is constantly displayed in structure \> views

> If you install the advanced help module from http://drupal.org/project/advanced\_help, Views will provide more and better help. Hide this message.

# Answer
Install the advanced help module

> When this module is installed, users with the view advanced help index permission can access the advanced help index by going to Administer -\> Advanced Help (http://www.example.com/admin/advanced\_help). Additional view advanced help popup and view advanced help topic permissions enable them to access the actual help pages and popups.
> 1 votes

---
Tags: views
---


title: Single field output with Views

text:
# Question
Title: Single field output with Views
I am having a view of users, in that I have added a field "Status" which is from the core Drupal 7 to display the user which are "Active" or "Blocked".

What I am trying to achieve is that:

1. I should get a clickable link to the field value status, assuming if its "active" **Achived**, here I have just rewritted the output
```
"user/[uid]/edit?destination=admin/people"
```
checked with
```
Use absolute path
```
itself in the View.
2. When I click on it I should only get a page with only value of "Status" where I can change the status of the clicked user; here I am stuck, any idea how can I achieve this?

# Answer
> 0 votes
Have you tried using the Views Bulk Operations (VBO) module? This allows you to perform operations on entities from your actual View page.

I've never used it with Users before, but I've managed to use it to Publish / Unpublish nodes from my own custom View's page.

---
Tags: views, 7
---


# Question
Title: Is there a module or easy way to break up nodes into multiple pages?
Is there a module or easy way to break up nodes (ie blog posts) into multiple pages?

# Answer
> 5 votes
The paging module will help you with that

# Answer
> 3 votes
Yes, you can use the paging module or possibly other contributed modules but you did use blog posts as an example so just to be clear - you could use the core teaser system - which works like a wordpress read more and allows you to show the "teaser" on lists verses the full node when viewing it.

Here is a pretty informative article on how to use it, config etc.

Manually controlling the teaser break point

# Answer
> 1 votes
You can use Views to generate node list with pager.

---
Tags: paging
---


title: Create a bundle programmatically?

text:
# Question
Title: Create a bundle programmatically?
I've been trying to figure out this problem of allowing the user to dynamically create project request forms (add his own fields including drop downs, multiselects, etc...). The user needs a way to create multiple project request types (bundles, perhaps?), for different business units. I figured the entity / bundle relationship would be perfect for this. So here is my idea:

Use the Schema API to define my base table "project". Use the Entity API hook\_entity\_info() to tell Drupal about my new entity, pointing it to the "project" table. Now in this hook I can define bundles - which is great. But I need for the user to be able to create a bundle. Where is the entity\_create\_bundle($entity\_type, $bundle) call?

Example:

Entity TYPE: Project (with common fields defined in DB, and it is fieldable)

Bundle: IT Project, HR Project - which share the common fields from Project

A project\_type table will store additional grouping I need (project requests for business units).

Now I've been reading Drupal 7 Module Development which has been great, and in chapter 6 they define an entity "artwork" that has a couple of bundles, "sculpture" and "painting". The way they describe the steps, is as if they are building an admin interface to create additional artwork types, but this is not true (from what I can tell). After finishing the chapter, I can only create entities of type "painting" or "sculpture".

How can I allow users to create bundles of the "project" entity type?

Am I missing something or is the functionality not there \[yet\]?

# Answer
> 16 votes
**Examining the default Node bundles**

The Node module does not create the "Article" and "Basic page" Bundles itself. After some digging I found the definitions for these bundles in the standard install profile's install file.

*/profiles/standard/standard.install*

```
  // Insert default pre-defined node types into the database. For a complete
  // list of available node type attributes, refer to the node type API
  // documentation at: http://api.drupal.org/api/HEAD/function/hook_node_info.
  $types = array(
    array(
      'type' => 'page',
      'name' => st('Basic page'),
      'base' => 'node_content',
      'description' => st("Use <em>basic pages</em> for your static content, such as an 'About us' page."),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
    array(
      'type' => 'article',
      'name' => st('Article'),
      'base' => 'node_content',
      'description' => st('Use <em>articles</em> for time-sensitive content like news, press releases or blog posts.'),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
  );

  foreach ($types as $type) {
    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }

  // clear the site cache

```

**A few notes about this code**

1. It doesn't use Entity API
2. `st()` function should only be used during a Drupal installation process
3. Node contains a lot of non Field API fields that it handles in `node_type_save`
4. Node calls `field_attach_create_bundle` to tell Field modules about the new bundle

---

**Creating a bundle with the Entity API**

I'm not sure how you've defined your entities, but if you've used Entity API then your bundle-creation code might look something like this:

```
$bundle = new stdClass();
$bundle->type = 'project_hr';
$bundle->label = t('HR Project');
$bundle->is_new = true;
$bundle->description = t("A super cool project");

$controller = new ProjectTypeController('project_type'); //assuming you defined this extension of EntityAPIController
$controller->save($bundle);

```

---

**A note about Entities**

* An entity type is an abstract base class
* A bundle is an extended entity type class
* A field is a class member, property, variable or field instance
* An entity is an object or instance of a base or extended class

More about entities

# Answer
> 3 votes
I spent quite a while trying to figure this out. I am working on a project based on Model module (https://drupal.org/project/model). In my install script I wanted to create bundles. The code sample for the Entity API example in the "Examining the default Node bundles" answer is close but not quite right (well it wasn't for me).

The following snippet should work:

```
$bundles = field_info_bundles('project_type');

if (empty($bundles['project_hr'])) {
    $controller = new ProjectTypeController('project_type'); //assuming you defined this extension of EntityAPIController

    $params = array();
    $params['type'] = 'project_hr';
    $params['label'] = t('HR Project');
    $params['is_new'] = TRUE;
    $params['description'] = t('A super cool project.');

    $bundle = $controller->create($params);
    $controller->save($bundle);
}

```

The field\_info\_bundles checks to see if the bundle exists (so you don't try and create it twice). This gets info for the bundles created for the project\_type entity.

If the bundle does not exist then you can then go ahead and create the bundle.

First up, you create a controller, then you create a parameters array with the options for the bundle that you want to create. You then use the controller to create a bundle object (this creates a PHP object with all the "standard" entity fields and methods, and then adds your parameters to the object. Then you use the controller to save the bundle. This last part persists the bundle in the database.

I hope this helps.

# Answer
> 2 votes
I'm trying to do something like that, and it looks like the Node module contains already the code, as when you create a new type of content, it creates a new bundle for the node entity, and adds the "body" field to it by default (using the field API). All these operations and forms (table of bundles, CRUD of bundles and etc) is made by hand.

Thanks to the Drupal developers, you can copy the code contained in the Node module.

I think later I can publish my work as drupal module for visual creation of entities and it's hierarchy of bundles.

---
Tags: 7, entities
---


title: Drupal Slow loading times

text:
# Question
Title: Drupal Slow loading times
I'm currently having a Drupal 6 (because some modules are not available in Drupal 7) site running. But the loading time is very slow(www.hard-dance.org)

Here's what I've tried so far to eliminate possible reasons:

1. I have looked in my admin panel for problems, and did a cron job manually
2. I have checked to see if Clean-URLs was causing the site to slow down, it was not.
3. I've disabled some modules, but no change.

I also noticed that my website is going slow, **once logged in.**

Does anyone have an idea of what the cause of it could be?

# Answer
> 1 votes
Check size of files folder, heavy images may increase site loading time.

# Answer
> 0 votes
There are too many different factors which can contribute to a slow site to include in one answer.

What I did notice when viewing your site is that you're not using any cache'ing or CSS/JS aggregation. These should definately be configured as the very minimum starting point for performance.

# Answer
> 0 votes
1. Check the apache log. located at /var/logs/apache2/error.log
2. Check the all the processes using ps -e or ps -A to show all the processes

---
Tags: users, nodes
---


# Question
Title: Live filtering of nodes by taxonomy terms?
As part of a company website redesign, the designer I've partnered up with has come up with an interesting way of displaying projects and people using taxonomy. We're just trying to figure out how to implement it in Drupal 7:

We have project, and people, and a vocabulary describing specific skills and topics that are common to both. Each project and person has an associated node containing the relevant terms.

What we would like to have is a master display for each type: people and projects. Each master display will show all the terms in the vocabulary (this vocabulary will be kept very small), and all projects/people. However, when a user clicks on one of the terms, the display of relevant nodes will be filtered to show only the nodes containing that term.

We already have the code to handle the live filtering - if these were static HTML pages it would be simple. But considering that we are using Drupal for the site, it seems rather silly not to take advantage of having a database to query.

I've spent the last few hours scouring the web for anything that will let me accomplish this. Ideally I need something that will identify/expose the terms associated with the nodes... It seems Views is the likely answer, but I can't seem to place both the terms and the content type lists in the same view. This page from a related question here seems to come close, but I am not currently using Panels **and** I'm still new enough to Drupal that I have no idea how to use the hook referenced.

Hopefully I've explained this clearly enough, but let me know if I haven't. Thanks in advance!

# Answer
> 0 votes
What you're after is known as Faceted Search. You're able to drill down your Views results based on taxonomy terms (or other fields for that matter) as you described.

A good example of Faceted Search can be found within the Commerce Kickstart demo store.

You'll need the Search API module as a basis, and I found a really good tutorial on getting started with Faceted search here: http://vimeo.com/15556855

If you're setting up a site which will get a lot of traffic, you might want to consider using Apache Solr to take some stress off your database when performing search queries.

---
Tags: views, taxonomy-terms
---


title: theme_field() render array

text:
# Question
Title: theme_field() render array
I hoped the documentation for theme\_field() would tell me how to create a render array that may be parsed by that function.

Based on that, I thought something like this would work.

```
return array(
    'test' => array(
        '#theme' => 'field',
        '#label_hidden' =>  false,
        '#title_attributes' => 'class="test123"',
        '#label' => 'test',
        '#content_attributes' => 'class="test456"',
        '#items' => array()
    )
);

```

It prints a ` `.

what am I doing wrong?

The ultimate goal is of course printing some field\_items, but I can find no documentation on how the render array for #items should look; nothing I tried outputs anything.

A pointer to better documentation might answer my questions.

# Answer
> 2 votes
If you absolutely *need* to piggyback on `theme_field()` rather than implement your own theme function (which would be preferable IMHO), then you'll have to jump through a few more hoops.

The key place to look is `template_preprocess_field()`, which will show you all of the elements that are expected to be in the array. Specifically for the label, the `#title` property is used. So this

```
return array(
  'test' => array(
    '#theme'                => 'field',
    '#label_hidden'         =>  false,
    '#title_attributes'     => 'class="test123"',
    '#label'                => 'test',
    '#title' => 'test',  // Required
    '#label_display' => 'visible',  // Required
    '#content_attributes'   => 'class="test456"',
    '#items'    => array()
  )
);

```

will return what you're looking for (with a bunch of notices about undefined indicies).

Eventually you'll also need to provide `#field_name`, `#field_type`, `#bundle` and `#entity_type` for each of your 'field' items.

---
Tags: theming
---


# Question
Title: added files to module: use drush to upgrade to a new version of this module will added files be deleted?
A co-worker has added a couple of .css files to the quicktabs 3rd party module. What will happen if you use drush to upgrade to a new version of this module. Will these added files be deleted or kept as-is?

# Answer
If the css files are stored in the quicktabs module directory, yes they will be lost upon upgrade.
> 4 votes

---
Tags: drush
---


# Question
Title: Views block for content that is older than current node created date
How should I go about creating a view that only shows content that is older than the current node's creation date? I've created the argument using 'Content: created date' but I struggle to pass this over to the filter criteria.

To be honest, I'm not even sure this is the correct way to do it.

# Answer
> 0 votes
Managed to get this working with a Views PHP field:

```
<?php
global $base_path;

if (arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
  $node = node_load(arg(1));
  $a1 = format_date($node->created, 'custom', 'm/d/Y');
  $a2 = date("m/d/Y",strtotime("-2 months",strtotime($a1)));
  $a3 = format_date($row->created, 'custom', 'm/d/Y');

  $b1 = new DateTime($a1);
  $b2 = new DateTime($a2);
  $b3 = new DateTime($a3);

  if ($b3 >= $b2 && $b3 <= $b1) {
    print '<h2><a href="'. $base_path . 'node/' . $row->nid . '">' . $row->title . '</a></h2>' . $data->field_body[0]['rendered']['#markup'];
    //dsm($data);
  }
}
?>

```

# Answer
> 1 votes
You'll need to create a block which accepts the node created date as an argument. Then you'll need to set the condition to only show nodes which have a created date \< the argument value.

To pass on the node's created date as an argument, I think it's easiest just to embed the View block into the node's template using a PHP snippet. So you'll be looking at something along the lines of:

```
<?php print views_embed_view('my_view','my_block_machine_name', $node->created); ?>

```

You might have to check for the correct variable name for the created date of the node, but I think "created" is correct.

hope this helps!

---
Tags: views, datetime
---


# Question
Title: Giving a user the choice to appear offline in a view showing online users
I created a views block which displays users which are online. I would like to give a user a choice to be able to appear offline (i.e not be listed in the block) when he/she is online.

Thank you in anticipation.

# Answer
Assuming Drupal 7, you can go to `/admin/config/people/accounts/fields`, attach a Boolean field to user accounts to allow the user to select their preference, then filter on that user field in your view to exclude those who opt out.
> 3 votes

---
Tags: views
---


# Question
Title: Is the current faceted search effective for SEO?
Seems that the url generated by faceted items are not good for SEO (unfriendly to search engines) eg. I have a facet that transforms the url to this format : http://localhost/mysite/property-for-sale/residential-sale?f\[0\]=field\_property\_type%3A71

I don't know how i can make it more friendly to search engines as this is automatically generated by the faceted links...

any suggestions, is this possible with the current version of facet search apis?

# Answer
> 0 votes
There is a module for it: Facet API Pretty Paths. But I didn't try it yet.

Here is a quote about it (from the module's project page):

> Enables pretty paths for searches with Facet API. You will likely use this module in combination with either Search API or Apache Solr Search Integration.

---
Tags: 7, search, views
---


# Question
Title: How to retrieve Apache Solr's current search filters?
I'm using Apache Solr Search, Search API and Facet API.

Is there a way to retrieve the current search filters being used when using Apache Solr on Drupal?

For example: I have a website using facets which reference a taxonomy called colours. In this facet, there's a list of colours - if I select Green, this generates an Apache Solr search - using green as the filter.

`www.example-website.com/?f[0]=field_colour%3A2712.......etc`

When the Solr search is created - I guess, I could grab the term id `2712` from the URL using GET - but there must be a cleaner way.

Any ideas?

# Answer
> 0 votes
Sounds like you're writing a module to do this?

If so, if you're implementing something like the `apachesolr_query_alter(&$query)` hook or something like that, which gives you access to the search query, you can use

```
function [getFilters][1]($name = NULL)

```

Note that the `name` parameter is optional: Returns all filters matching `$name`, if set; otherwise, **returns all filters**.

# Answer
> 0 votes
I did it using FacetApiAdapter (see facetapi\_adapter\_load):

```
// Get an instance of FacetApiAdapter
$searcher = 'apachesolr@solr' // your apachesolr server id
$facetApiAdapter = facetapi_adapter_load($searcher);

```

Then if you need to work on active filters:

```
$activeItems = $facetApiAdapter->getAllActiveItems();
foreach ($activeItems as $item_key => $item) {
  $facet = facetapi_facet_load($item['field alias'], $searcher);
  ...

```

Or you can use other FacetApiAdapter methods.

---
Tags: 7, search
---


# Question
Title: What arguments should I pass to l() so that the generated link would open a new popup window?
I have made my custom module in Drupal. I have a link that should open a popup window.

What arguments should I pass to `l()` so that the generated link would open a new popup window?

# Answer
The link formatter function l() takes 3 arguments:

```
l($text, $path, array $options = array());

```

The $options array specifies the parameters to be passed to the link. One of them is `$options['attributes']` which is itself an array and is used to specify the attributes of the anchor tag.

Use something like:

```
$options['attributes'] = array( 'target' => '_blank' );

```

when you are assembling the parameters to pass. This will open the link in a new window., which is the closest you can get with HTML.

For a real pop-up, you will have to add javascript to do the job, and adding something like:

```
$options['attributes'] = array( 'class' => 'popup' );

```

will give the javascript a target to use.
> 2 votes

# Answer
Have you looked at the External Link module? AFAICT there's no parameter for `l()` or even for `url()` that specifies a new window, but External Link provides additional behaviors that can be configured for external links.
> 0 votes

# Answer
You can use many widget as Dialog or Lightbox

In this case you need to add the attribute to the array

```
l(t('Link text'), 'open popup', array('attributes' => array('class' => array('YOUR-CLASS'))));

```

But you can add all the attribute you want, like target so:

```
l(t('Link text'), 'open popup', array('attributes' => array('target' => '_blank', 'class' => array ('your classes'), 'another_attr' => 'attr_val'));

```
> 0 votes

---
Tags: 6
---


# Question
Title: How do I block a user/cancel a user account in Simpletest?
I'm trying to write some tests for a module for situations in which a user is blocked. I know I can use `drupalCreateUser()` to make new users, but how do I block a user I have created in Simpletest?

# Answer
Once you've got the user object back from `drupalCreateUser()` you can use standard API methods to make changes (in this case `user_save()`):

```
user_save($user, array('status' => 0));

```
> 1 votes

---
Tags: testing
---


title: Detecting user site visits

text:
# Question
Title: Detecting user site visits
I some working code in `hook_user_login()` that awards 5 points to users for each day they log into the site. If they log in twice in one day, points are not awarded the second time.

Originally, I thought users would login each time they visit the site but since users stay logged in between visits, they are not getting points for visiting once per day. For example, if they log in today, they get 5 points but tomorrow and each day they visit thereafter, they don't receive any.

I would like users to be awarded for each day they visit the site whether they need to log in or not. I wasn't able to find another hook that could do it. Does anyone know of one or some other method of tracking user visits?

# Answer
> 4 votes
You could store the last updated timestamp in the session on login, and then check it on each page load to see if it's within your parameters:

```
function MYMODULE_init() {
  // Only proceed if there's a timestamp in the session. Otherwise defer to
  // hook_user_login() to take care of setting that.
  if (user_is_logged_in() && isset($_SESSION['MYMODULE_point_check_timestamp']) {
    // If the timestamp is more than 24 hours ago, award more points.
    if (REQUEST_TIME - $_SESSION['MYMODULE_point_check_timestamp'] > (60 * 60 * 24)) {
      award_points();
    }
  }
}

function MYMODULE_user_login(&$edit, $account) {
  award_points();

  // Track the time points were awarded.
  $_SESSION['MYMODULE_point_check_timestamp'] = REQUEST_TIME;
}

function MYMODULE_user_logout($account) {
  // Clean up.
  if (isset($_SESSION['MYMODULE_point_check_timestamp'])) {
    unset($_SESSION['MYMODULE_point_check_timestamp']);
  }
}

```

---
Tags: 7, hooks
---


title: Add taxonomy terms into submenu

text:
# Question
Title: Add taxonomy terms into submenu
I'm currently using drupal 7. I want to create an album gallery with different category. I wish to put "Albums" in the main menu, with the categories as sub menu under "Albums".

I had created a content type "Album", and plan to use taxonomy to creating vocabulary and terms as category.

However, I wish to make it automated. Once I create a album category, it will automatically appear in the sub menu under "albums". And each category will link to the list of albums under the category.

Anyone knows how to achieve the effect?

# Answer
For an action that is caused by an event I would use the Rules module.

Create new rule

Set rule name, etc.

Set event to act on - saving new term

Set a condition - term is in vocabulary album

Set action - add menu item

These options may not all appear with just Rules. You may need additional rules modules to get some of these events, conditions, or actions to be available (I think there is one for menus and one for taxonomy, but they may be built in to rules i can't remember.).

Take what I said as a starting point to put you in the right direction. Definitely sounds like what you want can be done with Rules.
> 2 votes

# Answer
it seams you need custom module, try rebuild menu on taxonomy term CRUD operations,

create new module and implement this hooks:
> 1 votes

---
Tags: views, taxonomy-terms, routes
---


# Question
Title: Is there a way to display the product image as a radio button instead of a select box when selecting a product in a product display?
Currently im setting up my Commerce and I want to be able to replace the default select box on the product display. This select box only comes up when there are multiple products referenced. I want each option in that select box as the **Product's Image Field**. Yes I can use the radio button, but you can only output the title of the product in the radio selection box.

**Currently I'm only getting this when i select radio button as the formatter**

##

**My end goal is this:**

# Answer
> 0 votes
If you use a taxonomy term reference field as your product attribute field to define the various options there, you could add an image field to the terms where you could upload the related image. Then using the Commerce Fancy Attributes module, you could choose to display those images instead of a radio button list. It requires some additional configuration, but you can see a quick example of this in action inside Commerce Kickstart 2.x.

# Answer
> 1 votes
You could do this through jQuery easily. All you do is add your own jQuery file through your theme info file:

https://drupal.org/node/171213

Then write some jQuery that adds a css class to the label when the page loads up and handles the clicking of the checkboxes/radios like:

```
(window).load(function() {
var myImageButton1_label = $('#some_drupal_label_ID');
var myImageButton1 = $('#some_drupal_checkbox_ID');
myImageButton1_label.addClass("button1_off");
myImageButton1.attr({'checked' : false});

myImageButton1_label.click(function(event){

if (myImageButton1.attr({'checked' : true})) {
myImageButton1_label.removeClass("button1_on").addClass("button1_off");
myImageButton1.attr({'checked' : false});
}

else {
myImageButton1_label.removeClass("button1_off").addClass("button1_on");
myImageButton1.attr({'checked' : true});
 }

});

```

Then hide the actual radio button with CSS and style your label to be an image. Then jQuery will handle the switching of classes and checking those radio buttons for you. Note this is a simplified example so you'll need to expand upon this for your needs. This an older article, but appears to be relevant: http://tutorialzine.com/2011/03/better-check-boxes-jquery-css/

---
Tags: 7, commerce
---


# Question
Title: In Drupal Commerce, on what page does this order status fire? When an order is first paid in full
I'm currently setting up my Drupal Commerce checkout Rules and came across that you have setup your own Paid Status on payment sucess. By default Drupal Commerce only updates the status to PENDING.

What I need to know on what page does the following Rule Event get fired?

> **When an order is first paid in full**

# Answer
This event is triggered on whatever page request results in the named event - an order first being considered paid in full. This means it's going to vary based on the payment method. Sometimes a transaction is completed as part of a checkout form submission. Sometimes it happens while the customer is on a third party payment gateway page. Sometimes it happens after the fact when an administrator captures an authorization created during the checkout process.

When a payment transaction is saved, however it happens, Drupal Commerce compares the total of all payment transaction amounts for an order against the order total to determine whether or not the order has now been paid in full. If so, it triggers this event and updates the order to prevent the event from being triggered again - hence the "first" part of the event name.
> 1 votes

---
Tags: 7, commerce, rules
---


# Question
Title: In Drupal Commerce - Rules configuration. What is the default operator in the conditions section?
I'm setting up Drupal Commerce in the checkout Rules section. But this question also applies to any Rules.

Currently I have 3 conditions in my rule set. By default what is the default operator in this section? Is it an **OR** or **AND**? I see you can add these in manually, but it would be good to know what they are by default.

> Data comparison
>
> Entity exists by property
>
> Data comparison

# Answer
If you're confused as to how a specific rule is being evaluated by Drupal, you should enable the debug display for Rules. You can do so here: /admin/config/workflow/rules/settings

I find this helps a ton when trying to understand the eventual outcome of a Rule, and will show you an audit trail of how each condition was evaluated.
> 1 votes

# Answer
AND

And here's some filler text to get me over the 30 character minimum.
> 3 votes

---
Tags: 7, commerce, rules
---


# Question
Title: Display all associated tags from content page
I have found many similar questions, but not quite the right way around. I have a large number of tags that are associated with multiple content pages. When viewing these content pages you can only see the parent term, and not its children terms, which are equally as important. How can I display the entire list of terms, and not just the parent term in a content view?

# Answer
If you are using D7 then check this lovely module for displaying child terms after rendering. Taxonomy display child terms.

You can look into Taxonomy Display module too.
> 0 votes

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


title: Preprocess functions and template files

text:
# Question
Title: Preprocess functions and template files
Are there any issues I should know about using a pre/process function and, simultaneously, a template file?

For example, I have some logic I would like to apply to a field and at the same time, I would also like to customize the HTML output for that field as well.

Can I create a pre/process function and create a template file specific for that field?

# Answer
Before answering YES/NO, let me make the context clear:

The .tpl.php files live near the city gates and are ready to produce code for the rest of the world. Moving towards the core of the city (our Drupal site) there is a very strong file: template.php. This file supports .tpl.php by providing new variables, changing variables, getting the HTML ready for pieces of our site and more.

Inside template.php there are 4 categories of things one can do:

* write **preprocess functions**, like `MYTHEME_preprocess_page(&$variables)` or `MYTHEME_preprocess_node(&$variables)`. With the aid of preprocess functions we can **add or alter variables inside tpl.php** files. Our **main weapon: kpr($variables)** or dpm($variables) provided by the devel module.
* write **theme functions** like `MYTHEME_links($variables)` or `MYTHEME_breadcrumb($variables)`. Through theme functions we **change the HTML output** of some chunks of our site, like the breadcrumb. **Main weapon: devel themer**. (We check which theme function is responsible for the HTML output and override that one)
* **preprocess functions for theme functions**. We manage to **change a variable used in a theme function**. For example, MYTHEME\_preprocess\_username(&$variables) prepares the variables for the theme\_username(). We could put the code directly inside the corresponding theme functions, but then we would probably have a mess. (anyway, that's the idea behind the separation of the code here, and is not obligatory). **Main weapon: kpr() or dpm()**
* implement **hook functions**. There are 4 hook functions available for template.php:

```
hook_css_alter
hook_js_alter
hook_page_alter
hook_form_alter

```

The first two change the css/js files loaded on a site (the one's we see as @import blah blah when we view the source code, and we can tell Drupal not to load a file (even if it a default module.css or anything else)

The third is used to change things around, regarding the whole page element of Drupal. So for example, we can move things around, from a node of the main content to the second block of the sidebar, etc

With the last one we can change variables inside any form in Drupal. Main methodology: call debug($form\_id) to take the unique id of the form you want to play with then target this form by `if ($form_id == blabla)`, then call dpm($form) or debug($form) to see what's inside the specific form and alter variables, etc.

And YES, of course you can use both a preprocess function AND a specific .tpl.php for example:

```
function MYTHEME_preprocess_node(&$variables){
if ($variables['type'] == 'article')
$variables['blabla'] = .. // creates a variable to be used in node.tpl.php
}

```

then create node--article.tpl.php and print that $blabla there
> 14 votes

# Answer
It is absolutely OK to have both pre/process functions in your template.php file and a template file for that content type (or even field) in addition to that.

Typically, the best practice in Drupal is the following:

* Use your template files to specify the HTML and layout for your content types and fields. Most template files do indeed have PHP in them, but that should be light and primarily for some small if/else logic. There is a strong tendency to try to separate **form from function**.
* If you find yourself doing complicated PHP logic in your template files, that's your cue to move things to your template.php file. Do heavy calculations in preprocessing functions here. Keep your template files clean and easy to read. The preprocessing functions are the ones that should do the heavy lifting in getting your variables all good and ready to go. Once they are all prepped, the preprocessing functions pass them on all ready to be displayed to the appropriate template file, which should then apply the necessary HTML.
> 9 votes

---
Tags: theming
---


# Question
Title: How can you price attribute options in drupal commerce properly?
Currently I am creating a site for a repair shop. Say I am repairing a laptop motherboard:

Motherboard Repair = $100

As with a motherboard repair, it could consist of a power slot repair, cpu replacement, memory replacement, or video card replacement. I charge $100 for any of those repairs, but I consider them as a Motherboard repair. I want to create a page where they can select one of those, but not create a SKU for it. How can this be done?

In Ubercart, it would just be 1 product and 1 attribute with those 4 options. Since they aren't tangible products they don't need an SKU. Its more of a reference for the business owner to know what to repair which is selected by the customer on checkout.

Now say if I did have varying prices for each of those options. How can that be done too?

# Answer
The core way to do this is through fields on the product line item type used to generate the Add to Cart form. This is facilitated through the Commerce Customizable Products module, which allows you to create any number of product line item types so you can use different line item fields for different products / product types. Fields added to the line item type can be included in the Add to Cart form, and then their values can be inspected by your product pricing rules to alter the price of the line item accordingly.
> 1 votes

# Answer
As per your requirement you want to give option to the user to select one from many option from your given list while purchasing the product, but you don't want to create separate SKU for each of them. I think Commerce Option module will work for you in this case...I hope it help...Good Luck :)
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Prevent the loss of EXIF using imageCache does not work
I want to limit image dimensions on upload, but obviously the exif information gets lost then. I am using the imagecache actions module resp. the imagecache autorotate, which actually works fine when I don't restrict image dimensions on file upload.

How do I set a maximum image resolution on upload and keep the exif so that imagecache can rotate images afterwards?

# Answer
Drupal (7 by itself, 6 via ImageCache) uses GD library. GD cannot handle EXIF, so if EXIF are ever kept during operations, it's more by accident than by design. If you need to keep EXIF, either avoid any processing based on GD (and that means any Drupal and ImageCache provided operations, both in Drupal 6 and 7), or save EXIF to text field on first upload, for example with EXIF Custom, and then add it back on download.
> 3 votes

# Answer
Use ImageMagick as toolkit or do the resize as part of the image style (thus not on upload) and after the autorotate effect.
> 3 votes

---
Tags: media
---


# Question
Title: How do I retrieve un-submitted values from a form and pass to another module?
I have created a custom module called trim\_users. What the module does is to alter the (menu) page callback of the user references module to execute a modified (by me) function of the user references module. The modification I've made is simple: I've altered a database query so that the users returned into my forms' autocomplete field is a trimmed down list of my users. I've joined on a 'user.team' field and I'm saying give me all the users where the team is 'x' and 'y'. So first the user enters the two teams into my form: team 'x' and 'y'. Then the user goes to enter a user. After the first character is input I want my trimmed list of users to drop-down in the autocomplete field.

I'm stuck on one bit: how do I send the values of team 'x' and 'y' sitting in my (as of yet unsubmitted) form so that the database query, in my trim\_users module, can populate the condition clause with these two values?

Do I need to add an AJAX property to my form elements: 'enter team 1' and 'enter team 2' so that on change a function is called and the entered values made available to my trim\_users module?

Thanks. Hope I explained that okay.

# Answer
First, you shouldn't have to modify the page callback from the user references module. Instead, use `hook_form_alter()` (or `hook_form_FORM_ID_alter()`) to change the `#autocomlete_path` attribute of the user reference text box to point to you're callback instead. That way you aren't modifying the module's stuff and you have the option of using the default implementation somewhere else. This is generally a better option than modifying another module's menu items.

For your particular use case, you'll do what you actually suggested; use the AJAX properties on the team fields to make the information available to the autocomplete callback. In practice it's slightly more complex than that, but you've already got the right idea. There's an article on Active LAMP that does pretty much the same thing.

First let's see about your custom autocomplete callback. You need to know which teams (Team X and Team Y as you put it) to filter by and what string to search for. In the following code, you first create a menu item for your callback, then define the actual autocomplete callback. The menu item uses two wild cards in the path to provide the ids for Team X and Team Y to the callback. You do not need to specify a wildcard for the search string, Drupal will handle that for you. In your callback, use the id information to narrow your user query results.

```
function trim_users_menu() {
  $item['trim-users/autocomplete/%/%'] = array(
    'page callback' => 'trim_users_autocomplete_callback',
    'page arguments' => array(2, 3),
    'type' => MENU_CALLBACK,
  );
  return $item;
}

function trim_users_autocomplete_callback($x, $y, $string) {
  // Here, use the query you altered for finding the correct users.
  $query = <youre altered query>;
  // Now, return the available User options.
  // Taken from user_reference_autocomlete, minus the hyperlink removal.
  $matches = array();
  foreach ($query->fetchAll() as $row) {
    $matches[$row['title'] . " [uid:$id]"] = '<div class="reference-autocomplete">' . $suggestion . '</div>';
  }

  // return for JS
  drupal_json_output($matches);
}

```

Now you need to alter the form to make the user reference field use this custom autocomplete callback. The url you use for the user reference field's `#autocomplete_path` will follow the pattern of the menu item you create. Suppose you want to filter the users to Team X, with id `1`, and Team Y, with id `2`. You're path will be `trim-users/autocomplete/1/2`. To get team ids for the path, you use `#ajax['callback']` settings on the Team fields to respond to change events. For example, set the `#ajax['callback']` property to `trim_users_team_selected`. When the Team field value changes, Drupal will rebuild the form then run your `#ajax['callback'] to update the form on the client. So, in`hook\_form\_alter()\`, check if the team fields have a value, and if they do use it to build the autocomplete callback path you assign to the user reference field.

```
function trim_users_form_alter(&$form, &$form_state) {
  // Check if it's the correct form, or use hook_form_FORM_ID_alter instead.
  ...

  // Check the $form_state to see if there's a value for the Team fields
  if (isset($form_state['input']['field_name']['#value']) {
    // Get the value of the field and use it in the autocomplete callback path
    ...
  }
  ...
}

// Return the User Reference field element from the rebuilt form. This will
// replace the existing field element on the client.
function trim_users_team_selected($form, $form_state) {
  return $form['user_reference_field'];
}

```

There's a few other things you have to do, like set the `#ajax['wrapper']` property, but that's all part of using `#ajax['callback']` so I'm not going to get into that here. This should at least get you on your way, you just need to figure out the specifics of retrieving and setting the form field values.
> 0 votes

---
Tags: ajax, users
---


# Question
Title: Is it possible to display a Boolean field in a block using views?
Using views,

1. I created a block that displays users that are online.
2. In order to allow users choose to appear online or offline, I added a Boolean field to the user account, which I subsequently used as a filter for the online users. All this works fine.

Now I need to find a way to have a form - (with the Boolean field as its only field) appear as an 'attachment' to the original block? In this way users can choose to appear offline without having to go to their user account page.

Please, is this possible using views,thanks.

# Answer
> 0 votes
Would a button do?

To do this you have to create a custom module, or add to an existing custom module.

First define your form. All you need is a submit button, and the value can be any label you want on the button.

```
function modulename_onlinevisibility_form( $form, &$form_state) {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Change my on-line visibility'),
  )
}

```

Then you need a submit handler for the form:

```
function modulename_onlinevisibility_form_submit(&$form_state) {
  global $user;
  $account = user_load($user->uid);
  $account->field_optout[LANGUAGE_NONE][0]['value'] =
    (isset($account->field_optout[LANGUAGE_NONE][0]['value'])
      && ($account->field_optout[LANGUAGE_NONE][0]['value'] == 1))
      ? 0 : 1;
  user_save($account);
}

```

This will switch the value of the boolean field turning it off if on and visa versa, for the logged in user. (Profile fields may not be included in the $user variable, so a full user object is loaded using user\_load.)

Then in your view, add a footer using the Global: PHP type, and add the code:

```
<?php
print render(drupal_get_form('modulename_onlinevisibility_form'));
?>

```

This will place a button at the bottom of your view which will toggle the user's on-line visibility.

EDIT.

If you are using the Profile2 module, then the code for the submit handler should be changed to:

```
function modulename_onlinevisibility_form_submit(&$form_state) {
  global $user;
  $profile_type = 'main'; // substitute the machine name of the profile if you are not using the default
  $profile = profile2_load_by_user( $user, $profile_type);

  $profile->field_optout[LANGUAGE_NONE][0]['value'] =
    (isset($profile->field_optout[LANGUAGE_NONE][0]['value'])
      && ($profile->field_optout[LANGUAGE_NONE][0]['value'] == 1))
      ? 0 : 1;
  profile2_save($profile);
}

```

Profile2 profiles are not loaded by user\_load.

---
Tags: views
---


title: Remove tax line item on checkout page

text:
# Question
Title: Remove tax line item on checkout page
I have installed the \*commerce\_kickstart\* install profile, and I am wanting to remove the Tax line item on the checkout page, and instead have some text instead that says VAT included (or in my Australia case, GST included).

Everything works well and as expected; however, my client would like to remove the line item for the VAT subtotal and just include text somewhere that says "All prices and totals are inclusive of VAT".

# Answer
Might be a bit late on this one, but there doesn't seem to be a posted solution online. You can remove the tax line using the below.

In your template.php file use the below, this should hide it from your order confirmation email as well. I haven't noticed any problems from this modification, but ymmv. The variation from the standard code is: $rows = array\_splice($rows, 2);

```
function THEME_commerce_price_formatted_components($variables) {
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');

  // Build table rows out of the components.
  $rows = array();

  foreach ($variables['components'] as $name => $component) {
    $rows[] = array(
      'data' => array(
        array(
          'data' => $component['title'],
          'class' => array('component-title'),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total'),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }

  $rows = array_splice($rows, 2);

  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}

```
> 3 votes

# Answer
Are your prices already inclusive of tax? If so, I'm fairly sure you just need to make sure there aren't any tax rates defined in Store \> Configuration \> Taxes then no taxes will be applied.
> 2 votes

---
Tags: commerce
---


title: How do I need to configure SMTP Auth?

text:
# Question
Title: How do I need to configure SMTP Auth?
I have dedicated FreeBSD box, The email sending **without** smtp module is working perfectly but very slow. The receiver receives email after almost 15 mins. I checked the `maillog` it says `delays` and `timeouts` that means the server keeps on trying to send email again and again until it successfully sends one. This is consuming lots of CPU.

I am seeking help for configuring `smpt module` to use my dedicated box's `smtp server`,
I need help in following places where I have `????` sign:

```
#SMTP server settings
SMTP server -> smpt.mydomain.com  # Tested by pinging, its working
SMTP backup server -> mail.mydomain.com  # Also verified by Ping
SMTP port -> 25
USE SSL

#SMTP Authentication
Username -> ???????
Password -> ???????

```

I tried using `localhost`, also username and password of the dedicated box or leaving both lines blank which gives me:

> Unable to send e-mail. Contact the site administrator if the problem persists.

also checking the `debug log` doesn't show any log, it says check `admin/reports/dblog` but when I got to the link it just shows me the contents from `admin/reports` no any `dblog`

# Answer
It wasn't so difficult to use my hosting providers smtp, instead of having my own. What I did is:

```
#SMTP server settings
SMTP server -> smpt.myhostingprovider.com
SMTP backup server -> mail.myhostingprovider.com
SMTP port -> 25
USE SSL

#SMTP Authentication
Username -> my-email@myhostingprovider.com
Password -> my email's password

```

Now, it is working perfectly, no delays !!!
> 0 votes

# Answer
Most providers block smtp ports, I had to use a mail redirection service when I set this up.

If the message gets through after 15 minutes though, I suspect you have a mail server misconfiguration. Nowadays, I usually go for a much simpler approach, I use google's smtp server to send the emails.

An easy way you can test if port 25 is blocked is by connecting by SSH to a remote server, then trying to telnet on local server port 25.

```
telnet mail.port25.com 25

```

If the port is open, you should get a response similar to this:

```
Trying 69.63.149.30...
Connected to mail.port25.com (69.63.149.30).
Escape character is '^]'.
220 mail.port25.com (PowerMTA(TM) v4.0) ESMTP service ready

```

Another thing to check, if you are using qmail make sure the trigger file has proper permissions. `qmail/queue/lock/trigger` should be `prw--w--w qmails:qmail`.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: One Drupal site affecting another cloned site
I have a weird situation with cloned site, I have copied the entire content from a production server, and made a different directory for testing environment. The steps I did to clone a site is:

1. Copied all the contents from the main folder /www/d7/ to new folder /www/test/
2. Made a separate server config in nginx to browse the content from browser
3. Original site can be browsed via http://d7.example.com and the copied site can be browsed via http://test.example.com, the nginx have separate logs for both
4. Dumped the original database after flushing drupal cache, created new database called 'test', with new username 'test' and new password 'test', imported the dumped database to new database 'test'.
5. Changed the database connection parameter in the file `/www/test/sites/default/settings.php` to accumulate newly created database.

Now, when I put the production site in offline mode, the test site also goes to offline mode, how come this is possible ? The most weird thing is if I put the site to online mode from test site, the production site also goes to online mode. I even tried creating new database, new database user and changing the `settings.php` still same issue.

I tried installing different modules to different sites, and the installed modules shows in their respective sites.

Can anyone tell me what's going on here ?

**Update with Answer:**

As Clive commented below, I changed the memcached\_storage settings in `settings.php` file to `$conf['memcache_storage_key_prefix'] = 'test_site';` and I don't have any issues now.

# Answer
As beth, said in the comment, I am answering this, even after updating the question with answer.

The culprit was Memcached bin, since I am using memcahce\_storage module for memcached, the bins of the main site and test site were same, hence, creating this confusion.

I edited the `settings.php` page of test site and changed the prefix for memcached for test-site as `$conf['memcache_storage_key_prefix'] = 'test_site';`, now everything is perfect !!!
> 2 votes

---
Tags: 7, migrations
---


# Question
Title: Use 2 different font sizes on combobox form elements
In a form combobox, is it possible to have each combo box element have 2 different font sizes?

Blue (like the sky)
Yellow (like the sun)
Green (like the mix of the above)

The color names would display using a 16px font. The text in parentheses would display using a 11px font.

# Answer
If it's possible in HTML & CSS flavour you are using, it is. There are two ways:

* Purely CSS one, described at w3schools and not really belonging to this site as it's Drupal independent.
* Class way - to get more flexibility and compatibility, add classes to your `<option>` tags inside your `<select>`. You can do this implementing theme\_select() in your theme. You would need to replace form\_select\_options() with your own function providing similar functionality, or parse original one's output to add your classes.
> 0 votes

---
Tags: theming
---


# Question
Title: Let users access account before confirming email address
I'd like to let users access their account without confirming email address. But still send the email confirmation. Then I'll display a message saying that if email is not confirmed within 3 days, account will be deleted. How can I do this in drupal 7 ? Is there any module that can help me do this, or if I need to do it in my custom module, please give me a hint about how can this be done ? Thank you.

# Answer
You can do this by help of LoginToboggan module. There are so many features of this module, immediate login is one of them.
> 5 votes

---
Tags: emails, users
---


# Question
Title: combine several exposed filters into one exposed (search) form?
Is there an easy way to combine two or more exposed filters into one shared exposed form? So that I don't have to have several search fields for each and every field that I want to filter.

Is this possible? Any modules that does this? I am using the Better Exposed Filters module.

Thanks in advance

# Answer
Views 3 provides solution for your question from the box. It's `Global: Combine fields` filter.

1. Add fields.
2. Add `Global: Combine fields filter` to filter criteria.
3. Check fields you want to combine in filter's settings.

If you use Display suite or teasers mode - force using fields in the View settings (under Format -\> Settings).
> 15 votes

# Answer
We accomplished this using Views filters populate

> This is an utility module. Its sole purpose is to fill in one blank that seems not easy to be done using normal views, which is to use one exposed string filter to search on multiple fields.
> 2 votes

# Answer
The search module packaged with core allows you to add a filter called "Search" which queries a users input against the search index. I have found this to be effective in similar situations.
> 1 votes

---
Tags: views
---


title: Views PHP filter criteria not working

text:
# Question
Title: Views PHP filter criteria not working
Why would this not work as a Views PHP filter criteria?

```
if (arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
  $node = node_load(arg(1));
  $a1 = format_date($node->created, 'custom', 'm/d/Y');
  $a2 = date('m/d/Y',strtotime('-2 months',strtotime($a1)));
  $a3 = format_date($row->created, 'custom', 'm/d/Y');

  $b1 = new DateTime($a1);
  $b2 = new DateTime($a2);
  $b3 = new DateTime($a3);

  if ($b3 < $b2) {
    return TRUE;
  }
}

```

The code should remove rows that are older than the current node except it doesn't?!

# Answer
It will remove the rows, when you return `FALSE`:

```
if (arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
  $node = node_load(arg(1));
  $a1 = format_date($node->created, 'custom', 'm/d/Y');
  $a2 = date('m/d/Y',strtotime('-2 months',strtotime($a1)));
  $a3 = format_date($row->created, 'custom', 'm/d/Y');

  $b1 = new DateTime($a1);
  $b2 = new DateTime($a2);
  $b3 = new DateTime($a3);

  if ($b3 >= $b2 && $b3 <= $b1) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

```
> 1 votes

---
Tags: 7, views
---


title: Debugging Imagecache related module

text:
# Question
Title: Debugging Imagecache related module
I'm trying to create a custom module that builds on top of imagecache and imagecache\_actions to dynamically add an overlay to image thumbnails based on fields of the node its attached to.

I used hook\_image\_default\_styles and hook\_image\_effect\_info with a callback to my custom effect function. I have it working under most circumstances, but I have a bug thats causing it to fail under some specific circumstances.

The problem I'm having is that there is no way to debug it. Normally for debugging, I run eclipse with zend debugger to set breakpoints and step through lines of code.

I've set breakpoints for the above functions. Cleared the existing files from the style directory, and loaded the page in the debug mode. All my other breakpoints will get hit, but for some reason its able to generate the image without hitting those breakpoints. I know its being called because (1) the image with overlay is being generated properly, and (2) every once in a while it was hitting the breakpoints - but not consistently, and now, not at all.

Does anyone who is familiar with imagecache know how this might be happening? Maybe it is somehow generating the images in a different php request than the standard page load?

Does anyone who uses a debugger know why this might occur, or has anyone seen this behavior before?

# Answer
It seems you are connected to page rendering process. Images are created with separate php calls, one for each image. If you want to connect to image generation call, disable retrieving images in your browser, load HTML, get image url with safety token and hit it directly, debugging.
> 0 votes

---
Tags: media, debugging
---


# Question
Title: Menu elements not being links, just to create submenu?
Is there a built in or module way to add menu items with hook\_menu to serve as containers, not links? I have a module set. Main module provides central configuration and satellite modules do actual work. main module should create submenu satellite modules will use to add their entries to, but there is no form nor page to put in the main element. Is there a way to avoid dummy content?

I want to avoid editing template.php \- I use theme downloaded from drupal.org and I don't feel creating a subtheme to get that is really worth the effort - there should be an easier way, shouldn't it?

I know there are ways to do this with Menu UI, but I need it to work out of the box for my clients, so UI is not an answer.

# Answer
I'm not sure how you'd get exactly that to work with the way Drupal's menus are structured.

Core provides a barebones page callback for handling the same sort of situation itself, the `system_admin_menu_block_page()` function. All it does for the page display is list the menu items that are underneath it in the hierarchy (like the `node/add` page). Think of it as a landing page for a menu item that doesn't need any other form/page data.

I believe if there are no sub-items under the parent, the menu link won't actually be displayed so that method should get you pretty close.

```
$items['admin/something'] = array(
  'title' => 'Something',
  'access arguments' => array('some permission'),
  'page callback' => 'system_admin_menu_block_page',
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

```

Then your other module can define paths like 'admin/something/something-else' and they'll appear underneath the parent
> 1 votes

---
Tags: 7, routes
---


# Question
Title: How do I integrate a nodes edit form on a page?
I would like to integrate a nodes edit form on a page. For example, I want to alter the node with ID id equal to 1.
I know there are a lot of ways to achieve this, but I can imagine there is only one right way.

I am having some troubles with my form. After certain time, the edit form shows values from different nodes: some from this, some from the other, etc. I really don't know why.

# Answer
> 3 votes
Use `drupal_get_form(NODETYPE . '_node_form', NODEOBJECT);` as callback in your custom menu item.
The original node module callback for menu item 'node/%node/edit' is located in the node.pages.inc file:

```
/**
 * Menu callback; presents the node editing form.
 */
function node_page_edit($node) {
  $type_name = node_type_get_name($node);
  drupal_set_title(t('<em>Edit @type</em> @title', array('@type' => $type_name, '@title' => $node->title)), PASS_THROUGH);
  return drupal_get_form($node->type . '_node_form', $node);
}

```

---
Tags: nodes, forms
---


# Question
Title: Content Types in Select list using views
How do I put all my content types into a select list so when users select a content type, they are taking to a page which makes them add new node to the content type?

# Answer
I think You can create exposed filter **Content: Type** which will give users the ability to select content type.

Then in *Fields* section add field **Content: Type**, select "Output this field as a link" and type: node/add/\[type\].

If You want to display only one "add" link per content type select "Exclude from display", go to **Format** settings and select "Content: Type" from **Grouping field Nr.1**'s options.
> 1 votes

# Answer
Why would you use views? Simply use node\_types\_get\_names() to fill a select list on a form or pass items on a page as a themed list.
> 0 votes

---
Tags: nodes
---


title: User reference (Profile2) with Views

text:
# Question
Title: User reference (Profile2) with Views
I have a D7 site where users are linked to other users (by References). User profiles are extended using the Profile 2 module and by so, containing some additional fields (phone, email,...).

I want to create a landing page where logged in users can see the info of the connected profile. So a logged in user should see the name, phone and email of the linked account.

I've been trying around for a while, but not able to close this issue.
It's not a matter of permissions, since the direct URL (`/profile-representative/16`) is accessible by the logged in user. On that page, he can see all the info. It's that info (phone, email,...) I want to get into Views.
But for some reason, it cannot be done by using relationships. At least not by me.

Is there anyone with experience concerning this matter?

# Answer
> 1 votes
I managed to fix this issue with a combinations of a relationship and a custom formatter.

First, in a (User) view, I created a contextual filter with `User: Uid`. Of course, no contextual filter will be given at the page, so I provided the default value *User ID from logged in user*.

Then, I created two relationships. The first one `User: Profile`and the second one `Profile: [your custom name]`. The second relationship is created with the first one as relationship.

Next, in my *Fields* section of my view, I added a Profile field and gave it a custom formatter. By using this custom formatter, I was able to display all the needed data.

If someone is interested in more code, please let me know!

---
Tags: 7, views, users
---


# Question
Title: How do I calculate outstanding balance for product inventory?
I have two content types, **Product In** and **Product Out**. Content types **Product In** has the *title* as *Product Code*, and a field as *Model*. The content type **Product Out** has a node reference (*Product Code*) to **Product In**, and a field as *Customer Name*.

I have a view, Product Inventory, with aggregation on. I have two fields:

* *Total Product In* (By counting Content types **Product In**'s title)
* *Total Product Out* (By counting Content types **Product Out**'s title)

How can I get the outstanding balance which I have inside my inventory?

# Answer
Balance Tracker creates a balance sheet to display account credits and debits belonging to users. It can be integrated with views.

> It also provides UI tools, Views integration, and an API to allow the site administrators or other modules to credit or debit a user's account. This is intended for any website or service which credits users for accounts, sales, or other activities, and needs to track payouts.

I'm not using this before. Hope it helps you!!!
> 0 votes

---
Tags: views
---


# Question
Title: Replacing display page with views in template.php
since yesterday I can not solve the problem with function preprocess\_views\_view: In the views named 'Calendar' I have a few display page(page\_classic, page\_mobile) and I would like to change preprocess\_views\_view function in mobile version of the site, which replace default display page(page\_classic) with page\_mobile. Below function, does not work:(

```
function mobiletheme_preprocess_views_view(&$vars){
    dpm($vars);
    $view = views_get_view('calendar');
    if($view->name=='calendar'){
        $display_id = 'page_mobile';
        $view->current_display = $display_id;
    }
}

```

Any ideas?

# Answer
Views' hooks are called whenever a View is called, yet you are calling the creation of the View once again inside of it, and then trying to change *that* View, not the original one.

Instead, you should be doing something along the lines of...

```
function mobiletheme_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  switch ($name) {

     case 'calendar':

       // process it here, eg change/add $vars['foo']
       break;

     // other Views here

  }

}

```

Now, that, changing template variables, doesn't appear to be what you want to be doing, so you will have to look into some of the other Views hooks, most probably views\_pre\_view to change the display, eg, something like...

```
function mobiletheme_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='calendar' && display_id=='page_classic') {
    $view->set_display('page_mobile');
  }

}

```

Addition/Caveat: This appears to have to be called from a module, not a theme (at least in D6), so you may need something like this...

```
function mobilemodule_views_pre_view(&$view, &$display_id, &$args) {
  global $theme;

  if ($theme=='mobiletheme' && $view->name=='calendar' && display_id=='page_classic') {
    $view->set_display('page_mobile');
  }

}

```

...inside a small module.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How do I allow users to select published content on the site to be displayed on their profile page?
I would like to have published content on my site which a user can select if he/she would like for it to be displayed within a block on their profile page.

For instance:

* Published content is an article with image and body,
* When the user is viewing this node there is a checkbox (or whatever that will work) that will say "Add To Profile".
* If selected, then the content teaser will appear within a block on that specific users profile page.

I know how to get content that is created by a user to appear on that users profile, but I have been having difficulty getting this right.

PS: I know very little php, but know my way around Drupal.

# Answer
You might want to look into the Flag Module. It provides links on nodes that allow them to be tagged/flagged. Then, with Views, you can create a block that will be displayed on user profiles with content flagged by that user. In fact, it comes prepackaged with a "bookmarks" view that might be a good starting point for this.
> 2 votes

# Answer
* Add an entity reference field to their profile page
* In Views create view that will show content based on field from previous point
* Use Viewfield to attach views to user profile page and to give uid back to views

It will not be a block, but it should work and you can template it to look like one.
> 0 votes

---
Tags: views, users, nodes
---


# Question
Title: How to use WYSIWYG editor with structured content in Drupal 7?
I am wandering what would be the best strategy to combine a WYSIWYG editor and structured content. I want the user to be able to add the following in the body field with a WYSIWYG editor:

* Images
* Links to other nodes
* Links to, for example, YouTube

I also want to be able to have these added images, links etc. as structured content (to put them out in a view, for example.)

Is there a solution for this? I think the best way would be to use entity reference module for that.

# Answer
For images use Insert module. For other fields, like YouTube links and entity References, you can create your own module based on Insert's code, or expand it's capabilities and put a patch in Insert's issue queue.
> 2 votes

---
Tags: entities, wysiwyg
---


# Question
Title: How to stop text-boxes in my custom block trailing past the block?
I am creating a module with a custom block. Even through googling, I still could not find an answer to my question "how do you theme the elements in a form?" I think it is the fact that I don't completely understand the array elements that need to be set on each textbox.

Image of my problem: https://www.evernote.com/shard/s188/sh/3bf8cc91-5341-4c55-91ca-41e0ddbd1922/feb9698ff407e60a064f92421510059d

# Answer
While creating this form in your custom module you set DIV class to form items which is textfield in your casy. All you will have to do is use `#prefix` & `#sufix` You will start your DIV class from `#prefix` before #type of form items & close the DIV at #`sufix`.

Here is the example

```
$form['first_name'] = array(
  '#prefix' => '<div class="demo-form">',
  '#title' => t('First Name'),
   '#type' => 'textfield',
  '#suffix' => '</div>',
  '#maxlength' => 128,
  '#required' => TRUE,
);

```

Open the CSS file or create your own at your theme folder, but if you create your own then you will have to declare it in theme.info file.

Write CSS for the class `demo-form` which you have applied to the form element & resize it as your wish. If you have created your own CSS file then don't forget to clear your cache.
> 0 votes

---
Tags: forms, theming
---


# Question
Title: user relationship node access is not working
I have enabled the module and tried to work on it. I have created the following users: mtest, emptest, and mdev. I'm using the Views module to show the nodes. The nodes posted by emptest should only visible to mtest, but this is not happening, even after using the Node access and Content access module.

How do I restrict this?

# Answer
If you are using a view, and trying to constrain the nodes listed in the view to those posted by the currently logged in user, you would use a Contextual filter to accomplish it, not Node access or Content access.

Assuming you are using Drupal 7, edit your view and under *Advanced* add a *Contextual filter*. Select `Content: Author: Uid`, and when the configuration screen comes up, under *When the filter value is NOT available* select *Provide default value* and use the select list to choose *User ID from logged in user*.

Save your view, and it will only list nodes authored by the current user.
> 0 votes

---
Tags: views, users
---


# Question
Title: Using pre-process to wrap multiple regions in html
I'm using Omega, and have 6 regions in a particular zone. The first and second region span the width of the zone with 12 columns, and the other 4 are 1/4 in-line blocks. I want to set the background for the 4 in-line blocks to a particular color. How can I wrap those 4 regions inside a div so I can set the background color?

# Answer
> 1 votes
> How can I wrap those 4 regions inside a div so I can set the background color?

You can use .tpl files for that.

```
<?php if ($region_first || $region_second): ?>
    <div class="your_color_class">

        <?php if ($region_first): ?>
            <div id="region_first">
                <?php print $region_first; ?>
            </div>
        <?php endif; ?>

        <?php if ($region_second): ?>
            <div id="region_second">
                <?php print $region_second; ?>
            </div>
        <?php endif; ?>

    </div>
<?php endif; ?>

```

---
Tags: 7, theming
---


# Question
Title: Using drupal_http_post() to submit to external site: What am I doing wrong?
I intended to make a module that utilized `drupal_http_request` with a webform so that the form gets validated before it gets sent to an external url.

I actually was recommended this method over `$form['#action']` from a previous inquiry earlier. I did as recommended, thought it worked, but found out that I was mistaken.

I did some troubleshooting and concluded my module is the culprit since:

1. The module utilizing `$form['#action']` had no problems posting to our external url/web app and another external site/service for testing HTTP POST submissions (http://requestb.in)
2. The module utilizing `drupal_http_post` could neither post to our external url/web app nor requestb.in

My setup uses the following:

* Drupal 6.x
* Webform 6.x-3.17

My custom module contains the following code.

```
function webform_to_data_repo_form_submit(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_765') {
        $url = 'external.url.goes.here';
    $headers = array(
                 'Content-Type' => 'application/x-www-form-urlencoded',
               );

$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));
   }
}

```

Is there something wrong with my module? Just wanted to make it post to some external URL.

# Answer
Thank you everyone for the pointers.

I realized that my custom module that uses the webform module to submit to an external url (via drupal\_http\_request) had to be written as two separate functions: one using hook\_form\_alter and one using a custom submit handler. The code is as follows.

```
<?php

function webform_to_data_repo_form_alter(&$form, &$form_state, $form_id) {

//I only want form 765 to submit externally //
if ($form_id == 'webform_client_form_765') {
$form['#submit'][] = 'my_additional_submit_handler';
 }
}

function my_additional_submit_handler(&$form, &$form_state) {

$url = 'your.external.url.here'
$headers = array('Content-Type' => 'application/x-www-form-urlencoded',);
$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));

}

?>

```

As a side note, I never got to test the result of using `dpm($response)` using the Devel module as beth suggested.

I'm using a webform (via the webform module) to test. What I wanted to happen are two things.

1. The webform validates the submission which in turn would keep a log of the submission through Drupal (webform module by default and by design).
2. Simultaneously submit inputs from #1 to external url.

For the longest time, only #1 is happening and I can't seem to make Devel look into `$response` because that variable only exists when there's an attempt on submission. How does one make Devel module load when a successful submission has been made through a Webform? I guess this is another question for another time.
> 2 votes

---
Tags: webforms
---


title: How to override a theme function?

text:
# Question
Title: How to override a theme function?
I'm using LoginToboggan as my login page, and on the login form, it has: "You are not logged in." I want to be able to edit this text, and the admin interface doesn't give an option to do so.

Searching around, I see that this is set in the LoginToboggan module in a theme function:

```
function theme_lt_unified_login_page($variables) {
...
$output .= '<div id="login-message">' . t('You are not logged in.') . '</div>';
...
}

```

So I can't edit the module directly, nor would I wish to "patch" it. I see that `theme_lt_unified_login_page` is called by:

```
function logintoboggan_unified_login_form($active_form = 'login') {
...
$output = theme('lt_unified_login_page', $variables);
...
}

```

I don't really understand what hook I would use to intercept and override / edit just this text? It doesn't appear in the `$form` object.

# Answer
> 6 votes
The quickest way might be/would be to copy...

```
/**
 * Theme function for unified login page.
 *
 * @ingroup themable
 */
function theme_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '<div class="toboggan-unified ' . $active_form . '">';

  // Create the initial message and links that people can click on.
  $output .= '<div id="login-message">' . t('You are not logged in.') . '</div>';
  $output .= '<div id="login-links">';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '</div>';

  // Add the login and registration forms in.
  $output .= '<div id="login-form">' . $login_form . '</div>';
  $output .= '<div id="register-form">' . $register_form . '</div>';

  $output .= '</div>';

  return $output;
}

```

to your theme's template.php file and rename it...

```
/**
 * Theme function for unified login page.
 *
 * @ingroup themable
 */
function YOURTHEME_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '<div class="toboggan-unified ' . $active_form . '">';

  // Create the initial message and links that people can click on.
  $output .= '<div id="login-message">' . t('PLACE YOUR CUSTOM MESSAGE HERE.') . '</div>';
  $output .= '<div id="login-links">';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '</div>';

  // Add the login and registration forms in.
  $output .= '<div id="login-form">' . $login_form . '</div>';
  $output .= '<div id="register-form">' . $register_form . '</div>';

  $output .= '</div>';

  return $output;
}

```

...along with whatever you wanted that `login-message` to be. Clear caches/theme registry and you should be on your way.

ADDITION:

This ***drupal fu*** works because, instead of calling `theme_lt_unified_login_page()` directly, it does it like this:

```
$output = theme('lt_unified_login_page', $variables);

```

and it is the `theme()` function that does the magic in that when you build the theme registry, it will discover that there is a *YOURTHEME*\_lt\_unified\_login\_page() function out there, and will call that as an override to the *theme*\_lt\_unified\_login\_page() one that logintoboggan provides.

(Note that the first argument doesn't start with `theme_` or `YOURTHEME_`, one of these are prepended by the theme system as described above.)

---
Tags: 7, theming
---


# Question
Title: get the content type 'machine name' by the 'human readable name '
I have a content type whose human readable name is *Post your blog*. How can I get the content type machine name by the human readable name?

Is there a function in Drupal 7, or do I have to query the node\_type table to get what I want?

# Answer
You can easily build a query to achieve this. However, as Molot mentioned, you have to handle human readable names that aren't unique.

```

  $machine_name = db_select('node_type', 'n')
  ->fields('n', array('type'))
      ->condition('name', 'Basic page')
      ->execute()->fetchField();

```
> 3 votes

# Answer
Look at node\_type\_get\_types for D7 and simply `foreach` looking for `$object->name` as `Post your blog`.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Why aren't the titles of my items in a new product type not displaying at check out? - Commerce
I am building a store based on Commerce Kickstart. I am using one of the original product types and two new product types that I created by essentially copying the field and display settings in the content type and product variations settings. After a lot of fiddling around I have everything displaying properly, except in a couple of places in the check out process.

1) In the cart ( mysite.com/cart# ) the line items that I created display the sku of the item but not a "view product" link. Where can I change this?

2) In the review order page ( mysite.com/checkout/ordernumber/review ) the line items of the product type that I created don't display the item title, while the item type that was there originally does. Where can I change this?

# Answer
Ok, I figured it out. The issue was that my product had a title, but the variation didn't have the title field filled out. So once I go to administration\>products\>find the failing product\>edit, then I filled out the title field and saved. Problem fixed. I need to modify the way that I create the product so that both of these title fields get filled out upon product creation.
> 1 votes

# Answer
It's a bit of a gotcha, but I suspect under user permissions, you may need to check the "View products of \[type\] type" permission for anonymous / authenticated users.
> 1 votes

---
Tags: commerce
---


# Question
Title: Drupal commerce get quantity per sku in hook_commerce_checkout_complete
Inside this hook I need the total products per sku. For example, user #1 buy 2 products with the sku #7, user #2 buy 5 products with the sku #10. I need to know how to get:

* sku #7 -\> 2
* sku #10 -\> 5

I was trying something like:

```
foreach ( $order->commerce_line_items as $line_item ) {
   $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
   $line_item_wrapper->commerce_product->sku->value();
}

```

But it gives me just sku #7 and sku #10. Also, this function commerce\_line\_items\_quantity($line\_items) didn't help so much because it gave me just the total of all sku's, not individually.

This way I can award the user with some "user points" (I think is easier this way than using rules).

# Answer
You need to wrap the `$order` object before looping over the line items. It also removes the need to wrap the line items explicitly.

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ( $order_wrapper->commerce_line_items as $line_item_wrapper ) {
  if ($line_item_wrapper->commerce_product->sku->value() == 'some-SKU') {
    // increment quantity counter, award points etc.
  }
}

```
> 1 votes

---
Tags: hooks, commerce
---


# Question
Title: Set trim_length of field through UI for blog entries
I am using the Blog module, but don't like the 600 character trim length. I want 2000 char.

But, I can't find out where to change this in the admin console.

I was able to update the trim length through the mysql console, but this seems less than ideal.

The code below was how I was able to complete the config change. How can i do this without a SQL update?

```
mysql> select * from field_config_instance where id=9\G
*************************** 1. row ***************************
         id: 9
   field_id: 2
 field_name: body
entity_type: node
     bundle: blog
       data: a:6:{s:5:"label";s:4:"Body";s:6:"widget";a:4:{s:4:"type";s:26:"text_textarea_with_summary";s:8:"settings";a:2:{s:4:"rows";i:20;s:12:"summary_rows";i:5;}s:6:"weight";i:31;s:6:"module";s:4:"text";}s:8:"settings";a:3:{s:15:"display_summary";b:1;s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:7:"display";a:2:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:8:"settings";a:0:{}s:6:"module";s:4:"text";s:6:"weight";i:0;}s:6:"teaser";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:23:"text_summary_or_trimmed";s:8:"settings";a:1:{s:11:"trim_length";i:600;}s:6:"module";s:4:"text";s:6:"weight";i:0;}}s:8:"required";b:0;s:11:"description";s:0:"";}
    deleted: 0
1 row in set (0.00 sec)

mysql> update field_config_instance set data='a:6:{s:5:"label";s:4:"Body";s:6:"widget";a:4:{s:4:"type";s:26:"text_textarea_with_summary";s:8:"settings";a:2:{s:4:"rows";i:20;s:12:"summary_rows";i:5;}s:6:"weight";i:31;s:6:"module";s:4:"text";}s:8:"settings";a:3:{s:15:"display_summary";b:1;s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:7:"display";a:2:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:8:"settings";a:0:{}s:6:"module";s:4:"text";s:6:"weight";i:0;}s:6:"teaser";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:23:"text_summary_or_trimmed";s:8:"settings";a:1:{s:11:"trim_length";i:3000;}s:6:"module";s:4:"text";s:6:"weight";i:0;}}s:8:"required";b:0;s:11:"description";s:0:"";}'
    -> where id=9;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0`

```

# Answer
You can go to `admin/structure/types/manage/blog/display/teaser` and on the right next to the format settings for *Summary or trimmed* you will see a button with a little star on it. Click on it and set your trim length.
> 2 votes

---
Tags: 7, entities, nodes
---


title: print cck field using node_load

text:
# Question
Title: print cck field using node_load
I found simple code to put inside custom module that prints extra field inside cart view table

```
<?php
function ucaddsku_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'uc_cart_view_form') {
$form['items']['#columns']['model']['cell'] = 'SKU';
        for($i=0;$i<count(uc_cart_get_contents());$i++){
        $form['items'][$i]['model']['#value'] = node_load($form['items'][$i]['nid']['#value'])->model . ": ";

    }
}
}
?>

```

How can be any cck field printed like this?

# Answer
> 1 votes
You can print the cck field like this.

```
// Load the node.
$node = node_load($nid);

// Print the fields.
print $node->title;
print $node->field_myfield[LANGUAGE_NONE][0]['value'];

```

or a more decent way like this...

```
$myfield = field_get_items('node', $node, 'field_myfield');

```

https://api.drupal.org/api/drupal/modules!field!field.module/function/field\_get\_items/7

See this also. https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field\_view\_value/7

---
Tags: theming, forms, 6
---


# Question
Title: Some of my Panel content is missing for anonymous users. What went wrong?
I've set up a landing page panel with two items in it, a content page with a welcome message and a view showing certain content. It works great, but when I look at it as an anonymous user only the view is showing up, not the welcome page message.

I haven't put any special access conditions and my only variant is the landing page and I can see all the content in the preview, so I don't understand why it isn't visible to everyone. The welcome message is on a published page as well, and caching is disabled for that panel for the moment.

# Answer
Ok, it was a caching issue after all. \>.\<

I'm not sure which caches Panels uses, but the very handy Administration menu's flush all caches link seems to have fixed the problem.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: #superfish ul also targets contextual links!
I am using superfish menu in D7 as follows:

* I have created a custom theme from scratch
* in my page.tpl.php I have created a region for my main menu as:

```
 <div id="superfish"><?php print render($page['main_menu']);?> </div>

```
* I place the superfish block inside the main\_menu region and it appears in place, as expected.
* I write my .css, but **when I target #superfish ul, the contextual links are also targeted and styled**! I suppose this is not the normal behaviour.

In all other modules I've encountered (including nice menus), contextual links are kind of greyed out and cannot be targeted with CSS, but in the context of Superfish menu they appear active and targetable as ever. They even get superfish classes applied to them.

What am I missing?

P.S. I am starting using `#suckerfish ul:not(.contextual-links)` :-O

# Answer
Try targetting `#superfish ul.menu`. This should discriminate the menu from `ul.contextual-links`. (Double check the class for your menu by viewing the page source if this does not work.)
> 0 votes

---
Tags: theming, navigation
---


# Question
Title: How to pass taxonomy reference field data into a views reference contextual filter arguement with PHP code?
My content type has a taxonomy reference and a view reference field. I currently want to pass the Term ID as an argument into my referenced View via a Contextual filter Taxonomy Term. If someone can provide me with an example of how to write the PHP code in the contextual section of my view that would be great.

# Answer
As the help text puts it, you just need to `return` the value. Of course, your actual question might be to access the term id but you have not specified that.

For example, if you want to show the view as a block on a regular node page, and the node contains the tid, you would use code like this:

```
// Lets assume that this view will always be shown on a node page.
$node = arg(1);
$tid = $node->field_term_reference[0][LANGUAGE_NONE]['value'];
return $tid;

```

This code could be improved a lot but it gives the basic idea.

As a side note, if your scenario is as per above, then consider using Panels and pass in the term id using contextual arguments.

Side note 2: Your screenshot shows filter dialog for Term Name whereas your question asks for term ID. I have given the example for the latter. I hope it helps get you started.
> 0 votes

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


# Question
Title: Advanced search: USASearch compared to Apache Solr Search implemented by Acquia
I have been asked by a US government agency to compare 2 different methods for advanced search:

* USASearch
* Apache Solr Search implemented by Acquia

This agency already has a contract with Acquia to host their Drupal site and this subscription includes (for free) Apache Solr Search which is implemented by Acquia so cost is not an issue when comparing the 2 options since USASearch is free to any government agency. What are the advantages and disadvantages of these 2 search methods, and which one would you recommend?

# Answer
I didn't go too deep into USASearch, but it seems to me as a tool similar to Google Custom Search Engine.

So, let's classify them first. We'll call all such services as **Search Providers**. On the other hand, we'll call ApacheSOLR instances (whether through Acquia or otherwise), regular search index in Drupal or other such index hosting services as **Indexes**.

The general difference between **Search Providers** and **Indexes** is mostly in the level of control.

**Search Providers**

1. Quicker to setup for static websites as it is just HTML/JS code.
2. Ideal for simple static content with limited customization.
3. You don't have to worry about the index at all. That is your provider's job.

**Indexes**

1. For Drupal, it is just a matter of installing a module.
2. You get complete control over results, templating, filtering, facet search, etc...
3. You have to take care of indexing content, permissions, and search configuration.

Generally speaking, go for Indexes, or in your case, Acquia Search. The configuration and indexing is one time (and sometimes not even that) and the added benefits are huge. There are very few scenarios where I would pick a search provider instead.
> 3 votes

---
Tags: search
---


# Question
Title: how to add parameters to html email template
I have a working html email using modules: *Mail System, HTML Mail, SMTP Authentication Support.*

And I want to include some parameters/variables in the html email template file:

```
htmlmail--htmlmail.tpl.php

```

some variables include: `$base_path` etc. from `page.tpl.php` variables

From what I've read from the Internet, you may use "hooking" and I haven't yet hooked variables so far for my template file.

# Answer
> 1 votes
you can use the **yourtheme\_preprocess\_htmlmail()** function for **htmlmail** email template in put in the **template.php** file of your current theme. I will give an example.

```
function yourtheme_preprocess_htmlmail(&$variables) {
  switch($variables['key']){
    case 'password-reset':
     $variables['var1'] = t('SAMPLE TEXT');
     break;
    case 'register-no-approval-required':
     $variables['var1'] = t('SAMPLE TEXT');
     break;
    break;
   }
   $variables['heading'] = t('Heading text');
   $variables['copyright'] = t('Copyright text.');
 }

```

In this example. I created some customized variables base on the mailkey and defined some others like **heading**, **copyright**

---
Tags: emails, theming
---


# Question
Title: Regarding content slider on mobile screen
I am trying to make a Drupal 7 desktop site into a responsive one. There is a view of type node listing the node title and image in a grid format on front page. I want that on the mobile screen instead of a grid it just becomes a list of horizontal fields and can be navigated by touch (maybe act as a slider). Any leads how to proceed.

Please shoot out if you need any more info. Would really appreciate any suggestion.

Thanks

# Answer
> 1 votes
**Option 1:**

Flex Slider allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

> 1. Touch enabled navigation
> 2. Keyboard navigation
> 3. Configurable slide animations
> 4. Multiple sliders per page

**Option 2:**

Views Responsive Grid provides a views plugin for displaying content in a responsive(mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality

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


# Question
Title: How to upload multiple images to Ubercart product pages via FTP?
I have a few thousand products that I plan to upload to a D7/Ubercart website and each one will have two or three images associated with it. Is there a way I can just dump all of those images onto the server and have them somehow be associated with their correct products? Or am I stuck uploading each one individually via the node edit fields?

Thanks!

# Answer
> 1 votes
The way I did it in similar, but not exact circumstances, was to use Node export module. It has it's import option. On an import, it expects images to be already uploaded, so the steps are:

* Create two products with couple of images manually
* See where it's images went
* Upload the rest of your images in the same place
* Export your products to a file format you are comfortable with, like CSV / DSV
* Add the rest of your products to that file, using your manually added ones as examples
* Import products from file

My nodes weren't Ubercart products, but above procedure should work none the less.

Remember: Files uploaded will not be managed until and unless you import nodes to use them, so it's a good idea to turn off any "garbage cleaning" modules you may have to avoid their deletion.

---
Tags: 7, media, ubercart
---