title: Display view on custom homepage

text:
# Question
Title: Display view on custom homepage
I have a site with custom home pages depending on role. The homepages are assigned with `hook_menu` (hook\_menu associates a URL with a function that returns a `$html` string.)

For one particular role, I need to generate a homepage that incorporates a view. I am looking at a list of views hooks, and not sure were to start.

In summary, how do I display a view that is generated from one of my hook\_menu functions?

Edit: I am currently looking into this code example from http://lucor.github.com/2011/10/drupal7-how-display-block-programmatically/ The view is in now in a block.
I have not yet figured out what I either one of the parameters are suposed to be set to.

$block = block\_load($module, $delta); print render(\_block\_gAet\_renderable\_array( \_block\_render\_blocks( array($block) )));

# Answer
You have many ways to apply what you are looking for.

The easy way is to use Context module with Empty Front Page module

Another way is to write your own module, something like the following code:

```
function myfront_menu() {
  $items = array();

  $items['frontpage'] = array(
    'title' => 'My homepage',
    'page callback' => 'myfront_front_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function myfront_front_page() {
  global $user;

  if (in_array('administrator', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('authenticated user', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('role2', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('role3', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  return '';
}

```
> 3 votes

# Answer
You could propably use

```
views_embed_view()

```

http://api.drupal.org/api/views/views.module/function/views\_embed\_view/7
> 1 votes

# Answer
You can try using context module (http://drupal.org/project/context) on your case or even use this for a better implementation of displaying different types of homepage depending on the user role without the hassle of using custom code.

You can preview what it can do here http://www.drupalove.com/drupal-video/context-module.
> 0 votes

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


# Question
Title: How to make Ubercart Ajax Attribute Calculations work with Fusion theme?
I have a website set up with the Fusion theme, and Ubercart Ajax Attribute Calculations is not working as expected. I switched my theme momentarily to Garland and it did work then, so it's definitely something to do with the Fusion theme, or a node-product.tpl.php file in my Fusion theme.

The UC AAC module page states

> Product node divs must have an identifier in the same form as the garland theme. For instance, trying to use bluemarine theme without adding the following code to node.tpl.php will result in the module not working. `id="node-<?php print $node->nid; ?>"`

I checked my node.tpl.php in my fusion core folder and in my fusion sub-theme folder, and I do have this line in both copies of the file:

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

```

I also have a node-product.tpl.php file in my fusion sub-theme folder, which has this line of code:

```
<div id="node-<?php print $node->nid; ?>" class="node clear-block <?php print $node_classes; ?>">

```

In my node-product.tpl.php file, this is the code that displays the product price on the product page. This is a file that was inherited from a prior developer for the website in question, and I am wondering if perhaps there is something in this code that is keeping the Ajax price change from working:

```
                <div class="productpage-right">
                <div class="pricecluster">

                                            <?php $lp = (int)$list_price; if ($lp != 0) { ?>
                    <div><span style="text-decoration:line-through;">Regular Price: $<?php print substr($list_price,0,-3); ?></span></div>
                                            <?php } ?>
                    <div><span style="font-weight:bold">Special Price: <span style="color:#5c9001; font-size:18px">$<?php print substr($sell_price,0,-3); ?></span></span></div>
                    <?php print $fusion_uc_add_to_cart; ?>
                                            <?php
                                            $current_rating = votingapi_select_results(array('content_id' => $node->nid, 'function' => 'average'));
                                            $current_rating = $current_rating[0]['value'];
                                            $converted = $current_rating / 20;
                                            $converted = round($converted,1);
                                            ?>

                                            <div class="ratingcluster">
                                            <div>Average Customer Rating:</div>
                                            <?php print theme('fivestar_static', $current_rating, '5'); ?>
                                            <?php if ($converted == 0): ?>
                                                <div>- Not yet rated -</div>
                                            <?php else: ?>
                                                <div xmlns:v="http://rdf.data-vocabulary.org/#" typeof="v:Review-aggregate">
                                                    <span property="v:itemreviewed" style="display:none"><?php print $node->title; ?></span>
                                                    <span rel="v:rating">
                                                        <span typeof="v:Rating">
                                                            <div><a href="#reviews"><span property="v:rating"><?php print $converted ?></span> stars out of 5 stars</a></div>
                                                        </span>
                                                    </span>
                                                    <?php if ($node->comment_count > 0): ?>
                                                        <?php $verbage = ($node->comment_count > 1) ? " Reviews" : " Review"; ?>
                                                        <div><a href="#reviews">Based on <span property="v:count"><?php print $node->comment_count.$verbage; ?></span></a></div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                            </div>

                </div>

```

When I remove the node-product.tpl.php file from the server, the AJAX price change does work in my Fusion theme, so I think it must have something to do with that block of code above. Can anyone tell me which part might be causing the issue?

Thanks!

# Answer
> 0 votes
Fixed it...

I changed this:

```
<div><span style="font-weight:bold">Special Price: <span style="color:#5c9001; font-size:18px">$<?php print substr($sell_price,0,-3); ?></span></span></div>

```

to this:

```
<div><span style="font-weight:bold">Special Price: <span style="color:#5c9001; font-size:18px"><?php print $fusion_uc_sell_price; ?></span></span></div>

```

(which is the sell price code taken from the original fusion node-product.tpl.php file, one version of which can be found here: http://drupalcode.org/project/fusion.git/blob/c2189d8:/fusion\_starter/node-product.tpl.php)

I'm still open to any suggestions to get the original version of the code to work, and am also curious whether anyone can explain what the other code's purpose was.

---
Tags: 6, ajax, ubercart
---


# Question
Title: Pseudo-fields and custom entity properties from additional schema
I'm trying to add property information to an entity which uses the entity API. Working from the commerce\_product module I am trying to manage additional information outside of fields and in my own database that ends up attributed with the resulting product object when the entity is loaded. I've been looking into the `hook_entity_property_info_alter` and `hook_entity_load` functions to get the additional custom or "pseudo-fields" loaded. I'm having issues when saving/creating the new entity (product) and information submitted from the form is not accessible. Am I supposed to alter the form and tack on an additional form submit handler? During a call to `hook_commerce_product_insert` I was expecting the $product object to have form field values included that I could work with. What would be the recommended way to approach this? I want to end up with data from my own database schema added to the entity and be editable through the entity's creation/edit forms.

I found this relevant solution but that approach deals with editing the original schema which is definitely something I want to avoid.

# Answer
You may have to override the form submit handler, or at a minimum add you're own submit handler in addition to the default. As long as the submit handler starts with an entity passed through the $form\_state, you could add your own handler to fire before the final handler that saves the entity and set your properties there.

While I don't have a ton of experience working with entities and hook\_entity\_load etc, you may get more milage from extending and overriding the default entity controller for product and overriding the load, save, and delete methods.
> 0 votes

# Answer
There is some kind of field other than usual CCK fields: extra fields.

hook\_field\_extra\_field

I'm going to use it to add additional information to entity (Parent NID, Parent UID) some stuff that entity-reference can't and shouldn't handle. You have said it must not be field, I don't know if you don't want to use this kind of field also, But you might overlook some issues.

I'm not 100 percent sure if it's the solution but for people looking for an answer it's good to look at it.
> 0 votes

---
Tags: entities
---


# Question
Title: drupal module defines front page using hook_menu...What does it need to return?
I am using hook menu to define the front page (/front) and I found out if I return '' it renders the theme with all the blocks.

If I return content, is that what gets rendered into the Main Content block? What is the purpose of returning data from this function?

```
function dc_mad_marchness_menu()
{
    $items['front'] = array(
        'title' => 'Home',
        'page callback' => 'dc_mad_marchness_front',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function dc_mad_marchness_front()
{
    return '';
}

```

# Answer
Yes, if you return either a string or a render array from a page callback function, it will be rendered in the main content region on the front end (well, under normal circumstances anyway. There are possible exceptions).

There's an in-depth description of `page callback` in the `hook_menu()` docs which is a bit long to reproduce here. I'd recommend giving it a read through.
> 1 votes

---
Tags: hooks
---


# Question
Title: Display an Array as a List inside a Table
I have an array that have a created with items in it that I want to populate a cell in a table. In my case this is a table of Orders in Ubercart and have created an array, called `$models` that is populated with the Model numbers of the line items in that order. What would be the best way to display this array in my table?

Currently,

```
$rows[] = array(
  ...
  array('data' => $models),
  ...

```

display's nothing in the Model column.

# Answer
> 1 votes
There's `theme_item_list()` which

> Returns HTML for a list or nested list of items.

e.g.

```
$rows[] = array(
  ...
  array('data' => theme('item_list', array('items' => $models))),
  ...

```

---
Tags: theming
---


# Question
Title: CKeditor: Add class to all ul and ol elements on output
The ul and ol elements are often used in theming outside of the 'text'-context (e.g. category blocks, etc.). Therefore the bullets are removed by default.

Is there a way to add a class to all ul and ol elements outputted by CKeditor? For example class 'editor', so that we can theme the ul/ol elements differently if they are outputted by CKeditor (with bullets or decimals).

# Answer
> 1 votes
There is no reason to do that for styling purposes. You can target the `ul` and `ol` elements by their parent container. The classes depends on your theme output, but consider this for the Garland theme:

```
/* Style all ul and ol elements from the body output. */
#center .node .content ul,
#center .node .content ol {
  /* Styles here */
}

```

If you are missing classes you can add those in the `page.tpl.php` and `node.tpl.php` templates.

---
Tags: theming, wysiwyg
---


# Question
Title: How do I get a block to use a URL to configure a contextual filter?
Blocks do not have paths so how can I pass a context to the block to get the correct results for a page?

# Answer
> 17 votes
A views page can read the url and use a path for the page to read a taxonomy term input for a contextual filter. A URL such as `example.com/a/term/b` would be read by the view page with a path of `a/%/b`. The value for the `%` in the URL is passed in to the contextual filter to determine what content to include in the view.

Since a block doesn’t possess a path it is necessary to do a bit more configuration to achieve the result. To do so:

1. Click on the contextual filter on the block view form in views.
2. Under `When the filter value is NOT available` select `Provide default value`.

If the page in the path is a taxonomy term try this step 3 and 4:

3. Choose `Taxonomy term ID from URL` from the Type drop-down box.
4. Check `Load default filter from term page`.

Or otherwise try this:

3. Choose `Raw value from URL`
4. Identify which part of the URL is the term. eg. for `A/term/B` the term is in the second position.

Then:

5. Under `When the filter value IS in the URL or a default is provided` check "Specify Validation criteria"
6. Select `Taxonomy term` and the specific vocabulary being used.
7. Under `Filter Value type` pick term name converted to term ID"
8. Checking `Transform dashes in URL to spaces in term name filter values` will ensure that any auto generated path alias' that have converted spaces to dashes are properly handled. Try your view with this checked and unchecked.

If your view is not appearing on the page troubleshooting steps should include verifying that the view works by testing input in the view preview. Make certain that any spaces are handled to match up with the setting in step 8. Also make certain that your view block is exposed in `admin/structure/block`.

# Answer
> 1 votes
If you want to select according to a Content Type instead of taxonomy, you need a different setup. Try the following:

1. Click on Contextual Filters
2. Add Content: NID On the **WHEN THE FILTER VALUE IS NOT AVAILABLE** section, select **Provide default value** and choose **Content ID from URL** on the dropdown list.
3. On the **WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED** section, select **Specify validation criteria**, choose **Content** on the VALIDATOR select box, and choose which Content Types you authorize to be displayed.

That should do it.

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


title: Make a field specific to a user

text:
# Question
Title: Make a field specific to a user
I would like to make a field that is specific to a single user, similar to a non-global flag but allowing more field types than just boolean. Is there a way to do this? For example, if User A sets this field on Node B to 5, then User C looks at that node, he won't see User A's value. If User C then edits the field to another value, then he will see that value instead, and User A will still see his value of 5.

# Answer
> 1 votes
To my understanding you want users to be able to set a value on a node which is specific to that particular user. This sounds much like a relationship between the user and the node, so my suggestion would be to look into the Relation module. I believe that module would let you achieve this functionality.

I have not used this module so I am afraid I can't help you with details at this point.

# Answer
> 5 votes
Yes, you can add fields to the user entity with the Field API to

*Admin \> Config \> Account settings \> Manage fields*

The variety of field types are available and each user has their own field value

---
Tags: entities
---


# Question
Title: I am unable to show the access denied message of the premium content module. How can I do this?
I have 3 view modes (teaser, presentation and full view mode). I have created a `node--content-type.tpl.php` and created the code for each view mode using a conditional statement

```
if($teaser) {}
else if($node->type == 'tu_mooc' && $view_mode == 'presentation') {}
else {}

```

I have linked the 3 view modes. So I can go from the teaser to the presentation and from the presentation to the full view mode.

I have downloaded the premium content module so that access to the full view mode is limited to authenticated users. I made a small change in `premium.module` so that anonymous users have access to both the teaser view mode and the presentation view mode. The problem I have is that when I try to access the full view mode (as an anonymous user) I don't get the access denied message. Instead I get the code that appears within the teaser view mode. i.e. In node/1 I get the teaser of node1 instead of getting the access denied message.

Do I need to include some code like `<?php print $denied_message; ?>` into the `node--content-type.tpl.php?` or what do I need to do?

Thanks in advance.

# Answer
I have included this code within the teaser in node--content-type.tpl.php:

```
<?php print $content['body'][0]['#markup']; ?>

```

And I have included this code in template.php:

```
function  mimooc_premium_body($arguments) {
  $node = $arguments['node'];
  node_build_content($node, 'teaser');
  unset($node->content['links']);
  $level = premium_level_load($node->premium);
  if ($level->denied_message) {
    $denied_message = $level->denied_message;
    $denied_message_format = $level->denied_message_format;
  }
  else {
    $denied_message = variable_get('premium_message', t('Full text available to premium subscribers only.'));
    $denied_message_format = variable_get('premium_format');
  }
  // Only display the premium message, if we actual have any content.
  if (!empty($node->content)) {
    return '<div class="premium-message"><h3>' . check_markup($denied_message, $denied_message_format) . '</h3><p>' . l('Click here to sign in', 'user') . '</p></div>';
  }
}

```

Now, when I access the full view mode of the node, I get the teaser of that node with the access denied message.
> 0 votes

---
Tags: 7, nodes, entities, status-messages
---


# Question
Title: How do I get access to fields of a node that a menu item links to?
For example, a menu item links to node/5. How do I retrieve that node so I can get its 'description' field?

# Answer
You could use the menu\_get\_object() function or the arg() function. One of these 2 functions should do the trick. If i get you right ...
> 0 votes

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


# Question
Title: How to hide the field names in a custom view?
I am new to Drupal and am working on a Drupal 6 (6.28) site. I have created a custom view and corresponding block which shows the most recent story created which has been promoted to Home. The view looks great except that it displays the "Title:" and "Body:" field labels before the Title and Body. How can I remove those?

Thanks in advance.

# Answer
> 0 votes
In Drupal 7 with views 3 it works like this: If you use fields as display format you can click in your field and disable the "Create a label" checkbox.

---
Tags: views, 6
---


# Question
Title: Adding an img inline with the content only on a specific page
I have a certain page on my site that has the following menus at the top:

I would like to add a logo just before the textual menus on the far left of the screen. This menu is in the main content of the page. So far I have been able to get the logo to show up just above the content by adding the img to my page.tpl.php file but I really want it to show up on the same line as my menus.

I thought maybe I could do this by adding the img into a region.tpl.php file but that would make the image show up on every page's region and I only want it to show up on this page's region. Is there a way to the image show up inline using a page.tpl.php file?

# Answer
Have you tried creating a block with your context, restricting the block to that one page, and then assigning the block to the correct region?

Your regions will depend on your theme.
> 1 votes

---
Tags: theming
---


# Question
Title: Get file or image path as string from uid
I need to get the relative path to a file, in this case, what i need is:

/sites/default/files/pics/DSC00873\_39.JPG

But all I seem to be able to get is the following:

```
$file = file_load($pic);
print $file->uri; // public://pics/DSC00873_39.JPG

```

Any ideas please?

# Answer
> 2 votes
Yep. There is a function for that.

http://api.drupal.org/api/drupal/includes%21file.inc/function/file\_create\_url/7

---
Tags: 7, files
---


# Question
Title: Additional classes for price based on price components
Is it possible somehow to add classes related to price components to the price container div? So you would be able for example to style a price based on how it is changed by its components. I thought it would be very nice.

# Answer
Yes, you could theme the price components to add your own classes via a theme override.

The base implementation is in commerce\_price.module

Here's a tweak that includes the price component $name in the class:

e.g, in template.php

```
/**
 * Themes a price components table.
 *
 * @param $variables
 *   Includes the 'components' array and original 'price' array.
 */
function MYTHEME_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', $name),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total', $name),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }

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

```
> 1 votes

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


# Question
Title: Restrict content access by term reference in profile
What I would like to accomplish is to have the following. Please let me know if anyone is aware of modules that can accomplish this already or what direction I should take developmentally to accomplish this. Thanks.

# Nodes

All nodes are tagged with terms from a particular vocab through the use of a taxonomy reference field. The nodes are only accessible to specific users that have permissions to view the tagged terms.

# Taxonomy

I have one vocab that I am working with for all of this control and it is enabled for all content.

# Users

All users are tagged with terms from a particular vocab through the use of a taxonomy reference field added to their profiles. This field should only be editable by a certain administrative roles. Additionally, the user will only be able to access content on the site that is tagged with the terms set in this field.

# Answer
> 2 votes
Turns out I went with Access by Terms module after finding that the Term Access module did not work for me. Access by Terms also has permissions the make the field editable by certain roles in the profile and nodes, so that takes care of administration requirements too.

# Answer
> 0 votes
As per your requirement you can use Term Access module or its related modules.

From module's project page:

> ... controls node access based on taxonomy term fields. When the nodes taxonomy terms and the user taxonomy terms match, the user is awarded certain permissions.

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


title: show empty on Empty text: PHP code View

text:
# Question
Title: show empty on Empty text: PHP code View
1. I have a View that shows the user's latest posts on his/her profile.
2. If the user has no posts and it's own profile it show a link to encourage forum posting.
3. If the user has no posts and it's someone else's profile, the view should not be there.

Currently the first 2 are ok, but the last one is not returning as expected. I'm getting an empty div (styled).

In the view's Empty text I have PHP code:

```
<?php
    global $user;
    if (something_get_username_from_url_alias() == $user->name) {
        echo '<span>You have no forum posts</span><br>';
        echo l('Go do some posting', 'forum');
    } // else scenario where block not shown
?>

```

If the question is not clear, please let me know. Thank you.

```
$handler = $view->new_display('block', 'Self Profile: User Posts', 'block_3');
$handler->override_option('fields', array(
  'subject' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'link_to_comment' => 1,
    'exclude' => 0,
    'id' => 'subject',
    'table' => 'comments',
    'field' => 'subject',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'timestamp' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'raw time ago',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'timestamp',
    'table' => 'comments',
    'field' => 'timestamp',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'timestamp' => array(
    'order' => 'DESC',
    'granularity' => 'second',
    'id' => 'timestamp',
    'table' => 'comments',
    'field' => 'timestamp',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('arguments', array(
  'name' => array(
    'default_action' => 'default',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '',
    'breadcrumb' => '',
    'default_argument_type' => 'php',
    'default_argument' => '',
    'validate_type' => 'none',
    'validate_fail' => 'empty',
    'glossary' => 0,
    'ignorecase' => 0,
    'limit' => '0',
    'case' => 'none',
    'path_case' => 'none',
    'transform_dash' => 0,
    'id' => 'name',
    'table' => 'comments',
    'field' => 'name',
    'validate_user_argument_type' => 'uid',
    'validate_user_roles' => array(
      2 => 0,
      4 => 0,
      3 => 0,
      5 => 0,
      6 => 0,
    ),
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
    'default_options_div_prefix' => '',
    'default_taxonomy_tid_term_page' => 0,
    'default_taxonomy_tid_node' => 0,
    'default_taxonomy_tid_limit' => 0,
    'default_taxonomy_tid_vids' => array(
      1 => 0,
      8 => 0,
      3 => 0,
      34 => 0,
      33 => 0,
      32 => 0,
      31 => 0,
      7 => 0,
      6 => 0,
    ),
    'default_argument_user' => 0,
    'default_argument_fixed' => '',
    'default_argument_php' => 'return something_get_username_from_url_alias();',
    'validate_argument_node_type' => array(
      'magento_group' => 0,
      'magento_product_4' => 0,
      'magento_product_4_global' => 0,
      'magento_product_4_website' => 0,
      'magento_store' => 0,
      'magento_website' => 0,
      'forum' => 0,
      'article' => 0,
      'blog' => 0,
      'expert' => 0,
      'ingredient' => 0,
      'page' => 0,
      'profile' => 0,
      'recipe' => 0,
      'webform' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      1 => 0,
      8 => 0,
      3 => 0,
      34 => 0,
      33 => 0,
      32 => 0,
      31 => 0,
      7 => 0,
      6 => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_transform' => 0,
    'validate_user_restrict_roles' => 0,
    'validate_argument_node_flag_name' => '*relationship*',
    'validate_argument_node_flag_test' => 'flaggable',
    'validate_argument_node_flag_id_type' => 'id',
    'validate_argument_user_flag_name' => '*relationship*',
    'validate_argument_user_flag_test' => 'flaggable',
    'validate_argument_user_flag_id_type' => 'id',
    'validate_argument_php' => 'return true;',
  ),
));
$handler->override_option('filters', array());
$handler->override_option('empty', '<?php
    global $user;
    if (something_get_username_from_url_alias() == $user->name) {
        echo \'<span>You have no forum posts</span><br>\';
        echo l(\'Go do some posting\', \'forum\');
    } // else scenario where block not shown
?>');
$handler->override_option('empty_format', '3');
$handler->override_option('items_per_page', 5);
$handler->override_option('row_plugin', 'fields');
$handler->override_option('row_options', array());
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);

```

# Answer
> 1 votes
1. Use the No Results Behaviour (of type Text) under the Advanced section within the Views Module.
2. In the text part of the behaviour, add your code

if (something\_get\_username\_from\_url\_alias() == $user-\>name) { echo 'You have no forum posts
'; echo l('Go do some posting', 'forum'); } // else scenario where block not shown else { echo 'Nothing to see here...
'; }

---
Tags: views, 6
---


# Question
Title: My admin panel view fancy box not working
I am new to drupal. I searched this problem in google but could not get the solution that could solve my problem. My problem is,

I used a fancybox for one of my news post page. It uses latest version of Jquery. When, I use this, my fancybox works well. But, when I come to view page, My light box does not work there. Like,

When I click on add button \[Add button to add fileds or filters \], the sceen goes black and nothing happens. When I remove the fancybox, it works well. It is important for me to use fancybox. Please suggest how to solve this problem.

# Answer
I also faced the same problem. This is due to jquery problem. Let me tell you that jquery contains default support to jquery. It uses older version of jquery in its core. So, if u want to use that module, then, what u can do is:

1. Download jquery update module and enable the moudle,
2. Then you open the project code, moudles folder and find the jquery update moulde, there you will find replace folder. You, will find various version of jquery there. You can include or replace the latest version of jquery.
3. However the drupal core works in older version, so what you can do is open the jquery\_update.module file and find the line that says.

// Replace files for jQuery 1.7 and up if (version\_compare($version, '1.7', '\>=')) { $javascript\['drupal.states'\]\['js'\]\['misc/states.js'\]\['data'\] = $path . '/replace/misc/1.7/states.js'; } Now what you need to do is. You need to check, if the user is logged in then replace the jquery with core old jquery and if user is not logged in then, use the latest your fancybox jquery.
> 1 votes

# Answer
I found the same thing and patched fancy box. There was a missing permission for the settings page.

You might like to grab the dev release. http://drupal.org/node/1888814
> 0 votes

---
Tags: views
---


# Question
Title: Drupal response time incredibly slow, but only from some end-users
I am running across a super strange issue that is killing me. I am seeing response times coming back from my Drupal site of nearly 5+ minutes, but only for some end-users.

I have tested and ruled out a DNS problem. Pings comeback with 100ms response times, and when I swap the Drupal index.php out for a static index.html file, response time is lightning for all users.

I have an end-user in Argentina that sees 4 sec response times, and then when I try from my machine here in Los Angeles, 5+ min. The server is hosted on EC2 in their Virginia data center.

I have also tail'd the access logs and I see the Argentina user's traffic come in right away, but my traffic takes forever to show in the logs.

Is there anything in the Drupal configuration that you can think of that would cause something like this?

# Answer
> 2 votes
These kind of problems are extremely hard to debug, because it can be one of a million things. **My bet is that there's some server misconfiguration.**

If I was in your position, here's what I'd try to do:

1. **Try to reproduce the problem reliably** \- If you can reproduce this 100% of the time, then you know you have some method to reliably recreate the problem that you're facing. Try to identify any recent changes that might have caused this -- has it always been like this, or did you do something recently to cause this?
2. **Isolate the problem** \- You're most likely running on a LAMP stack. I doubt your OS is a problem, but it's most likely related to the Apache, MySQL or PHP side of things. Double check your php.ini settings, then your mySQL settings, and then your Apache settings.
3. **Debug / Profile** \- There's a bunch of ways to do this. Try the devel module and performance modules. If you're comfortable writing code and developing modules, try using debug statements to figure it out. If you're more advanced, profile your site using xdebug.

Good luck.

EDIT: I missed the part of about you running on EC2 -- still, the issue still stands. See if you can reproduce it reliably, and jump straight to profiling / debug.

# Answer
> 1 votes
If the users have the same role, I doubt it's a drupal issue. Most likely it's net, ping, route issue. Try to confirm this by accessing a small php script not related to drupal and check the responding time in both locations.

Try also a traceroute to your site from several locations. traceroute.org should give some help

---
Tags: performance
---


# Question
Title: How to use latest jquery version on specific page or code?
i am using D7. i want to use jquery1.9 on a specific block. so at where that block visible, only load jquery with it. how it wil??? any help?

# Answer
When I make a custom theme I use a little different solution. Maybe it's not perfect (and is very redundant) but I can use latest jQuery with my theme. I'm creating jquery.js with following code:

```
var oldjQuery = jQuery;
// latest jQuery code goes here
var jQuery19 = jQuery.noConflict(true);
jQuery = $ = oldjQuery;

```

and main.js with my whole JavaScript surrounded with:

```
(function($) {
  // my JavaScript code
})(jQuery19);

```

This allows me to use latest jQuery in my themes and default Drupal jQuery with admin theme. I'm adding this files directly in tpl.php files or sometimes in .info file. I'm sure you can use this also with custom blocks.
> 0 votes

# Answer
There are several ways to do it. If you want to update jquery, you can use jquery update moudle.

Second thing is you can use, `drupal_add_js()` function to include the jquery file to particular node.

Third thing is you can use the js, that is used in all the page in template.php or in theme.info file. I hope you are looking for second method. Also, this question will help you much.

Updating jquery
> 1 votes

---
Tags: 7
---


# Question
Title: Entity references linked to a wrong referent
On a Drupal 7 multilingual site, I have a content type containing a field\_group containing itself entity references fields.

I haven't enabled the i18n submodule "Synchronize translations" ("i18n\_sync").

I have a content in French:

* contentFR

+ entityreferenceFR 1
    + entityreferenceFR 2

I want to translate this content in Italian, so I translate the entity references first, like this :

* entityreferenceIT 1 (translation of entityreferenceFR 1)
* entityreferenceIT 2 (translation of entityreferenceFR 2)

Then, I translate "contentFR" in Italian, and associate my 2 Italian entityreferences to this new Italian content, like this:

* contentIT (translation of contentFR)

+ entityreferenceIT 1
    + entityreferenceIT 2

Everything seems to go perfectly well, except that, when I go back to my French content, the references are the italian ones, like this:

* contentFR

+ entityreferenceIT 1
    + entityreferenceIT 2

If I edit again the French content to set the French references instead of the Italian ones, the switch happens again in the other way:

* contentIT

+ entityreferenceFR 1
    + entityreferenceFR 2

This is a live production site with 5 enabled languages. We've just enabled Italian and the issue exists only since then. Before, with other languages, everything was working well; the entity references were not linked to a wrong referent.

Also, I've seen this quite similar thread (Node translation syncing problem with entity references) but:

* In my case, there's no synchronizing set on the reference field
* There wasn't any answer given in the original thread

The enabled i18 modules are: Block languages, Multilingual content, Multilingual select, Path translation, String translation, Taxonomy translation, Translation redirect, Translation sets, and Variable translation. The disabled modules are: Field translation and Synchronize translations.

Do you have any idea why this happens?

# Answer
> 1 votes
I guess you need to enable entity translation for this field; it can be done in the field UI, after installing the Entity Translation module.

---
Tags: 7, entities, i18n-l10n
---


# Question
Title: How can I create a select list with all languages?
I need to have a field on a form, where the user can choose from the set of world languages for an event.

It's going to be an Autocomplete term widget (tagging) field.

How can I reuse the inbuilt language list in Drupal for this purpose?

# Answer
there is the \_locale\_get\_predefined\_list which return you an array. so you need to do the field yourself.

you also could try language\_field, you should be able to use that directly in your form.
> 3 votes

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: white-space and minimum length validation in custom search
I'm using custom search for my website. Now I wan't to validate user input before search like validate white-spaces (just enter space in search box and you'll find all things goes wrong).

For minimum length validation drupal take cares for minimum 3 character, but if you enter less then 3 characters and press search button search results page appears and then it shows an error that you need to enter keyword with 3 characters or more.

I don't want to go on search results page until all validation criteria passes. In this case I want just red border on search box (this is happen when no text inserted in the search box and you press search button).

How can I validate white-space, minimum search keyword length and restrict user on same page until all validation criteria passes in custom search module?

# Answer
Found solution.. :) You need to modify `custom search` js file for achieve this. This file can be found at `sites\all\modules\custom_search\js\custom_search.js`. Edit this file as following..

```
if (!Drupal.settings.custom_search.solr) {
        // Check if the search box is not empty on submit
        $('form.search-form', context).submit(function(){
          var box = $(this).find('input.custom-search-box');

       //Search Box Patch Start

      var searchBox=$.trim(box.val());
          var searchLen = searchBox.length;

          if(searchLen < 3)
          {
            searchBox = "";
          }
          if (searchBox != undefined && (searchBox == '' || searchBox == $(this).find('input.default-text').val())) {
            $(this).find('input.custom-search-box').addClass('error');
            return false;
          }

          //Search Box Patch End

```

Here I edited this file for minimum 3 characters to search (without white-space) and if this criteria fails then no redirecting on search results page, you'll find red border on search box on the same page. This is my requirement, but you can edit file this as per your desire output.

(NOTE: Make sure that you disable Block Lazyloader module for use `custom_search.js` otherwise it will not work).

Hope this will help you...
> 0 votes

# Answer
You can use hook\_form\_alter(&$form, &$form\_state, $form\_id) and extend your validation process by adding $form\['#validate'\]\[\] = 'custom\_validation()'
> 0 votes

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


title: Webform i18n doesn't work

text:
# Question
Title: Webform i18n doesn't work
We have installed and enabled:

* Webform 7.x-4.0-alpha6
* Webform Localization 7.x-4.x-dev
* Internationalization 7.x-1.7

We have created several webforms (in English).

When I look `admin/config/regional/translate/translate` and select "Limit search to" to "Webform Localization", I see an empty list of strings to be translated.

This way we are unable to translate our webforms. Please help.

# Answer
Need to refresh in `admin/config/regional/translate/i18n_string`.
> 0 votes

---
Tags: webforms, i18n-l10n
---


# Question
Title: update only a part of url path in database
I am migrating website and I changed my mind about url path where my images are stored. Before the path looked like: files/name-of-article/image.jpg now I would like to change it to files/img/name-of-article/image/jpg. How it is possible to replace "files" with "files/img" string? I found following sql code but it works only for replacing whole urll path.

```
UPDATE field_data_body  SET body_value = REPLACE(body_value,'src="/olddirectory','src="/newdirectory');

```

Thank you.

# Answer
> 1 votes
Try the scanner module instead:

http://drupal.org/project/scanner

> Search and Replace Scanner can do plain text search-and-replace, or regular expression search-and-replace, against the title, body and text content fields on all nodes in your system. This is useful for finding html strings that Drupal's normal search will ignore. The module is very handy if you are fixing typos in a lot of content, changing the name of your company, **or are changing the URL of a link included multiple times in multiple nodes, among other things**.

Your sql query might work but this is a little more robust and has a rollback option.

# Answer
> 0 votes
Simple sql code like this did the job update `file_managed` set uri = replace(uri, 'public://', 'public://img')

---
Tags: 7, database, uri
---


title: How to use commerce_shipping hooks

text:
# Question
Title: How to use commerce_shipping hooks
I'm trying to construct a shipping module for UK's Royal Mail (or at least the parts I need right now...!). I've written PHP code for calculating what methods are applicable based on shipping address and weight, but plumbing this logic into my site is eluding me. I should add that, as Royal Mail doesn't have an API for pricing, my module bundles the rate-tables for the various methods/services (CSV format) so I need to use code, not Rules, to implement it.

It seems the way to do this is to use the **hook\_commerce\_shipping\_\*** hooks, but it doesn't appear that I'm doing so correctly.

This is my first experience with using hooks (and Drupal on a serious dev level, TBH) but I have successfully implemented **hook\_commerce\_cart\_product\_prepare()** in another custom module, so I think what I'm doing should be working. In my module I wrote the following, just to test that I'd successfully implemented the hook:

```
/**
 * Implements hook_commerce_shipping_calculate_rate()
 */
function royalmail_commerce_shipping_calculate_rate($line_item) {
    drupal_set_message(print_r($line_item, TRUE),'error');
}

```

...and it seems I hadn't, because the message never appeared when I progressed to the shipping pane of the checkout.

I also tried various other "canaries" I should be able to spot evidence of, including but not limited to drupal\_exit(), echo, die(), var\_dump() and so on, but nothing appears. Same story for hook\_commerce\_shipping\_collect\_rates(), which I actually tried to implement first but ended up doing so with Rules instead while I was scratching my head (though I'd prefer this be in native code too, ideally).

Am I doing it wrong? Thanks in advance.

# Answer
It looks like you are using commerce shipping 2.x which differs a lot from 1.x in terms of integration.

What you need to do is:

1. Define a shipping method, use `hook_commerce_shipping_method_info`.
2. Define one or more shipping services use `hook_commerce_shipping_service_info`
3. When you define the shipping services, you can select a rate callback, if none is selected, commerce shipping will by default try to use `SERVICE_NAME_rate`, where `SERVICE_NAME` is the keyed name used in the `hook_commerce_shipping_service_info` hook. The rate callback have this signature:

```
function service_name_rate($shipping_service, $order) {
  // Logic here.
  return array(
    'amount' => $amount,
    'currency_code' => $currency_code,
    'data' => array(),
  );
}

```

You can look at the example module within the commerce shipping module which serves as documentation, or you can look at some of the other shipping methods, like UPS.
> 0 votes

---
Tags: 7, commerce
---


title: Using debug with services 3

text:
# Question
Title: Using debug with services 3
I'm desperately trying to debug some problems I'm having with creating an manipulation of nodes in drupal 7 Services 3.

I've tried to insert a few debug statements to figure out where things are going wrong. When I create a node using poster (from the browser) it worked great, it prints the info I want.

When I do it from my app (iphone app), the same function is called, but the debug does not seem to print out to the page, even if I refresh it. I wonder what I am doing wrong.

Thanks

# Answer
Standard debugging functions like `dpm()` and `dvm()` use the `drupal_set_message()` function, which is tied to a user's session. When you try using the node form, you see the message because it is saved to your session. However, when you use the service via your iphone app, the messages get saved to a session that is probably not the one you're logged in under.

Fortunately, for situations like this, you can use the `dd()` function, which will print the debugging information out to a file in the `/tmp` directory, typically called `drupal_debug.txt`.

**\[edit\]** I notice you're using the `debug()` function, which triggers error handling, note that this also uses `drupal_set_message()`, so the above is still relevant. (The `dpm()` and `dvm()` functions are from the Devel module.)
> 2 votes

# Answer
You could also try using `watchdog()`.

```
watchdog('debug', '<pre>'. print_r($example_array, TRUE) .'</pre>');

```
> 1 votes

---
Tags: 7, services
---


# Question
Title: Is it a great idea to upload php instead of writing phps in drupal interface
At each time I write PHP code in blocks and views, I always think about this question : "What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?".

Is it a great idea to make users able to send php files instead of writting it. It would be a first step to manage the code after with name conventions to find the code easily and to be also able to read easily the code?

Or it's just a stupid idea that will generate a security mess ??

# Answer
> 1 votes
I think the solution is to put PHP codes in hooks... And anyone could say that it's insane to create a module just for one or two lines of codes... But most of time, drupal users has to do somthing like this several times in drupal. So why not combine all these hooks in one module that we might call whatever we want. So then just well-comment the code for good reading.

The little snag is : is there hook for each actions where we can add php code ?

---
Tags: security
---


# Question
Title: How do I automatically load a bunch of JS/CSS from sites/all/libraries without hook_library?
My question is simple.

Is there a straightforward method to load a library e.g. ibeginshare (it contains 2 css, an images folder and 1 js) which I copied in `sites/all/libraries` to use it in my module?

I have created a module that implements hook\_block\_info and hook\_block\_view and I want to load this library in its hook\_init.

Is it mandatory to use hook\_library and define there everysingle file then call it via drupal\_add\_library? I am confused. What if I have dozens of js/css files ? What if I don't want necessarly to share the library with other modules?

NOTE I managed to load the file like this:

**METHOD 1**

```
function MYMODULE_init() {
  drupal_add_js('sites/all/libraries/ibeginshare/share.js');
}

```

I would like a more elegant way so I tried:

**METHOD 2**

```
function MYMODULE_init() {
  drupal_add_library('MYMODULE', 'ibeginshare');

}

/**
 * Implements hook_library().
 * @return string
 */
function MYMODULE_library() {
  $libraries['ibeginshare'] = array(
    'title' => 'ibeginshare',
    'website' => '',
    'version' => '1.2',
    'js' => array(
      'sites/all/libraries/ibeginshare/share.js' => array(),
    ),
    'css' => array(
      'sites/all/libraries/ibeginshare/share.css' => array(),
    ),
     'css' => array(
      'sites/all/libraries/ibeginshare/share-print.css' => array(),
    ),
  );

  return $libraries;
}

```

this loads all libraries but the plugin doesn't initialize. I wonder why. I think will work if I add a weight property in the hook\_library but anything I tried didn't work.

# Answer
Assuming you are on Drupal 7, `drupal_add_library()` will do just that for you. From the function's API page:

> Adds multiple JavaScript or CSS files at the same time.
>
> A library defines a set of JavaScript and/or CSS files, optionally using settings, and optionally requiring another library. For example, a library can be a jQuery plugin, a JavaScript framework, or a CSS framework. This function allows modules to load a library defined/shipped by itself or a depending module, without having to add all files of the library separately. Each library is only loaded once.

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_library/7

Note that you first need to define and register the library with `hook_library()`.

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_library/7
> 2 votes

---
Tags: hooks, theming
---


title: Loading Video Files via Ajax and Views

text:
# Question
Title: Loading Video Files via Ajax and Views
I am looking for a way to implement a gallery style selection for a content type containing multiple videos. I am using Drupal 7.

I have a content type called roles which has a title, banner image, description, videos and video thumbnails.

The videos and video thumbnails are file fields which can accept multiple files (the idea being that you can upload the videos then the thumbnail for each video in the same sequence).

At the moment to display videos on the site I am using mediaelement - however for this page layout I need to be able to show the video thumbnails then let the user select and have it load the video via an ajax call.

I have tried using views filters exposed to the user based on the videos file id, however this seems to break the videos.

Is there another way to accomplish this in views? Or is there another way to accomplish what I am trying to do?

# Answer
I slightly changed the way I handled this after following the excellent tutorial Creating a Simple AJAX Interface with Views

All is up and working now.
> 0 votes

---
Tags: views
---


title: Create webform on node insert?

text:
# Question
Title: Create webform on node insert?
How do you create a webform on a node insert?

I create an event content type and want to automatically add a webform with 3 fields (lastname, firstname, e-mail) on node insert of the event. I do not want the client to add the webform each time he creates an event node. I want a webform per node.

# Answer
Under /admin/config/content/webform you can enable your event content type for webforms, and the form will be created as part of the node creation process.

Edit: Misunderstood!

Webforms are one-off forms. If I now understand correctly, you want to re-use a standard form on each event page (only one form created).

To do this, create a webform with the required fields, and while editing the form, go to the webform tab \> Form Settings. Under Advanced Settings at the bottom select 'Available as Block'.

You can then use the Block settings to display the form on every Event page as required.
> 2 votes

---
Tags: 7, webforms
---


# Question
Title: Omega and Panels: Is there a way to change "Omega XX column grid" layouts?
I´m trying to work with the 3.x Omega version and Panels. I´ve selected "Omega 16 column grid" at the panel´s layout category. **Is there a way to change those layouts?**

***ie. There´s this "Two Column 8-8" and I need "Two Column 9-7"*** I´ve tried with "create custom layout", but can´t make that work.

Thanks for your help!

# Answer
What you need to do is update your region area in omega to adjust the # of columns each one takes up.
> 0 votes

---
Tags: 7, panels, theming
---


# Question
Title: Is there any performance issues in using Omega theme with Context, Delta and Panels modules?
Is there any performance issues in using Omega theme with Context/Delta modules **and** Panels module too? (I mean the context standalone menu, not the one inside panels)

Is there any known issue? I´ve read about some issues with Omega and panels *in the past*, but now they work just fine. And I need context for my homepage, to create a slighty different layout than the rest of the site.

# Answer
it depends on your site and server configuration. if you get alot of anonymous traffic that doesnt require users to login, you should be fine as the cache would handle alot of that load. Also be sure to turn on js / css aggregation. I've built many sites with those modules combined and they run fine. But if your all about performance, you can just do everything by hand and write your own templates/css and not use the bloated ones they have, but you'll be spending alot of time. in that effect you'll have total control over what gets outputted to the user.
> 1 votes

---
Tags: panels, theming, 7
---


# Question
Title: how to edit multiple menu itmes on menu management page
Is there a way to edit multiple menu items on menu management page. I have a site with lots of menu items under one menu, if I want to change the parent of multiple menu items I will need to drag each menu item individually to the parent. Is there a way we can select multiple menu items and change there parent.

And is there a module which allows us to collapse and expand the menus as per our requirement.

Some thing like Taxonomy Manager Module.

# Answer
i dont think there is a module that lets you do bulk menu item edits. another option you might want to try is just show the weights of each item and manaually adjust it in that manner so you dont have to drag each one.
> 0 votes

---
Tags: routes, nodes
---


title: Workflow edit but not publish

text:
# Question
Title: Workflow edit but not publish
I am using workflow module to manage article moderation. I have created different state for that and for each state, I have set permissions using workflow content access.

Now, when an article is flagged, I am changing it's workflow state to say "s1" and unpublished the content.

In this state, author's can allow to edit the content but not publish it, the edited content will be sent to admin for review.

Now when I go to edit tab, it is showing "Publish" button too, by which author can Publish the content.

How can I remove these buttons ? Also is there any way, I can show workflow comment box in edit node page only.

-- Many thanks for your time.

# Answer
The 'Publish' button isn't determined by the **state** of the node according to your workflow. Actually, whether the 'Publish' button appears is determined by the **permissions** you have as a user.

So if *you* look at the content in the s1 state, you may see the 'Publish' button, because you're an admin. An author looking at that same piece of content in the s1 state, however, shouldn't see that button based on the workflow moderation permissions you've given them. Does that make sense? It's not the workflow state, but the individual's permissions that determine whether that button is available.

So test it out by logging in as an **author** to see what they would see. If you can still see the 'Publish' button when you're logged in as an author, that may mean that you've inadvertently given that role a permission you didn't intend, such as 'Administer content', so double-check the permissions again. :0)

My authors definitely can't publish in some of my workflow states!
> 0 votes

---
Tags: 7, workflows
---


# Question
Title: How do I cache the result of db_query()?
I used `views_get_view_result()` to get results from a view because it was convenient at that time. The query result rarely changes; I could use views caching for 6 days.

If I wanted to convert it to a call to `db_query()` how could I enable caching?

# Answer
> 9 votes
Doesn't mattter for caching if you use views or db\_query(). Caching works always the same, how the data is fetched when the cache misses is completely up to you.

1. Build a cache ID to identify your cache entry. Can be a simple, hardcoded string or something complex based on arguments and so on.
2. Check if can load from the cache.
3. If not, rebuild data and put it into the cache with the desired expiration time.

To see some examples, you can look at the functions that use cache\_get(), for example variable\_initialize().

If your function is called multiple times then you probably want to combine it with a static cache, see for example archiver\_get\_info(). And if the data rebuilding is really slow, you can prevent it from happening multiple times by using the locking framework as variable\_initialize() does.

Note that caching a single query only makes sense if it's a slow one, because a cache\_get() is also a db query unless you use an alternative cache backend like Memcache.

And lastly, Views has caching already built-in and can be configured in your view. So that might be an option as well.

# Answer
> 8 votes
I don't think the DB layer has any built in caching mechanism (though I might be wrong), but you could make use of the default cache API.

This is just a basic example that will cache the results of a query to get nodes of a certain type:

```
function MYMODULE_get_nodes_by_type($type) {
  // Setup a cache ID
  $cid = 'MYMODULE:node_types:' . $type;

  // If a cached entry exists, return it
  if ($cached = cache_get($cid)) {
    return $cached->data;
  }

  // Otherwise load the data
  $data = db_query('SELECT * FROM {node} WHERE type = :type', array(':type' => $type))->fetchAll();

  // And cache it
  cache_set($cid, $data, 'cache', strtotime('+6 days'));
}

```

# Answer
> 3 votes
In addition to the standard cache\_set / cache\_get mechanism that Drupal provides, if you are using MySQL as your database, then you can enable the query cache, which can cache the results of views, or any other database queries, transparently. mysqltuner can aid in figuring out good values for the cache size.

Just note that if you are doing a lot of writing to the database, then query caching becomes less effective because of the way the cache invalidation strategy works (a write to a table invalidates all entries that SELECT FROM or JOIN that table).

There is also a caching mechanism for PostgreSQL, but I don't have direct experience with it.

# Answer
> 3 votes
I recently discovered the Cache Actions module. With this module, you can set your view caching to Rules-triggered Cache and create a rule for invalidating the cache on specific views and views displays.

For example, the cache for a view that lists nodes of a specific content type can be emptied when a new node is created of that content type.

---
Tags: 7, caching
---


# Question
Title: Drush: Wrong PHP version when trying to sql-sync with SSH
I'm trying to upload a database on the server with SSH by using sql-sync, but I'm getting the following error:

> PHP Parse error: syntax error, unexpected '{' in /home/luken/programs/drush/includes/environment.inc on line 517 X-Powered-By: PHP/4.4.7 Content-type: text/html \[...\]

As you see from the error message, it is using PHP 4.4.7, while I want to use PHP 5.4.

I tried adding the following line to .bash\_profile.

```
export DRUSH_PHP=php54 (that is php version I wanted to use, and it works when I normally log in)

```

I also tried with `PATH=/home/luken/programs/drush:${PATH}`.

What else can I do?

`phpinfo()` gives this path to PHP: /usr/local/php54/.

**Breaking news:**

Ok, now I'm totally confused, it appeared that the whole database WAS copied, regardless of error that sql-sync has been producing (suggesting that nothing has been accomplished). I hope that anyone who will get this error will check now if it really didn't do anything, and now the winner will be the one who can explain that O\_o.

# Answer
> 1 votes
Check the user that is specified in your Drush alias file. From the error message above, my guess is that you have configured your alias file to use the web server user, and your web server user is probably not configured to use php-cli -- that's probably why you're getting an old php-cgi instead. Log in as the web server user (you may need to edit /etc/passwd and change the shell to /bin/bash first), and then configure your path and DRUSH\_PHP environments as you describe above.

Alternately, you could use some other user in your Drush alias file. I like to create a user called 'www-admin', or something similar, and make all of my web files owned by that user.

# Answer
> 0 votes
from a terminal try:

`$ which php`

Look at @greg\_1\_anderson's answer as a drush native drush configuration approach to fixing this problem.

You can always fix this in Bash using an alias to your drush command to the absolute path of the PHP version you want to use, eg in `.bash_aliases` or `.bashrc`:

`alias drush=/usr/local/php54/bin/php /path/to/drush/folder/drush`

or

`alias drush=/usr/local/php53/bin/php /path/to/drush/folder/bin/drush`

---
Tags: 7, drush
---


# Question
Title: Commit doesn't show up in profile on Drupal site
I submitted a small patch on no trigger dependencies in job\_scheduler\_trigger.info. It looks like the patch worked, but when I look at the commits tab of the drupal.org profile, I don't see any entry.

When using Git, I created a new branch for the issue, made the changes, and then checked in. Should I have switched back to the development branch and checked in?

# Answer
Commits submitted in the issue queue are only counted when the maintainer accepts them and credits you with the patch. Otherwise, people could just spam useless patches through drupal.org to increase their commit counts.
> 3 votes

---
Tags: community-official-site, version-control
---


# Question
Title: how to retrieve the index size of a field array
What I am working with it this. I have a custom content type with an image field (field\_img) that accepts multiple images so they are stored in an array. what I need to figure out how to do is one of two things and I need to do them from the node--custom.tpl.php if possible.

1: get the size of the $node-\>field\_img array so I can then loop through and assign appropriate HTML id's for each image in the content type.

OR

2: directly loop through the field\_img array using maybe foreach() to set the id of each image in the content type to an appropriately unique value.

what I am able to do here works for one value because I can put in the actual index of the instance I am working with but the arrays are not all the same length some have 10 images some have only 6 so I need something that will loop through the array.

Here is the static code that works for one element

```
<div id="gallery-img-wrapper">

<?php $i = 0 ?>

<img class="album-image<?php print $i ?>" src="<?php print render (file_create_url($node->field_img['und'][$i]['uri'])); ?>">

</div>

```

this is inside node--gallery.tpl.php and it works fine but it only displays 1 image and I need 14 or how ever many there are for the instance of the content type.

# Answer
You mention `foreach()`, but did you try it? Seems to me that it should work. `foreach($node->field_img[LANGUAGE_NONE] as $key => $value)`
> 1 votes

---
Tags: entities, theming, media
---


title: Customized Vertical Menu

text:
# Question
Title: Customized Vertical Menu
I am little bit familiar with Drupal but have no idea how to approach this problem. I want to create a menu in the following style with straight continuous lines for each tab.

```
                  ----- sub1
                 |
    tab1---------|----- sub2
                 |
                  ----- sub3

```

How can I do it?

# Answer
> 1 votes
use the super fish module. http://www.drupal.org/project/superfish that should do what you need.

---
Tags: 7, routes
---


# Question
Title: Use email to validate post, not unlike craigslist
I'd like for anonymous users to be able to post nodes to my site. By default their post is unpublished, but when they submit it, the site sends an email with a verification URL. When they revisit the site with that URL they can then publish their node.

Call this the 'craigslist model.' :-)

Restating: I want users to be able to publish their own node anonymously, by linking out of an email.

I've been unable to find a module or setting that does this, and I thought I'd ask before diving into code.

Update: Found this unmaintained Drupal 5 project: Anonymous publishing.

Similar question: How can anonymous users be allowed to post while still maintaining content integrity?

# Answer
> 6 votes
You can use the Rules module, but you'll have to write a custom rule to grab the email from the submitted node and send a verification link to the email address. You could also do this with a custom function through hook\_entity\_insert().

For the verification link you could do use drupal\_hmac\_base64() to create a url-safe hash of the content of the post or of the node + timestamp + email or something like that.

Then you can create a custom menu to fire a callback function that takes arguments from the verification link to publish the node if the verification link is correct.

# Answer
> 5 votes
You should be able to use Anonymous Publishing for this.

There is now a Drupal 7 port that can be downloaded. It is still in development, but the "Craigslist model" for anonymous publishing has been working on my test-site and seems to be stable. I am now looking for others that are willing to test the code, and confirm that it is ready for a full release.

Disclosure; I an the maintainer of Anonymous Publishing

# Answer
> -1 votes
You could use the Rules module for this: When a user posts a node, an email with a link to the node is sent to the admin, or a user role that you want to revise the node.

Using this method will save you much time than diving into code.

---
Tags: 7, emails, nodes
---


title: Jquery animate in Views slideshow

text:
# Question
Title: Jquery animate in Views slideshow
Is there any way to add some jQuery animations in each slide of a slider created with Views Slideshow module?

# Answer
You might want to try the Views Slideshow Xtra module

> Views Slideshow Xtra is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.
> 1 votes

---
Tags: views, javascript
---


# Question
Title: How to theme "My Results" (quiz module) tab that´s inside the user´s profile?
I´m using quiz module in Drupal 7, and need to theme the output in "My Results" (wich is a tab in the user profile page).

Here´s the module´s function :

```
// THEME FUNCTIONS

/**
 * Theme the user results page.
 *
 * @param $results
 *  An array of quiz information.
 * @return
 *  Themed html.
 *
 * @ingroup themeable
 */
function theme_quiz_get_user_results($variables) {
  $results = $variables['results'];
  $rows = array();

  while (list($key, $result) = each($results)) {
    $interval = _quiz_format_duration($result['time_end'] - $result['time_start']);
    $passed = $result['score'] >= $result['pass_rate'];
    $grade = $passed ? t('Passed') : t('Failed');
    $passed_class = $passed ? 'quiz-passed' : 'quiz-failed';
    if (!is_numeric($result['score'])) {
      $score = t('In progress');
    }
    elseif (!$result['is_evaluated']) {
      $score = t('Not evaluated');
    }
    else {
      if (!empty($result['pass_rate']) && is_numeric($result['score'])) {
        $pre_score = '<span class = "' . $passed_class . '">';
        $post_score = ' %<br><em>' . $grade . '</em></span>';
      }
      else {
        $post_score = ' %';
      }
      $score = $pre_score . $result['score'] . $post_score;
    }
    $rows[] = array(
      'title'       => l($result['title'], 'node/' . $result['nid']),
      'time_start'  => format_date($result['time_start'], 'short'),
      'time_end'    => ($result['time_end'] > 0) ? format_date($result['time_end'], 'short') . '<br />' . t('Duration :  @value', array('@value' => $interval)) : t('In Progress'),

      'score'       => $score,
      'evaluated'   => $result['is_evaluated'] ? t('Yes') : t('No'),
      'op'          => l(t('View answers'), 'user/quiz/' . $result['result_id'] . '/userresults'),
    );

  }

  if (empty($rows)) {
    return t('No @quiz results found.', array('@quiz' => QUIZ_NAME));
  }

  $header = array(
    t('@quiz Title', array('@quiz' => QUIZ_NAME)),
    t('Started'),
    t('Finished'),
    t('Score'),
    t('Evaluated'),
    t('Operation'),
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= '<p><em>' . t('@quizzes that are not evaluated may have a different score and grade once evaluated.', array('@quizzes' => QUIZ_NAME)) . '</em></p>';
  return $output;
}

```

Now, all I need is to theme the output, and maybe add some special header before the results.

I´ve tried this at my template.tpl.php file, without any success:

```
function mythemename_quiz_get_user_results($variables) {
print "This is some information";
print "<div class="results">";
print $variables;
print "</div>";
}

```

Now I know that `print $variables;` isn´t the way it should print an array, but the way to do this in Drupal 6 was this (I´ve took this code from an issue in Drupal´s forums):

```
function phptemplate_quiz_get_user_results($results) {
  // $results - An array of quiz results.
  // overriding statements
  print_r($results);
}

```

The function´s name changed, but the process shouldn´t be similar?

Thanks for your help!

# Answer
> 1 votes
Copy and paste (and rename) the original theme function to your template.php file, than just change what you need. Remembering that $variables is an array. Use the dpm function of the devel module to look at what values are in $variables that you can use.

---
Tags: users, theming, quiz
---


# Question
Title: Zen Theme Outputting Term Desc in Node - How To Add To Views
Hello i am using a zen based them Plain Grail. I nitice that on nodes it shows the term description on hover in nodes. I would like to achieve this effect in some of my views.

I have seen this question asked on here before but because my theme is already outputting this i thought it best to ask a new question.

I cannot see any reference to this in Plain Grail or Zens template.tpl

Does anyone know how i can show the term description in Views? thanks

Drupal 6 and Views 3

# Answer
> 0 votes
See source of term:

```
<a href="/index.php?q=taxonomy/term/1" rel="tag" title="Some descr term01">term01</a>

```

So term's descrtiption here just title attribute.
So for **Views** you can add field with link (or rewrite output), and put in Title some placeholder name.

---
Tags: views, 6
---


# Question
Title: overriden term name not translated on a taxonomy overriden views page
I'm using Title module with Entity translation to translate my taxonomy terms. I have overridden my term page with a view with term id as contextual filter. In the contextual filter section, I'm overriding the title view page with the contextual filter %1. I'm validating the contextual filter by checking if it's a term id.

Unfortunately the title page is not translated. In my case term name displayed is always the one in English.

Just to test further, if I'm adding 2 fields term name and term description to my views. The 2 fields are correctly translated, by switching languages.

# Answer
Install Internationalization Views module.

then select this, Advanced \> Contextual filters \> Content: Has taxonomy term ID (with depth)" \> select the validator "Taxonomy term (i18n)"

See here
> 2 votes

---
Tags: 7, views
---


# Question
Title: Back button form in node linking back to view
I think the user who asked https://drupal.stackexchange.com/questions/49853/how-to-setup-go-back-button-in-views is trying to do a similar thing.

Is there a way within the Views module to add one to the node content output content from a view?

I don't want to use the Back Button module for this; I would prefer to use the Views module, if possible.

# Answer
> 2 votes
You can not do this with the views module alone. A views link will simply link you to a node page and when you are on the node page, it does not know how you got there.

you could do this, which is basically the same as pressing the browser back button:

```
<input type="button" value="Go Back" onclick="window.history.back()" />

```

or this:

```
<?php
  $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
  echo '<a href="'.$url.'">go back</a>';
?>

```

# Answer
> 0 votes
```
<FORM><INPUT Type="button" VALUE="Back" onClick="history.go(-1);return true;"></FORM>

```

I am using the above in initial page for view but it is the node which needs it as well.

I invite further answers.

---
Tags: views
---


title: Error on installing module

text:
# Question
Title: Error on installing module
I've got Drupal 7.20 on my server (skyislands.pl). I wanted to install (from my local computer) Wysiwyg module (http://drupal.org/project/wysiwyg), but I see this error. My server is running on EHCP. How can I solve this problem ?

Thanks for any help,

# Answer
It is a permissions problem. You will be able to install the module by downloading it and putting it into your sites/all/modules folder
> 2 votes

---
Tags: 7
---


# Question
Title: Views Slideshow, show alternating content types
Does anyone have an idea how i might display a slideshow with alternating data (odd even style) of content type?

Currently the view is loading the fields, and i guess it could be one step closer to load the rendered node, but how can one alternate it, and limit it?

So like : Slide 1: Article Slide 2: blog Slide 3: Article Slide 4: blog etc..

# Answer
> 0 votes
In broad strokes, you could use Views' views\_pre\_render() hook to reorder the result of the View, eg...

```
function YOURMODULE_views_pre_render(&$view) {

   switch ($view->name) {

      case 'NAME_OF_YOUR_SLIDESHOW_VIEW':

        // to figure out what you have to work with, take out when done debugging
        drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

        // and here are the broad strokes... cycle through $view->result and
        // grab all the "rows" and re-order them by whatever business logic
        // you need, in this case even or them by content type instead of whatever
        // logic it is sorted in originally.  it you then set $view->result to this
        // new order, it will then be rendered by the Slideshow in that order

        break;

      // other Views might go here

   }

   // other code might go here, too...

}

```

---
Tags: views
---


# Question
Title: Lightbox 2 - Embeded Media Field / Media : Youtube can't play videos on LightBox2
I tried using both 'Embed media field' and 'Media : Youtube' module in D& website to create a content-type field to embed youtube videos and play in on lightbox2. Although images work well with the lightbox, there is some problem with videos.I enabling the videos settings under configuration/User interface/Lightbox2 but is of no use.

All i want is to play youtube videos in the lightbox

# Answer
Something I have done in the past is create a content for my video and use your embedded media stuff you already have.

I then change the Manage display to not show the video on the full content view.

I then use a module like Colorbox Node to render just the video in a colorbox window. You do this be editing the Colorbox display to only show the video.

So your full node page content has everything but the rendered video. You add a link that points to the current node page as a colorbox node link. When the user clicks on that link it will show the video.

So you are essentially switch the display based on how the node is rendered. Either through a full page or through a colorbox modal. Saves on code duplication :) and keeps it compact.

Does that make sense?
> 0 votes

# Answer
You can install Embedded Media Field module and Video Embed Field module.

Then add a cck field of type "Video Embed" and widget "Video" for a content type.

In that field you can enter the youtube video url. Then display that node in lightbox and it will work fine to play in the lightbox.
> 2 votes

---
Tags: nodes, media, javascript, files
---


# Question
Title: Blank window when i press select media link
I have created a video content type, created a video field, and used media asset.
When I create a video node and click on "Select media," a blank popup shows up. In this blank popup, I have to choose in which way to upload file.

In the Firefox error console I see the following error:

> TypeError: this.contentWindow.Drupal.media is undefined

I am using Drupal 7.20 and the latest version of the Media module.

# Answer
Use Firebug or Chrome Developer tools and look at the "Network traffic" and "Console" windows. I'll bet your getting a 404 or a JS related error in 1 of those windows.

You can then correct your server file permissions, fix the JS code error, or whatever.

You dont just have a blank page -- you have a blank page and an error reported somewhere.
> 2 votes

---
Tags: media
---


title: Custom Fonts in Drupal

text:
# Question
Title: Custom Fonts in Drupal
I use an Omega subtheme in my Drupal 7 site, and I'd like to change the default font to a custom font. How can I do this?

# Answer
> 13 votes
This question is over 6 months old. The best solution now for adding custom fonts is to use the @fontyourface module.

# Answer
> 8 votes
I highly recommend Google Webfonts, as @dibs suggested.

Here's the code to include the webfont into your Omega subtheme:

```
function omega_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=Lato',array('type' => 'external'));
}

```

Add that to your sites/all/themes/your\_omega\_sub\_theme/template.php file.

The URL is the one google webfonts gives you (pick a font and click "Quick use"). Or you can use another online font site.

Now that your font is imported (I used "Lato") you can edit your subtheme with something like this:

```
body {font-family: 'lato'}

```

# Answer
> 6 votes
@font-your-face is the best to use Fonts on your drupal site, just enable the font and make changes to your css files. you are done

# Answer
> 3 votes
If you want to use custom fonts, you should give font-face a try.

You can read more about this technique here.

Once you have created your font-face font, you should use your theme CSS files to set this font to whatever elements you want.

You might also consider to go with Cufón library, and you can even find a Drupal module for it.

The Cufón library renders fonts using canvas tags, which makes text unselectable; Fontface is a much more flexible solution.

# Answer
> 0 votes
If you do want non-standard fonts on your website and are unsure about the copywrite of using them, try a font web deliverer such as typkit.com. They have a plan where you can use any of their fonts and they sort out the copywrite for you. There is a module which implements this into drupal 7 also.

# Answer
> -1 votes
You should check out Google web fonts.

http://www.google.com/webfonts

* They are easily added to a site
* Open-source
* Large selection. 500+ font families at time of writing.

# Answer
> -3 votes
Fontyourface module now supports google fonts so no need to add code manually.

---
Tags: 7, theming
---


# Question
Title: How to creat different user type in drupal?
I want to create two different type of users for example internal and external users. For internal users need to be authenticate against different database. Any suggestions?

# Answer
> 6 votes
Unless you wish to write a custom module with direct access to the second database, with its own login system, the only way this is going to work is with direct manipulation of the drupal database, renaming tables, and using 'Create View ...' to give you access to the information. The amount of work, maintenance problems, and security implications would be horrendous.

If the number of 'internal' users is fairly static, my suggestion would be to use the User Import module, and give them all a role of 'Internal', using the user permissions to control their abilities on the site. Any new Internal users could be added manually.

# Answer
> 0 votes
I suggest you redirect each user based on his IP address, to a different domain, so take a look at these modules:

Domain Access

IP to Locale

Update: Prior to your comment, take a look at this doc

---
Tags: 7, users
---


# Question
Title: How do I enable comments for forum like statuses module?
i used this module project statuses (drupal 7) i want that write comment for forum like above module.
how can i do assign statuses style to comments forum?

# Answer
> 0 votes
You cant, the statuses module has quite a different concept and doesn't have anything to do with content-types commenting(e.g drupal forum), but if your problem is just to make your forum comments look like statuses, you can simply achieve that via some styling or templating your forum comment tpl file (better approach). for the sake of Ajax, you can use Ajax Comments module, but its not so much stable yet. if you still need further help don't hesitate to ask!

---
Tags: views, 7, ajax, comments
---


# Question
Title: Store anonymous user selection temporarily until registration
I want to let my first time visitors to first select a city, which will control what they see in my site, so it should be stored where I can see it everywhere (views, search and when posting content) until the user registers which then I store it in the user profile for later use.

Is that possible without development? if development is mandatory, what are the right steps to do so?

# Answer
> I want to let my first time visitors to first select a city.

okk... so is this selection apart of say their Registration Process, if so you have 0 code to write? or some other random landing page on the site you are funneling new traffic too ... in which case you have to write some code ...

Anyways I would:

* Add a field like `user_location` to their Account Profile fields under `Admin -> Account Settings -> Manage Fields` ... or use the Profile module to add such a field to a profile. There are "location" contributed modules for location type drupal Fields as well ... not sure what or how you want to store a "city" reference (string, geocode, zip, country + city, whatever).
* Then that field will be available everywhere as apart of the `$user` object.

If, you want this field to be collected before a user has registered (or separate from the registration process -- any fields in a users account settings can be made *apart* of the registration process). I would:

* create a simple module and define a FAPI form with a country list. The list\_predefined\_options module may help you make this list and manage it in code ...
* store the value in the users Cookie session value. Upon login use hook\_user\_login to look for the cookie value on 1st login to update the account `user_location` field with the session value.

Good luck.
> 0 votes

---
Tags: views, users, sessions, cookies
---


title: Replaced form AJAX not working

text:
# Question
Title: Replaced form AJAX not working
I'm facing a problem with Ajax enabled forms, so this is the scenario. I have 2 blocks, the first one has some buttons and the other one has a form ,constructed using the Form API.

When I click any of the buttons in the first block and AJAX Request is sent to the server, then in my callback function it replaces the second's block form data with new values, for doing this I call the drupal\_get\_form function, so the code for the callback is more or less like this:

```
$form = drupal_get_form('panorama_info_form');
print render($form);

```

And the elements of the form have the following style:

```
//Text field for title
$form['panorama_titulo'] = array(
        '#type' => 'textfield',
        '#title' => t('Nombre del panorama'),
        '#default_value' => $panorama['titulo'],
        '#description' => t('Nombre del panorama'),
        '#size' => 40,
        '#maxlenght' => 120,
        '#required' => TRUE,
        '#prefix' => '<div id="panorama_titulo_div">',
        '#suffix' => '</div>',
        '#ajax' => array(
          'callback' => 'panorama_info_form_callback',
          'wrapper' => 'panorama_titulo_div',
          'method'  => 'replace',
          'effect' => 'fade',),);

```

Now, in my jQuery Http 200 success function I replace the old form with the response data like this:

```
function reload_element(data){
    $("#panorama-info-form").replaceWith(data);

```

}

where data is the rendered form.

This works, and I can see my form with the new default values that I declared, however after the form is replaced, ajax is no longer triggered by events. What I mean is that before I replaced the form with jQuery, it used to work, the value was sent to the server and the callback function declared for the textfield was in fact getting called. However after the replacement, no more ajax request... Why is this happening??? I guess that's because there's some kind of script that uses the form's element's classes to attach functions dynamically to it... Maybe that could be one reason. How could I fix this??? Thanks a lot.

# Answer
> 2 votes
You don't post the code performing the actual AJAX request, so I have to assume it's directly calling an URL returning just the rendered version of the textfield wrapper with id "panorama\_titulo\_div".

Since this is sort of side-stepping Drupal's own AJAX functionality (which operates on a per-form basis, initiated by the "#ajax" key being present on certain elements), you'll need to perform some steps manually.

First you need to tell elements in the form that they are about to be removed using `Drupal.detachBehaviors($('#panorama_titulo_div').get(0), Drupal.settings, 'unload');`

Then you replace the form like you already do.

Finally, you need to re-attach all the JavaScript behaviors since any script operating on the elements in the replaced form won't have any references to the new elements.

`Drupal.attachBehaviors($('#panorama_titulo_div').get(0));` This is where Drupal would normally pass the settings received together with other commands returned from an AJAX operation. We don't have that here, and it's not that important since we're not adding/removing elements or otherwise alter the DOM structure and won't introduce any new scrips. Just to be sure every behaviors works, Drupal calls `Drupal.attachBehaviors()` again with the entire form as the context argument. You may want to do that too if you notice some things aren't working. It's a safe operation since all behaviors are required to keep track of whether they're already attached or not (often done using jQuery's `.once()` method.

---
Tags: forms, ajax, javascript
---


# Question
Title: How to access the raw content of a views field, for use with Services Views
I have a user that I want to expose to services. Using Services Views. I'm using fields as the format, and adding the "photo" field to my display. My issue is that when I view the service (as JSON). I get all the HTML as well as th image URL, for instance

```
users_node_picture: "<img typeof="foaf:Image" src="http://mysite.com/sites/mysite.com/files/styles/thumbnail/public/pictures/picture-36.png" alt="" />",

```

I need just the url, I've tried the following with no luck.

1. Strip HTML (removes everything)
2. Rewrite output (same result)
3. Row theming (does not effect the services result, only the html page)
4. Installed Views PHP (by returning the row, I simply get the field id)

Is there any other way to effect the output of this field before it is outputed by Services Views? I thought perhaps I could do something with template\_preprocess, but I'm not really sure how I would go about doing it.

# Answer
You can do it using relationships! Under `Advanced`, add the relationship `File Usage: File`. Then go add a new field, and you'll see `File: Path`.

Alternatively, you could use the Image URL Formatter module. This allows you to print an image as a URL. Then in the field settings in Views select this under 'Format' for the image field. The module has some features that would be harder to achieve with the relationship, but for most cases the relationship should work.
> 5 votes

# Answer
* Create a file called `field.tpl.php` in your theme folder
* In this new file, add the code detailed here:
* Edit the code to suit how you want it show, for example if you want the raw output with no Divs etc

$item) : ?\> type); $item=$items\[0\]; //Just display the first date $display=field\_get\_display($instance, 'default', $node); $display\['settings'\]\['format\_type'\]='short'; //Alter the display $vars\['dates'\] =date\_formatter\_process('date\_default', 'node', $node, $field, $instance, $langcode, $item, $display); $output=theme('date\_display\_combination', $vars); ?\>
> 0 votes

---
Tags: views, entities, theming, services
---


# Question
Title: Find and display lowest value from one field in a node type
I have a Drupal 7 website that tracks values associated with "Content Type A". I have another content type, "Content Type B", which is a part that is associated with Content Type A. Any A item may have one or more B items associated with it:

A-101 (B-201 B-202 B-203)

A-102 (B-301)

Each B item has a field that shows its total number of available uses (its limit, if you will). This is a static integer field. Each A item has a field that shows "aggregated uses" of that item, based on a third content type: "Content Type A-Usage". The "aggregated uses" field in A uses Views and aggregation to add up the A-Usage items referenced/linked to that A item.

I need to take that aggregated A-Usage value and subtract it from the "B-available uses/limit" value, and then display that result in a view or a CCK field.

So let's say A-101 has an aggregated usage of "100", and B-201 has a limit of 500 uses. I need to display the remaining uses for B-201 (400, in this case) in a view or CCK field.

One step further, I also need to take into account the remaining uses for B-201, B-202, and B-203, and pluck the lowest value from those remaining uses and display it in a view/CCK field. Let's say B-201 has 400 remaining uses, B-202 has 350 remaining uses, and B-203 has 100 remaining uses. The view/field in question would simply display "100", as that is the lowest remaining value of those B items.

I'm hoping someone can point me in the right direction, or provide some type of php snippet or guidance to help me accomplish these tasks. Views would be my method of choice, as much of the site's pages are already compiled using Views.

Thanks!

# Answer
It is not clear from your question if your 'aggregated uses' and 'available uses' are CCK fields already. If they are, I hope this helps... You can access each of the fields available $a and aggregated $b with this code:

```
$items = field_get_items('node', $node, 'field_YOUR_FIELDNAME');
$first_item = array_shift($items);
$YOUR_VAR = $first_item['value'];

```

then deduct `$a-$b=$c` and store $c in another CCK field using the `node_load` and `node_save`:

```
 $node = node_load($nid = YOUR_NID);
 $node->field_YOUR_FIELDNAME[$node->language] = array(
    0 => array('value' => $c)
 );

```

once $c field is stored in your node, you will be able to access and display it from Views.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Drush error during adding an install profile as platform
In Aegir, I add a platform with a buildfile:

```
core = 7.x
api = 2
projects[] = drupal
projects[profiler_drupal_base][type] = "profile"
projects[profiler_drupal_base][download][type] = "git"
projects[profiler_drupal_base][download][url] = "git@bitbucket.org:joachimroeleveld/profiler_drupal_base.git"
projects[profiler_drupal_base][download][branch] = "master"

```

I made an install profile which I pushed to the my public repository containing a .info, .make and .profile file (and the .build file so Aegir can read it).

After a bunch of tasks Aegir succeeded running (including downloading Drupal; the first step of the build file), I get this erors:

```
Unable to clone profiler_drupal_base from git@bitbucket.org:joachimroeleveld/profiler_drupal_base.git.
Could not download platform using drush make. No platform present

```

Is something wrong with the structure of my repo?

# Answer
> 1 votes
The solution for me was to use the HTTPS-link instead of the SSL-link.

```
projects[drupal_development_base][type] = "profile"
projects[drupal_development_base][download][type] = "git"
projects[drupal_development_base][download][url] = "https://joachimroeleveld@bitbucket.org/joachimroeleveld/drupal_development_base.git"
projects[drupal_development_base][download][branch] = "master"

```

# Answer
> 0 votes
Try to change the line for repository URL like this:

```
projects[profiler_drupal_base][download][url] = "git://bitbucket.org:joachimroeleveld/profiler_drupal_base.git"

```

# Answer
> 0 votes
I was having the same problem with a theme I have on bitbucket. Got it to work this way:

* Log into but bitbucket and navigate to the repository you're downloading.
* Navigate to Downloads\>Repositories. Right click on the 'gz' link next to the branch you need and copy the link.
* Paste this into your make file:

```
projects[dws2012][type] = "profile"
projects[dws2012][download][type] = "file"
projects[dws2012][download][url] = "https://bitbucket.org/joachimroeleveld/profiler_drupal_base/get/master.tar.gz"

```

---
Tags: aegir, drush
---


title: How to delete values in Link field?

text:
# Question
Title: How to delete values in Link field?
I have a content type with a Link field which allows an Unlimited number of values. However, it appears there is no way to Remove values like there is on an Image field with multiple values.

With an Image field, there are Remove buttons next to each item so that I can remove them:

Any idea why the Link field doesn't have a Remove button? I'm logged in as user #1 (an administrator) and just to be sure I've double checked that I have all permissions and such.

Any ideas?

# Answer
> 3 votes
It's perhaps not that obvious but all you need to do is empty the text field containing the value you want to remove. Once you save the entity the value will be gone.

Files need a remove button as there's no other way to 'empty' that particular field (a round-trip to the server is required to purge the file that was temporarily uploaded). Other, less complex fields (like text fields), don't need to contact the server via Ajax to do that, so I guess the remove button is deemed unnecessary.

If you're interested in the mechanics of this, have a look at the `hook_field_is_empty` function, which all field modules are required to implement.

# Answer
> 0 votes
Don't know is the most straight snippet in the world, but this in a custom module is doing what I ask him to do:

```
<? php
/**
 * Implements hook_node_update().
 *
 * Delete the node's link field when the title is empty and the url is not
 * for every field of type link in this node
 */
function link_field_update_node_update($node) {
        if($node->type == 'top_menu_item' || $node->type == 'normal_web_content' ||
                        $node->type == 'schools') {

            if(!empty($node->field_link_1['und'])) {
                if($node->field_link_1['und'][0]['title'] == '' &&
                            $node->field_link_1['und'][0]['url'] !== '') {

              db_delete('field_data_field_link_1')
                ->condition('entity_id', $node->nid)
                ->execute();

        drupal_set_message(t('The value of the link1 field for @node was deleted',
                                 array('@node' => $node->title)));
                }
            }

          if(!empty($node->field_link_2['und'])) {
              if(isset($node->field_link_2) && $node->field_link_2['und'][0]['title'] == '' &&
                            $node->field_link_2['und'][0]['url'] !== '') {

              db_delete('field_data_field_link_2')
                ->condition('entity_id', $node->nid)
                ->execute();

        drupal_set_message(t('The value of the link2 field for @node was deleted',
                             array('@node' => $node->title)));
              }
            }

        }
}
?>

```

---
Tags: 7, entities, navigation
---