# Question
Title: How to show a link only if a node author has a certain role
I have a block with which I'm creating a menu for users

```
<?php global $user;?>
  <a href="/user/<?php print $user->uid; ?>/ideabooks">MENU1</a>
  <a href="/user/<?php print $user->uid; ?>">MENU2</a>
  <a href="/user/<?php print $user->uid; ?>/ideas">MENU3</a>

```

This block will only be visible on user profiles. Now I want to add another link only if the profile owner has a certain role.
So I guess I have to be able to get the node author(profile owner) and then check it's role.

How may I do this?

# Answer
> 3 votes
You can use menu\_get\_object() to easily and cleanly get information on what you looking at, eg, something along these lines:

```
$mgo=menu_get_object('user');

if ($mgo) { // we are looking at a user

  if (in_array('CERTAIN ROLE', $mgo->roles)) {

    // do whatever

  }

}

```

and if the user you are looking at, eg, `user/###`, has a CERTAIN ROLE, then you can do whatever.

Now, from your question, I am going to go out on a limb and assume you are creating this block from the Block UI and using the PHP Filter, so I guess it would look like this:

```
<?php $mgo=menu_get_object('user') ?>
<?php if ($mgo): ?>
  <?php if (in_array('CERTAIN ROLE', $mgo->roles)): ?>
    <a href="/user/<?php print $mgo->uid; ?>/menu4">MENU4</a>
  <?php endif; ?>
<?php endif; ?>

```

but I would strongly urge you to consider writing a module for this as the PHP filter opens up soooo many potential holes.

Also, as @olyn has pointed out, `$user` points to the logged in user, not to the owner of the profile you are looking at, so you will want to look into that in your code as well for your other links, eg, `$user->uid` is the uid of the currently logged in user; in my code above `$mgo->uid` is the user id of the profile you are looking at.

# Answer
> 0 votes
I'm assuming your code goes into a template file for the block. Early on in the template, add the following, to set up the profile owner.

```
<?php
//get system path components.
$arg = arg();
//check that we're on a user profile
if($arg[0] = 'user' && is_numeric($arg[1])){
  $profile_owner = user_load($arg[1]);
} else {
//block isn't on user profile. set up an empty $profile_owner->roles array
//this prevents "trying to get property of non-object" errors.
  $profile_owner = (object) array('uid' => 0, 'roles' => array());
}
?>

```

Then, you can use the following to add content depending on the profile owner's roles.

```
<?php if(in_array('role_name', $profile_owner->roles)): ?>
<a href="" >link text</a>
<?php endif;?>

```

To comply with best practices, you might want to consider creating a special permission in a custom module, and checking whether the user has that permission instead, though.

Btw. the code in your snippet will create links to the currently logged-in user's content (and there might not be any), not to the profile owner's. For the latter, use $profile\_owner-\>uid instead :)

---
Tags: nodes, blocks, users
---


# Question
Title: How do I synchronize sites/default/files wtith a AmazonS3 bucket?
I need to sync sites/defalut/files with a amazons3 bucket. I found the AmazonS3 module, which replaces the storage location, while I still want to use the files at sites/defalut/files.

I want to use AmazonS3 as a sort of backup, and not as a storage solution. The files will not be served from it.

How can I do this?

I also found the Storage API module.

# Answer
> 0 votes
If the need is to occasionally copy files from a directory to a corresponding directory on S3, you can use S3 CLI from AWS.

```
It provides a recursive copy:
aws s3 cp /tmp/foo s3://bucket/ --recursive

```

Reference: s3 — AWS CLI 1.2.13 documentation : http://docs.aws.amazon.com/cli/latest/reference/s3/

I programatically called this once using the shell-exec from python and invoking the CLI commands.

The long route require the use of AWS S3 REST API (or one of the client SDKs). I havent done this myself, but it is possible since the CLI itself is implemented this way. May be you can take a look at the CLI code on github

---
Tags: backups
---


title: Content Type Field value in variable

text:
# Question
Title: Content Type Field value in variable
I've created a content type with some fields like `link` , `address`. And I did content-type node theming with name **node--machine-name.tpl.php** and all fields are printed by this code

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

```

or individual fields like this

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

```

But I want to save the **link** field in a variable, which will be used in various ways.

I just want this **field\_link\_url** field to not be **printed** but to be stored in a variable

**What I Tried**

1. echo $link = $field\_link\_url\['und'\]\[0\]\['value'\];
2. echo $link = $content\['field\_link\_url'\]\['und'\]\[0\]\['value'\];

Apart from that I got the message with all the array fields with this

```
`drupal_set_message("<pre>". print_r($node,true) . "</pre>");`

```

which gave me this..

```
stdClass Object
(
[vid] => 51
[uid] => 1
[title] => Run Tests on the Cloud. No Software or Hardware Required!
[log] =>
[status] => 1
[comment] => 1
[promote] => 0
[sticky] => 0
[nid] => 51
[type] => landing_pages
[language] => und
[created] => 1392994690
[changed] => 1393072611
[tnid] => 0
[translate] => 0
[revision_timestamp] => 1393072611
[revision_uid] => 1
[body] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] =>
                            No software or hardware to buy or maintain.
                        [summary] =>
                        [format] => full_html
                        [safe_value] =>
                            No software or hardware to buy or maintain.

                        [safe_summary] =>
                    )

            )

    )

[field_link_title] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => START A FREE TRAIL
                        [format] =>
                        [safe_value] => START A FREE TRAIL
                    )

            )

    )

[field_link_url] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => http://xyz.displaybox.in/why-xyz/easy-to-manage-your-tests
                        [format] =>
                        [safe_value] =>  http://xyz.displaybox.in/why-xyz/easy-to-manage-your-tests
                    )

            )

    )

```

# Answer
> 0 votes
On template file **node--machine-name.tpl.php** $node is an object. So you can access its value like $node-\>nid as node id. So if you want to access **field\_link\_url** field value directly then use following code . `$link = $node->field_link_url['und'][0]['value']`

# Answer
> 0 votes
> echo $link = $content\['field\_link\_url'\]\['und'\]\[0\]\['value'\];

This way must be correct! Check \*field\_link\_url\* key in *content* variable with dsm or kpr fucntion.

And try to get \*field\_link\_url\* value from this key.

---
Tags: nodes, theming
---


# Question
Title: Custom field validation with date time field
I have a content type called 'Event' in which I have used one date time field for storing the event starting and end time. Now I should have a field validation for a that date time field. For example, For one event, admin has choosed '27/02/14 08:00' as a 'starting time' and '27-02-14 09:00' as a 'end time' respectively. Then if admin try to create a new event with time between previously entered event time, like '27-02-14 08:30' and '27-02-14 09:40', then we need to show a error that ' particular time period is already choosed'. For this feature, I have create a custom validation using my custom module with the following code

```
function my_module_node_validate($node, $form) {
  if ($node->type == 'event') {
        //starting time
        $time1=$node->field_event_date['und'][0]['value'];
        //End time
    $time2=$node->field_event_date['und'][0]['value2'];
     $sql_query = db_select('field_data_field_event_date','ed');
    $sql_query->fields('ed', array('entity_id'));
        //Condition to check whether start time is greater than or equal to existing database starting time value
        $sql_query->condition('ed.field_event_date_value',$time1,'>=');
         //Condition to check whether start time is less than or equal to existing database end time value
    $sql_query->condition('ed.field_event_date_value2',$time1,'<=');
        $count = $sql_query->countQuery()->execute()->fetchField();
        if($count){
           form_set_error('field_event_date', 'Time is already booked.');
    }
  }
}

```

The problem is, condition are not working with database values. It seems that event date field is storing its value in mysql in datetime format but the above query is not doing proper validation. Please tell me, is there any problem with above query or do we have any other methods to do this validation.Thanks in advance.

# Answer
When comparing datetimes with each other I always find it easier to convert to unix timestamps first. Example would be:

```
function my_module_node_validate($node, $form) {
    if ($node->type == 'event') {
        //starting timestamp
        $time1 = strtotime($node->field_event_date['und'][0]['value']);
        //End timestamp
        $time2 = strtotime($node->field_event_date['und'][0]['value2']);
        $sql_query = db_select('field_data_field_event_date','ed');
        $sql_query->fields('ed', array('entity_id'));
        //Condition to check whether start time is greater than or equal to existing database starting time value
        $sql_query->where('UNIX_TIMESTAMP(ed.field_event_date_value) >= :time', array(':time' => $time1));
        //Condition to check whether start time is less than or equal to existing database end time value
        $sql_query->where('UNIX_TIMESTAMP(ed.field_event_date_value2) <= :time', array(':time' => $time1));
        $count = $sql_query->countQuery()->execute()->fetchField();
        if($count){
            form_set_error('field_event_date', 'Time is already booked.');
        }
    }
}

```
> 0 votes

# Answer
Drupal store datetime in UNIX\_TIMESTAMP on database. So before using it on your own code convert datetime value in your site or user timezone's timestamp.
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Adding confirm email field to entityform
I am using email field module and entityform for a simple contact form on a Drupal 7 install. I need to add an extra field where the user re-enters their email address (no copy and paste) to prevent typos.

This seems like a simple enough requirement so I'm wondering if I'm just overlooking something in entityform or email field that will help me do this, or perhaps an additional module?

Can anyone recommend a method to achieve this?

Plan B is to use jquery.

Thanks!

# Answer
> 0 votes
You can use CCK Match to achieve this goal.

---
Tags: 7, entities
---


# Question
Title: Programmatically add fields to content type
I have created a content type in Drupal 7 using the following code.

```
function module_node_info() {
  return array(
    'module' => array(
      'name' => t('module'),
      'base' => 'module',
      'module' => 'module',
      'description' => t("You can add a content for module from here."),
    ),
  );
}

```

This seems to be working fine: I see the content type and I can add fields. When I create fields for this content type through code, the fields show up when I click on 'add content' but they are not showing in my content type. When I add nodes of that specific content type, the nodes are not showing and the fields are empty when I edit them.

I miss something, but I have no idea what that could be. I use the following code to create the fields.

```
function module_form($node, &$form_state) {
  $form = array();

  $form['module_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter the name of your module'),
    '#required' => TRUE,
    '#description' => t('This name will be visible on the website'),
  );

  return $form;
}

```

# Answer
> 1 votes
The second piece of code creates a field in the Form API. This means that you do that when you create a custom form with several fields in it and then you have to handle its submission in your custom way. If this is what you want to do, fine. In this case you would need to add your custom form in your `hook_menu()`.

Instead, from what I can understand with your question, you would like to add a field of the Field API to tour custom node type. For this matter you would need to use the `field_create_field()` and `field_create_instance()` functions. The excellent examples module provides very neat examples of how to accomplish that.

# Answer
> 0 votes
Adding it the form isn't enough, you need to register your custom fields in the .module and create your fields in the module.install. You'll also need to create the widget display.

Tutorial here: http://clikfocus.com/blog/how-set-custom-field-type-using-drupal-7-fields-api

And review the schema API here: https://api.drupal.org/api/drupal/includes%21database%21schema.inc/group/schemaapi/7

---
Tags: nodes
---


# Question
Title: Where are the permissions need for a content creator to set the URL and path alias for an article?
I am creating content as a user given the necessary permissions but I can't find the settings needed to set the URL and path alias for an article I am creating.

I have checked all the permissions and there doesn't seem to be anything preventing?

Does pathauto and the URL fields only work for admin?

# Answer
> 1 votes
It is in the Permissions settings - `/admin/people/permissions` under Path. Using the Filter Permissions module, entering `path` in the `Filter list` control brings up the checkboxes quickly.

The settings to change are `Create and edit URL aliases` and `Administer URL aliases` if that is also necessary

# Answer
> 0 votes
It is *Administer content* under *Node*.

---
Tags: path-aliases, users
---


# Question
Title: Off-site payment method from the terminal
Just wondering if it is possible to setup an off-site payment from the terminal. I've already created a custom module for a custom offsite payment method for standard user checkout process. I also need to add this option to the terminal so it can be used by Admins when creating an order in the backend

Is that doable?

Just to note, I'm a Drupal beginner so I may have missed something obvious.

# Answer
> 0 votes
This isn't doable, unfortunately, because it would require a redirection process that is currently only supported by the checkout form. If it's a requirement for a site, I'd pursue a way for administrators to use the checkout form like a normal customer and submit payment being redirected from there instead.

---
Tags: commerce
---


# Question
Title: How to change price in shop based on location? If in US then US dollars etc
I really hope that someone can help me out here..

We set up our shop with drupal commerce, but we ran into a problem regarding currencies..

On old shop (Custom) we had option enabled if visitor is in US, currency will be set to US dollars else GBP.

Any advice on that? Im sure that somehow this could be done.. Maybe with geolocation?

Or if you have any other ways to do this, I will be happy to see what we can do.

Thanks for any advice!

# Answer
> 0 votes
Start your search at Commerce Multicurrency and find ways to detect the customer's country from there. Here is an excerpt about it from the module's project page:

> ... enhances some of the multi-currency capabilities of Drupal Commerce.
>
> Current features:
>
> * UI for fine granular definition of exchange rates. (Every currency combination can be defined separately if needed)
> * Synchronization of currency exchange rates directly from the European Central Bank (ECB).
> * UI to specify which rates shall be synchronized and which are handled manually.
> * Generation of currency specific price fields inclusive generation of rule-set to handle them.
> * hooks for easy integration of custom currency exchange rate sources.

---
Tags: commerce
---


# Question
Title: only allow to upload profile pictures of a certain size
I want to limit the user to only upload profile pictures of 160x160 size. What is the simplest way to validate that the resolution of uploaded avatar picture is actually 160x160, and provide an error message if it's not?

# Answer
You need to form alter `user_account_form()`. Remove `user_validate_picture()` as the validator. Duplicate that function into your own module, and add as a validator. Inside that, update the size line to be:

```
'file_validate_image_resolution' => array('160x160', '160x160'),

```

This should enforce the same value for both minimum and maximum size before the file gets saved off. I don't think you can add a second validator; I think the size check needs to be done in one step.
> 0 votes

# Answer
Well you can change the picture upload dimensions here at /admin/config/people/accounts.

That doesn't limit the actual upload to those dimensions though. You would need a custom validation handler for that I suppose. The user profile picture is a bit tricky actually because even if your form fails validation and doesn't get submitted, the new avatar is used anyway - as reported here.

You could always add your own custom image field to profiles instead - then you have all the control of a standard image field.
> 0 votes

---
Tags: 7, users, media
---


title: How to modify admin pages?

text:
# Question
Title: How to modify admin pages?
Everytime I log in into the Drupal site there is a resume of the posts that I have written. I would like to modify it and show all the accumulated views of each user post.

I plan to use the Views UI to make the query but I am not sure which file modify to change the admin site.

Thanks.

# Answer
If you are meaning the Drupal dashboard (admin/dashboard), there is a documentation page on how to customize the dashboard.

If you want to go further on the customization of the dashboard, there are modules like Homebox that can be useful.
> 0 votes

---
Tags: views, theming
---


title: Update aliases through admin or module?

text:
# Question
Title: Update aliases through admin or module?
I used the blog module for what I am calling "story" on the site I am building.

The URI and various parts of the site still say "BLog" -- most noticeably when the user attempts to add a new blog.

I have figure out I can just override the URI using aliases through admin, but I am wondering if it would make more sense to simply rename the 'blog' references in the table itself, via a module or one time hack?

Opinions?

EDIT | I also want to change the "forum" module to "forums" making all references plural not singular

# Answer
> 0 votes
Pathauto module fits in exactly to serve your requirements.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

---
Tags: path-aliases, nodes
---


# Question
Title: How to store a list of bundles in a select field (programmatically)?
I need to be able to present a list of available bundles (in this case, Commerce Line Item types) as a select field on an entity, so I can use the value in a custom module. Suggestions?

I've tried creating a select list (using commerce\_line\_item\_type\_get\_name) and then populating the field's "allowed values" programmatically, but the problem is that when bundles are added/removed, I can't change the allowed values if data is already stored. I don't actually need this kind of data management, as it doesn't matter if stored values reference a bundle that no longer exists. Perhaps I don't need a select list, but a textfield with a dropdown menu input widget or something? I would appreciate any advice on how to proceed.

Thanks! :)

# Answer
I've found that there is an "allowed values function" setting for list fields. Perfect! :)

http://www.phase2technology.com/blog/setting-the-allowed-values-function-property-on-text-fields/
> 0 votes

---
Tags: entities
---


# Question
Title: formating sum decimal place in view aggregator plus
I am using view aggregation plus and views calc. I have calculate duration by subtracting two dates and display it with 1 decimal point. it work fine.

then I use sum function of view aggregation plus on views calc column to have total duration, everything work fine, but the result is with 4 decimal point i.e. 5.2302 it should display it as 5.2 only.

any suggestion how to set the decimal points of result of sum in view aggregation plus? I believe the problem is somewhere in view aggregation plus output formatting.

# Answer
> 0 votes
You could add a php field to your view. Then hide the actual calc field from display and formatt the rounding in your php field:

```
<?php echo round($data->field_data_field_rating_field_rating_value,1); ?>

```

---
Tags: views
---


# Question
Title: how to show an image at the top of a views page
I want to show an image at the top of each page. The pages are created by views. The images not slide show. it is like a banner which always displaying in the page.

# Answer
> 4 votes
There are more ways to achieve this:

* Block - you create simple block with img html in it and add it to the desired pages using block configuration.
* Views header - in view settings, add header with custom text and add the img html in it.
* Views attachment - if the images should be dynamic (e.g. some nodes with image field), you can create another view of attachment type which displays these images and attach it before your page view.

and some more...

---
Tags: views
---


# Question
Title: Different format show for pages that have been created with contextual filter
Using *view contextual filter* and *taxonomy term* that we can design our site. But how can I customize each page differently. For example my site has three sections such as *Product*, *Learning*, *Home*. I use arguments as an option to dynamically create a page, However I would like to have different format show for those that I want (Home and Product). Is there any solution for this approach or should I create the views separately?

# Answer
If you just want each content type to look unique when displayed in your view you can already do that.

You could use the view row style 'Content' to display the content with the 'teaser' view mode (or whatever), you can then change how the teaser view mode looks for each content type in the display settings for that content type:

/admin/structure/types/manage/CONTENT\_TYPE/display/teaser

The Display Suite module extends this if you need more flexibility here.
> 1 votes

# Answer
Well, it depends on what kind of changes you are looking to make - by default you are going to have unique body classes automatically added to the page that you can use for simple CSS changes.

If it's something more complex than CSS you might want to consider a solution such as Display Suite or Panels. It is hard to say without knowing exactly what you are trying to achieve.
> 0 votes

---
Tags: views
---


title: block--[region].tpl.php not working

text:
# Question
Title: block--[region].tpl.php not working
I Copied the file

```
bootstrap\theme\system\block.tpl.php

```

to my subtheme

```
bootstrap_subtheme\templates\block.tpl.php

```

I made another 2 copies and renamed them to

```
bootstrap_subtheme\templates\block--sidebar-first.tpl.php
bootstrap_subtheme\templates\block--sidebar_first.tpl.php

```

In the subtheme.info file it says regions\[sidebar\_first\] = 'Primary'

The block.tpl override works but the sidebar-first.tpl.php does not get overridden.

What am I doing wrong?

# Answer
The name of your template block--sidebar\_first.tpl.php is correct. Clear the cache to override the template. OR Put this function in template.php and clear the cache. You will get the suggested template for your block.

On suggested name replace double underscore with double dash for your tpl file, and clear the cache.

```
function THEMENAME_preprocess_block(&$variables) {
    print_r($variables['theme_hook_suggestions']);
}

```
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How to install a drupal distribution using Drush quickstart command?
What is the command for drush qc to install a drupal distribution? I'm trying to install this one: https://drupal.org/project/onepagecv

# Answer
The drush command is

```
drush site-install <profile>

```

as noted here in the quickstart documentation, you can use this to install a full drupal site using a specific profile from a single command, ex:

```
drush site-install onepagecv --db-url=mysql://[db_user]:[db_pass]@localhost/[db_name] --site-name=Example

```

This assumes you already have Drupal core downloaded and this profile in your profiles folder.
> 1 votes

---
Tags: drush
---


title: Can I export token through features

text:
# Question
Title: Can I export token through features
Can I export token through features from one environment to another

# Answer
No - at this point it is not possible to export tokens using the custom tokens module. There is an open issue here on Drupal.org referring to this that has been waiting for a while without response and its unlikely the module maintainers will add this functionality as this is meant as a simple solution for developers who don't want to create their own tokens in PHP.

Depending on the complexity of your token operation, the best option might be to either manually sync up the two environments or to create your own custom token function following the instructions here (or other guides on the web). I would encourage you to try writing your own export functionality, its easier than it would seem and will open up more possibilities for you on future projects.
> 1 votes

---
Tags: 7, tokens
---


# Question
Title: Form hidden field doen't keeps its values
I'm creating a form with hidden field, I change the values of that field with jQuery:

```
function mymodule_form($form, &$form_state) {
    $form = array();

    if (empty($form_state[FIELDS_NUM])) {
        $form_state[FIELDS_NUM] = 1;
    }

    // the form name
    $form[FORM_NEW_NAME] = array(
        '#type' => 'textfield',
        '#title' => t('New form name'),
        '#description' => t("automatically will be prefixed by isrh_form_"),
        '#required' => TRUE,
    );

    $form[FORM_SEND_AUTH_EMAIL] = array(
        '#title' => t('Send authentication email'),
        '#description' => t('If check will set the status field to disabled'),
        '#type' => 'checkbox',
        '#default_value' => 1,
    );

    $form[FORM_EMAIL_TYPE] = array(
        '#type' => 'select',
        '#title' => t('Email type'),
        '#options' => $mailTpls,
        '#default_value' => 0,
        '#description' => t('will be added as field:  Email template  (field_XYZ_email_tpl)'),
        '#required' => TRUE,
    );

    // Build the number of name fieldsets indicated by $form_state[FIELDS_NUM]
    for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++) {

        $isFieldRemoved = isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0;
        //dpm($form_state['values']['field'][$i][FORM_IS_REMOVED]);
        if($isFieldRemoved == 1){
            drupal_set_message("removed field");
        }

        $form['field'][$i] = array(
            '#type' => 'fieldset',
            '#title' => t('Field #@num', array('@num' => $i)),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
            '#prefix' => '<div class="new-field-wrapper">',
            '#suffix' => '</div>',
        );

        $form['field'][$i][FORM_FIELD_NAME] = array(
            '#type' => 'textfield',
            '#title' => t('Field name'),
            '#description' => "max 20 characters",
            '#size' => 20,
            '#maxlength' => 20,
            '#required' => TRUE,
        );

        $form['field'][$i][FORM_FIELD_TYPE] = array(
            '#type' => 'select',
            '#title' => t('Field type'),
            '#options' => $fieldTypes,
            '#default_value' => 0,
            '#required' => TRUE,
        );

        $form['field'][$i][FORM_FIELD_REQUIRED] = array(
            '#type' => 'checkbox',
            '#title' => t("Required"),
            '#description' => t("Is this field will be mandatory in web service."),
            '#default_value' => 0,
        );

        $form['field'][$i][FORM_IS_REMOVED] = array(
            '#type' => 'hidden',
            '#value' => isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0 ,
            '#attributes' => array(
                'class' => array('remove-value'),
            ),
        );
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Create form',
    );

    // Adds "Add another name" button
    $form['add_name'] = array(
        '#type' => 'submit',
        '#value' => t('Add field'),
        '#submit' => array('mymodule_form_add_name'),
    );

    return $form;
}

function mymodule_form_add_name($form, &$form_state) {
    // Everything in $form_state is persistent, so we'll just use
    // $form_state['add_name']
    $form_state[FIELDS_NUM]++;

    // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
    $form_state['rebuild'] = TRUE;
}

```

The jQuery:

```
jQuery(document).ready(function($) {

    //if ($(".new-field-wrapper").length > 1) {
        $('.new-field-wrapper .fieldset-legend')
            .append('<input type="button" value="remove" class="remove-button" style="margin-left: 10px;"/>');

        $('.remove-button').click(function () {
            var fieldSet = $(this).closest("fieldset");

            var removeField = $(this).closest("fieldset").find('.remove-value');
            var isRemoved = removeField.val();
            //var textBox = $(this).closest("fieldset").find(':text');
            if (isRemoved == 0) { // need to remove
                removeField.val(1);
                $(this).val("restore");
                //textBox.removeClass('required');
            } else {
                removeField.val(0);
                $(this).val("remove");
                //textBox.addClass('required');
            }

            $(this).closest("fieldset").find(".fieldset-title").click();

        });
    //}

});

```

This code add remove button to each field set lengend and when it pressed the value of the hidden field became 1.
When I submit the form ("add field button") I never get the 1 value (I checked that with 'Inspect element').

What am I doing wrong?

# Answer
> 9 votes
From the Form API Reference:

> Note that if you plan to use JavaScript to change your hidden element's value, you will need to use the #default\_value property rather than #value.

So you just need to change you line

```
'#value' => isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0 ,

```

to:

```
'#default_value' => isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0 ,

```

---
Tags: 7, forms
---


# Question
Title: block_html_id for view comes with uuid drupal
I am not sure but to my understanding the block\_html\_id for the views should be with the patter of block-views-NAME-OF-VIEW-MACHINE-NAME, however it is coming up as block-views-UUID...i am guessing it is uuid some kind bunch of letters and numbers. Is this a bug? or this can be configured. The problem with the block-views-UUID pattern is that i am unable to use it in the preprocessor functions such as THEME-preprocess-block()

Any help is much appreciated. Thank you

Env: Drupal 7.26, views 7.x-3.7

# Answer
> 0 votes
The answer is in the following: Views Block's machine name is being "hashed" (?)

It hashes block view name if the view name is larger than 32 chars

---
Tags: views
---


# Question
Title: What is a "fluid" column in Display Suite?
What is "fluid" in Display Suite? I want to create a two-column layout, with a 25% left and 75% right. Is the fluid 2-column layout what I want?

# Answer
In Display Suite, the "fluid" refers to the templates ability to expand the column width if one (or more) columns are empty.

For a 2 column layout, the CSS is:

```
.ds-2col > .group-left {
  float: left; /* LTR */
  width: 50%;
}

.ds-2col > .group-right {
  float: left; /* LTR */
  width: 50%;
}

```

So even if there is no content in .group-right, the .group-left element will still take up only 50% of the available width.

For the fluid 2col layout, the CSS is:

```
.ds-2col-fluid > .group-left {
  float: left; /* LTR */
  width: 50%;
}

.ds-2col-fluid > .group-right {
  float: right; /* LTR */
  width: 50%;
}

.ds-2col-fluid.group-one-column > .group-left,
.ds-2col-fluid.group-one-column > .group-right {
  width: 100%;
  float: none;
}

```

The last ruleset (the one with '.group-one-column') means that if either of the columns contains no content then the other column will expand to 100% of the available width. You can see the little piece of PHP logic that adds the extra CSS class to the template here: http://drupalcode.org/project/ds.git/blob/refs/heads/7.x-2.x:/layouts/ds\_2col\_fluid/ds-2col-fluid.tpl.php

For your case, either is fine, but to get the 25% / 75% split, you'll need to override the DS CSS code in your own theme's stylesheet.

You could use something like

```
body .ds-2col .group-left {
    width: 25%;
}
body .ds-2col .group-right {
    width: 75%;
}

```
> 8 votes

# Answer
The *fluid* word is used to refer to an element that will expand to fit the available area which means in this case that you'll have two columns with `50%` width each one if both were filled or one column with `100%` width if just one was filled.

To achieve your goal using a brand new Display Suite layout you will need to implement a custom display suite layout in your theme.

Here goes a link to the Display Suite documentation page that covers this subject:

https://drupal.org/node/1098068
> 1 votes

# Answer
Atually, to get rid of any CSS coding, a fast way is to use "Three columns fluid - 25/50/25", and then place content only in "Left" and "Middle" columns.

By leaving no content in the right column, it will collapse and the middle column will enlarge from 50 to 75%, as requested.
> 0 votes

---
Tags: 7, display-suite
---


# Question
Title: How to build an Isolated Drupal instance for testing
In order to run DrupalWebTests on travis-ci, I need to build a new Drupal instance where these tests are ran.

Typically, one runs these tests with `drush -l http://localhost.example test-run SomeTest`

This, however, assumes Drupal installed, being served on http://localhost.example (a webserver) and it being connected to a database as set in `settings.php`, having simpletest enabled.

Typically, this means installing MySQL, Apache and installing and configuring Drupal. Those are heavy depedencies and doing so for each test-case or even just every build, will require a lot of overhead; a build server like Travis will need to install these servers for each test-run.

Drush has `drush run-server` to run a lightweight server. Drupal can run off a sqlite database, which would be extremely usefull for these tests.

Moreover: as far as I can make out, the actual web-tests are not ran from that Drupal-instance at `http://localhost.example`, but get a clean build and isolated database (as should be, when testing). It appears that the Fully-functional Drupal at http://localhost.example is merely used as bootstrap for the web-tests.

Can I circumvent that bootstrap in some way?

And if not, what is a quick and easy way to get a Drupal installed and serving with as little dependencies (like Apache/Nginx, MySQL etc) as possible?

Also note that I am running Travis already for tagadelic, but so far, only for the phpunit tests. I want to extend this to run the DrupalWebTests there as well.

# Answer
You could just use different git branches to isolate your code tests.

```
git checkout -b iss_tst1
<make changes>
git add <changes>
git commit -m "my new changes" <changes>

git checkout -b iss_tst2
<make changes>
git add <changes>
git commit -m "other new independent changes" <changes>

```

Then you should be able to run independent tests on each branch.
> 0 votes

---
Tags: drush, bootstrapping
---


# Question
Title: CKEditor Inline Styles Getting Removed on save
I am trying to edit the font size for CKEditor, however whenever I save these changes, the inline styles are removed.

Now I saw that it may be due to a custom Javascript configuration issue, and so I've put this in the Advanced Options dropdown:

```
config.allowedContent = true;

```

Even after putting this on both full and filtered, I've had absolutely no luck getting my inline styles to stay correct. What am I doing wrong? Is this a CKEditor problem, or a Drupal problem?

Nevermind, this is only happening on filtered. So I'm pretty sure it's just a Drupal setting in how filtered is configured. I'll post the solution soon.

# Answer
> 3 votes
You write:

> Nevermind, this is only happening on filtered.

Sure! The `Filtered HTML` text format is *supposed* to do that.

For CKEditor, you need to configure the WYSIWYG filter module to retain inline styles (Unless you allow users to use the `Full HTML` text format. This is *not* recommended as it is insecure. The `Full HTML` text format lets unfiltered user input pass into rendered content.)

I am written up a short cookbook about configuring CKEditor for Drupal, including how you configure the CKEditor ACF and the the WYSIWYG filter text filter to give your users the power of the CKEditor without jeopardizing security.

Here's a link to my CKEditor cookbook.

---
Tags: 7, wysiwyg
---


title: Format date in Rules

text:
# Question
Title: Format date in Rules
I'm using a rule to send out emails when a node is created. Under *Action* and *Message body*, I insert \[node:field\_calendar\_date\]. The token is replaced with (for example) "2012-12-14T08:00:00" in the email message, but I would like it to be replaced with "Friday, December 14, 8:00am" (same date, but a different format).

I tried to follow format\_date(), but it doesn't work.

How can I get the format I want?

# Answer
> 10 votes
You can use `[node:field_calendar_date:custom:l, Fd, gia]`, if `[node:field_calendar_date]` is a date token. In that case, `[node:field_calendar_date:custom]` returns the date in the custom format listed after the following colon. The format string is the one accepted by date().

If you want to use the format set as short/medium/long format set in the Drupal date settings, then you can use the following tokens:

* `[node:field_calendar_date:short]`
* `[node:field_calendar_date:medium]`
* `[node:field_calendar_date:long]`

# Answer
> 8 votes
OK, got it, it is not working even if I do not really understand the logic under the hood... Actually, the two blocking issues I had were the following:

1. A date may be a range, therefore \[node:field\_date\] cannot be considered as a date token. Install Entity API and enable the module "Entity tokens" to get access to the actual date value,
2. Beware that for an obscure reason Entity token replace the underscore (\[node:field\_date...) of the original tokens name by a dash (\[field-date...), you will then have access to a properly formatted date (in my case "\[node:field-date:value:custom:Ym\]", in the original question I guess therefore "\[node:field-calendar-date:value:custom:l, F d, gia\]")

---
Tags: datetime, tokens
---


title: Custom join with an external database

text:
# Question
Title: Custom join with an external database
I am trying to join two tables on the same database, db2. I am trying to join *tablename* to *tablename2* using the condition `tablename.ItemID = tablename2.ItemID`. While the values from *tablename* are selectable from a view, those from *tablename2* aren't.

Do I need to specify in what database tablename2 is?

```
/**
* Implementation of hook_views_data
*/

function  mydatabase_views_views_data() {
  $data['tablename']['table']['group'] = t('Title name');
  $data['tablename']['table']['base'] = array(
    'field' => 'ItemID',
    'title' => t('db2'),
    'help' => t('Autoincremented ID field, to enable views integration'),
    'database' => 'db2',
    'weight' => -10,
  );

  $data['tablename']['table']['join'] = array(
    'deals_addon' => array(
      'left_field' => 'ItemID',
      'field' => 'ItemID',
    ),
  );

  $data['tablename']['ItemID'] = array(
    'title' => t('Item ID'),
    'help' => t('Item ID'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['tablename']['ItemInfo'] = array(
    'title' => t('Item Info'),
    'help' => t('Item Info'),
    'relationship' => array(
      'base' => 'tablename2',
      'base_field' => 'ItemID',
      'handler' => 'views_handler_relationship',
      'label' => t('Label'),
      'title' => t('Title'),
      'help' => t('Help'),
    ),
  );
  return $data;
}

```

# Answer
> 0 votes
Some time ago (D6) I was facing the same problem but then I could not find a solution. I ended up creating database views in my original db looking to the tables of the second db. This way, I was joining tables in default drupal db, which is easy. I dont know the exact changes in the api from d6 -\> d7, but this might be an easy solution for you if you cannot solve it other way.

---
Tags: views, database
---


# Question
Title: How to cancel installation of my module if requirements are not met
My module depends on a PHP library (sites/all/libraries/xyz/xyz-library.php). I want drupal to continue with installation only if library requirements of my module are met.

I want something of this kind, in my `mymodule.install`:

```
function mymodule_install() {
  if( library_exists() )   return; //continue with installation
  else{
    drupal_set_message(t('Installation failed. Please put xyz-library.php in sites/all/libraries/xyz folder.'), 'error');
    return FALSE; // installation failed
  }
}

```

# Answer
You can do this in `hook_requirements`, from the documentation:

> During the 'install' phase, modules can for example assert that library or server versions are available or sufficient. Note that the installation of a module can happen during installation of Drupal itself (by install.php) with an installation profile or later by hand. As a consequence, install-time requirements must be checked without access to the full Drupal API, because it is not available during install.php. For localization you should for example use $t = get\_t() to retrieve the appropriate localization function name (t() or st()). If a requirement has a severity of REQUIREMENT\_ERROR, install.php will abort or at least the module will not install. Other severity levels have no effect on the installation. Module dependencies do not belong to these installation requirements, but should be defined in the module's .info file.

After your check, you return array (see docs again) with `REQUIREMENT_ERROR`.

```
function example_requirements($phase) {
  $requirements = array();
  // Ensure translations do not break at install time
  $t = get_t();

  $requirements['example'] = array(
    'title' => $t('Example Library'),
  );

  $libraries = libraries_get_libraries();
  if (isset($libraries['example'])) {
    $requirements['example']['value'] = $t('Installed');
    $requirements['example']['severity'] = REQUIREMENT_OK;
  }
  else {
    $requirements['example']['value'] = $t('Not Installed');
    $requirements['example']['severity'] = REQUIREMENT_ERROR;
    $requirements['example']['description'] = $t('Please install the example library %url.', array('%url' => 'http://example.com'));
  }

  return $requirements;
}

```

You can check this code example here.
> 12 votes

# Answer
Sounds like you're looking for hook\_requirements(), which will abort the installation if the requirements are not met.

So if your module was named `mymodule`, you'd create a function called `mymodule_requirements()` inside the file `mymodule.install`.
> 4 votes

---
Tags: 7, installation
---


title: js doesn't work for anonymous

text:
# Question
Title: js doesn't work for anonymous
for admin work good!

for test i just write this:

```
jQuery(document).ready(function(){
   alert(1)
});

```

Thanks for any help -)

**UPDATE:** my JS file attached to tag but code not run, any js code not run in any place... fo anonymous, for admin work fine

# Answer
> 2 votes
First of all, you should avoid using `.ready()`, you should use Drupal.behaviors mechanism like this:

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      alert(1);
    }
  };
})(jQuery);

```

This might also be the problem why it does not work for anonymous. See documentation for more details.

You also need to add the .js file correctly, if it should be in theme then you need to add it in the .info file like this: `scripts[] = somescript.js`

See more in the documentation already posted.

Edit: I found this presentation on D8 js changes, it could be helpful. It shows how to add js by implementing `hook_library_info` and `#attach` (slide 18)

# Answer
> 0 votes
Adding js files to your module or theme alone won't work because pages no longer need to load with drupal.js (or jquery for that matter). A lot of work went into making the front end faster that this is one of the decisions. You need to actually add the jquery library to your page to be able to use the library and this can be done by either converting your js into a library that depends on jquery (as m1n0 answered above), or by attaching the jquery library to your page build followed by attaching your js. The latter would be something like the following:

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {
  $path = drupal_get_path('module', 'MYMODULE');
  // Attach libraries (which is in an array format of LIBRARY_NAME, COMPONENT_NAME)
  $page['#attached']['library'][] = array(
    'core', 'jquery'
  );
  $page['#attached']['js'][$path . '/mymodule.script.js'] = array('every page' => TRUE);
  $page['#attached']['css'][$path . '/mymodule.base.css'] = array('every_page' => TRUE);
}

```

---
Tags: javascript, 8
---


title: Inherit/override core module

text:
# Question
Title: Inherit/override core module
I have made a single tiny change to a core module. I copied it into my site modules directory. I am curious as to whther I can simply override it's hook\_menu() method in my copy so as not to carry over all the additional code which the core version provides?

Similar to theme inheritance, do modules support anything similar?

# Answer
> 4 votes
There's no inheritance for modules, but much of the functionality they provide can be altered using hooks (search this page for `_alter` and you'll see the ones core provides).

Specifically for items defined in `hook_menu()`, you can use `hook_menu_alter()`, e.g.

```
function MYMODULE_menu_alter(&$items) {
  // Replace the page callback for the foo/bar path
  $items['foo/bar']['page callback'] = 'MYMODULE_some_function;
}

```

If I've misunderstood and you mean you literally want to inherit from a module, like subclassing a class, and just change a couple of things, then unfortunately not. Copying the module is the way to go; you'll need to change the names of all the functions so they don't collide with those in the core module, and change paths/cache keys/variables for the same reason.

---
Tags: hooks
---


title: Print module PDF attachment

text:
# Question
Title: Print module PDF attachment
I have a custom module that provides a path that sends an email (mimemail) with a pdf attachment generated from the print\_pdf module that comes with the print module.
Here is what my HOOK\_mail function looks like.

```
function custom_send_email_mail($key, &$message, $params) {
  $node = $params['node'];
  $user = $params['user'];

  $message['subject'] = t($node->title.' attached');
  $message['body'] = 'Hello '.$user->name.'<br><br>Please find '.$node->title.' attached.';
  //$message['params']['attachments'][] = $attachment;

  module_load_include('inc', 'print_pdf', 'print_pdf.pages');

  $attachment = array(
    'filecontent' => print_pdf_generate_path($node->nid),
    'filemime' => 'application/pdf',
    'filename' => $node->title.'.pdf',
  );
  $message['params']['attachments'][] = $attachment;

}

```

The problem I have is that the pdf versions of pages use a template file, which works fine when navigating to the pdf version url, ie. /printpdf/nid but when getting the pdf file string with the (silly named) print\_pdf\_generate\_path() function, it does not use the template file.

# Answer
> 1 votes
It seems it was a silly mistake on my behalf.

My module defined a custom path to send the email and the theme files for the pdf were in the admin theme folder, so I had to set my path to use the admin theme for the email theme files to be found.
I did so by implementing HOOK\_custom\_theme.

```
function custom_send_email_custom_theme() {
  return variable_get('admin_theme');
}

```

I will leave this question up as the code may help someone in the future (and maybe me if I need to send an email with attachments again :) )

---
Tags: 7, files, mimemail
---


# Question
Title: Problem with adding Views - they cannot be saved
I have problem with creating new views (or clone old ones). All process is doing well, I choose my filtres etc; but when I'm trying to save it's an error - and they don't show in the views list (even if it's said that it "has been saved"). I've already tried several times but it doesn't work. I dont know why - before I didn't have this problem...

# Answer
Have you tried running update.php? Or try clearing the Drupal cache which you can do quickly with drush using drush cc all.

I find this is always a good place to start.
> 0 votes

# Answer
It's stated in the error message. You're missing the `core` column in the `views_view` table. If this is a new install, then you can disable, uninstall and after wards re-enable the views module.

Otherwhise execute this code in SQL (PHPMyAdmin or whatever database GUI you use):

```
ALTER TABLE `views_view` ADD `core` int(11) DEFAULT '0' COMMENT 'Stores the drupal core version of the view.';
UPDATE `views_view` SET core = 6;

```

Assuming an SQL dialect, e.g. MySQL, and Drupal 6.
> 0 votes

---
Tags: views
---


# Question
Title: Translated node does not use translated entity reference, how to fix this?
So I have 2 translatable content types: event and artist. I've also created an English artist and his French translation.

I now create an English event and link my English artist to it through Entity References. If I now translate my English event to French, my French event will have a reference field with my English artist instead of my French artist...

How can I solve this problem?

I want it to try to fetch the translated reference and if it does not exist, I want to entity referenced field to stay empty.

# Answer
Some people told me this happends on default, but I've just set up a test site with i18n and entityreferences enabled, and it gives the same result.

But I found a sandbox project that worked for me after changing one line of code in the entityreference\_translation.module:

This didn't work:

```
if ($item['target_type'] == "node") {

```

This works:

```
if ($field['settings']['target_type'] == "node") {

```
> 1 votes

# Answer
You can make the reference field as synchronised. That way you need to link to English artist once only. So if you link from French event to English artist and if it has French version then it'd be automatically redirected to the French version.
> 0 votes

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


# Question
Title: How to always show Save as ... when download a image file in Webform result?
If the upload file is an image in a Webform's result, clicking the link will show the image in the browser.

Is it possible to force to popup a Save as... dialog? Such the user downloads the file instead of viewing it?

# Answer
> 1 votes
This is technically not a drupal specific issue it is just how browsers deal with certain file types on the web in general.

Also note that you can right click a link to save the file always, so if this is an admin only feature then maybe that is sufficient?

If you are using Drupal's public file system for the images then it is possible to change your .htaccess file to change the behaviour of certain file types.

For more info on that see: Force files to download instead of showing up in the browser.

The .htaccess method should be the best performing and most reliable method, however if there is any reason you don't want to do it the .htaccess way there are a couple of drupal module that can help.

The File Force and Download File modules will allow you to configure file downloading however if you are making custom links to your files (for example if you are entering links directly into a text field or in custom code) you have to use a different url for the images to make sure that the links use the module's functionality, so be sure to read the documentation for whichever module you are using.

The modules are quite similar so use whichever you prefer.

**\[Edit\]** I just remembered you are interested in webform related links. Unfortunately since the current version of webform doesn't use Drupal's normal fields it won't work properly with these file downloading modules out of the box. A feature request for the modules will be needed to add webform support.

Alternatively you could modify your webform links to use the special formatting the download module you are using supports.

For example, overriding the themeing of the webform file display like this would work if you are using the file force module:

```
/**
 * Format the output of text data for this component
 */
function THEMENAME_webform_display_file($variables) {
  $element = $variables['element'];

  $file = $element['#value'];
  $url = (!empty($file) && !empty($file->uri)) ? webform_file_url($file->uri) : t('no upload');
  return (!empty($file) && !empty($file->uri)) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url, array('query' => array('download' => '1')))) : ' ';
}

```

It would be a similar process with the download file module.

# Answer
> 1 votes
You can do it overriding below webform theme function in your theme

```
/**
 * Format the output of text data for this component
 */
function theme_webform_display_file($variables) {
  $element = $variables['element'];
  $file = $element['#value'];
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
}

```

Override theme function in your theme folder ... I did for seven theme using code below , replace seven with your theme name in your template.php file..

```
function seven_webform_display_file($variables) {
  $element = $variables['element'];
  $file = $element['#value'];
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url, array('attributes' => array('download' => $file->filename)))) : ' ';
}

```

Trick here is to use Download attribute in HTML and it worked :-)

PS: The download attribute is not supported in Internet Explorer, Safari or Opera 12 and earlier versions.

---
Tags: 7, webforms
---


title: Wrong Currency symbol in view filter

text:
# Question
Title: Wrong Currency symbol in view filter
I have a view with BEF which is generating a criteria box like this below

I have no clue where this $ sign is coming from and how to remove it or change it.

**Update**

I investigated further and what I have noticed is that the currency symbol is linked to the theme settings. There is a field in the theme settings to accept currency code which was by default EUR. That I changed to INR which is not working but when I change to JPY it shows proper japan yet currency symbol. This confirms that this is the place where we need to look at.

Can some one help me where to start from?

# Answer
Your currency symbol is most likely coming from the field definition. Check the "prefix" value for the field in question at `admin/structure/types/manage/<content_machine_name>/fields/<field_machine_name>` replacing the items in `<>` as appropriate.
> 0 votes

# Answer
I figured out that the symbols were tweaked in the jquery.currency.js

It has format\_current function which has a list for mapping 3 Letter currency symbol to actual currency symbol

I have added this line to that mapping list

```
            if(bc == 'INR') currency_before = 'Rs.';

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Drupal show breadcrumbs on certain nodes
I've been using the path by bread crumbs module (https://drupal.org/project/path\_breadcrumbs), which allows me to create bread crumbs based on nodes. However the page the crumb is on, shows the title of the crumb.

Example: Home\>\>Node\_Title

I want the Home crumb, but not the Node\_Title (I'ts a long title as well).

This is what I want:

Node 36 URL= TitleExample

Breadcrumb example for Node 36: Home\>\> (no node URL)

Does this make sense?

# Answer
When using the path breadcrumbs module it doesn't append the title to the end unless you add it yourself when configuring the breadcrumbs.

It is quite possible that what is adding the title is your theme.

For example the zen theme has an option to show the page title at the end of the breadcrumbs, as do lots of other themes.

To get to these settings, on your site go to admin/appearance and then click the settings link for whichever is your theme.
> 1 votes

---
Tags: uri, breadcrumbs, nodes
---


# Question
Title: How to change page title for admin users to easly find which admin page they are
During development I need to work with modules, views, site configurations, nodes etc.. I open all of them in new tabs (browser). It would be much convenient to switch between tabs to choose desired page if page title (**html title that displays in the browser)** has name of the admin navigation link/name. I have set 'Seven' as admin theme. Is there any configuration available to enable this or I need to tweek code?

# Answer
You can use shortcut bar,

> The Shortcut module provides a toolbar on the top of the page to which you can add links. This toolbar is site-wide, so any links added will be visible to all users who have permissions to see the Shortcut toolbar. This is useful for creating links to commonly-used pages within your site. You can organize these links in multiple sets of shortcuts.

Click on the + sign as shown below in any page you want to bookmark

You will see links next to Add Content , Find Content like below

Explained in link given above...
> 0 votes

# Answer
By default with drupal the title should be \[page-title\] | \[site-name\]. If yours are not then it is possible that your theme or a module is changing your page titles.

For enhanced page title configuration there is also the page title module.

It allows you to set the page titles for nodes, users, etc.

It doesn't specifically have settings for admin pages, however it has a default page title, which will affect admin pages.

So you can enable that module and configure the default to whatever suits you best.
> 0 votes

---
Tags: 7
---


# Question
Title: How to grant access to anonymous users to submit contact form in webform module
I installed Webform module and also Permission per Webform to configure permissions for each webform. this is configuration in `Permission per Webform`:

>

but anonymous users are still unable to see the Webform submit form. how can I enable them to see and submit the form?

# Answer
You understood wrongly, the image you posted is for webform submission results, meaning permission to access the results of the webform after submitted.

You need to give permission in the webform itself, simply go to that webform and then click the **form setting** tab and then give permission for **anonymous user**.

>
> 2 votes

---
Tags: webforms, users, emails
---


title: generate commerce coupon bulkly

text:
# Question
Title: generate commerce coupon bulkly
Is there any way to generate Drupal commerce coupon code bulky? I found commerce\_coupon\_batch module but it require `Commerce_coupon_ui` module that there is not exist in sub module of `commerce_coupon version 7.x-2.0-beta1`.

I don't try anything yet, How can I generate coupon code bulky? I look at db and found there is a table for coupon ,`commerce_coupon` is just sufficient to add record to this table programmatically?

I try below code to create one coupon , but nothing added to coupon list in `admin/commerce/coupons :`

```
$No=$form_state["values"]["code_NO"];
    $type_id=$form_state["values"]["type"];
    $record['type']='discount_coupon';
    $record['code']=commerce_coupon_generate_coupon_code($type_id);
    $record['commerce_discount_reference']['und']['0']['target_id'] =$type_id;
    $record['commerce_coupon_conditions']['und'][0]=Array('condition_name'=>'commerce_coupon_usage_evaluate_usage',
            'condition_settings' =>Array( 'max_usage'=> 1),
            'remove_condition'=> 'Remove',);
ym(entity_get_controller('commerce_coupon')->create($record));

```

# Answer
> 0 votes
I think your code is good but you forget save `entity` .I hope this get clue to you to achieve your job.

```
$No=$form_state["values"]["code_NO"];
    $type_id=$form_state["values"]["type"];
    $record['type']='discount_coupon';
    $record['code']=commerce_coupon_generate_coupon_code($type_id);
    $record['commerce_discount_reference']['und']['0']['target_id'] =$type_id;
    $record['commerce_coupon_conditions']['und'][0]=Array('condition_name'=>'commerce_coupon_usage_evaluate_usage',
            'condition_settings' =>Array( 'max_usage'=> 1),
            'remove_condition'=> 'Remove',);
$entity=entity_get_controller('commerce_coupon')->create($record);
commerce_coupon_save($entity);

```

---
Tags: commerce
---


# Question
Title: How can you add a node dropdown list to choose from when adding a link inside ckeditor?
We have ckeditor on our wep page which allows users to select text and format it as link by clicking that little chain icon. Users can set the protocol, the target, etc.

We wondered if there is a way to add a dropdown of all nodes (which the user has access to) to pick from? Is there a module/plugin which does that?

# Answer
You are looking for CKEditor Link - A plugin to easily create links to Drupal internal paths.
> 4 votes

# Answer
The linkit module provides this kind of functionality, however it adds its own button to the editor instead of using the regular link button.
> 4 votes

---
Tags: nodes, wysiwyg
---


# Question
Title: How do I link to the homepage from a node?
I used to had a logo provided by a theme which automatically linked to the home page. But now I replaced this with a custom block. How do I link to the homepage from that custom content type?

Using php in the block code is not an option because of caching.

# Answer
You can just create a link to the path `/` (slash with nothing else). That will take the user to the homepage.
> 1 votes

---
Tags: navigation
---


title: load commerce coupon

text:
# Question
Title: load commerce coupon
I want to load coupons that have `commerce_discount_reference=4`. I find that can load them by commerce\_coupon\_load\_multiple but I dont know how I add condition `commerce_discout_reference=4`.
maybe something like

```
  commerce_coupon_load_multiple(array(), array('commerce_discount_reference'=>4));

```

**what is correct way?**

# Answer
> 2 votes
Sounds like the perfect job for an `EntityFieldQuery`:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_coupon')
  ->fieldCondition('commerce_discount_reference', 'target_id', 4);

$results = $query->execute();
if (!empty($results['commerce_coupon'])) {
  $coupons = commerce_coupon_load_multiple(array_keys($results['commerce_coupon']));
}

```

# Answer
> 1 votes
commerce\_coupon\_load\_multiple function in turn uses entity\_load function.

```
 if (empty($commerce_coupon_ids) && empty($conditions)) {
    return array();
  }

  return entity_load('commerce_coupon', $commerce_coupon_ids, $conditions, $reset);

```

As above documentation says

$conditions : An array of conditions to match against the {commerce\_coupon} table.

Below is the commerce\_coupon table schema

```
function commerce_coupon_schema() {
  $schema['commerce_coupon'] = array(
    'description' => 'The base table for coupons.',
    'fields' => array(
      'coupon_id' => array(
        'description' => 'The primary identifier for the coupon.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'An identifier for the user who owns this coupon',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'type' => array(
        'description' => 'The type of this coupon.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'code' => array(
        'description' => 'The code of this coupon.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'bulk' => array(
        'description' => 'Whether or not this coupon code was generated in bulk.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the coupon was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'status' => array(
        'description' => 'Whether or not this coupon is enabled.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0
      )
    ),
    'indexes' => array(
      'uid' => array('uid')
    ),
    'primary key' => array('coupon_id'),
    'foreign keys' => array(
      'uid' => array(
        'table' => 'users',
        'column' => array('uid' => 'uid')
      ),
    ),
    'unique keys' => array(
      'code' => array('code')
    )
  );

  return $schema;
}

```

As you see in above schema there exists no field called "commerce\_discount\_reference" which you can query on .. I believe "commerce\_discount\_reference" field is a custom field... So you need to use Entity Field Query as explained above by Clive...

---
Tags: entities, commerce
---


# Question
Title: How to limit number of "Promoted to Front Page" option for each user/role
I want to limit the option "Promoted to Front Page" per role. For example, a user with role "promoter" should only be able to promote 5 nodes a day to promote to front page. And same with sticky option.

I am using 'rules\_link' module as well.

Any help.

# Answer
You can achieve above by writing a small custom module in Drupal... Steps are outlined below to achieve the same.

* Create install file and define schema hook with table name as user\_promote\_counter with below fields
* uid, timestamp, nid
* Using hook\_node\_presave($node) update above table with a record of uid, timestamp, nid of the node updated whenever promote is set to true so that you can track only promoted to front page actions.
* Use hook\_node\_validate($node, $form, &$form\_state) in your custom module to verify current user who has promoter role exceeded the limit of 5 by querying above table using timestamp and uid columns. Raise an error if limit is exceeded. That will prevent user to promote more than 5 nodes per day.
> 3 votes

---
Tags: 7
---


title: Undefined function user_load()

text:
# Question
Title: Undefined function user_load()
My Drupal 7 installation works fine, except for drush, which does not.

> $ cd /srv/www/drupal\_site
>
> $ drush pm-refresh
>
> PHP Fatal error: Call to undefined function user\_load() in /usr/share/php/drush/includes/drupal.inc on line 138
>
> Drush command terminated abnormally due to an unrecoverable error.
>
> Error: Call to undefined function user\_load() in /usr/share/php/drush/includes/drupal.inc, line 138
>
> Drush was not able to start (bootstrap) Drupal.

This is Drupal 7.24 and drush 5.10.0 from Debian. A couple of modules and themes have been installed from drupal.org but IMHO nothing fancy. Curent versions of drush6 or drush7 refer to a missing drupal\_get\_profile() function but otherwise don't help.

Any ideas what the cause of this problem is, and/or how to debug this?

EDIT: It works fine, except for these spurious error lines displayed on the web page (even though I do not use any sort of debug mode), as reported by a user:

> Notice: Undefined index: post-load integration files in `libraries_load_files()` (line 697 of /var/www/drupal7/modules/libraries/libraries.module).

This may or may not be related to my problem.

I tried using Drush 6.x/7.x, but it just returns a different error message.

> Call to undefined function `drupal_get_profile()` in /usr/share/php/drush/includes/bootstrap.inc on line 963

`drush cc` hits an error before it can do anything; the same happens with `drush rr`, which returns a different error, but equally intractable.

php-apc is not installed; I have Memcached, but killing it didn't change anything.
I did not change any module weights.

# Answer
We got the same errors here.

After some time we recognized that our database-import (cloning production db to local dev machine) went wrong and the database wasn't populated properly. After fixing the db the errors went away...

So - my hint: check your database structure and data.

BTW: There is a similar question \- but with an memcached in the drupal setup
> 1 votes

---
Tags: 7, drush, debugging
---


title: how to create a custom profile page

text:
# Question
Title: how to create a custom profile page
I want to create a page which have user details like Name, user picture, designation, about , user's social link, these details should in left side and user uploaded images in right site both things in a single page. Please help me.

# Answer
> 1 votes
You can use custom templates for user profile pages.

Basically, you have to copy the **user-profile.tpl.php** from **/modules/user** into your theme directory, clear the cache and edit it according to your needs.

To see the list of available variables to use inside the tpl.php file, look here: https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7

I think that another possible approach (that doesn't require coding) would be to use Panels + Views

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


# Question
Title: Difference between hook_services_services and hook_services_resources
I'm doing this tutorial to get familiar with the concepts of the Services module. In that tutorial, you implement a custom service for the Services module. Therefore it uses `hook_services_services`. But there are other tutorials (e.g. An introduction to Drupal 7 RESTful Services) that use `hook_services_resources` for the same thing. So what is the difference?

# Answer
The first article is incorrect, there is no `hook_services_services()` (at least not according to any documentation for the services module, nor in my experience).

The correct hook to use is `hook_services_resources()`. See the docs/services.services.api.php file included with the module for full details.
> 3 votes

---
Tags: 7, hooks, services
---


title: views3 error with contextual filter

text:
# Question
Title: views3 error with contextual filter
I'm trying to show user posts in their profile with views 3 by following this post http://drupal.org/node/228959#comment-4591334

after i add the following code to the contextual filter

```
if (arg(0) == 'user' && is_numeric(arg(1))) {
  return array(arg(1));
}

```

and it works, but also giving this error

```
Notice: Array to string conversion in views_handler_argument_numeric->title()
(line 77 of /test_drupal/sites/all/modules/views/handlers/views_handler_argument_numeric.inc).

Warning: html_entity_decode() expects parameter 1 to be string,
array given in decode_entities() (line 429 of test_drupal/includes/unicode.inc).

```

# Answer
> 2 votes
It looks like it's expecting a string, but your code is returning an array.

Try changing your code to the following:

```
if (arg(0) == 'user' && is_numeric(arg(1))) {
  return arg(1);
}

```

That should return the string value rather than returning `[0] => uid`.

# Answer
> 0 votes
I had the same error on the same line (unicode.inc, line 429) when I embedded a view from within a template the wrong way. My code was:

```
<?php print views_embed_view('view_name', 'display_name', array(4, 2) ); ?>

```

The arguments should not be passed as an array, but as normal arguments after the first two, this solved the errors:

```
<?php print views_embed_view('view_name', 'display_name', array(4, 2) ); ?>

```

---
Tags: 7, views
---


# Question
Title: how to create file programmatically only login users download it
I want to create file programmatically ,I want only authenticated user can download it and direct access return 403 to them. I search and saw How Can I Make File Downloads Available Only to Authenticated Users? but my files not field files(not record in file table) and programmatically I created them with:

```
    $temp1=variable_get('file_public_path').'/export';
      if(!file_prepare_directory($temp1,FILE_CREATE_DIRECTORY)){
          drupal_set_message(t('Problem in write file in directory'),'error');
          return;
      }
    $filename='Export-giftcard-'.time().'.csv';
        $filepath=$temp1.'/'.$filename;
    //    $filepath='sites\\defauls\\files\\Export-giftcard-.csv';
        $df = fopen($filepath, 'w');
        if(!$df){
            drupal_set_message(t('Can not write file in').$filepath,'error');
            return;
        }
        fputcsv($df,array('code','credit'));
   fclose($df);
    $path = file_create_url($filepath);
    drupal_set_message(t('Export done. ') . '<a href="' . $path . '">' . t('Download export file') . '</a>');

```

after `rooby` answer I update my question

I set private file system to `system/files/export` and in my code use it `$temp1 = variable_get('file_private_path');` also I implement `hook_file_download`

```
function mymodule_file_download($uri) {
  // Check if the file is controlled by the current module.
  if (!file_prepare_directory($uri)) {
    $uri = FALSE;
  }
// I will put my conditions later
      $info = image_get_info($uri);
      return array('Content-Type' => $info['mime_type']);
}

```

but when I try to click on link to download file return **Forbidden** to me.I think `mymodule_file_download` not run when I try to access `system/files/export/myfile.csv`

# Answer
> 2 votes
You can use the private file system instead of the public file system. The private file system restricts direct access to files.

Then you link to the files like: system/files/filename.ext. Then when someone clicks one of those links it calls drupal core's file\_download() function, which in turn invokes hook\_file\_download().

Drupal core implements hook\_file\_download() in the file module as file\_file\_download(), which handles these private files to allow users with the appropriate access permissions to download the file.

However file\_file\_download() won't work out of the box with non drupal field files (like your custom files appear to be), it only works for files attached to drupal fields.

So you will also have to implement your own version of hook\_file\_download() to handle your particular files.

One way to single out your files and avoid massing with the files that file\_file\_download() already handles is to put your custom files in a sub-directory of the private files directory that is not used by any other files, then in your hook\_file\_download() you check for that directory in the file path, return headers if the file is in the right directory and the user has the correct permissions, otherwise, if the user doesn't have perms return -1 and if the file is outside of your special sub-directory just return null to ignore the file and let drupal handle it as normal.

To implement hook\_file\_download() you have to create a custom drupal module that implements the hook like so:

```
/**
 * Implements hook_file_download().
 */
function YOURMODULENAME_file_download($uri, $field_type = 'file') {
  // Your code goes here.
}

```

See file\_file\_download() as an example.

For more information see:
https://drupal.org/node/292
https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7

**Note:**
Your private file system path will be something like sites/default/files/private (a directory on your server). The path system/files is a drupal website url, not a path on the file system, and is only used to create hyperlinks to the files that are in the private files directory.

So if you set your private file system path to sites/default/files/private, a hyperlink on your site that points to /system/files/export/filename.txt will open the file on your web server at /sites/default/files/export/filename.txt.

# Answer
> 2 votes
Create a private file field as you would if they were regular private files.

Hook in to the file download function: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_file\_download/7

Let Drupal handle permissions, create your file dynamically.

---
Tags: files
---


# Question
Title: Is it possible for two drupal views to share the same pager limit
I have two separate views 'now' and 'next', they both collectively must only have three items. Is there a way for them to share the same pager limit for example if the 'now' view has one item the 'next' view can only display two items as the pager limit is three.

# Answer
If you want to create the blocks yourself, eg, not just via the Block UI and Views, you can hack it together with using various hooks available within Views.

First out the door, I could see using Views' standard block for the `now` View, but in the `next` block, using `views_get_view_result()` to look at the results of the `now` View and depending upon its result, eg, how many results there are, changing the pager of the `next` View to be whatever you want, in this case 1 or 2.

Note that this of course entails running the `now` View queries twice, so you could create custom blocks containing both Views and statically save the information to be shared across the Page but that introduces other ugliness.

And then if any of these Views are cached, another set of issues crops up.

So, as @molot has mentioned in comments, there is a bunch to think about here.
> 1 votes

---
Tags: views
---


title: Problem with table schema

text:
# Question
Title: Problem with table schema
I'm working on an API that pulls data from a Drupal site. Everything has gone pretty well I normally use Drupal Bootstrap to load Drupal use the functions I need then spit out a JSON array. I am having one issue though with a module, for some reason Drupal's schema doesn't seem to think the table exists. The module I am working with is VotingApi.

So in my API call I connect to the drupal db. Then if I run:

```
print_r(module_list());

```

I get a big list of modules installed and `votingapi` is included. If I run:

```
var_dump(module_exists('voting_api'));

```

I get a `true` response. I can also run:

```
var_dump(db_table_exists('votingapi_vote'));

```

And get a `true` response. However if I run:

```
print_r(drupal_get_complete_schema(true));

```

The `votingapi_vote` and `votingapi_cache` tables don't show up in the list. So then when I try to write a record to those tables with `drupal_write_record()` it doesn't work because that function checks the schema to see if the table exists. I have tried clearing the schema cache like this before I call `drupal_get_complete_schema()`:

```
cache_clear_all('schema', 'cache');

```

It doesn't help, when it is rebuilt from the API the voting tables never show up. If I go into Drupal's admin and Clear All Cache then the table schema is rebuilt correctly and includes the voting tables. Any ideas on how I can get the schema to rebuild correct for the API?

# Answer
> 2 votes
Figured it out. It had to do with using MultiSite apparently when you use multisite and bootstrap it will only bootstrap to the main site. I found an article talking about it here https://drupal.org/node/2080819

Basically you need to override what the system variable is for the url so that it will bootstrap to the correct site.

```
define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$variables['url'] = 'http://subsite1.example.com/';
drupal_override_server_variables($variables);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

---
Tags: caching, database, bootstrapping
---


# Question
Title: How can I reference a field from a product display when calculating a price?
I am creating a product where you can buy a shirt in custom quantities (3 smalls, 1 large, 4 mediums). The user types in the quantity, as well as select various product variations. Then by rules I calculate the price based on a fields I made called small\_price, medium\_price etc. So it would pull the users quantity input for each field and multiply accordingly e.g. small\_price\*small\_quantity + medium\_price\*medium\_quanitity. This is all working well, however it is currently implemented on the product level and not product display.

What I am trying to do is have the rule multiply a field from the product display by a field in the product variation. However the product display field is not available to me in rules. I have seen a couple of short hand answers on here about writing a custom rule but is there anyone who could explain it to me a little more in depth?

Thanks!

# Answer
I generally recommend any information required for the pricing / fulfillment of a product to be stored on the product itself. I can see where you might need to do so based on information in the display, though (e.g. discounting products in a particular category).

In that case, you can't traverse from the line item / product to its display mode via the standard Rules data selector. Instead you need to use the appropriate action to load the node that references the product in question. Then you'll need to pass the line item and that node to a Rules component where you can use additional conditions to bring field data from the display node into scope (e.g. "Entity has field") and use the line item unit price manipulation actions on the line item to affect the pricing.
> 0 votes

---
Tags: entities, commerce
---


# Question
Title: I'm trying to get all duplicate rows using db_select
Before I run db\_delete, I'm trying to run db\_select to test that I am getting all duplicate rows, based on a specific column value.

```
db_select('node_revision', 'n')
    ->where('n.nid NOT IN SELECT MIN(n.nid)')
    ->groupBy('hash')
    ->execute()
    ->fetchAll();

```

Basically, delete (select for the test) all rows with the same hash value, except for the first one, is my goal.

I'm basing it on this page:

http://blog.sqlauthority.com/2007/03/01/sql-server-delete-duplicate-records-rows/

But for some reason I get the following error:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node_revision n WHERE (n.nid NOT IN SELECT MIN(nid)) GROUP BY hash' at line 1: SELECT FROM {node_revision} n WHERE (n.nid NOT IN SELECT MIN(nid)) GROUP BY hash; Array ( ) in include()

```

What am I doing wrong? Why is ; array ( ) there?

# Answer
> 1 votes
At the moment your query is:

```
SELECT
FROM
{node_revision} n
WHERE  (n.nid NOT IN SELECT MIN(n.nid))
GROUP BY hash

```

You need to add some fields...

```
db_select('node_revision', 'n')
  ->fields('n', array('vid'))
  ->where('n.nid NOT IN SELECT MIN(n.nid)')
  ->groupBy('hash')
  ->execute()
  ->fetchAll();

```

---
Tags: database
---


# Question
Title: how to open custom form in popup onclick in menu link drupal
I made a custom form in drupal. I just want to open that form on popup form when user click on menu.

Here is my code

```
function acoma_extra_divide_element_horizontaly($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('At which height should the element be divided? (distance
    from cupboard floor)'),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Divide draw up horizontally'),
    '#suffix' => 'cm',
  );

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

  return $form;
}

```

Menu code is:

```
<div id="step3-menu" class="step3-menu" style="display:none;position: absolute">
        <ul>
            <li><a href="#">Divide element horizontally</a></li>
            <li><a href="#" class="popup">Divide element vertically</a></li>
            <li><a href="#" class="popup">Reset element</a></li>
        </ul>
    </div>

```

I just want when use click on menu this form loads in popup. I used the popup module.

Any help would be appreciated.

# Answer
There are many ways to do this. You can use Popup forms module. Its configuration is in documentation of module or Modal Frame API module.
> 1 votes

---
Tags: 7
---


title: Multiple nodes in a single Views row

text:
# Question
Title: Multiple nodes in a single Views row
I have a content type **Cars** and a content type **WheelManufacturer**. Of course a **WheelManufactorer** node is referenced by a **Car** node.

I'm trying to create a View (in D8) that will fetch some fields from the **Car** nodes and some fields from the corresponding **WheelManufacturer** node.

I'm trying to do that by using **relationships** in Views... but I have a problem: I can add relationships to, ie Term Reference or Image fields, but not to Entity Reference ones... those fields just don't appear in the list.

Any ideas why?

# Answer
As far as I've understood, it is actually NOT possible in Drupal 8: https://drupal.org/node/1906806

**EDIT**: the patch at the above link DOES work for me with the interdiff I just posted, so if you feel adventurous, you can give it a try!
> 1 votes

---
Tags: 8, views
---


# Question
Title: What is the name of the sql table that relates to all of the field tables
What is the name of the MySQL table that relates to all of the field tables

# Answer
"field\_config" contains general information/definitions.

"field\_config\_instance" tells us which fields belong to which content type
> 0 votes

# Answer
To answer your question literally, there isn't a single MySQL table that relates to all of the field tables.

There are:

* `field_config` \- Holds config information for all fields.
* `field_config_instance` \- Holds config information for all instances of fields.
* `field_data_*` \- Holds data for multiple instances of the same field.
* `field_revision_*` \- Holds revision data for the equivalent `field_data_*` table.
> 0 votes

---
Tags: database
---


title: Print image path in a View?

text:
# Question
Title: Print image path in a View?
I have a content type that has an image attached. In a View I need to print the full path to the image.

I thought this would be easy but for some reason I cant figure it out. I can find the image field in the view, but when I rewrite the output I cant see any patterns for the file path.

In my view Ive created a relationship to the image field to the node, but this doesn't provide me with any more rewrite patterns, or any fields that look like they could be the image path.

# Answer
> 4 votes
Found the answer here: https://drupal.org/node/1051320

1. Create your view as normal.
2. Add your image field as normal.
3. Go to relationships
4. Add Relationship "File Usage"
5. Go back to fields section
6. Under groups, a new option "File" will appear
7. Selecting file will output the path for every file field on your site. If you want it just for one particular image field follows these steps:

* Add the new "File" field
    * In file field, select "exclude from display".
    * Go back to your image field (created in step 2)
    * Select "Rewrite the output of this field"
    * Under tokens, use the token for the file field (created in step 6). (NB the file field must come before the image field, or else the token will not appear).

Hope this helps somebody!

# Answer
> 1 votes
In D7 you need to add (or if none exists) a field formatter. In your case there already is a contributed one that does exactly what you need: display the URL instead if the image itself:

https://drupal.org/project/image\_url\_formatter

---
Tags: 7, views
---


# Question
Title: Bypass Login if a specific URL is visited
I am into a strange fix with my site.

Firstly, my site is password protected. So, when I visit, http://www.example.com it is greeted with a nice shiny login page. User puts in the credentials and goes in.

Now, I am hoping that for some special people, they don't have to login. For that I need to have some specific URL, say, http://www.example.com/bypass which takes me to the site without any login page.

Is it possible?

# Answer
With no coding, you might be able to use this module: https://drupal.org/project/rolereferral

With coding:

Create a new user role that has all the same permissions as "Authenticated user". Call it "bypass", for example.

Create a unique page, or a menu hook, that adds the new "bypass" role to the current PHP $user object.
> 1 votes

---
Tags: users
---


title: Zebra stripping each block in a region

text:
# Question
Title: Zebra stripping each block in a region
I'm trying to apply this to each block in a region:

http://figure-w.co.uk/zebra-striping-in-php/

He is generating zebra striping per div here, which is fine, but I'm wondering how I would apply this to each block in a given region.

Would I use something like `block_list($region)`?

This code is supposed to go in template.php

```
function likemind_zebra($id = 'global',
                     $odd_class = 'odd', $even_class='even') {
  static $cursor = array();
  if(!isset($cursor[$id])) {
    $cursor[$id] = 1;
  }
  return $cursor[$id]++ %2? $odd_class: $even_class;
}

```

I'm just trying to figure out how I would get it to apply to each block in a region, rather than the whole region.

# Answer
A `$block_zebra` variable is defined within the block templates to allow for the ability to zebra stripe them in a region.

See hook\_preprocess\_block() for more info.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: Creating a file upload field with a translatable title attribute field
I have a File field with the title attribute enabled and I'm trying to figure out how to make the title attribute field translatable using entity translations without affecting the actual file field itself. I'd prefer to allow users to upload one file with a title attribute that can be translated.

# Answer
What I ended up doing was I used `hook_i18n_string_info` to define a new "Captions" text group, `hook_field_widget_form_alter` to attach a new process function to the desired upload widgets, and my callback for `hook_field_widget_form_alter` cloned the title field (into title\_fr for me), then also checked to see if #default\_value was a string and used `i18n_string_translate` to update title\_fr's default\_value.

What I did and wouldn't recommend doing was I put the translation handling in the submit function for my form. In there I constructed my translation "name" using `caption:$field_key::$nid::$field_delta` and then calling `i18n_string_translation_update($name, $french_caption, 'fr', $english_caption)`.
> 0 votes

---
Tags: files, i18n-l10n
---


# Question
Title: Content display errors - Missing styling and content
I have a local Drupal 7.2.6 installation that I am experiencing a strange issue with. If I log in and go to Find Content the it displays my content as expected. Clicking on an item takes me to the relevant page and everything looks ok,

However a few of the content items take me to a page that looks like this....

Anyone any ideas?

# Answer
> 1 votes
Seems to be related to a PHP error, see which are the the resources (images, css, js, ...) that are returning 500 HTTP error.

Check if the issue only happens with a specific content type.

Check the Drupal log (admin/reports/dblog) and the Apache log to find more info about this issue.

---
Tags: nodes
---


# Question
Title: Grouping fields with field group doesn't work on display of Drupal Commerce product in product variation
I've got a content type for a product and fields for variation. I'm writing about fields in that variation. I have created new group containing some fields using field groups. Let's say:

```
[Field group]
 1. Foo
 2. Bar

```

The group setup is done properly on content type/field display in product variation tab. I'm using drupal commerce, I have tried updating CRON, flushing cache, drinking beer, resaving content. It didn't help. Anyone has any idea?

# Answer
> 0 votes
The Field Group module provides the ability to group on both the edit form and the display independently.

This means to add a field group to the form you have to do so on `admin/structure/types/manage/CONTENTTYPE` and to add a field group for display you do it on `admin/structure/types/manage/CONTENTTYPE/display` (this is for nodes, this will be in different places for other entity types).

If you want the group on both the form and the display you have to add it in both places.

# Answer
> 0 votes
My specific question instead of normal nodes was about **drupal commerce product**. Everything is ok if you create group for a content type and select for ex. `<div>` wrapper. But groups are not showing when you change display in product variation (`product-variation-types/product/display`) and they also don't work with HTML5 wrapper (*see bottom*).

I've got code like this

```
<div>
    <label></label><field></field>
</div>
<div>
    <label></label><field></field>
</div>
<div>
    <label></label><field></field>
</div>
<div>
    <label></label><field></field>
</div>
<div>
    <label></label><field></field>
</div>

```

And I wanted to put the fields into a group:

```
<div id="field-group">
    <div>
        <label></label><field></field>
    </div>
    <div>
        <label></label><field></field>
    </div>
</div>
    <div>
        <label></label><field></field>
    </div>
    <div>
        <label></label><field></field>
    </div>

```

*HTML5 wrapper bug* But the result after selecting **HTML5 wrapper** was:

```
<div>
    <id="field-group">
    <div>
        <label></label><field></field>
    </div>
    <div>
        <label></label><field></field>
    </div>

    <div>
        <label></label><field></field>
    </div>
    <div>
        <label></label><field></field>
    </div>
</div>

```

---
Tags: commerce, entities
---