title: Put structure fields in a div

text:
# Question
Title: Put structure fields in a div
i'm beginning with Drupal 7, and i would like to do a "block" with a picture to the left, a title right to the picture, and a description below the title.

I made a new structure, there is already a field title, and a field body, so i just added a field image.

Then I made a new view containing this new structure, but the problem is that it shows the title, then the picture, then the description.

I think the solution would be to put the title field and the description field into a div block, and then with css, declare the div and the image as "inline-block". How could i do this please?

# Answer
Your question is indeed very confused. You might first clarify some Drupal basic concepts.

**What is a block ?** "Blocks are the boxes of content (such as "User Login" or "Who's online") that can be displayed in regions (such as footer or sidebar) on your page." Read Working with blocks (content in regions) for full understanding.

**What is a content type ?** We don't speak about *structures* but content types : a Content Type is a pre-defined collection of data types (Fields), this is how site editors can input original content on a Drupal site. Read Working with content types and fields.

**What is a view ?** "Using the Views module, you can fetch content from the database and present it to the user as lists, posts, galleries, tables, maps, graphs, menu items, blocks, reports, forum posts etc." Read Working with Views.

**How to change the way blocks, fields, and so on display ?** this is a very wide question.

1. Without editing any code, you can make some basic choices in *admin/structure/types/*, and for the content type you'd like to edit, manage display of each of the fields
2. you can install an infinity of contributed themes
3. you can create your theme, and then customize your regions, edit your stylesheets... A good place to begin might be the Theming Guide

Drupal is a very powerful CMS / CMF , but you'll have to deal with these concepts to feel a bit more confortable
> 1 votes

# Answer
I guess the following example might help you,

**Create a view with the following options,**

**View Name**: Custom View Theming (Machine name : custom\_view\_theming)

**Fields :**

Content: Title Content: Body Content: Image

**FORMAT :**

Format: Unformatted list | Settings Show: Fields | Settings

If your requirement requires a filter add it , I have just added the following filters

**FILTER CRITERIA :**

Content: Published (Yes) Content: Type (in Article, ...) Content: Type (exposed)

**EXPOSED FORM :**

Exposed form in block: Yes Exposed form style: Basic | Settings

Now the view is created and ready to populate in a block configured in the block section.Next step is to override the default-theme supported by the views,

Create the following .tpl.php files in the (default-theme \[OR\] custom-theme-enabled directory)/themes/templates directory.

```
views-view-fields--custom-view-theming.tpl.php
views-view-field--custom-view-theming--title.tpl.php
views-view-field--custom-view-theming--body.tpl.php
views-view-field--custom-view-theming--field-image.tpl.php

```

After Creating all the files click on the theme : inforamtion to scan all the relevant template files created now. Once all the files are listed in the theme check the row style output ans save the view.

Now update the following template files,

views-view-fields--custom-view-theming.tpl.php file is to place a overall container for each row if you need, but I just used the default $fileds it contains the following,

```
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

```

views-view-field--custom-view-theming--title.tpl.php contains the actual html for theming the output, I have done the following,

```
<div class="main-content" style="float: left; clear: both;margin-bottom: 30px;">
<a href="#" title="<?php print_r($row->node_title);?>" style="float: left; padding-right: 20px;">
  <img width="170" class="bordered-image -align" title="<?php print_r($row->node_title);?>" src="sites/default/files/field/image/<?php print $row->field_field_image[0]['raw']['filename']; ?>" />
</a>
<h2>
  <a alt="" title="<?php print_r($row->node_title);?>" href=""> <?php print_r($row->node_title);?> </a>
</h2>
<div class="article-additional-info">
  <?php print $row->field_body[0]['raw']['value']; ?>
</div>
</div>
<div style="clear: both;"></div>

```

**NOTE**: Since we have included all the three fields in the a single templare file, leave the following template files empty.

```
views-view-field--custom-view-theming--body.tpl.php
views-view-field--custom-view-theming--field-image.tpl.php

```

That's all about the steps, flush the cache and check out your new block.
> 1 votes

---
Tags: views, entities
---


# Question
Title: How to show the parent and child taxonomy term?
I have a vocabulary like this:

* Parent 1
    + Child 1
    + Child 2
    + Child 3
* Parent 2
    + Child 1
    + Child 2

Now I would like to use a view to create a list of a Parent term with its Child terms. I try to do this with Views UI, but only show the term parent... No the child term's. It is very confusing for me.

Can anyone help with this case? Thanks :D

# Answer
> 14 votes
Views can do this. Views is a UI for sql searches so you are setting the definition for the query that will be made of the content database.

1. Create a view to display a taxonomy term with a page with a path configured along this line `category/%`. The `%` is a wildcard that will make the view respond to any value applied in the URL that matches this format.
2. Set up your display and any filters desired.
3. Define a relationship (third column of view UI page) and set it to taxonomy term: parent. This tells the view to look at the parent field in each taxonomy term searched. (Note that Drupal includes a field for each term that identifies its parent, but not its siblings or children).
4. Next we tell the view to interpret the wildcard from the URL we used in the path for the view: Define a contextual filter (above the relationship selection) and set it to a taxonomy:termID. In the form, set the relationship to Parent in the drop down box. This tells View that the term being called in the URL will be applied as a filter for the 'parent' field of the taxonomy terms as they are searched.
5. Finally we must complete refining the contextual filter. You can tell the view what to do if it does not find an answer in that section of the form if you want, but we must tell it what to do if it does find solutions in the query. To do so check the validation check box. Set the Validator to Taxonomy term and select the vocabulary that applies to your hierarchy. Then select either Term ID or Term name converted to term ID as the Filter value type. If the value you are passing in the % is a term ID, then you are done. If the passed value is a term Name, then you may want to check the box to convert dashes to spaces. IF you have multiple word term names, the URL will have dashes, which do not match the actual spaces in the term name. This little correction makes them agree so a test succeeds.
6. Finally go to the preview area and enter the name or ID for a term you know has children and you should get the list of children terms. Use the sorting settings to arrange them in whatever order you need.

Good Luck!

# Answer
> 8 votes
I have archive this use view too, but in slightly different way compare Ashlar.

1. Add **Taxonomy term: Term ID** in CONTEXTUAL FILTERS.
2. Add **Taxonomy term: Parent term** in RELATIONSHIPS. (leave Require this relationship unchecked.)
3. Add **Taxonomy term: Parent term** in filter section. select **great than 0**.
4. do not forget to filter your taxnonmy term in mycase Taxonomy vocabulary: Machine name (= Business Directory).
5. add Taxonomy term: Rendered Taxonomy term to your fields , select relationship to **parent** , check the Exclude from display.
6. In setting, under FORMAT section. In grouping field 1, select **(Parent) Taxonomy term: Rendered Taxonomy term**.

You should good to go. you can use view tpl to add more class base on the group. I have enclose my screenshot for references. Sorry for my English.

# Answer
> 0 votes
If you'd like to use that view as a field, you can create such a list without using Views, by using Taxonomy Term Reference Filter by Views module and you can specify the parent, so the list can be filtered automatically.

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


title: Dynamic default value for select list

text:
# Question
Title: Dynamic default value for select list
I am trying to make a reservation system for equipment in a laboratory. People reserve equipment by creating "reservation" nodes that are tagged with the taxonomy term "Equipment". In the "create reservation page" the referenced taxonomy field is a dropdown list.

On the other hand I have a table view with all the equipment with its corresponding taxonomy term. I would like to have in a third column a link to the "create reservation page" and I would like that in the "create reservation page" the corresponding taxonomy term in the dropdown list is already selected. Any idea how to succeed?

# Answer
The Prepopulate module allows you to construct a special URL inside your table view that, when clicked, will prepopulate the correct taxonomy term on the "Create reservation page".

The special URL will looking something like this:

```
http://www.example.com/node/add/reservation?edit[field_equipment_term_reference]=123

```

You need to:

1. Download and install the Prepopulate Drupal module.
2. In your table view, add the Taxonomy Term ID field (if not already added).
3. In your table view, add a Global Text custom field.
4. In the Global Text field config screen, specify the text "create reservation page" and then expand the rewriting section, and turn the field into a link, with link destination of `node/add/reservation?edit[field_equipment_term_reference]=[tid]`.

Please note:

* the `[tid]` is the substitution token from the field added in step 2.
* replace `field_equipment_term_reference` with the real machine name of the taxonomy term reference field you're using on the Reservation node.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to hide specific fields and the according label in a view, based on field permissions?
I have a view called *Profile* that displays some of the user fields. Amongst these is a *Name* field (field\_name). I'd like to hide this field except for the administrator and the user himself/herself. I installed the Field Permissions module, wich nicely gives me the opportunity to mark the field as private. When this is checked, the *Name*'s value disappears in my *Profile* view, but the according label is still there - and that's not very nice.

How can I hide the label aswell?

# Answer
On the Name field's edit config popup, remove the text from the Label field and disable the label checkbox; expand the Rewriting section, and paste in the label followed by the name field's substitution pattern.... it will look something like this `Name: [field_name]`. Finally, ensure the option to disable rewriting when field is empty checkbox is checked.
> 2 votes

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


# Question
Title: How do I extend the xmlsitemap module to include the google news / images and videos formats
The xmlsitemap module covers the standard google xml site map. However, https://support.google.com/webmasters/answer/178636?hl=en is the information for the google image search and the specific markup for creating a sitemap for image content. Likewise https://support.google.com/webmasters/answer/80472?hl=en is for video content. I don't think that the xmlsitemap module supports these additional types. (Google news sitemap is another one). Can anyone offer any more information about extending the module or if there are any patches that will achieve the above.

# Answer
For news there's the Google News sitemap module

> The Google News module generates a Google news compatible sitemap feed from your Drupal site's content.

I don't think there are existing modules for images/video (I've looked for the same thing before myself and ended up hacking something together).

There's a feature request in the XMLSitemap module's issue queue for exactly this, but it's currently postponed. There are a couple of links on that thread pointing to how others have achieved it, those might be worth a look.
> 2 votes

---
Tags: xml-sitemap
---


# Question
Title: View my local site on smartphone and tablet
I want to view my website on my iPad and iPhone to take a look how my responsive design looks like. I'm running on a macbook air and I was wondering if there is any type of way to run my local drupal site on the ipad or iphone. I heard you could connect through the ip or somehow. Any ideas?

Anyone done this before?

# Answer
> 4 votes
Go to the terminal and type

> ifconfig

Check for you IP address.

Suppose your drupal url is

> www.localhost/drupal

then go to your iPad and iPhone browser and type

> IP Address/drupal

Using this you could see your local drupal site on iPad and iPhone.

# Answer
> 1 votes
There are some pretty significant details missing that makes answering this difficult.

If you have a web server running on your local computer and your iPad/iPhone is connected to the same local network, you can definitely view the website on those devices.

You'll need to determine the local IP address of your machine (usually starts with 192.168), and then try to visit that IP address in your mobile browser. How you do this varies greatly depending on your operating system.

See: http://www.bitwiseim.com/wiki/index.php?title=Determine\_your\_LAN\_/*Local*/\_Internal\_IP\_Address for common ways to find this.

There are so many other factors involved, though, that I don't know if an answer can be given that is useful without knowing more about your setup.

---
Tags: theming
---


# Question
Title: Unset the "please wait" in drupal commerce
I've got a product with different taxonomy like "S" "M" "L". When you change the size in the display product, it shows the ajax div "Please wait..." I've tried

```
function bartik_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
unset($form['attributes']['field_size']['#ajax']['progress']['message']);
}

```

If I have a look at it with dms($form) I see attributes -\> field\_size -\> #ajax -\> callback(commerce\_cart\_add\_to\_cart\_form\_attributes\_refresh)

There is not message. How can I get rid of it?

Thanks in advance.

# Answer
A simple way could be to hide it with CSS, but what is displayed by Drupal is actually configurable. The throbber with the *Please wait...* message is the default behavior but you can change it to a number of things. What you need to look at is the `#ajax['progress']` attribute.

Usually `#ajax['progress']` is not set in the form, and Drupal will add the default throbber with the *Please wait...* message in the JavaScript that handle the ajax request. The solution it quite simple, all you need to do is to set it like this:

```
$form['element']['#ajax']['progress'] = array('type' => 'throbber');

```

It will kill the message and only show the throbber. There are a number of ways to configure what Drupal does to show the user progress - you can read all about it in the link above.
> 4 votes

# Answer
Thanks, but in comment mistake: not 'attribute' - 'attributes'.

```
function bartik_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
  $form['attributes']['field_NAME']['#ajax']['progress'] = array('type' => 'throbber');
}

```
> 1 votes

---
Tags: forms, ajax, commerce, theming
---


# Question
Title: PDO Error, __construct(): php_network_getaddresses: getaddrinfo failed:
I'm pulling a site from my production server down to a new development server that I'm setting up.

I can't get this to work though unfortunately. I imported my database into mysql and made sure that all of my account/privileges information was correct with what I had in my site-root/settings.php file. I even created a new account with all the privledges and edited my settings.php file to it and still couldn't get it to work.

Is there somewhere else in my drupal installation that I need to input this information that I'm not aware of? As a side note, I have other sites running locally in the same development environment, and they're running fine, however, I've noticed that they don't have a settings.php file.

Details:

This installation was originally created in MS WebMatrix using the Acquia Distribution As far as I can tell there's not a huge difference between this and other drupal distros beyond it having some really basic stuff already included. My other sites, that work, are running bear distro and my development server is just your basic XAMPP setup.

This is what's in my settings.php file. Obviously, the db, user and passwords where all replaced with comments for security reasons. You'll just have to trust me that they match up.

```
$databases = array( 'default' => array( 'default' => array ('database' => '####commented for security###', 'username' => '####commented for security###', 'password' => '####commented for security###', 'host' => 'localhost', 'driver' => 'mysql', 'port' => '3306', 'prefix' => '' ) ) );

```

Here is a screenshot:

**Thanks in advance for your time!**

# Answer
The default settings.php is located at sites/default/settings.php, not in the root of your drupal installation. I have no idea why one of the server techs at my hosting company moved the settings.php into the root, but that was what my previous confusion was.

As a side-note, if your moving from a production to a development server, make sure that you setup your host in settings.php to localhost. As a corollary, if you're moving from development to production, make sure you set your host field from youraddress.com (or youraddress.hostingaddress.com) from localhost. It would be nice if there was a field somewhere in drupal settings to handle this, so that you didn't have to snoop through the settings.php to find/set it. However though, this is likely not possible since drupal pulls everything like this from databases and it has to have these settings in order to see the database. Just food for thought.

I also normally find it useful to look at code snippets rather than trying to understand what someone said, so here's an example of what your database line in settings.php should look like if your settings up a generally basic development server.

```
$databases = array (
  'default' =>
     array(
        'default' =>
         array (
            'database' => '##Your_database_name##',
            'username' => '##your_database_username#', #comment & store old user from production server here for safe keeping
            'password' => '##your_database_password##', #comment & store old pw from production server here for safe keeping
            'host' => 'localhost',   #comment and store production database url here
            'driver' => 'mysql',
            'port' => '',  #localhost shouldn't normally need a port, but your production sever likely does, so comment and store that on the side here.
            'prefix' => ''
         ),
    ),
);

```
> 1 votes

---
Tags: configuration
---


# Question
Title: Allow users to edit the list of CCK allowed values for "select list"
I have a CCK field ("City") that is a select list, and has manually entered cities in the allowed values list. I added these cities (as the administrator of the website) but I would like to hand control over to the client.
However, changing their permissions, and allowing them full access to the CCK content types would be potentially disastrous; I need a way to give authenticated users permission to add values to this select list.

Is this possible?

# Answer
A simple solution would be to use taxonomy.

* Taxonomy has it's own permission system.
* Drupal adds a lot of nice features for taxonomies.
* Categories such as cities is a perfect match for a taxonomy.
> 1 votes

# Answer
There is a module which does exactly this - allows regular users to edit CCK field values. The module is called 'values' (http://drupal.org/project/values).
> 1 votes

# Answer
With CCK I would do the following:

* create a content type "cities" with a "cityname" field
* in the "City" field you defined, I would put some PHP code to populate the "allowed values" textarea:

```
$cities = Array();
$result = db_query("SELECT nid FROM {node} WHERE status = 1 AND type = 'cities'");
while ($row = db_fetch_array($result)) {
  $node_city = node_load($row['nid']);
  $cities[$node->nid] = $node_city->field_cityname[0]['value'];
}
return $cities;

```

A couple of remarks here:

* the code is for D6 but can be adapted quite easily I think.
* you'll have to put in place some validation in the creation of "cityname" to avoid duplicates (maybe also think about a country field).
* it can be quite heavy to load a big number of `$node_city`, personnaly I'd rather use the tables of CCK to query the value directly, it's a little more complicated but ligther.

```
$cities = Array();
$field = content_fields('field_cityname');
$db_info = content_database_info($field);

$result = db_query("SELECT n.nid, " . $db_info['columns']['value'] . " AS city
          FROM {node} n
          INNER JOIN {'. $db_info['table'] . '} c ON c.vid = n.vid
          WHERE status = 1 AND type = 'cities'");
while ($row = db_fetch_array($result)) {
  $cities[$row['nid']] = $row['city'];
}
return $cities;

```
> 0 votes

# Answer
I've created a (sandbox) module that does what you want. I'd just like to reiterate that you might find taxonomy a better fit... but if you do want to continue the CCK route this module might help :)
> 0 votes

---
Tags: entities, users
---


# Question
Title: Transfer field from Organic Group to group content
I have a field on an Organic Group and I want to transfer the field to a piece of content related to the group and have it stored in the database rather than being referenced. I've been able to do that with the Field Reference module, and the referenced field shows up when the view is rendered on the content node; however, I can't seem to pull that field into a "schedule evaluation date" in Rules Scheduler because I think it is not a hard-coded value.

So, is there any module that just takes a field from one entity/node and stores it in another entity/node when you save a new piece of content?

Or would the Computed Field module let me do this? I know I don't see a "date" type to store in the database there.

Thanks in advance!

# Answer
> 0 votes
I actually just ended up doing a hook\_form\_alter and adding a submit handler that saved the referenced field value from the form state into the field that I wanted to save it in on the non referenced node.

This worked nicely, but you had to save the node before it updates and you have to make sure to tell the web admins that the date field won't update until after they save the node. This provided a little confusion at the beginning.

So, this is a great solution for any node where you want to save form state data from one node/entity to another and have a unique identifier like nid/gid to do database lookup and save. Code sample below. I realize that node\_load might be expensive to do, but since it's only happens when an admin user saves a form, I thought it was alright.

```
/**
 * Implements hook_form_alter().
 */
function custom_add_survey_date_form_webform_node_form_alter(&$form, &$form_state, $form_id) {

  //Add submit handler to grab and change date values
  $form['#submit'][] = 'custom_add_survey_date_submit_handler';
}

 /**
 * Adds a submit handler to webform_node_form
 */
function custom_add_survey_date_submit_handler($form, &$form_state) {

  //grab reference to event date
  $og_reference = $form_state['values']['og_group_ref']['und'][0]['target_id'];

  //load date from event plan node
  $og_node = node_load($og_reference);
  $event_date = $og_node->field_date_of_event['und'][0]['value'];

  //Store date on survey node
  $form_state['values']['field_date_of_event02']['und'][0]['value'] = $event_date;
}

```

---
Tags: organic-groups, entities, rules
---


# Question
Title: FAQ page access denied for anonymous users
I've installed the FAQ module and created some FAQ content. The FAQ page is found here: http://www.inadaydevelopment.com/faq-page

I have given Anonymous users the "View FAQ pages" permission, but anonymous users still cannot view the FAQ content of the above page. It shows the header block which I configured to appear only on that page, but the body of the page shows Access Denied.

What am I missing?

# Answer
> 0 votes
It looks like I needed to flush my cache, the page was cached with old permissions and so anon couldn't see it last night when I made the change, but can see it now.

---
Tags: users, 7
---


# Question
Title: Commerce Feeds - Taxonomy term processor Issue
Using Commerce Feeds version: 7.x-1.3

I am running the "taxonomy term processor". I have tried every available combination for "Update existing terms" (Do not update existing terms, Replace existing terms, Update existing terms . . . even Skip hash check - 'checked' and Skip hash check - 'unchecked').

No matter what I do, the csv import file that I am uploading just adds to what I have already imported. If I am uploading the same file and have added additional terms, I would think there would be a way of JUST adding the new terms, not duplicating everything again.

Am I missing something or is this a bug?

Thank you!

Tom

# Answer
Tom, I found your question today while fighting the same problem in the standard Feeds module. In the Processor \> Mapping setup, do you have fields set as unique targets in the "target configuration" column?

In my system, I found that even though I had tried to set the imported column to be a 'unique target', that setting had not been saved. After going through the process of setting unique targets, updating the column map, and saving again, the duplication problem has now been solved in my system.
> 0 votes

---
Tags: taxonomy-terms, commerce, feeds
---


# Question
Title: Cannot redeclare libraries_drush_command()
After issuing the following command in the base drupal folder (/var/www/html)

```
$ drush status

```

I get the following response.

```
PHP Fatal error:  Cannot redeclare libraries_drush_command() (previously declared in /var/www/html/profiles/commons/modules/contrib/libraries/libraries.drush.inc:13) in /var/www/html/sites/all/modules/libraries/libraries.drush.inc on line 25
Drush command terminated abnormally due to an unrecoverable error.                                                                 [error]
Error: Cannot redeclare libraries_drush_command() (previously declared in
/var/www/html/profiles/commons/modules/contrib/libraries/libraries.drush.inc:13) in
/var/www/html/sites/all/modules/libraries/libraries.drush.inc, line 25

```

This is a new server install using RHEL 6.4 (Santiago) and drush 6.0 installed through pear.

Where I might begin to fix this?

# Answer
Removing /var/www/html/sites/all/modules/libraries/libraries.drush.inc cleared things up. I bungled things up somewhere. IRC #drupal-commons confirmed Clive's note above.
> 2 votes

# Answer
Drush seems to load duplicate command files as reported in https://github.com/drush-ops/drush/issues/280 and looks like the they fixed the same https://drupal.org/node/644126
> 0 votes

---
Tags: drush
---


title: How can i sell files using ubercart

text:
# Question
Title: How can i sell files using ubercart
I want to sell `files` as product using `ubercart`.

How to add files using product content type?

I want user to `pay for the file first` and then `get file downloaded`.

Is it possbile?Then how ??

Also i want each `role` called '`vendor`' to have there own `payment details` and `get paid from buyers`. Is that possbile?

Thanks.

# Answer
There is already module `File downloads` in the `ubercart` which allow user to sell `file` with the `product`.

* Install the module `File downloads` from the module list.

**Assigning directory to `file donwload`:**

* Go to `Administration -> Store -> Configuration -> Product`
* In the `File download settings` section, set the path of the `directory` of the files and save the form.

**Uploading files:** \- Go to `Administration -> Store -> Products -> View file downloads` \- Upload `files` into directory (which you have configured in above step) using `upload file` action.

**Adding files to product:**

* Edit your `product` and you will get the `feature` link in top of page. click on this link.
* In `feature` form, you can add `file download` feature to the product and it will redirect you to form to assign file to product.
* Select `file name` in `File download` text field. This is autocomplete field, so you need to configure correct files and save form.

When the user purchase product and pay the amount, it will send a link to user in his mail to download the files.

Regarding your second question, there is module Ubercart Marketplace.

> Ubercart Marketplace adds multiple seller support to the Ubercart module. It includes a series of modules that limit the access to Ubercart functions for sellers. Additional functionality is added to support this from both a marketplace seller's point of view and the store administrator's view. Sellers (with the proper access permissions) gain the ability to view their products, track and fulfill their orders, and monitor their sales reports. Store administrators can view seller reports based on seller order statuses and seller sales. Support is included for Paypal Mass Payments, with which an administrator can automatically pay his/her sellers for custom periods.

Kindly see that Ubercart marketplace is still in development version for Drupal 7, so may be there could be some issue in this module.
> 3 votes

# Answer
There are so many tutorials available, i found it by Googling

> Many stores online deal in digital goods. Known Ubercart sites are already selling music, photos, movies, and more using the core file download system. Large sites like Riff Trax and corporations like AOL are using this system to sell and distribute files. Props go to early community member CpILL for getting the ball rolling and torgosPizza for his extensive testing and use of the system. Its creation was and its improvement continues to be a community effort.

https://www.google.co.in/search?q=ubercart+file+downloads+&oq=ubercart+file+downloads

Selling Files

Setting Up Ubercart File Downloads
> -2 votes

---
Tags: 7, ubercart, files
---


# Question
Title: Error while uploading file in drupal "An HTTP Error occured 0"
**TLDR:** I already figured out when exactly my problem happens so for people too lazy to read full thread please read here. Whenever I have some html content in any textfield in Open Atrium (I'm not sure if that happens just in OA or in Drupal) and I want to upload a file an error "`An HTTP Error occured 0`" pops up. When I'm disabling javascript I get `Error: 403 Forbidden`. The HTML must be there before I want to upload something, so it happens when I'm editing some field, not just creating it (so it must be in the database already). And one more thing - it happens also on newly installed instance of Open Atrium downloaded from Drupal's site. (version 1.7)

I'm using open-atrium in drupal. Recently an error started to pop up - "An HTTP Error occured 0" while I try to upload files while editing a node (not while I'm commenting - there it works).

**EDIT:** I figured when it happens and why, but I cannot figure how to repair it! This issue happens when I have HTML inside content editor. When I select plain text or Markdown the issue doesn't show up and I can upload files! What do you suggest I can try now?

I checked, the file is actually uploaded to server (so it's not permission to directory problem) and I have jQuery Update installed (as some other topics state).

I disabled JavaScript (so it wouldn't be sent with ajax) and the problem still persisted - this time with 403 Permission Error. My page is like this: http://example.com/example/node/225/edit and the permission error is showing something like this:

`POST http://example.com/example/upload/js 403 (Forbidden)`

Does anyone have any idea what might be wrong? How can I debug it to check what's happening before/after upload? Remember that I actually upload the file to the server, but it just won't attach to the topic while editing (it works on comments).

I'm attaching full HTTP headers sent with the request when JS was disabled:

```
http://example.com/example/node/225/edit

POST /example/node/225/edit HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://example.com/example/node/225/edit
Cookie: __utma=118809371.977078118.1375778041.1376992641.1378820396.3; __utmz=118809371.1375778041.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); SESSc3f285b6f1567ee5f358af2cabd3c968=5ae3330852770b675d5a76c42a9bbcf1; Drupal_l10n_client=0; DrupalAdminToolbar=expanded%3D0; has_js=1
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------198552096025328
Content-Length: 277355
-----------------------------198552096025328
Content-Disposition: form-data; name="title"

testtest
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[pid]"

128
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[assign_to]"

Test Test
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[case_status_id]"

4
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[case_priority_id]"

2
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[case_type_id]"

11
-----------------------------198552096025328
Content-Disposition: form-data; name="field_due_date[0][value][date]"

11/23/2013
-----------------------------198552096025328
Content-Disposition: form-data; name="teaser_include"

1
-----------------------------198552096025328
Content-Disposition: form-data; name="body"

<p>fadsfdsf <strong>gfgdf</strong> fgd s</p>
-----------------------------198552096025328
Content-Disposition: form-data; name="format"

4
-----------------------------198552096025328
Content-Disposition: form-data; name="notifications_team[selected]"

1,11
-----------------------------198552096025328
Content-Disposition: form-data; name="files[upload]"; filename="tinymce_4.0.6.zip"
Content-Type: application/octet-stream

PK
HTTP/1.1 403 Forbidden
Content-Encoding: gzip
Vary: Accept-Encoding
X-Powered-By: PHP/5.2.9
Content-Type: text/html
Transfer-Encoding: chunked
Date: Tue, 19 Nov 2013 11:57:47 GMT
Server: LiteSpeed
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100
----------------------------------------------------------

```

# Answer
> 1 votes
This is one of those extremely frustrating errors that can be caused by a lot of things.

Here is a 300+ post long issue in the Drupal 6 Filefield issue queue: HTTP error 0 #297035

Basically, HTTP Error 0 means that an error occurred during some JavaScript or AJAX/AHAH behavior... and that's as helpful is it gets. The linked issue suggests hundreds of potential causes, but I don't think the short summary's list of solutions necessarily applies to your specific case. I'm also not 100% certain that the upload/js 403 issue is related.

You indicated that it only happens when a content field is set to allow HTML. That makes me hopeful that if you enable error logging something is going to show up somewhere. Even if you don't see anything in your Drupal logs it might be worth digging around for where your PHP is configured to put logs.

You might also want to skim the whole thread and see if one of the many many many solutions there will have a surprise solution.

---
Tags: files, distributions
---


# Question
Title: Youtube video does not play after clearing the cache
I have added a Youtube video inside the CKEditor to load the video in Colorbox, in a content type from CKEditor plugin (plugin is extact data from view). It works fine after creating content.

After clearing cache the URL does not work. It show only http:// in Colorbox. Please give me some suggestions.

The sample URL is /?q=vef/load/fe380247ab1fef057fca83a1df37326c&width=640px&height=363, inside CKEditor.

# Answer
> 1 votes
You just need to enter url in the embed\_video\_field. Following is the sample url http://www.youtube.com/watch?v=BRWKsjaEtKs

You can set other parameters like height, width using embed video field configuration.

---
Tags: wysiwyg, files
---


# Question
Title: How to duplicate image file in the same folder
i want to duplicate a image file in the same folder programmatically , so i'm used file\_copy() function for this but the original file image replaced or renamed and in file\_managed table on database no row created.

```
if ($form_state['values']['image'] != 0) {
            $fileo = file_load($form_state['values']['image']);
            $fileo -> status = FILE_STATUS_PERMANENT;
            $file = file_copy($fileo,'public://img_files/',FILE_EXISTS_RENAME );
            file_usage_add($file, 'image', 'file_img', 1);
        }

```

Thank you :).

# Answer
To add entry for a file to a `file_managed` table, you could use code like:

```
global $user;
$file = new stdClass;
$file->uid = $user->uid;
$file->filename = 'image.png';
$file->uri = 'public://path/to/file/image.png';
$file->status = 1;
$file->filemime = 'image/png';
file_save($file);
file_usage_add($file, 'mymodule', 'mykindofusage', $node->nid);

```

Code shamelessly stolen from this answer by Clive.

**Now, if you are using a `file_copy` function**, it should work all right and create these entries for you. But you should **always check what's in return value** (`$file` in your case). If it's `FALSE`, you should not call `file_usage_add`, but output a message to check watchdog entries for failure reason.

If you will tell us what's in your watchdog, probably in another question, we'll be able to answer with more details about the reason of failuer.
> 1 votes

---
Tags: files
---


# Question
Title: Best way to migrate content and various other changes from development to production
I'm about to make a bunch of updates and changes to content types, views, themes and actually adding content on my development server. I was wondering if there was an easier way to migrate things from development to production beyond doing the following:

* putting the production server in maintenance mode.
* copying over everything (development -\> production) from site root (excluding sites/default/settings.php)
* exporting the development database and importing it on the production server
* crossing fingers and hoping that nothing crashes for unforeseen reasons.

I've seen that there's already some posts on workflows that involve using the features module, but does it actually export content or settings changes to things like blocks and views? I was wondering if there was a module or a tutorial that I wasn't able to find on google that gave some good advice on this.

# Answer
The most user friendly way to do the content migration you are talking about is by using the Backup and Migrate module.

You'll want to upload and enable the module on both development and production instances. The project page links to this tutorial series for a more detailed explanation. I also saw a helper module that backs up your files directory too.

Features does in fact allow you to quickly import a "feature" to a website that you may have developed on your development environment and want to move to production.

Ideally though, you'd want to use features to develop locally and then push to dev/staging server. The final push you'd want to just replicate the database from dev/staging to lessen the chance of configuration errors.

You could also use Drush if you want to do more advanced operations. You can write your own Drush commands and with aliases you can have this down to one command in a terminal if you'de want to. You can rsync files, sqlsync the databases, and use features commands to sync configuration options. Drupalize.me has a nice series on some of this stuff.

I highly recommend Drush, if you are getting more into Drupal, and also recommend checking out Drupal 8's CMI initiative for what lies ahead: https://groups.drupal.org/build-systems-change-management/cmi

P.S. I would have posted more links but don't have the reputation yet to do so. So, just Google the missing pieces.
> 1 votes

# Answer
The main problem with deploying changes from a development site to a production site is the to me very annoying fact, that in Drupal version before D8, the database tables contain both configuration and content.

If you are the only one in charge of content, the deployment of updates and new features from development to production is straight forward:

1. Make sure the development site has the same content as the production site.
2. use backup & migrate to dump your current database content (development)
3. make sure all modules that you used are present in the module directory of the production site
4. import the development backup to the production site.

Of course, you should put the site into maintenance mode before applying the backup.

It becomes problematic, when the content of the production site diverges from the content of the development site. If you use the procedure above, you'll loose all content changes on the production site. This is where the features module becomes important (http://drupual.org/project/features), and lately the configurations module, which is a quasi subset of the features module just for configurations - still in alpha (http://drupal.org/project/configuration). With these, you can export the configuration updates from the development site, and then apply them to the production site.

Fortunately, Drupal 8 separates the configuration and content in the database (configuration only included in cache tables), so this problem will go away once Drupal 8 is ready for production.

For more details, see: Efficient and easy Drupal 7 Development to Production workflow
> 1 votes

# Answer
You can use configuration module to migrate changes from development server to live server.

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

---
Tags: 7, workflows, nodes, importing-exporting
---


# Question
Title: How to display JSON returned (from external REST API) in a Block? [my code attempt inside]
I am trying to display the data from a REST API (URL: 'http://api.kivaws.org/v1/loans/38239/lenders.json') to display in a block. Below is my code. It is not working, any hint on why will be sincerely appreciated.

```
/**
 * Implements hook_block_info().
 */
function restapiexample_block_info() {
  // This example comes from node.module.
  $blocks['kiva'] = array(
  'info' => t('Kiva Test Block'),
  'cache' => DRUPAL_NO_CACHE
);

return $blocks;
}

/**
 * Implements hook_block_view().
 */
function restapiexample_block_view($delta = '') {
// This example is adapted from node.module.
$block = array();

switch ($delta) {
  case 'kiva':
    $block['subject'] = t('Kiva Example');
    $block['content'] = array(
    '#theme'  =>  'page',
    '#markup' =>  kiva_list_loans(),
  break;
}
return $block;

```

}

```
function kiva_list_loans() {
  $request = drupal_http_request('http://api.kivaws.org/v1/loans/38239/lenders.json');
  return drupal_json_decode($request->data);
}

```

You can try the URL, good JSON data is being returned. Error I receive is several instances of the following text in the $messages area: "Warning: Cannot use a scalar value as an array in drupal\_render() (line 5859 of /home/drupalpro/websites/example7.dev/includes/common.inc)"

**UPDATE 1**: With help from comments/answer below, I made some progress. from my function "kiva\_list\_loans()", I am able to see the response in my $page array. I changed the '#theme' in my "$block\['content'\]" in hook\_block\_view to 'page' - but still I only see the word "Array". How to get this to render?

# Answer
`$block['content']` should be an array, like in the example for `hook_block_view`:

```
$block['content'] = array(
    '#theme' => 'feed_icon',
    '#url' => 'rss.xml',
    '#title' => t('Syndicate'),
  );

```

For more examples, see Examples for Developers project, block\_example module.

If you are putting array there, it *must* be a renderable array. If it's not, then either:

1. Implode it into string. With nested arrays, it can get a bit complicated.
2. Put it as an element in `$block['content']` array, and set `$block['content']['#theme']` element to something that can theme it. More complicated, but also more versatile and cleaner solution.
> 1 votes

---
Tags: blocks, 8
---


# Question
Title: image disappears which uploaded with managed_file type
I have implemented a configuration page which is at admin panel. It is something like this:

```
  $form["footer"]['xyz_cust_image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image title'),
    '#default_value' => variable_get('xyz_cust_image'),
    "#description" => t("Image description"),
    '#required' => TRUE,
    '#upload_location' => 'public://',
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg')
    )
  );

```

but have a different situation. the thing is I successfully upload image and it is appearing when i upload it at the browser for that day. When the day passed, the image disappears. When I looked to variable table, the record exists; but the image not appears.

# Answer
> 6 votes
Drupal prunes files that haven't been explicitly marked as permanent. This happens on a cron job, which explains the delay you're seeing.

To avoid this, you need to add a submit handler to your form which updates the status of the file. e.g.

```
MYMODULE_some_form_submit($form, &$form_state) {
  $file = file_load($form_state['values']['xyz_cust_image']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}

```

---
Tags: 7, hooks
---


# Question
Title: OG groups: How to check if user is a member or not?
What code can I use to check if a user is a member of a group?

# Answer
For the 7.x-2.x branch of Organic Groups you need to use the following code.

```
og_is_member('node', $gid, 'user', $user)

```

'node' is the entity type. The function og\_is\_member requires 4 parameters to return the correct value.
> 6 votes

# Answer
In Drupal 7 for the For the 7.x-1.x branch of Organic Groups, you can use `og_is_member()`.

```
$gid = 12;
if (og_is_member($gid)) {
  drupal_set_message('Current logged in user is member');
}

```

```
$gid = 12;
$account = user_load(3);
if (og_is_member($gid, 'user', $account)) {
  drupal_set_message('User id 3 is member of group 12');
}

```
> 5 votes

---
Tags: users, organic-groups
---


# Question
Title: Content not showing up by default with exposed filters
I have a view with 2 taxonomy term fields. I have these fields presented as expose filters for site users to select from dropdown, which works fine. However, when I first land onto the view page, none of my content is showing up. All I see is a blank view. However, if I click apply, with all the fields unselected (e.g. - Any -), then all my content shows up. How do I make the content show up by default without having to click on Apply?

Upon landing on the page for the first time:

After clicking Search:

# Answer
> 1 votes
In exposed filter section try to deselect all values in **Select terms from vocabulary Event type** field

---
Tags: views
---


# Question
Title: Fixing Notice: Undefined variable: content_share in include() (line 39....node.tpl.php)?
I followed online tutorials and defined a new region in litejazz Drupal 7 theme info file as :

```
regions[content_share] = Content Bottom

```

and exposed the new block using the code below in `node.tpl.php` as :

```
<div class="clearfix clear"></div>
  <?php if (!empty($content['links']['node']['#links']) || !empty($content['links']['comment']['#links']) || !empty($content['links']['blog']['#links'])): ?>
    <div class="links">» <?php print render($content['links']); ?></div>
  <?php endif; ?>
      <?php if ($content_share): ?> //<<<<<<<<<<<- THIS LINE CAUSES WARNING
  <div>
    <?php print render($content_share); ?>
  </div>
<?php endif; ?>
  <?php if ($content['comments'] && ($page)) { ?>
    <?php print render($content['comments']); ?>
  <?php }; ?>

```

Now my logs are getting filled with following warning :

> Notice: Undefined variable: content\_share in include() (line 39 of /srv/bindings/ertr88c9reretrea25f7b405eeee/code/sites/all/themes/litejazz/templates/node.tpl.php).

I had tried clearing cache as suggested in other solutions but none worked.

# Answer
> 2 votes
Regions are only available in page.tpl.php, not node.tpl.php.

In page.tpl.php you can use

```
print render($page['content_share']);

```

# Answer
> 0 votes
Check whether the region is available in the scope before assigning any value to it.

Check with get\_defined\_vars() in the node.tpl.php

```
var_dump(get_defined_vars());

```

Same issue is well explained in this thread

---
Tags: theming
---


# Question
Title: How do I add a date field that can be filtered by a relative value?
If I create a view, I can add a filter that filters on a relative value on some built-in date field, such as *Post date*. For instance, the screenshot below shows a filter I've created that will show articles posted in the last four days.

Unfortunately, there is no date field type in core. To get a date field type, you can install the Date module. This allows you to create nice widgets for inputting dates. However, I've found no way to filter the date fields created by the date module by a relative value (like the filter shown above for *Post date*). There are `Is equal to` and `Is not equal to` operators, but no greater than operator, in the "Configure filter criterion" screen.

I believe that this should be possible, as is also evident from Nigel Waters's upvoted answer to this question: view to show content with future date. However, the exact steps one must take to reproduce the result shown in the upvoted answer eludes me.

# Answer
I've found the solution. (Doh!)

It turns out that there is a module named **Date Views** that comes as part of the **Date** package. If you enable this, the filter criterion screen changes, and you can use relative operators.
> 9 votes

---
Tags: views, entities
---


# Question
Title: Ubercart product quantity count in product view page show as smsung 2/10 sold?
I added a product and say it has count of ten(of that product), If one is bought, then I want to show in the product view page out of 10/1 sold like that.

Is there any contributed modules available, or custom way to do it? I can add the quantity as field in the product content type, but what do I do after that?

# Answer
Code snippets to display total and sold item from stock:

```
$output = '';

$array_sku = uc_product_get_models($node->nid, FALSE);

foreach ($array_sku as $sku) {
    $stock_level = uc_stock_level($sku);

    $stock_counts = db_select('uc_order_products', 'up')
                    ->fields('up', array('nid','qty'))
                    ->condition('up.model', $sku, '=')
                    ->execute()
                    ->fetchAll();

    $quantity_count = 0;

    if(isset($stock_counts))  {
        foreach($stock_counts as $stock_count ) {
            $quantity_count += $stock_count->qty;
        }
    }

    $total = $stock_level +  $quantity_count;

    if($total == 0){
        $total = 1;
    }

    $output .= $total . " / " . $quantity_count . " Sold out";
  }

 print $output;

```

Kindly see that above code will be check stock level for each different `SKU` of the product. If there is attribute of the product and each attribute has different `SKU`, then it will display the `stock` for each `sKU` of the product.

It will work perfect in fresh "Ubercart" installation with "stock" configuration.

You can add this code in `node--product.tpl.php` file in your theme directory.
> 1 votes

# Answer
This is not an answer, but you can find the stock level using the below code, just put in the node.tpl.php, and print the var $stock\_html in a proper place, probably in node-product.tpl.php `<?php print $stock_html ?>` .

```
<?php
if ($node->type == 'product') {
  $arr_sku = uc_stock_skus($node->nid);
  $stock_html .='<table>';
  foreach($arr_sku as $sku){
    $stocklevel = uc_stock_level($sku);
    if ($stocklevel) {
      if ($stocklevel < 1) {
        $stocklevel = '<span class="nostock">'.$stocklevel.'</span>';
      }
      $stock_html .='<tr><td>'.$sku.'</td><td>:  '.$stocklevel.'</td></tr>';
    }
  }
  $stock_html .='</table>';
}
?>

```

or you can try this http://www.ubercart.org/comment/60577
> 1 votes

# Answer
```
         <?php
                $array_sku = uc_product_get_models($node->nid, FALSE);
                foreach ($array_sku as $sku) {
                    $stock_level = uc_stock_level($sku);
                    //$stock_count = db_select('uc_order_products', 'up')->fields('up', array('nid'))->condition('up.model', $sku, '=')->execute()->rowCount();

                    $stock_counts = db_select('uc_order_products', 'up')
                                    ->fields('up', array('nid','qty'))
                                    ->condition('up.model', $sku, '=')
                                    ->execute()
                                    ->fetchAll();
                    $quantity_count = 0;
                    if(isset($stock_counts))
                    {
                        foreach($stock_counts as $stock_count )
                        {
                            $quantity_count += $stock_count->qty;
                        }
                    }
                    $total = $stock_level +  $quantity_count;
                    if($total == 0){
                        $total = 1;
                    }
                    $output .= $total . " / " . $quantity_count . " Sold out";
                }
          ?>

```

This will output exact stock level and sold level of the product.
> 0 votes

---
Tags: 7, ubercart
---


title: Force an empty region to display

text:
# Question
Title: Force an empty region to display
I'm looking for a way to force an empty region to display. I notice Omega does this via a theme-settings checkbox, but I'm unable to track down how it's done.

Regardless of removing the if ($page\['regionname'\]): around print render, the region still does not display unless it's populated with block content. Perhaps injecting content into the $content var somehow?

Example:

In a custom theme, the header variables such as logo, sitename and secondary links are placed in a region template called region--branding.tpl.php.. (the variables have to be passed from preprocess\_page to preprocess\_region so this can work and a template suggestion needs to be made). Once this region is printed in page.tpl.php, it must always be rendered even if there is no block content in that area.

# Answer
Omega does it this way:

in omega.info

```
settings[alpha_region_xxx_force] = ''

```

in \`omega/alpha/includes/theme-settings-structure.inc

```
$form['alpha_settings']['structure'][$section][$zone]['regions'][$region]['alpha_region_' . $region . '_force'] = array(
  '#type' => 'checkbox',
  '#title' => t('Force this region to be rendered'),
  '#description' => t('Enabling this will always render this region, even if it is empty.'),
  '#default_value' => $item['force'],
);

```

Call `alpha_alpha_page_structure_alter()` in `alpha_page_alter()`

```
#omega/alpha/template.php
foreach ($theme->regions as $region => $item) {
    if (($item['force'] || !empty($vars[$region]))) {
      $temporary[$item['section']][$item['zone']][$region] = !empty($vars[$region]) ? $vars[$region] : array();
...

```

this way your code should be:

```
function THEMENAME_page_alter(&$page) {
    $regions = system_region_list($GLOBALS['theme'], REGIONS_ALL);
    foreach ($regions as $region => $name) {
        $page[$region] = !empty($page[$region]) ? $page[$region] : array();
    }
}

```
> 3 votes

# Answer
Here's an alternative way, quite hacky but it works - essentially create a fake block in each empty region in hook\_preprocess\_page()

```
function MYTHEME_preprocess_page(&$vars){
  global $theme;
  $regions = array_keys(system_region_list($theme));
  foreach($regions as $region){
    if (empty($vars['page'][$region])){
      $vars['page'][$region] = array(
        'not_really_a_block' => array(
          '#markup' => '',
        ),
        '#theme_wrappers' => array('region'),
        '#region' => $region,
      );
    }
  }
}

```
> 1 votes

# Answer
The answers given here were not satisfactory, they either overwrote content that might have been added to the block (*krisbulman*), or they were not sufficient to really force the block to display (*Mohammad*). So here is the solution i finally stuck with:

**Problem**

Force the display of one specific region with the name REGIONNAME in the theme THEMENAME

**Solution**

```
function THEMENAME_page_alter(&$page) {
    if ( !isset($page["REGIONNAME"]) || empty($page["REGIONNAME"])) {
        $page["REGIONNAME"] = array(
            '#region' => 'REGIONNAME',
            '#weight' => '-10',
            '#theme_wrappers' => array('region'));
    }
}

```

**Note**

*Mohammads* answer and explanation how it works in Omega was great, but his suggested solution set the $page\["REGIONNAME"\] to an empty array, which was not enough (at least for my 7.24 installation, maybe it worked in older versions)
> 1 votes

# Answer
Here is the solution I went with to force a region to display

```
function THEMENAME_page_alter(&$page) {
  foreach (system_region_list($GLOBALS['theme'], REGIONS_ALL) as $region => $name) {
      if (in_array($region, array('REGIONNAME'))) {
        $page['branding'] = array(
                  '#region' => 'REGIONNAME',
                  '#weight' => '-10',
                  '#theme_wrappers' => array('region'),
        );
      }
    }
  }

```
> 0 votes

---
Tags: 7
---


# Question
Title: how to replace title field with some other field in entity reference field list?
I created a content type 'country' with three fields title,description,code and i referred this content type 'country' in content type 'city' using entity reference module. In the creation page of the content type 'city' it displays a dropdown with the list of 'country's title. every thing working fine.

but i want concatenated value of title and code in the drop down list is it possible ?

# Answer
1. Create a view and add the **Title** and **Code** fields.
2. Add an **Entity Reference** display to your view. In the *View edit page*, under the **Settings** for the **Format: Entity Reference list**, check one of your fields.
3. On your *City* content type, under the *Country* reference fields settings, change the target type on the *Mode* field under *Entity Selection* to **View: Filter by an entity reference view**. After selecting, the fields in that fieldset should update making your newly created view available under the **View used to select the entities** field. Select your view and save the fields settings.

Your dropdown should now have your Title and Code fields.
> 1 votes

---
Tags: entities
---


# Question
Title: Image files aren't recognized when changing a html file to page.tpl.php
I want to create a drupal theme base on a static web template. after googleing I've found out that I should set up a `.info` file and also put my header in the `html.tpl.php` and body in `page.tpl.php` and so on.
I change index.html file into `page.tpl.php`, but the image in the site aren't recognized by drupal(although the index.html worked correctly).
It seem to me that drupal should show the page exactly same as static version because I have't added any code into the page ( in order to change the static version into the dynamic one ).
if so, how can I find the problem. Thanks

HTML:

```
    <script type="text/javascript" src="js/modernizr.js"></script>
    <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="js/rgpars-custom.js"></script>

```

=====\>

.info file:

```
    scripts[] = js/modernizr.js
    scripts[] = js/jquery-1.8.2.min.js
    scripts[] = js/rgpars-custom.js

```

html.tpl.php file :

```
    <head profile="<?php print $grddl_profile; ?>">
      <?php print $head; ?>
      <title><?php print $head_title; ?></title>
      <?php print $styles; ?>
      <?php print $scripts; ?>
    </head>

```

# Answer
If your images (ie. your *img* directory) are in your theme directory, use something like `<img src="<?php print base_path() . path_to_theme(); ?>/img/works/works-full8.jpg" />` to include them.

If they are in your *sites/default/files* directory, use `<img src="/sites/default/files/img/works/works-full8.jpg" />`.

If they are in your site root, use `<img src="/img/works/works-full8.jpg" />`
> 0 votes

---
Tags: theming
---


# Question
Title: Backup & Migrate scheduled backup silently fail
I've tried to use backup & migrate for backups on my omega8 based aegir server.

Although I've defined a schedule, and setup cron interval to 1 hour, it doesn't work - no backups are generated. Scheduled backup silently fail.

Attached is a screenshot of the current schedule:

Notes:

* Module's permissions are default (all marked V for admin).
* Backup profile is the default as well.
* I'm using Drupal 7. Module's version is 7.x-2.7

Any idea?

# Answer
It is because you are using buggy module with known issues. This has nothing to do with BOA nor Aegir. There is a reason why we have removed this notoriously buggy module from BOA recently. You should report any such issues in the `backup_migrate` issue queue on drupal.org - and you may find them reported already, in fact.

This module may still be useful, but only if you follow its issue queue and use release which happens to work. The regressions rate in this module is way too high for us, so we no longer include it by default. Just one example:
https://drupal.org/node/1997354
and a fix:
https://drupal.org/node/1997354#comment-7426824
> 0 votes

---
Tags: 7, cron, backups
---


# Question
Title: Drupal nginx configuration. PHP files being downloaded
**Problem**

I'm trying to configure my nginx server. I've been building from the default rather than jumping straight into Perusio's because I don't understand a lot of it.

I'm trying to deny access or require authentication to access *update.php*, *install.php* and *apc.php*.

I think they're locked down but on navigating to the file it's downloaded instead of being run.

For example after entering my authentication for *apc.php* it downloads to my computer. The same thing happens for *update.php*.

I've taken a lot of the configuration from another excellent post on here: Is there a common nginx conf for Drupal 7 sites?

**My Server Config**

```
server {
      listen 8080;
        server_name website website.com;
        access_log /srv/www/website/logs/access.log;
        error_log /srv/www/website/logs/error.log;
        root /srv/www/website/public;

        location / {
           index index.php index.html index.htm;
           error_page 404 = @drupal;
        }

        ##drupal rewrite rules
        location @drupal {
            rewrite ^(.*)$ /index.php?q=$1 last;
        }

        ##secure private file directory
        location ~* /privatefiles {
             internal;
        }

        ##Add headers to advagg
        location ~* files/advagg_(?:css|js)/ {
            access_log off;
            expires    max;
            add_header ETag "";
            add_header Cache-Control "max-age=290304000, no-transform, public";
            add_header Last-Modified "Wed, 20 Jan 1988 04:20:42 GMT";
            try_files  $uri @drupal;
        }

        ## Replicate the Apache <FilesMatch> directive of Drupal standard
        ## .htaccess. Disable access to any code files. Return a 404 to curtail
        ## information disclosure. Hide also the text files.
        location ~* ^(?:.+\.(?:htaccess|make|txt|log|engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
            return 404;
        }

        location ~ \..*/.*\.php$ {
            return 403;
        }

        ##deny access to update and install for everyone except the server
        location ^~ /update.php {
            allow 127.0.0.1;
            deny all;
        }

        location ^~ /install.php {
            allow 127.0.0.1;
            deny all;
        }

        ##authentication required to access apc.php
        location ^~ /apc.php {
            auth_basic "Restricted access"; #realm
            auth_basic_user_file /srv/www/website/public/.htpasswd-users;
        }

        ##rules for running php
        location ~ \.php$ {
            try_files $uri =404;
            include /etc/nginx/fastcgi_params;
            if ($uri !~ "^/default/files/") {
                fastcgi_pass 127.0.0.1:9000;
            }
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /srv/www/website/public$fastcgi_script_name;
         }

 }

```

# Answer
*I created a really long guide on how to set-up Perusio's nginx config. (EDIT: We turned it into a wiki so anyone can add. Also I forgot to link.) The config itself is excellent and well worth a look. If you couldn't get it working before, hopefully my guide will help.*

Ok so here we go.

When you use either of the following expressions for a location block in nginx:

* =
* ^~

Then it will stop searching for more matches immediately after it hits one of them. It checks = with priority then all the other 3 expressions at the same time in the order of the nginx config file.

So in my case it was finding ^~ on `update.php` and `install.php` and stopping the search immediately. This means it never runs php processing on the files and so they're downloaded instead of opening. Adding the php logic to the location blocks, means nginx then runs the php as well as blocking them for all bar me.

```
      location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        if ($uri !~ "^/default/files/") {
            fastcgi_pass 127.0.0.1:9000;
        }
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/website/public$fastcgi_script_name;
      }

      location = /update.php {
          allow 127.0.0.1;
          deny all;
          fastcgi_param SCRIPT_FILENAME /srv/www/mysite/public$fastcgi_script_name;
          fastcgi_pass 127.0.0.1:9000;
          include /etc/nginx/fastcgi_params;
      }

      location = /install.php {
            allow 127.0.0.1;
            deny all;
            fastcgi_param SCRIPT_FILENAME /srv/www/mysite/public$fastcgi_script_name;
            fastcgi_pass 127.0.0.1:9000;
            include /etc/nginx/fastcgi_params;
      }

```

You might note that I've also changed to = from ^~. This is because = is always picked with priority and prevents me from accidentally breaking this later. Choose = and avoid the difficulties I'm about to mention below.

Another useful point: I don't think nginx can ever match two location blocks. It'll pick the more specific one.

**Stuff that doesn't quite make sense**

Lastly I don't quite understand the priority order of the 3 expressions. If I put \*~ in the update block in the example above, it chooses the php block (which has ~), apparently case sensitive overrules the more specific match? This seems weird and isn't mentioned in the docs. If I use ^~ it works as expected.

If anyone has found a great explanation of location I'd love to see it because I'm not sure the docs make perfect sense.
> 3 votes

---
Tags: 7
---


# Question
Title: How can I convert a node title to a lowercase string with hyphens?
I need to convert the title of a node, for example, from this

> John Doe

to

> john-doe

Is there Drupal function for it? (Easier to use than using preg\_preplace etc.)

# Answer
> 9 votes
If you're just looking for a way to convert the title into a URL friendly machine name, then the following regex will do what you need:

```
$machine_name = preg_replace('@[^a-z0-9-]+@','-', strtolower($title));

```

# Answer
> 0 votes
Check this answer.

If you are on the node template (ie. *node.tpl.php*), you should have `$node->nid` available.

---
Tags: 7
---


# Question
Title: javascript aggregation disables the font-your-face module and views-slideshow on the main page
When I turn on the aggregate js option on my drupal commerce (kickstart 1) site, the font-your-face (dealt with by FYF module) and the slideshow on the main page stop working. The fonts seem to show up fine on the other pages.
Does anyone has any idea why it might be so? I obtain a "syntax error" in the JS console.

# Answer
> 1 votes
It turned out the problem is with the *fields slideshow* module and its use of js/jquery libraries.
I've realised that JS error happens after calling some slideshow libraries, so i googled for aggregate js / field slideshow.
As per https://drupal.org/comment/7874537#comment-7874537 , I used the 2.1.x version of the imagesloaded library and everything worked nice afterwards.

---
Tags: javascript, caching, theming
---


# Question
Title: need to print current row position number in block for most popular article
I created a view mode named "small-sidebar" and here I need to print current row position number in this block...

I'm using this code :

```
    <article class="large-sidebar-article">
      <div class="article-image">
        <?php echo $content['small_image']; ?>
      <div class="label-no">
        <?php echo $label; ?>
      </div>
    <div class="article-title">
      <?php echo $content['title']; ?>
       <span>
        <?php  echo $content['read_more_link']; ?>
       </span>
    </div>
    <?php render($node); ?>
    </article>

```

but it not show the current position

in the div class `lebel-no` I need to print the current position

# Answer
> 0 votes
You can do this in two steps below,

**STEP : 1**

Add the views result counter under the fields option Ex: **Fields** Global: View result counter Content: Title Content: Body

**STEP : 2**

If you want to theme it in your own way add the following tpl.php file in your theme folder,

views-view-field--custom-view-theming--counter.tpl.php

I have added the following html to theme it like a tab

```
<span style="margin-bottom: 20px;padding: 5px;border-radius: 3px;background: #479ED2;color:#fff;">
    View result counter:<?php print $output; ?>
</span>

```

Thats all about bringing a view counter in your block.

---
Tags: theming
---


# Question
Title: Overwrite field theme function from within form alter
I'd like to modify the html of a form field from hook\_form\_alter(). Any hook for this one?

# Answer
Your question itself the answer, inside hook\_form\_alter use the following

```
$form['field_job']['und'][0]['#prefix'] = 'yours html'

```

and `$form['field_job']['und'][0]['#suffix']='yours close tags of html'` this html will wrap field.
> 2 votes

# Answer
you just need implement hook\_form\_alter in your custom field and according drupal form api change what you want :

**notice "&" before $from(call by refrence)**

**get your form id by view source of you page and search form `<from .... id="your-form-name"` ..../\>**

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

if($form_id=="your_form_name"){
// your change come here
}
}

```
> 1 votes

---
Tags: forms
---


title: How to check another user is logged in?

text:
# Question
Title: How to check another user is logged in?
There is a lot of questions how to check the current user is logged in, but I need to check another users (by uid for example). Is there any easy way to do it?

# Answer
There aren't any functions in Drupal that I am aware of. You'll need to query the database.

```
$time_active = db_query("SELECT timestamp FROM {sessions} WHERE uid = :uid ORDER BY timestamp DESC LIMIT 1", array(":uid" => $uid))->fetchField();

```

That will fetch the last time that the user was active if they have a current session open.
> 4 votes

# Answer
Hope this will help you,

You can use **sessions** table. You can fetch a list of all logged in users by querying the sessions table

```

// Check if user $uid is online in the last 10 minutes
$online = db_query("SELECT uid FROM {sessions}
          WHERE uid = :uid
          AND timestamp >= :time", array(':uid' => $uid, ':time' => (REQUEST_TIME - 600))->fetchField();

```

Reference : Check if user is online
> 0 votes

---
Tags: users
---


# Question
Title: If user leave comment, print "You have already written a comment"
how to show this 'You have already written a comment' if user have comment in this node -)

Thanks for any help)

# Answer
> 2 votes
Try this

```
function custom_cv_node_view($node, $view_mode, $langcode) {
 global $user;
  if ($view_mode == 'teaser') { /* Teaser */
      $cid = db_query('SELECT cid FROM {comment} WHERE uid= :uid AND nid = :nid', array(':uid' => $user->uid, ':nid' => $node->nid))->fetch();
      if($cid) {
          $node->title = $node->title.' (Commented)';
      }
  }
}

```

# Answer
> 1 votes
You can also use the Comment limit module.

> Limits how many comments a user may post on a node. Adjustable on a per node type basis.
>
> This module can be handy for instance when comments are used as "Reviews" and "Ratings" for products and a user may only review and rate a product once.

# Answer
> 0 votes
Make a small custom module that implements hook\_form\_alter . If the form ID is the node comment form run a check to see if the current `global $user`has commented on this node before (you might have to write a custom function for this). If the user has commented on the node in question disable the submit and the textarea.

---
Tags: 7
---


# Question
Title: Operations in find content page not working
I am using Drupal 7 and I don't see any options listed down in the operations drop down in the find content page. The options are listed in content's tab, but when I move to files tab, the drop down is not shown.

Do you have the options to operate(delete, unpublish) files as we do to nodes? Any help would be appreciated.

Thank you

# Answer
Did you try selecting some files before (tick checkbox)? Some filters only appears when contents are selected (in the Media tab for example in my website)
> 0 votes

---
Tags: 7
---


# Question
Title: Adding tool tips to menu items and views
I need to add tool tips to some of the primary links in my menus, and also to a link in a view, I tried to use the Tool Tips module, but it doesn't seem to be designed for this kind of use... is there another module I can use, or is there another way I can integrate tips to my dynamic content?

# Answer
Take a look at the qTip module or the Tipsy module as alternatives to get "good looking" tooltips or simply add a description to the menu items for basic browser created tooltips
> 4 votes

# Answer
Beautytips would do the trick, I think:

> The Beautytips module provides ballon-help style tooltips for any page element by integrating the BeautyTips jQuery Tooltip plugin by Jeff Robbins with Drupal. It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.

The module page has a very nice video to achieve what you need
> -1 votes

---
Tags: views, 6, routes, tooltips
---


# Question
Title: Drupal Commerce: how to add "Middle name" field to the "Address" pane?
Currently for "Address" pane (field named "commerce\_customer\_address") available two options:

1) Name (First name, Last name) 2) Name (single line)

In my country middle name is very important. How to add this as separated field from custom module?

To Rayan: By the way, does it make sense to include this option in the Commerce core?

# Answer
I have a similar issue with the dynamic address form, in that I want to replace the "county" textfield with a drop down of all counties without having to add it as a new additional field underneath the dynamic address form widget. Is there any way to amend the dynamic address form widget? The closed I can get in to it is at: admin/commerce/customer-profiles/types/billing/fields/commerce\_customer\_address/widget-type
> 1 votes

# Answer
You can add the field under store -\> customer profiles -\> profile types -\> Billing Information -\> Manage Fields (Or go to admin/commerce/customer-profiles/types/billing/fields)

You can add any additional fields there. You can't add any fields directly to customer\_commerce\_address, but if you add any fields under the Billing Information they will show up during checkout.
> 3 votes

# Answer
You have to create a plugin for the address field, that you can use to extend the form. This is how the different selections like single name form vs first and last name form.

You have one challenge in doing this: the address field has not support for storing middle names. The reason is most likely that middle names are considered to be first names.
> 2 votes

# Answer
You should use the Extra Fields Checkout Pane module.
> -2 votes

---
Tags: commerce, entities
---


title: How to provide back link to page?

text:
# Question
Title: How to provide back link to page?
I have created grid view page. When I go click on one specific grid its display content of that grid. Now I want to put one 'back' link in side the page of content, that back link displays main view page.

# Answer
Though they seem rather simple, "back" links on pages are rather tricky. For the sake of this post, lets assume that you have a shopping site with a search page, and item detail pages.

One complication arises from the fact that users can arrive on the item detail page from multiple paths, including from Google and other pages that aren't in your site. The back link really only makes sense when they have come from the search results page.

Another complication comes from how Drupal handles page caching. You could potentially render a back link on a page, but unless you take some URL parameter into account (to have a different `$cid`), users may see the wrong cached page. However, if you do tack on a `back=` to the URL parameter, you now severely lower the probability that a user will actually get a page from the cache.

I have mostly settled on Javascript based solutions. There are two main options. All are real variants on each other. On the detail page, you jQuery in a link that goes back to the search results.

One way is to jQuery some logic on the search results page that sets a cookie with the exposed filer values, URL, or something similar. Then on the detail page, you use this to go back. However, this does not work cross-window / cross-tab, and there are security implications with building links this way.

The second way (and the way I have been using lately) just jQueries in a link on the item detail page that calls `window.history.back()`. This also isn't ideal, but it tends to be the least bad solution.
> 4 votes

# Answer
I would use the javascript solution (window.history.back()), because it's easy to implement.

You could add a php check to display or not the button to be sure you're coming from your website, and not from a Google search for example.

For this, check the $\_SERVER\['HTTP\_REFERER'\] variable. If it matches your DNS, then you display the link, otherwise not.
> 1 votes

# Answer
In the content for which you have created a grid view page
add a link field which will point to view page.

So eventually this Link field will be displayed when u see the view of particular content .So you can click on this link which will act as Back Link . You can hide the link field in the grid view page by css .
> 0 votes

---
Tags: views
---


# Question
Title: Search index as custom view for taxonomy term with hierarchy. Showing all children results in term parent in taxonomy menu
Ok so title is pretty epic, but it goes like this: Key elements: views, taxonomy\_menu, taxonomy, search api, facets.

I created vocabulary "Products" (Drupal Commerce but I don't think it's important), and there term - "Chemistry" - which should be a root of tree of other more specific terms. I added some products. Next I enabled Taxonomy Menu and created a menu, so far so good, but I wanted to use search api, so I created a view of my search index with path:

> /taxonomy/term/%

That way I wanted to override view of my taxonomy, and be able to have facets in it. And it perfectly displays indexed products of terms that have them, but it fails to display all products of CHILDREN terms. So if I have my term "Chemistry" - after clicking it - I would like to be able to see every product of its children terms. I cannot see how can I do this with current approach, as it seems that I doesn't have contextual filters for that (as my view is displaying search index).

What can I do?

# Answer
> 4 votes
If I'm understanding correctly what you're asking, here are some tips.

Under your defined search index, go to Fields. If you have "Products" taxonomy defined, uncheck the taxonomy term, then go to the bottom and open "Add Related Fields" and add "Products", then save changes. When it reloads, you'll now have more taxonomy options. Check "Products \>\> All parent terms". You should now have additional facets for parent/child terms.

Use in conjunction with Facet API Pretty Paths for even more powerful usage. Take a look at one of my other response about how to use that.

# Answer
> 1 votes
Using the following in a custom module will automatically add the parent terms to the node when it is saved.

```
/*
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  // Get the taxonomy terms.
  if ($terms = field_get_items('node', $node, 'MYVOCABULARY')) {
    $tids = Array();
    foreach ($terms as $term) {
      // Add the term to a list of tids.
      $tids[$term['tid']]['tid'] = $term['tid'];
      // Get the parents of the taxonomy term.
      $parents = taxonomy_get_parents($term['tid']);
      foreach ($parents as $parent) {
        // Add the parents to a list of tids.
        $tids[$parent->tid]['tid'] = $parent->tid;
      }
    }
    // Add the list of tids to the node.
    $node->MYVOCABULARY['und'] = $tids;
  }
}

```

# Answer
> 1 votes
The KyleTaylored direction was right.

But I only have to in `admin/config/search/search_api/index/product_display/workflow` (product\_display is my machine name of Product display index DB) **check checkbox Index hierarchy**. Reindex content `admin/config/search/search_api/index/product_display/status`.

Thats all.

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


# Question
Title: Drupal pages translated, but both translated and untranslated pages showing up on view
I recently started working on adding translation to my Drupal 6 site. I am using the modules 1)Translation Manager 2)i18n 3)Language Switcher Dropdown

It seemed pretty straight forward to me. I read the multilingual drupal guide http://drupal-translation.com/content/setup-multilingual-site

I sent all my content type/strings to one of my translators (using local translators). My translator translated one of our pages for a certain content type, and finished the translation.

The only problem is that the content type she translated has both the english and the translated version showing up on the same page.

Here is the page http://caribbeanenvirolaw.org/ngos The duplicated page is "Jamaica Environment Trust (JET)

I notice when I go to the french JET page the Language dropbox shows "Francais", and when I go to the english JET page the language dropbox shows "English".

I would like the french translated pages to only show up if the language select box shows French, and have the English pages be the only ones that show up if the language selectbox is set to English.

The NGO page that is showing both french/english JET pages is a view, but I couldn't find anything in the views section regarding translation and only showing the current languages pages.

Little help?

\***Update\****

The page in the picture is a drupal "view". The content type "Belize - ....." is in English, and has been translated to spanish/french. Those spanish and french translations show up as separate content type's on the drupal page (the view).

Since the language dropbox is set to "English" you would think that it would hide the spanish/french versions, but it is not.

For each of the "Belize - ...." content types (english, french, spanish), I tried multiple configurations to get drupal to leave out language content that is not for the language currently selected. In the last image you see I'm setting the url to be "belize". I used this same value for each of the translated contents.

Scrolling over the links for each translated "Belize - ...." content shows

```
1)English url =  caribbeanenvirolaw.org/belize
2)Spanish url =  caribbeanenvirolaw.org/es/belize
3)French url =  caribbeanenvirolaw.org/fr/belize

```

When I open, for example the spanish translation of belize page from the view, I see

Notice that the language dropbox now say Espanol, meaning it is recognizing that it is a spanish page, but still it shows the spanish/french translations (as well as english) on the view (first image) no matter what the Languages dropbox has selected.

Keep in mind that I have also tried to not edit the url path's manually (leaving them blank). I get the same results from doing it that way too.

# Answer
> 1 votes
# ANSWER

Heya, found the answer. The view needs to have the correct filter added to it.

Go to Adminstration-\>views Click the plus button next to the Filters section.

You will then see a list of filters pop up. Find "Node Translation: Language. Add it. You will then see a section that asks what you want to do with the filter.

Choose "Is One Of: Current User's Language" That is it. Your views should now NOT contain multiple translations of the same document.

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


# Question
Title: Define ckeditor add media library location
we're currently using ckeditor successfully, but when i go to add media from the library tab it loads up all media, we want to exclude profile images from this, is it possible to define the ckeditor library path, or would we really want to move the profile images to private directory

# Answer
You could use the Views Media Browser module

> This module adds a Views based Media browser to the site that allows filtering files based on fields attached to the various file types.
> -1 votes

---
Tags: wysiwyg, media, theming
---