# Question
Title: How do I configure the Stock module in and know how many products are sold out of stock?
I have installed the Stock module, but I don't know how to configure or include that to my product content type, nor do I know how to use it.

Do you have any idea or suggestion?

# Answer
You can follow the below step:

* Go to Content management -\> Content
* Filter content for content type "Product"
* Edit your product content
* Click on "stock" link in top of page
* Set the "Stock" and "Threshold" quantity and check "active" check-box save the form.

**Edit:**

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_count = db_select('uc_order_products', 'up')->fields('up', array('nid'))->condition('up.model', $sku, '=')->execute()->rowCount();

  $total = $stock_level +  $stock_count;

  $output .= "<div>SKU:" . $sku . " Total :" . $total . ", Sold out:" . $stock_count . "</div>";

}

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.

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

---
Tags: 7, ubercart
---


title: bullet points in view

text:
# Question
Title: bullet points in view
I created a block-view which shows me the titles of the newest content. By default drupal simply lists the titles. I would like that the list appears with bullet points. Is this only possible to do in CSS? Is there no way to format it in the view module?

Thanks for any feedback

# Answer
In the settings of your view, change the format from "Unformatted list" to "HTML list".
> 6 votes

---
Tags: views, blocks
---


title: Custom Template Help

text:
# Question
Title: Custom Template Help
I am making a custom module on Drupal 7 and I am into to use templates for showing the info. How can I pass values from the module to the template?

# Answer
> 1 votes
Well, You need to use theme() function, which will allow to define the template name to be called, and the variables (values) to be send over to the template file defined. Please refer documentation here - https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7

```
$read_more = theme('more_link', array('url' => 'aggregator/sources/' . $feed->fid, 'title' => t("View this feed's recent news.")));

```

In the above code "more\_link" is template name and associative array of values to be passed. In Template, you will get value of $title as "View this feed's recent news." Hope you got the point.

---
Tags: theming, 7
---


# Question
Title: Filter out script tags in a view but leave link (from user input)
Users of my site will enter their twitter widget code into a field for their profile:

```
<a class="twitter-timeline" href="https://twitter.com/ussername" data-widget-id="400306334257818144">Tweets by @username</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

```

In a view I need to display the link exactly how it was entered, but not display anything in the script tags.

Ive tried making the node field both plain text and filtered html (which allows links). Ive also tried the default view and with 'Strip HTML tags' selected but `<a>` allowed. In every instance the link prints out as I want it to. The script tags however are removed but the content is printed as plain text (see below).

```
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

```

How can I stop this from showing?

# Answer
I believe, you can use https://drupal.org/project/views\_php to add a custom PHP code, where you can manipulate on the data that user has added.

If you are saving this field somewhere and is available as a field in views too, add the field, and select "exclude from display" option. Now, add a custom php code field and take the input from the field above, extract URL from it and return the same.
> 0 votes

---
Tags: views, input-formats
---


# Question
Title: How to do Question and answers with email notification in drupal 7
To make question and answers for users, I found Answers or Question/Answer modules can be used. But these are only for flow of making questions and answers. If any user (Role: customer) asks question in that site, then that question should sent to the other users (Role: Support). Any suggestions?

# Answer
Well, this can be achieved using Rules module.

Also refer to this question - https://stackoverflow.com/questions/4463011/drupal-rules-sending-an-email-address-to-a-user-reference
> 1 votes

---
Tags: 7
---


# Question
Title: Add class-element to a link though a module (or can I implement theme_link in a module instead of in a theme)?
I'm the developer and maintainer of a module on the Drupal website. It implements an API so that a certain third party service can be easily integrated in Drupal.

I'm currently having the following problem: I need to add a class-element to the logout link. So my module has to arrange that all the these links `<a href="/user/logout">Log out</a>` becomes the following: `<a href="/user/logout" class="mymodule">Log out</a>`

For the logout link in a menu it's easy, I have to implement `hook_menu_link_alter()`.

However, I also want to catch all occurences where somebody is using `l("Log out", "/user/logout")`. The latter function calls `theme_link`, so if I would implement that, I think it could solve my problem.

So my questions are:

1. Can I implement theme\_link in a module? If so, can somebody tell me how to do this?
2. Is there another way in which the above could be accomplished by means of a module?

# Answer
> 0 votes
OSSGuys pointed me in the good direction. I needed to implement hook\_preprocess\_hook, in my case I needed hook\_preprocess\_link:

The code that finally solved my problem is:

```
function mymodule_preprocess_link(&$variables) {
  if ($variables['path'] == 'user/logout') {
    $variables['options']['attributes']['class'][] = 'mymodule';
  }
}

```

# Answer
> 1 votes
What I understand is that you want to have a class in every link that comes on the site. I believe, you can achieve this by skinr module - https://drupal.org/project/skinr, which not only adds up classes but also provides you UI to achieve the same.

Also, in module, you can try this.

```
/**
 * Implements hook_preprocess_HOOK
 */
function MODULENAME_preprocess_menu_link (&$variables) {
  if ($variables['element']['#original_link']['menu_name'] == 'main-menu') {
    $variables['element']['#title'] = '<i class="icon-' . _sanitize_words($variables['element']['#title']) . '"></i>' . $variables['element']['#title'];
  }
}

```

The above could should work, Worked for me atleast :)

---
Tags: 7, theming
---


# Question
Title: Not able to show node comments on a view -content pane
I' a bit stuck with this. I am using panels in Drupal 7. I have created a new content type. I am crating a page (page manager) and I am using a view content pane inside a panel in the page. In that view I am filtering nodes of that particular content type I created. I am not using fields but the full content of the node and I can't figure it out why it doesn't show comments. If I change to page view, for example, I can see the comments, but not using content pane.

What am I missing? Might it be something about the template?

Thanks in advance for your help.

# Answer
> 1 votes
I have been playing around with comments in views for a while. It seems there is a kind of bug as checking "Display comments" on the Full content settings doesn't seem to work. You can solve this, using display suite as the format used by views, which comes with the option "Comments -load comments for every node to display" which does work as expected.

I hope it can help to someone else in the future. :-)

---
Tags: 7, views, panels
---


title: Duplicate content in views

text:
# Question
Title: Duplicate content in views
I implemented the media browser module for image uploading and changed one of the image fields to utilise the media browser for a particular content type. After which, the views which displays a list of that particular content type is showing duplicate content.

After googling I found some one who had a similar problem to mine, however, I don't understand how he solved his problem. https://drupal.org/node/1764042

I would greatly appreciate any help given. Thanks a lot.

Update: Figured out the problem. I was using a file:usage relationship to generate the path url for rewriting the output. Hence having multiple files linked to that node would generate multiple views.

# Answer
> 0 votes
Figured out the problem. I was using a file:usage relationship to generate the path url for rewriting the output. Hence having multiple files linked to that node would generate multiple views.

# Answer
> 1 votes
This may happen if you are have applied filters on any date field. I had similar problem, try this, in Views Advanced Settings under OTHER options, select "Query Setting" and check "Distinct" option.

---
Tags: views, media
---


title: custom module in user

text:
# Question
Title: custom module in user
I am making a custom module and the link to the path appears on navigation menu by default but I am interested it appears on primary menu when module is enabled. Is it possible in Drupal 7?

# Answer
> 1 votes
Set the `menu_name` key of your menu-router item. From the docs:

> **menu\_name:** Optional. Set this to a custom menu if you don't want your item to be placed in Navigation.

By default the primary links are set to the *Main menu* (machine name: `main-menu`). Therefore use something like this in your implementation of `hook_menu`:

```
function hook_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}

```

---
Tags: 7, debugging
---


title: Reasonable use of Custom Content Types?

text:
# Question
Title: Reasonable use of Custom Content Types?
Should I be paranoid about creating new content types or should I create them for each new content type I come across.

My particular scenario is having several distinct blogs on my site.

* Kitchen Blog
* Gardening Blog
* Wine Blog

I could have each of these as a standard blog type and just ask the person to remember to set the correct tags. I know I can set up a view to only show each blog with the correct content type but it all seems a bit messy.

Alternatively I could set up a content type for each based on the blog, then I can set a custom template to look differnt for each blog.

We currently have about 10 content types on the site, could I go to 30 without worrying too much about performance or anything else?

# Answer
I would not expect any performance problems on a site with 30 different content types. Nevertheless I wouldn't recommend implementing a scheme like you are intending. Should you come into the situation where you have to add a new field or change field/display settings, it will require you to go over all blog-types.

In order to simplify the creation of new content for your authors, I recommend to create shortcut links where the term-id of the blog is passed by an url parameter. You may use the Prepopulate or the Entityreference Prepopulate module, or simply alter the `node_form` in a custom module.
> 2 votes

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


# Question
Title: Finding commerce custom fields inside a rules loop
I have a few custom fields added to line items (so buyers can add specific information for each item they add to their cart.)

I need access to those custom fields using rules. However, I can't seem to get at them inside of a loop.

In order to get access them in the first place, I used "Entity has field", and they show up just fine to use in actions, until I get inside a loop. line-items:... doesn't include those custom fields.

What am I missing?

# Answer
> 0 votes
The trick for this is to use a component.

Create a new component, and check for the fields using "entity has field". Then, in the original rule, loop over the line items, and put the component inside that loop.

The kicker is that it is impossible (possibly? not I couldn't find a way) to get other product-level fields into this component.

---
Tags: commerce, rules
---


# Question
Title: Accessing location field programmatically in Drupal 7, via hosting entity object and wrapper
I'm using Location module (particularly its Location CCK part) with Drupal 7. Added location field 'field\_location' to User (as an example of hosting entity), and initialized location values for test users in user edit interface. However, I'm unable to access location data of the current user:

```
global $user;
$user_id = $user->uid;

$loc = $user->field_location;

```

or:

```
$wrapper = entity_metadata_wrapper('user', $user_id);
$loc = $wrapper->field_location;

```

The statements with $loc don't work for object and wrapper (while both user object and wrapper are initialized successfully). Same for:

```
$loc = $wrapper->field_location[0];
$loc = $wrapper->field_location->raw();

```

I've read a number of posts on this topic, however haven't found a workable solution, would appreciate insights on this.

# Answer
For a custom field to be available to the wrapper, the module defining it needs to implement `hook_entity_property_info()` (or, which is new to me, by adding property metadata to the field using `hook_field_info_alter()`).

The location\_cck module doesn't do that, but the bundled location\_entity module does.

If you enable that module you should be able to access the location field as you'd expect.
> 1 votes

# Answer
What about loading the user?

```
$my_user = user_load($user->uid);

```

Then you should be able to access all fields of the user...
> 0 votes

---
Tags: entities, location
---


# Question
Title: Hiding an image field based on theme in Drupal 7
I want to hide an image field(field\_image) of a node when a different theme is selected.

How can I do it?

I'm not able to find any sample code in internet but I know it can be done both in tpl.php and template.php files.

# Answer
> 2 votes
It can be done in node.tpl.php

```
hide($content['field_image']);

```

or in hook\_preprocess\_node

```
hide($variables['content']['field_image']);

```

It works with views as well if you are using content row plugin. For fields you have to override views-view-fields.tpl.php and remove image field from $fields variable.

```
unset($fields['field_image']);

```

Also take look at this modules:

https://drupal.org/project/cs\_adaptive\_image

https://drupal.org/project/adaptive\_image

# Answer
> 0 votes
You should be able to get the current theme with this code (inside your template for example):

```
<?php global $theme; ?>

```

Then you can do

```
<?php if($theme=="my_awesome_theme") { render($item); } ?>

```

---
Tags: 7, theming
---


# Question
Title: EntityFieldQueryException when saving node
I have created a node type which I want to use to store events in. I can create new nodes of this type with no problems, but when I want to edit and save a existing node, I get this error:

In english, this means "Unknown field:". However, a field with this name isn't even defined in my node type:

Full size image here: http://d.pr/i/8V36

Do you have any idea what could cause this error?

# Answer
I would check and see if the field (field\_event) exists. Go to Fields list under reports (admin/reports/fields). You can also check the "field\_config" table directly and see if the field exists.
> 1 votes

# Answer
Did you ever have a field\_event on your site, do you know? It's likely that this error is caused by a previous field, that was improperly deleted.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: How to make a "term reference" > "taxonomy vocab" display alphabetically in a content type?
Hello I have a content type that has a field type \> term reference using the "Check Boxes/radios buttons" widget.

When adding content using that content type the checkboxes (which are of course being populated by a taxonomy) arn't being displayed in alphabetical order which will be difficult for my client to use. I've tried setting the taxomony to alphabetical but that doesn't seem to have any effect on its display within the content type.

Help appreciated :)

# Answer
> 3 votes
Change the order (weight) of the terms within the vocabulary to be alphabetical.

I've just tried this and it works in D7.23 using a 'Term Reference' field. To test this I ordered terms into non-alphabetical, saved the vocabulary, then created a node. Terms were in the order I'd specified. I then 'reset to alphabetical', saved the vocabulary and created a node. Terms were now in alphabetical order.

I found your question title confusing as it talks about terms reference but then the question itself mentions node reference. Please edit the question and clarify.

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


title: How to change field value of a node

text:
# Question
Title: How to change field value of a node
I have a field in a node where users entered data in an inconsistent format. I need to parse that data (it's HTML) and re-format it so it looks correct. Where is the best place to do this?

# Answer
1) Use EntityFieldQuery to load a list of entity ID's.

2) Load the full entity using entity\_load.

3) Optionally wrap the entity using entity\_metadata\_wrapper.

4) For each entity, manipulate the field to your desire then save the entity. If you have it in a wrapper use $entity\_wrapper\_object-\>save() or if using the entity it's entity\_save.

If you want to do this quickly and easily, install the devel module and use the PHP execute page @ example.com/devel/php. Go through each step and ensure you have the correct data to work with at each stage.

Optionally you could use something like VBO to create a view and manipulate the data using a PHP field. This might be easier depending on your experience level.

How to use EFQ
> 1 votes

---
Tags: 7, entities, hooks, theming
---


title: Insert grid of images into about page

text:
# Question
Title: Insert grid of images into about page
Im new to the forum Hope you are all well?

I have a really simple thing I want to do with drupal but for the life of me I cant seem to get it right (I'm a beginner with drupal)

So I have an about page, and I add the body to the page. But what I want is to add images of members of the company the site is for above the body of text in the about page, like in a grid. So it would be the grid (say 3x3 image grid) then the body text at the bottom of the grid. How do I do this? I cant seem to find an answer anywhere and I'm pulling my hair out here.

Can anyone help me?

# Answer
> 0 votes
There are different pieces to this problem.

1. The grid with images.
You can do that with Views. I'd say create a Views display of type "Block". E.g. if every member of the company is a node or a user with an image field, then you can use the view to show an image for each of them. There is a display plugin to show items in a grid.
2. Display this stuff on one page.
One way to do that is with panels.
Another way is to create a node type with a Block reference field in addition to the body text field. You create the about page as a node of that type, and fill in the body text and reference the Views block you just created.
Yet another way is to simply put the block into a theme region, and configure it to only show up on the "about" path.

Another way for all of this is to create a node type with a multiple-value image field. This is if you don't want every single member of the company to be a node or user entity by itself.

Then you can use a custom formatter, or just some CSS, or Display suite hook\_ds\_field\_theme\_functions\_info(), to display the images in a grid.

# Answer
> 0 votes
I believe, the best and easiest way to achieve this is using a WYSIWYG editory like CKEDITOR, which is available for Drupal - https://drupal.org/project/ckeditor and yes, its free too. For image, you can use IMCE as well With this you can have much control as to how your page looks like and can change the layout of the page too.

---
Tags: media
---


title: User profile field used to filter view?

text:
# Question
Title: User profile field used to filter view?
OKay - I'm either brain fading or truly confused (probably both).

I need to filter a view based on the value of a field, but in a unique way. The content type (task) has a field (location) which is also used on the user profile. I need the view to only show those tasks which have the same value as the logged in user in that field. What the \*&% am I missing?

# Answer
> 0 votes
may be this will help you views\_conditional

How to use Views Conditional in your Views:

* Create a view. Add some fields under "FIELDS".
* Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
* Add and configure fields
* Choose a field to run a condition against, and provide values accordingly.
* Save, views conditional handles the logic and returns as specified. use replacement variables

---
Tags: views
---


# Question
Title: Make views slideshow responsive - remove inline styles
How does one remove the inline hard coded styles of height and width from views slideshow? I'm trying to make views slideshow responsive.

I'm trying to make my slideshow responsive (no i'm not interested in flexslider or another slideshow module at the moment).

# Answer
The flexslider module mentioned above seems great with it's mobile swipe support, but only images are supported and I needed videos slideshow, with overlays support. So I've added the following lines in my theme's CSS file and it worked:

```
.views_slideshow_cycle_main { width: 100%; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .field-content { max-width: 100%; width: 100%; }
.views_slideshow_cycle_main .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding: 0; }

```

With SCSS, it may be easily written as:

```
.views_slideshow_cycle_main {
  width: 100%;
 .views-slideshow-cycle-main-frame {width: 100% !important; height: auto;}
 .views-slideshow-cycle-main-frame-row {width: 100% !important; height: auto;}
 .field-content { max-width: 100%; width: 100%;}
 .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding:0;}
}

```

The overlays were added by views\_slideshow\_xtra\_overlay.

Adapted from This discussion
> 9 votes

# Answer
Better option is to use the 'Advanced Options' of the views slideshow module itself.

You need to do the following

1. Create directory called json2 in sites/all/libraries and download https://raw.github.com/douglascrockford/JSON-js/master/json2.js and rename the folder json2.
2. Under FORMAT slideshow settings in the view, scroll "jQuery Cycle Custom Options" and under advance options set,

```
height: auto
width: auto
containerResize: 0
slideResize: 0
fit: 1

```
3. Make the slide window height fit the largest slide: leave unchecked
4. Update the view and voila! The slideshow will be responsive even while dragging the browser window.

Ref: here and here
> 7 votes

# Answer
This thread has a very nice solution: https://drupal.org/node/1510526

The css recommmended gets you a very nice slideshow, and there is some javascript too get a little further along. The only problem I have is that if you slide the browser narrower and wider, the slideshow's height causes problems around it in a vertical direction. You can mitigate this with different max-height css values for your different media query css files.
> 3 votes

# Answer
There is also this sandbox project which gives you a jcycle2 views slideshow plugin...

https://drupal.org/sandbox/BenYoung/1832338

which uses the new and improved jcycle2 library -- fully responsive!! http://jquery.malsup.com/cycle2/
> 1 votes

---
Tags: theming, views
---


# Question
Title: adding data to an existing content type programmatically
I am sure this question has come up before, but right now my google skills are failing me. I am trying to create a migration module since I haven't had any luck with either the migrate module or migrate\_d2d. Right now I am trying to populate a content type with the data from my field remap, but I can't find out how to do it.

would a simple db\_insert work or is there something special I need to do to generate the field data?

# Answer
> 0 votes
Matt,

To create a node programmatically,

1. You firstly need to create a content type for same. This will make sure that Drupal architecture is followed to create a node.
2. Now you need to create a node from UI, and in hook\_node\_presave, make sure you print the node object - `dprint_r($node); die;` and see what is the Object architecture like.
3. Now you need too create the same object before saving it.
4. To, create the object, create `$node = new stdClass();`, define the node type `$node->type = 'YOUR CONTENT TYPE NAME'` and do a `node_object_prepare($node)`, this will make sure that all the basic settings are added to the node object.
5. Post this, make sure you create the object, same as it was in node presave stage.
6. Just before calling node\_save, call node\_submit, which will prepare the node for submission.

Hope this helps !!!

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


# Question
Title: Trying to remove options form an exposed filter
In drupal 7, I'm trying to remove an exposed taxonomy filter. This taxonomy filter has a depth of 2. I'm only trying to expose the parent item.

As a quick fix I'm trying (poorly) to remove them with the following theme function below.

```
<?php
function theme_preprocess_views_exposed_form(&$vars, $hook) {

    //  views-exposed-form-instructor-profile-list-page
    switch($vars['form']['#id']) {

        // instructor profile
        case 'views-exposed-form-instructor-profile-list-page':
            foreach ($vars['form']['term_node_tid_depth']['#options'] as $option) {
                foreach ($option->option as $key=>$v) {
                        if (stristr($v, '-')) {
                            print $v . '<br>';
                            $vars['form']['term_node_tid_depth']['#options']['option'][$key] = 'FILTERED';
                        }
                }
            }

            print_r($vars['form']['term_node_tid_depth']['#options']['option']);
            break;

        // do nothing
        default:

    }
}

```

In the end I'm trying to figure out what exactly to `unset()` any option that begins with '`- child item`'.

# Answer
Instead try the following it will help you by using `hook_form_alter()`

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

  if($form['#id'] == 'views-exposed-form-[your-view-here]') {

    foreach ($form['tid']['#options'] as $term_key => $term) {

      // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == '-') {
          unset($form['tid']['#options'][$term_key]);
        }
      }

    }

  }

}

```

taken from the source
> 3 votes

---
Tags: theming, views
---


# Question
Title: Is it possible to put existing/shared Content type fields as Feature code each in their own individual file to simplify/avoid git merge conflicts?
We have a set of content types that share common fields - in that we re-use them in several content types.

When recreating these content types as a Feature, the fields are all in one large file. This has proven to be difficult when resolving git merge conflicts when people adjust/remove/or add fields to content types as a normal part of development. The git ===== \>\>\>\>\> \<\<\<\<\< conflict markers 'cross over' different fields and make it hard to see how the merge should be done correctly.

I think a better solution is to have each field in its own file, even if there are hundreds, the host file system should be able to handle this, perhaps even use of directories may help, this would avoid complex merge conflict resolutions.

Is this single file per field possible?

# Answer
> 2 votes
We faced similar problems, what we did was, we created a 4 features of similar fields that were used in multiple content types. This made sure that if a person is working on a similar funtionaltiy, he is responsible for all the content types. Yes, we still need to be careful for this, but dividing it into multiple features did solve many issues.

---
Tags: 7, entities, features
---


# Question
Title: How to Sum up 2 fields of integer, and present as "Time period"?
I am building a drupal site. I have 2 fields: "prep time" and "cook time". Both fields are:
FIELD TYPE = Integer
WIDGET = Time Period

I need to sum up the two fields to one field (total time), and present it with widget of Time period, Or at least present it in time format ("2 hours 35 min").

**Question Update (3/12/2013):** In addition, I need to present the date with ISO format in the HTML code (datetime="PT3H45M"). After I am using the Computed Field module, I don't know how to present the computed number as time format ("2 hours 35 min") and add the ISO format in the HTML code. as you will see below, I created a "field--field\_preptime.tpl.php" that works great for the "prep time" and the "cook time", but when I am passing the computed value, the out put is wrong - as I don't see the the time format correctly, and the iso foramt in the html code is also wrong.

can someone help me fix it?

**here is how I created the prep time and cook time**:
I created the following field override template file called: "field--field\_preptime.tpl.php"

```
<?php
function time_to_iso8601_duration($time) {
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );

    $str = "P";
    $istime = false;

    foreach ($units as $unitName => &$unit) {
        $quot  = intval($time / $unit);
        $time -= $quot * $unit;
        $unit  = $quot;
        if ($unit > 0) {
            if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
                $str .= "T";
                $istime = true;
            }
            $str .= strval($unit) . $unitName;
        }
    }

    return $str;
}
 ?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
    <?php $time = strtotime(render($item), 0); ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>></div>
          <time datetime=<?php print time_to_iso8601_duration($time); ?> itemprop="prepTime"><?php print render($item); ?></time>
    <?php endforeach; ?>
  </div>
</div>

```

The Output of "prep time", when I am viewing in the "view source" on the relevant page (I don't know how to do the same for the calculated value of "total time"):

```
<div class="field field-name-field-preptime field-type-number-integer field-label-hidden">
    <div id="md11" class="field-items">
              <div itemprop="prepTime" class="field-item even"></div>
          <time datetime="PT3H45M" itemprop="prepTime">3 hours 45 min</time>
      </div>
</div>

```

Thanks.

---

UPDATE 1/10/2014:
I couldn't do it without using computed fields. when I tried, I got an error: "Notice: Undefined variable: field\_cooktime in include() (line 54 of D:\XXX\field--field\_totaltime.tpl.php). I got the same error for preptime. I guess that is the reason the output is always 0 sec for total time, even though I put the totaltime field after the preptime and the cooktime fields.

**How can I get the value of two fields in my override template, and then Sum up?**

Thanks.

# Answer
Re your update 2013-12-03. I've absolutely no idea why your using the Computed field module for this - that seems like a completely unnecessay complication.

As I've *already* pointed out by me on 2013-11-15, to sum up 2 fields of integer in PHP, you just add them together using the + operator. And to display in a suitable format consisting of hours and minutes, you can use the PHP function `format_interval` to turn the number of seconds into a suitable string.

So you should have something like this near the beginning of `field--field-totaltime.tpl.php` (i.e. after the opening comment).

```
<?php
function time_to_iso8601_duration($time) {

  // Lot of PHP code not shown for brevity

  return $str;
}
?>
<?php
$prep_time = ($element['#object']->field_prep_time['und'][0]['value']);
$cook_time = ($element['#object']->field_cook_time['und'][0]['value']);
$total_time = $prep_time + $cook_time;
$totaltimestring = format_interval($total_time, 2);
?>

```

is all you need. Below this, you put the template to render the **total time**.

The template for **total time** should be very similar to the template you already use for **prep time** and **cook time**. Example:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>></div>
          <time datetime=<?php print time_to_iso8601_duration($total_time); ?> itemprop="totalTime"><?php print $totaltimestring; ?></time>
    <?php endforeach; ?>
  </div>
</div>

```
> 2 votes

# Answer
One way to do this is the Computed Field module, which will allow you to use PHP to perform calculations.

To use this, you could add a field, **Total time**, of type *Computed Field*. Then you could write some PHP code to calculate the value for **Total time** based on the other two fields. This way, every time the node is updated, the correct calculation value will be saved in the **Total Time** field.

If you need to customize the display output, the Computed Field module allows you to optionally add PHP code to output the field for display with custom formatting as well.

**But**

Please note the warning on the module's page:

> This module is intended to be used by PHP developers to insert & execute PHP code on a Drupal website. It does not provide a macro interface, a code builder or anything other than insert your working code here into this text area. You need to have a good working knowledge of PHP and the Drupal API to use this module. To get the best results with this module, pre-test your PHP code in the Body field of a Page in Drupal.
> 2 votes

---
Tags: entities
---


title: node edit tabs in a block

text:
# Question
Title: node edit tabs in a block
Is it possible to move node edit tabs links in some block. I want to hide them from the orignal position and want to create a floating block which may contains all those links which are available in tabs.

# Answer
I think you want to do something like this?...

http://vimeo.com/79462942

I did this with some jQuery and CSS.

jQuery to create and place "button" - in my case, this is a font-awesome icon. This may seem strange, but we're placing the button inside the div.tabs tag, and then placing div.tabs tag inside the h1 tag...

```
// edit node buttons
(function($){
    // wait til everything loads before firing
    $(document).ready(function(){
        //insert edit icon into div.tabs
        $('div.tabs').prepend($("<i class=\"icon-edit\"></i>"));
        //insert div.tabs into page title
        $('h1').prepend($('div.tabs'));
    });
})(jQuery);

```

Now, if this is all we did, it would look crazy! We need CSS to do the magic part...

```
/*first we hide div.tabs, but we also define properties for when we expose it later*/
    div.tabs ul {
    display:none;
    position:absolute;
    padding:10px;
    margin-top:-10px;
    background:rgb(0,0,0);
    border: 0px none;
    width:260px;
    border-radius: 4px 0 4px 4px;
    z-index:100;
    }

/*this exposes the tabs when we hover over the icon!*/
    a:hover.icon-edit,
    div.tabs:hover ul,
    div.tabs:active ul {
    display:block;
    }

/*position button - I want it to the left of the h1*/
    div.tabs {
    float:left;
    width:1em;
    }

```

Your selectors and styles may differ, but the essential thing is to have a trigger/button class (or id) that is inside the div you want to hide/show.
> 2 votes

---
Tags: 7, theming, routes
---


title: Database query with notExists

text:
# Question
Title: Database query with notExists
I can't figure out how to select all aid's from the areas table that do not exist in the field\_data\_field\_area\_parent table.

It almost works, except it returns Windy Ridge with an "aid" of "11". I am guessing that this is because "IN" is the same as "ANY", and the number "1" is in the subquery results.

How can I use `NOT EXISTS` instead of `NOT IN`?

```
function verb_get_parent_areas () {
  $query = db_select('areas', 'a');
  $query->distinct();
  $query->fields('a',array('name','aid','parent','latitude','longitude','description'));
  $subquery = db_select('field_data_field_area_parent', 'p');
  $subquery->fields('p', array('entity_id'));
  $query->condition('a.aid', $subquery, 'NOT IN');

  $result = $query->execute();
  while ($record = $result->fetchAll()) {
    $areas = drupal_json_encode($record);
  }

  return $areas;
  exit;
}

```

I've thought of trying this, but it returns nothing.

```
function verb_get_parent_areas () {
  $query = db_select('areas', 'a');
  $query->distinct();
  $query->fields('a',array('name','aid','parent','latitude','longitude','description'));
  $subquery = db_select('field_data_field_area_parent', 'p');
  $subquery->fields('p', array('entity_id'));
  $query->notExists($subquery);

  $result = $query->execute();
  while ($record = $result->fetchAll()) {
    $areas = drupal_json_encode($record);
  }

  return $areas;
  exit;
}

```

# Answer
> 0 votes
Here is another approach to write Dynamic queries. We generally write queries in phpmyadmin or mysql command prompt and then convert them to D7 style or dynamic queries using Query coder module.

For example, as per your question, you want to find out all those records in child table which don't exist in parent table.

So D6 style query,

```
db_query("SELECT c.* FROM {child} c LEFT JOIN {parent} p ON c.p_id = p.p_id WHERE p.p_id IS NULL");

```

after converting to D7 style query using query coder module would look like,

```
$query = db_select('child', 'c');
$query->fields('c', array('*'));
$query->leftJoin('parent', 'p', 'c.p_id = p.p_id');
$query->isNull('p.p_id');
$result = $query->execute();

```

# Answer
> -2 votes
Have you tried out `drupal_write_record()` function? if no then see below link,

https://stackoverflow.com/questions/5825337/help-with-db-query-in-drupal-if-exists-update-else-insert

This may helpful to you.

Thanks.

---
Tags: 7, database
---


# Question
Title: Get customer shipping information entered in checkout page, from shipping page
Following inline documentation on example shipping module api, I have an implementation of hook\_commerce\_shipping\_services\_info(), in which I set callback function for 'rate', 'details\_form' etc.

I'm trying to calculate the rate based on the zip code entered by the customer, but the callback for 'rate' only takes two arguments, which are $shipping\_services and $order. I dpm both objects, but didn't see any shipping information, entered on the previous page (checkout). The field \[commerce\_customer\_shipping\] has `Array
 (
 [und] => Array
 (
 [0] => Array
 (
 [profile_id] => 2
 )
 )
 )`

How do I get the values for the individual fields, such as address, city, and zip code?

# Answer
> 0 votes
See the replacement patterns and give like as below, for example, \[commerce-order:commerce-customer-shipping:field-name-line\]. Use "-", not "\_".

---
Tags: commerce
---


title: Taxonomy term node count with depth

text:
# Question
Title: Taxonomy term node count with depth
I want to achieve the following term listing:

* clothing (17)
    + dresses (2)
    + skirts (3)
    + tops (12)
* accessories (5)
    + bags (1)
    + jewelery (4)
    + necklaces (2)
    + rings (2)

Is this possible with views? I know you can use the "Taxonomy Term: Content with term" relationship, but this only counts the nodes attached to the parent terms and not those attached to the child terms...

# Answer
> 0 votes
Yes, this is possible with only views. Here is a good thread to get you started. http://drupal.org/node/301485#comment-1065230

# Answer
> 0 votes
Here is the step by step instructions with screen shots to create a view,

http://www.brightwebsitedesign.com/how-to-use-views-aggregator-to-create-taxonomy-term-count-block

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


# Question
Title: Why would my site start creating locked MySQL processes?
I am working on a Drupal 7 development site, and had not installed any additional modules for a couple of weeks.

I was working creating a view to display a list of custom content, and suddenly everything went slow. I soon realised that the site had started creating locked processes and was basically eating all the available memory and MySQL resources, and I was no longer able to view admin/content or run cron. I had to manually kill the processes to get the server working again.

Any idea on where to start trying to work out why this has happened? I am using MyISAM, and I understand that this can cause some performance issues on larger sites - but this was a development site that only I am looking at!

For example, this is from my MySQL process log:

`634 tavata_usr localhost tavata_db Query 1655 statistics SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM dpnode node INNER JOIN dptaxonomy_`

`657 tavata_usr localhost tavata_db Query 1593 Locked SELECT 1 AS expression FROM dphistory history WHERE ( (uid = '1') AND (nid = '267') ) FOR UPDATE`

`868 tavata_usr localhost tavata_db Query 1108 Locked SELECT * FROM 'dphistory'`

`902 tavata_usr localhost tavata_db Query 1056 Locked SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM dpnode node INNER JOIN dptaxonomy_`

`918 tavata_usr localhost tavata_db Query 993 Locked SELECT 1 AS expression FROM dphistory history WHERE ( (uid = '1') AND (nid = '267') ) FOR UPDATE`

`1141 tavata_usr localhost tavata_db Query 198 Locked SELECT timestamp FROM dphistory WHERE uid = '1' AND nid = '267'`

`1142 tavata_usr localhost tavata_db Query 185 Locked SELECT timestamp FROM dphistory WHERE uid = '1' AND nid = '267'`

`1184 tavata_usr localhost tavata_db Query 73 Locked SELECT timestamp FROM dphistory WHERE uid = '1' AND nid = '267'`

ETA: OK, the way I dealt with this was to restart the MySQL server to get rid of all the locked processes and the general eating of my system resources. Then I went straight to https://example.com/admin/modules and turned off everything apart from the core modules.

This fixed my problem, although of course half my site stopped working.

I then turned things back on, until I worked out that there was something about the View I had been working on that was causing everything to fall over and lock up. I am still not sure what, but I'm going to go back and rebuild that view from scratch.

# Answer
> 0 votes
As we all know, MyISAM does table level locking and InnoDB does row level locking so it is recommended to use InnoDB storage engine for MySQL.

Secondly, If you generate a block within Views, you can make use of this block cache from the "block caching" option in View UI. You can also use Views content cache mdoule to improve the performance of views. Please refer to below links for more details,

http://www.millwoodonline.co.uk/blog/drupal-7-performance-gains-with-views-cache http://2bits.com/caching/overcoming-long-views-rendering-time-drupal-sites.html

---
Tags: 7
---


# Question
Title: Images loading from server on every page load
I am using the views flexslider with same images on every page but when ever we go from one page to another or come back to the previously browse page it take a time to load images.

It seems like views always loads the images from the server. Is there a way those images could appear instantly on every page. May be loading the images through browser cache ??

EDIT

**The problem was actually because of Adaptive Image module I have turned that off and the images are loading normally now.**

# Answer
Caching problem was not with the views, it was actually Adaptive Image module which was causing the frustrating image reload issue.

After trying several caching options, I disabled the Adaptive Styles and use normal image styles and the issue was resolved.

For adaptive images I am now using Adaptive Image Styles and it is working fine. Though this require some modifications in .htaccess file but that is acceptable.
> 1 votes

---
Tags: caching, media, theming
---


# Question
Title: Undefined property: stdClass::$collapsible
After creating a vertical tab in my installation profile I keep getting these notices:

`Notice: Undefined property: stdClass::$collapsible in field_group_pre_render_tab()`

and

`Notice: Undefined property: stdClass::$collapsed in field_group_pre_render_tab()`

Here is the code I use to make a vertical tab in my installation profile:

```
$verticalTab = new stdClass();
$verticalTab->disabled = FALSE;
$verticalTab->identifier = 'group_attachments|node|foo|form';
$verticalTab->group_name = 'group_attachments';
$verticalTab->entity_type = 'node';
$verticalTab->bundle = 'foo';
$verticalTab->mode = 'form';
$verticalTab->label = 'Attachments';
$verticalTab->children = array( 1 => 'attachment');
$verticalTab->format_type = 'tab';
$verticalTab->weight = '0';

```

So am I missing something? or has this notice got nothing to do with the vertical tab and do I have to look elsewhere?

Any help to fix this notice would be appreciated.

# Answer
> 0 votes
Normally the `collapsed` and `collapsible` properties are used on fieldsets. It looks like `field_group` is expecting for an undefined property on the vertical tabs object.

You could try adding them to your definition as such:

```
$verticalTab->collapsible = FALSE;
$verticalTab->collapsed = FALSE;

```

That should keep the `field_group` module happy.

---
Tags: 7, installation-profiles, forms
---


title: How to add meta title?

text:
# Question
Title: How to add meta title?
I want to add this line above my title

```
<meta name="viewport" content="initial-scale=1.0, width=device-width,  minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />

```

How can I ?

# Answer
You can put this on html.tpl.php in drupal 7 , else you can have it on page.tpl.php.

As a note if you are putting it on page.tpl.php remember you have to put it on every other page overriding template page--front.tpl.php etc.
> 2 votes

# Answer
You can use the `drupal_add_html_head()` function. Add something like this to a page preprocess function:

```
$tag = array(
  '#type' => 'html_tag',
  '#tag' => 'meta',
  '#attributes' => array(
    'name' =>  'viewport',
    'content' => 'initial-scale=1.0, width=device-width,  minimum-scale=1.0, maximum-scale=1.0, user-scalable=no',
  ),
);
drupal_add_html_head($tag, 'meta_viewport');

```
> 2 votes

---
Tags: meta-tags
---


title: Services 3 and session authentication

text:
# Question
Title: Services 3 and session authentication
I am creating a *titanium mobile app* that consumes and uses Drupal Services. I'm able to create a node but the user is always anonymous. I've tried setting the request headers so that the *Authentication* is basic.

```
authstr = 'Basic ' +Titanium.Utils.base64encode('admin'+':'+'password');
xhr.setRequestHeader('Authorization', authstr);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify(params));

```

For some reasons it still gives me;

> Code=3 "Authentication needed"

What is the best way to troubleshoot this? Is it even possible to use sessions in this manner?

# Answer
Session authentication is different than Basic authentication.

Session authentication requires that you login, by sending a POST request to ENDPOINT/user/login. It will return the session header information and you need to store that for future use and send it along with every request.
> 7 votes

# Answer
Thank you very much for your help. I finally manage to autenticate and retrieve files from my rpc server. Here is my syntax in case anyone needs it.

```
// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

//RETRIEVE FILE
$file= xmlrpc($settings['server'], Array('file.retrieve' => Array(Array("fid"=>$fid),Array("file_contents"=> 'true'),Array("image_styles"=>'true') )),$options);

```

EDIT: AFTER SERVICES 3.5 you should do:

```
// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

// GET TOKEN
$token = xmlrpc(url($this->endpoint, array('absolute' => TRUE)), array('user.token' => array()), $this->headers);

//INSERT TOKEN INTO HEADERS
$options['headers']['X-CSRF-Token'] = $token['token'];

//RETRIEVE FILE
$file= xmlrpc($settings['server'], Array('file.retrieve' => Array(Array("fid"=>$fid),Array("file_contents"=> 'true'),Array("image_styles"=>'true') )),$options);

```
> 9 votes

# Answer
you can use services\_basic\_auth module (https://drupal.org/project/services\_basic\_auth) to enable basic authentication for drupal services module .

After installing services\_basic\_auth module you need to enable it by going to, Structure--\>Services--\>Edit

Now you can use Basic Authorization Header to create nodes.
> 0 votes

---
Tags: 7, services, theming
---


title: Multiple widget for same field?

text:
# Question
Title: Multiple widget for same field?
I have defined some extra fields for User information in `configuration > account settings > manage fields`.

One of these fields is of type `List (text)` and the widget I have chosen for it is `Select List`.

I want to display this field using `Select List` widget in **Profile Edit Form** but as `Check boxes/radio buttons` in **User Register Form**.

How can I do so?

# Answer
By using form\_alter hook you can alter the type of field. I am assuming you are using Drupal 7. The below code will alter the **field\_working\_as** List (text) profile field in user\_register\_form in to checkboxes.

And the same field will show as selectbox in profile edit page. I hope this will help you.

```
function mycustommodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    unset($form['field_working_as']['und']['#options']['_none']);
    $form['field_working_as']['und']['#type']='checkboxes';
  }
}

```
> 5 votes

---
Tags: entities
---


title: Facebook OAuth (FBOAuth) fails to login

text:
# Question
Title: Facebook OAuth (FBOAuth) fails to login
I've installed the Facebook OAuth module which is an essential part of the website I am building. Unfortunately, the connection fails:

> "The Facebook login could not be completed due to an error. Please create an account or contact us directly. Details about this error have already been recorded to the error log."

The module seems to perform just fine in the beginning. Once I click on the FConnect button, I am redirected to facebook website, asked to login and grant access to precisely that information which I asked for when configuring the module.

(Also, when I misconfigure the facebook app, for instance by entering the wrong site domain, I am blocked much further in the process.)

The problem occurs when I am sent back from facebook to my website. Then instead of being connected, I receive the error message I mentioned.

I have had a valuable exchange with the maintainer of the module that can be found on http://drupal.org/node/1994900#comment-7419898. Unfortunately, he could not figure out the problem.

I have spent two days on it, trying many different things, but I could not find a solution. You can find a complete record of my different attempts on http://drupal.org/node/1994900#comment-7419898, but to summarize I have:

* checked solutions proposed in related issues, http://drupal.org/node/1441978, http://drupal.org/node/1466598, http://drupal.org/node/1974488.
* Tried with and without clean url's
* Tried to disable absolutely all the modules except for fb oauth to check whether it was a module compatibility issue (also tried a clear install of drupal with only Facebook Oauth module)
* Checked that http requests were enables on my server.
* Tried the alternative Fbconnect module, but I could not configure it either (I got unsolvable errors message before I could even try a connection).

Now I am short of ideas... Anything to propose?

I must say that **I am a beginner**, so I do not get most technical details. **My sepcs** are:

* Drupal 7.22
* Facebook OAuth 7.x-1.6
* Hosted by Host1Free.

# Answer
For its functionality you need to follow these steps:

1. Make an Application on Facebook.
2. Visit https://developers.facebook.com/apps/ and create a new application.
3. While making the application on Facebook don't forget to disable the Sandbox Mode.
4. Add a Website domain name on which you want to use the fboauth login button.
5. From there copy the App. ID and App Secret to **/admin/config/people/fboauth**

That would work for you.
> 1 votes

---
Tags: 7, authentication-authorization, social-network
---


# Question
Title: Cannot import database. An error occuring in wamp server
I am using Drupal. I export the sql database from the wamp server and make a new database where I am importing it. It's approx 6 MB. I increase the `upload_max_size` and clear the cache before exporting, but this error is occurring. Then what I do

SQL query:

INSERT INTO `cache_menu` (`cid`, `data`, `expire`, `created`, `serialized`) VALUES ('links:management:tree-data:en:.......

# Answer
To make this on-topic on a Drupal Answers, you should have asked: How do I migrate a Drupal configuration from a WAMP server?

I'll pretend you did that, and suggest you take a close look at the Backup and Migrate module.

It knows about Drupal-specific stuff (such as what tables are not worth migrating), and is also very simple to use.
> 1 votes

---
Tags: database
---


# Question
Title: How do I add a non-exposed field to node programatically?
I need to add a non-exposed field to a node programatically. By non-exposed, I mean a field which users will not be able to interact with. I need to be able to store data in this field through hook\_folder\_form().

There's always the accepted answer to Add field in hook\_node\_info();, but that seems to imply that we're talking about exposed fields.

# Answer
> 0 votes
You can add field via structure-\>content types-\> manage fields in your content type, add field that you want to hide.

to hide field in a edit-form/node you can use

```
function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'formtypename') {
hide($form['fieldmachinname']);
]

```

---
Tags: 7, entities
---


# Question
Title: Accidentally deleted uploaded files, now I can't remove missing files from node
So I made a bit of an mistake and accidentally deleted some uploaded files via FTP. In the backend, when I try to remove the missing files from the node itself, it presents an error "The website encountered an unexpected error. Please try again later." Upon checking the error logs it says:

PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file\_managed} (filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> 1 \[:db\_insert\_placeholder\_2\] =\> 1384489746 ) in drupal\_write\_record() (line 7166 of /Applications/MAMP/htdocs/fung/includes/common.inc).

Any ideas how to fix this?

# Answer
> 0 votes
You should upload via FTP a file with the same filename and path as the deleted file. The file content doesn't matter.

Then edit the node and delete the file from the node editor.

---
Tags: 7, files
---


# Question
Title: Removing Queue Table Items / Queue UI Module D7
While attempting to export the mysql database, I found that there was a large number of items in the drupal 7 queue tables "feeds\_importer\_expire" and "feeds\_source\_import", both have about 80,000+ records dating back over a year.

I have installed the Queue UI module but have a question before I proceed.

In the "Queue Manager" at "admin/config/system/queue-ui" there is a delete queues button. If I delete the queue e.g. "feeds\_importer\_expire" will it regenerate the next time it is needed? Or am I deleting the queue all together and causing major issues.

# Answer
> 0 votes
The default Drupal supplied queues only exist when they have `$items` within them. It will be regenerated when it's next inserted into.

Depending on whether or not a worker process is working on a `claimed item` the queue item(s) when you delete the queue -- you may raise like a warning when the process tries to notify the queue of completion of an item. It shouldn't break the queue itself; the worker processes may need to be reset of course.

---
Tags: queue
---


title: Update programmatically Group Audience

text:
# Question
Title: Update programmatically Group Audience
I have made a hook\_node\_insert which when I create a group content of type A, it create a node group. I want to associate my type A with the created group with the field audience. I have changed the field group audience like that

```
$nodeA->group_audience = array(
    LANGUAGE_NONE => array(
        '0' => array(
            'gid' => $group->gid,
        ),
    ),
);

```

But it doesn't save the data into the database. I have tested with node\_save but I have the error that primary key nid is duplicated.

Thank

# Answer
Unless you're changing the `$node` inside a `node_save()` or something, your changes won't make it into the database unless you add a `node_save()` after the change to `$node`.
> 0 votes

---
Tags: nodes, organic-groups
---


# Question
Title: Entity Registration: Override built-in registration list with custom view
I'm trying to override existing registration list (in Registration tab) with my custom built view, however if I set my View's path to "node/%/registrations", the tab "Manage registrations" is gone from entity tab.

What should I do?

# Answer
> 0 votes
In case someone is interested, I came up with a very nice and simple solution. I'm implementing hook\_menu\_alter() and overriding tab's "page callback" so that my custom view is called instead built-in registration list. (Note that solution below covers only tab for NODE entity!)

```
function MYMODULE_menu_alter(&$items){
    $items['node/%entity_object/registrations']['page callback'] = 'regstrations_view';
}

function regstrations_view(){
    $node = node_load(arg(1));
    return views_embed_view('my_registration_list_view','page', $node->nid);
}

```

---
Tags: views
---


# Question
Title: Change language for date cck field of a webform in drupal7?
Can we change language for date cck field of a webform in drupal7? If I create a component of date type in webform then drupal provides a dropdown having month,day and year values in English e.g. Jan 1 2013 , I want a drop down for this component having options in different language say spanish (witout using any translation module, I am translating webform manually) Is it possible?

# Answer
> 0 votes
go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates

---
Tags: webforms, entities, datetime
---


title: Admin Menu at bottom of screen

text:
# Question
Title: Admin Menu at bottom of screen
My admin menu keeps randomly showing up at the bottom of the page. Any ideas why?

EDIT: I've continued to pay attention to the behavior.. and it appears to only happen when there is a "message" displayed at the top (in the green box).

# Answer
> 3 votes
Drupal core 7.16 with Omgea 7x-3.1 theme and loads of modules. Just experienced the similar behavior where admin menu was locked at bottom of the page. Read through this, decided to not touch Skinr and instead:

Home » Administration » Configuration » Administration

Turn of the "Adjust top margin", save, clear cache, turn on "Adjust top margin" AND "Keep menu at top of page" - this solved the problem in my case.

# Answer
> 2 votes
I think this CSS might take care of the problem:

/\* to fix admin menu at bottom of page - http://drupal.org/node/1588158 \*/

body.contextual-links-region { position:static; }

It seems to be caused by CSS position set to relative for the body element. See http://drupal.org/node/1588158#comment-6180760

I had this problem myself, and notice that also, disabling the Skinr UI module - not Skinr itself - fixes the problem.

# Answer
> 0 votes
the quickest and cleaner way to fix this is to edit the views page and set HIDE CONTEXTUAL LINKS to YES.

---
Tags: 7, users
---


title: Authored By field conditional statement

text:
# Question
Title: Authored By field conditional statement
I am racking my brain trying to figure out how to create a conditional statement in Drupal concerning the "Authored By" field.

Right now, I have a special node template for a content type in my Drupal installation. I need to be able to define in that template when the "Authored By" field is filled in to display JUST the author full name but if it is not filled in, to display NOTHING.

I don't know I am having such a hard time accomplishing something so seemingly elementary, but any help would be greatly appreciated!

# Answer
> 0 votes
I believe the default variable for the author is $name. So you could perform a simple if statement in the template:

```
if (isset ($name)) {
print $name;
}

```

That will check if the $name variable is set - and if it is, print it out. If it's not set, nothing will happen.

---
Tags: nodes, entities
---


# Question
Title: "Check boxes/radio buttons" Widget is NOT displaying content in Drupal7
In Drupal 7 Admin, I added a choice field of Type "List (text)" and widget "Check boxes/radio buttons", in which I see the list of check boxes in the Admin. But I don't see anything in the Live Website (it does not show up)

Below is the code that I am using in the `node-view-VIEWNAME.tpl.php` page:

```
<?php if ( render ($content['field_choice']) ): ?>
Choice(s): <?php print render ($content['field_choice']); ?>
<?php endif; ?>

```

The code above works fine for Fields of Type Text. How would I modify the code to render the content for check-boxes?

# Answer
> 1 votes
Never mind. I had a typo in the $content\[\] array element. The one I set in the admin is slightly different than the one I declared in the template. (small typo). Amazing!

My code above also works fine with check-boxes.

---
Tags: views
---


# Question
Title: date in spanish webform component coming out in day month year , need month day year
My webform in english shows the date component as month day year. but when I translate it to spanish it shows the date as day month year. How can I modify the format for dates when in different languages?

FOUND THE ANSWER: go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates

# Answer
> 0 votes
Posted on behalf of Diana that can't do it due to reputation limits.

Go to `/admin/config/regional/date-time/locale/es/edit` and change the date format to month first for the long, short and medium dates.

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


# Question
Title: Strict URL alias checking with optional 404 redirect
When I create a node with "This is sample title" as title, the Pathauto module will create "this-is-sample-title" as URL alias and some "node/123" as real node URL. But we can browse the same content with a different URL such as

```
SERVER/this-is-sample-title
SERVER/this-is-sample-title/some-garbage-here

```

In node head source code canonical url is set to "/this-is-sample-title" and shortlink to "node/123". How do I make Drupal strict on the URL alias and redirect to 404 if URL garbage found (even if first URL segment is correct)?

# Answer
You can use the `url_inbound_alter` hook to verify if the internal path of the request matches the used url alias. If not, trigger a 404.

```
function YOURMODULE_url_inbound_alter(&$path, $original_path, $path_language)
{
    if ($path === $original_path) {
        // path is same as url alias - don't do anything
        return false;
    }

    $alias = drupal_get_path_alias($original_path);
    if ($alias && $alias === $original_path) {
        // alias is same as url alias - don't do anything
        return false;
    }

    drupal_not_found();
    drupal_exit();
}

```

I've tested on some projects which are using the most common contrib modules (Pathauto, Globalredirect, Views, Sitemapxml, Wysisywyg, ...), and I don't have the problem. Url alias verification is strict and returns 404 for non existing aliases. But I'm able to reproduce it with custom menu callbacks (custom code or views).
> 2 votes

---
Tags: 7, path-aliases
---


# Question
Title: how to detect current language to show the other(s) in the menu
I'm using i8n to host a bilingual site and I only like to display the inactive language in the top bar. What php code do I need to detect the current language so I place the inactive language in the template? Thanks:

```
<a href=
<?php
global $language;
if (($language -> name) == 'English') {
print "\"http://www.mangallery.net/fr\"".">french";
} else {
print '"http://www.mangallery.net"'.">english";
}
?>
</a>

```

# Answer
Use the global variable `$language`

https://api.drupal.org/api/drupal/developer%21globals.php/global/language/7
> 1 votes

# Answer
If you are planning to use the existing **Language switcher** block of Drupal which links directly to the translated page(s) on a multilingual website, here is some sample code to remove the active language from the list.

You can add this code in the `template.php` of your theme. Replace `YOURTHEME` with the name of your theme and don't forget to clear the cache.

```
function YOURTHEME_preprocess_links(&$variables)
{
    if (!isset($variables['attributes']['class']['0'])) {
        return false;
    }

    // Only alter links for the language switcher block
    if ($variables['attributes']['class']['0'] === 'language-switcher-locale-url') {
        global $language;

        // Remove active language from the list
        if (isset($variables['links'][$language->language])) {
            unset($variables['links'][$language->language]);
        }
    }
}

```
> 0 votes

---
Tags: routes, theming, i18n-l10n
---


# Question
Title: Drupal 7 check logged in user has both roles in tpl file?
I want to print in a page--node--17.tpl.php a code to check for roles from the logged in user and then determine what should be shown, so basically a user must have BOTH roles A and C and if they do i print xxx If they have roles A and B i write yyy if they have roles B and C i print zzz

So the code below can check for one role, but how do i do both.. its important that BOTH roles need to be there, a user with just one of the roles will not qualify.

thank u

```
<?php
  global $user;
  // Check to see if $user has the administrator user role.
  if (in_array('administrator', array_values($user->roles))) {
    // Do something.
  }
?>

```

also i have this code but i think this is only checking one of the roles, so it checks for either A or B

```
<?php
global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
    if (empty($check) ? FALSE : TRUE) {
    // is admin
    } else {
    // is not admin
    }
?>

```

# Answer
It would be simple as:

```
global $user;

if (in_array('administrator', array_values($user->roles)) &&  in_array('moderator', array_values($user->roles))) {
    // is admin
} else {
    // is not admin
}

```
> 2 votes

# Answer
`array_intersect()` returns the intersected array, so your condition will pass if *either* of the roles are present.

There are different ways to approach it but this is probably the simplest:

```
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
if (count($check) == 2) {
  // ...

```

On a slightly separate note, there's a bit of redundancy in your code

```
if (empty($check) ? FALSE : TRUE)

```

Would be simply

```
if (empty($check))

```
> 1 votes

---
Tags: 7, theming, hooks, users
---


# Question
Title: Want to add tabs from /user/* pages to other pages
When I go to any "user" pages on my site in /users/\* I have menu tabs for the various pages in that section, like below.

I want to add the top level of tabs to another set of pages. Specifically, I am trying to setup the Private Msg module, which has everything in /messages/\* When someone is reading their messages, I want to have the same top level of tabs they see in /users/\*

# Answer
You can use Tab Tamer module to arrange tabs at your **user/%** location or some where else too. You can change orders or enable/disable as per your requirement.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
>
> Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.
> -1 votes

---
Tags: 7, routes
---


# Question
Title: How to resize images in a slideshow for a Responsive Theme?
I am using a responsive theme in which I have a slideshow on the homepage of the slide. I am creating the Slideshow as a Block using Views.

Question: How do I make the slideshow (i.e. the images) re-sizable as the screen size is changed?

# Answer
You can use Flex Slider either alone, or in combination with FlexSlider Views Slideshow (which provides integration with Views Slideshow in case you already use that one).

Flex Slider module integrates the Flex Slider library with Drupal and allows you to build responsive and resizable slideshows. You'll find plenty of documentation on the project page to fit it to your needs.
> 2 votes

# Answer
You could try the below CSS

```
.views-slideshow-cycle-main-frame {
  width: 100% !important;
}
.views-slideshow-cycle-main-frame-row {
  position: relative !important;
}

```

Or visit this page to know more.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Check if field is empty in Views field Template
I have about 4 fields displayed in a view.

What I am looking to achieve is when one of the fields have a check box ticked, to hide a different field in the view display. e.g

Price on application \[Ticked and displayed\]

Price GBP \[Hidden\]

Price USD \[Hidden\]

OR

Price on application \[Un-Ticked\]

Price GBP \[Dispalyed\]

Price USD \[Dispalyed\]

I am editing the views-view-field.tpl for 'Price USD' and 'Price GBP' field. (views-view-field--clone-of-gallery--gallery--field-listing-price-usd.tpl.php)

The basics I am trying to achieve are:

```
if 'price_on_application' = '1'
"Empty"
else
Print $output

```

The if statements i have tried so far are:

```
<?php if ($row->field_listing_price_on_request == "POA"): ?>
<?php if ($field->field_listing_price_on_request == '1'): ?>

```

and several other variations of the above.

Any ideas?

# Answer
You can use the Views Conditional module. With it, you can add a conditional field that would evaluate the value of your 'Price on application' field. You can then add the other two fields in a personalize text excluded from display and use you conditional field to display it or not depending on the condition you want.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How do I restrict view/edit access to a custom content type node to only the user it belongs to?
There is a content type; let's call it Contract. I have an user role; let's call it Consultant.

I added a Consultant field to the Contract content type with Entity Reference.

How can I restrict access to view/edit that specific node to only the user it belongs to?

# Answer
> 2 votes
You can use the Node access user reference module.

> Gives content access permissions to users for content that references the users with User reference or Entity reference.

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


title: Images not showing correctly

text:
# Question
Title: Images not showing correctly
I'm adding a logo image to my page.tpl.php template this way:

```
<a class="mobile-brand" href="#"><img src="<?php print drupal_get_path("theme", "my_custom_theme"); ?>/img/logo-mobile.png"></a>

```

The image is being displayed fine in the homepage, but if I go to the /user page, for instance, the image won't show up.

Any ideas why is that happening?

Thanks!

# Answer
> 4 votes
Without a leading '/' (or '/foo/' if the site is in a subfolder) the browser will always to try to find the image relative to the current path, not to the root of the site. That's why your current code works on the home page, but not on other pages.

To fix it you just need to add the base path as well:

```
<a class="mobile-brand" href="#">
  <img src="<?php print $base_path . drupal_get_path("theme", "my_custom_theme"); ?>/img/logo-mobile.png">
</a>

```

---
Tags: theming, media, 7
---


title: Displaying title of an empty view

text:
# Question
Title: Displaying title of an empty view
I would like to display the title (and the field titles) of a view even when the view is empty. By default, if a view is empty its title and fields are hidden. How can I force displaying title and fields on an empty view?

I am using views in a panel if that makes a difference.

# Answer
Quick and dirty way: make a view that displays just one row, take the source html, edit relevant part of it so that it looks the way you would like to printed when there are no results, ie remove field contents and leave only field titles. Copy and paste that html to No results behaviour -\> Global text area.

The view title should always be displayed, right?
> 1 votes

---
Tags: views, panels
---


# Question
Title: How do I print out values from a select field with multiple values
Currently I have a select field with multiple string values in a custom node. I'm trying to print them out without any html markup.

Currently I am declaring my variable like this:

```
$categories = $content['field_category'];

```

And I'm trying to print it like this:

```
foreach ($categories['und'] as $item) {
    echo $item['value'];
}

```

But nothing gets printed out. What am I doing wrong?

# Answer
> 0 votes
I ended up just making a custom loop like this and it works fine (Also added a custom if statement to change html output based on single or multiple categories in the field.

```
<?php
    $categoryCount = count($field_category);
    if ($categoryCount != 1):
?>
    <p><strong>Categories:</strong>
<?php else: ?>
    <p><strong>Category:</strong>
<?php
    endif;
    $i = 0;
    while ($i < $categoryCount) {
        if ($i != 0) {
            $html .= ', ';
        }
        $html .= $field_category[$i]['value'];
        $i++;
    }
    echo $html;
?>

```

---
Tags: entities, theming
---


title: How to add an "or" to Rules event?

text:
# Question
Title: How to add an "or" to Rules event?
Is it possible to add an "or" relation to a rule's event? I'd like to do exactly the same things when two different events took place. With an "or", I don't have to clone the whole rule.

# Answer
Just edit the rule and add another event to it. Reaction rules can have multiple associated events.
> 3 votes

---
Tags: 7, rules
---


# Question
Title: Use single create content flow to create many nodes
I am building a site for a charity. Amongst other things, the site lists a number of upcoming events. I have created a custom content type for these events (with fields like `title`, `body`, `date`, `location`). I want users to be able to upload photographs taken at these events, and am not sure what is the best way to do it.

I was going to create a new content type called something like *Event Photographs*, and by using a module like Entity Reference I could require the users to select an event.

But our users will probably have many photographs to upload for each event.

**Is it possible for my users to follow a single add node / create content flow but upload many photographs at once to create many nodes?**

An alternative is to have a single node, with multiple fields, but then I lose the benefits of each photo being its own node (e.g. commenting).

# Answer
> 0 votes
Bulk File Nodes is the solution for you to upload many files/pictures and create a node of it. Rest depends on your Logic how you implement it.

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


# Question
Title: Using drupal_add_feed() in template.php gives warning errors
As soon as I add a call to drupal\_add\_feed in my theme template.php file I get this warning:

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, no array or string given in theme\_get\_registry() (line 277 of /var/www/example.com/includes/theme.inc).

The feed (created by Views) is valid, and the code *works*, i.e. it does add the meta tag. But the warning is unacceptable, obviously.

Fix? Something I'm doing wrong?

# Answer
> 0 votes
You need instal Zen and STARTERKIT theme in (...sites\all\themes).Because STARTERKIT need Zen theme to work.

---
Tags: 7, theming, feeds
---


# Question
Title: The "Add another item" button doesn't work with field groups
I am working on a site that uses a lot of horizontal field groups. I am having a problem where any fields that sit in a field group and have "unlimited" set for the number of entries is unable to use the "Add another item" button. The AJAX call is returning some JS settings but no HTML.

The fields themselves range from simple text fields to node references. If a field is not residing in a field group then it works fine.

I will point out that I am using Drupal 7 and field\_group version 7.x-1.1.

It seems that the Drupal core is unable to properly identify which button was clicked and so has not idea how to respond.

# Answer
another option is to use the field\_collection as described here: http://openconcept.ca/blog/mducharme/creating-multiple-value-field-groups-drupal-7

i'd like to see this in field\_group to though - as the detour of making collections under 'structure' isn't as intuitive as under 'manage fields'
> 3 votes

---
Tags: 7, ajax, javascript, entities
---


# Question
Title: How do you make nodes automatically publish one by one after specific time?
I'm going to do a comic site. I saw the MemeCenter. It automatically publish comics after 10 minutes. Is there a module to do this on Drupal?

# Answer
> 0 votes
You can use Rules module with rules scheduler, check this tutorial for better understanding on how to configure.

and also take a look at Scheduler module

---
Tags: views, nodes
---


# Question
Title: Why is my taxonomy term name no longer outputting?
I have created a custom node with a field where you can select one tag from a list of a custom taxonomy term (location)

I was originally using this to print out the name of the selected tag for the node:

```
echo $field_location[0]['taxonomy_term']->name;

```

However it has since stopped working (it now outputs NULL). All I have done since is remove an unrelated field in the content type.

Now when i do a var dump of `$field_location` all I get is:

> array(1) { \["und"\]=\> array(1) { \[0\]=\> array(1) { \["tid"\]=\> string(1) "1" } } }

Wheras before I had a load of extra stuff like the name of the tag etc...

Anyone have any ideas what's happened?

# Answer
Go to Structure \> Content types \> Article \> Manage display, for Article for example. If your field is in Hidden section (bottom of the page) then change Format of this field to other than Hidden.
> 0 votes

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


title: Show/Hide Column in Views Table

text:
# Question
Title: Show/Hide Column in Views Table
Is there any way I can show/hide entire column in Views Table?

**Exclude from Display** completely excludes the column which is not possible to show again, so, I am using Views Dynamic Fields Module to exclude the column initially and showing it when the filter is checked. Like in the picture, the initial view when Column is hidden using ***Views Dynamic Fields*** module.

When the ***Nick Name*** checkbox is checked the column is shown like:

However, I want to hide the ***Name*** Column entirely when ***Nick Name*** is shown.

I initially tried it with **jQuery** like:

```
// Hide the Name Column when Nick Name is shown
$('#edit-dyfield-field-girls-nickname').change(function() { // id of checkbox
                if ($('#edit-dyfield-field-girls-nickname').is(':checked')) {
                    $('.views-field-title').hide(); // Title points to Name field so all the th td have this class in Name
                }
            });

```

But it hides both *Name* and *Nick Name* for a while, and shows both fields again.

Any solution Drupal based or some tricks with jQuery/JavaScript would be fine, thank you.

# Answer
> 2 votes
I am not sure if this is **The Drupal Way** to fix this, but I fixed it with jQuery `hide()` and `show()`.

```
// Hide the Name Column when Nick Name is shown
$('#edit-dyfield-field-girls-nickname').change(function() {
                if ($('#edit-dyfield-field-girls-nickname').is(':checked')) {
                    $(document).ajaxStop(function() { // Forcefully stopping Ajax function in the page as other ajax load was main culprit in my case
                        $('.views-field-title').hide();
                    });
                }

                if ($('#edit-dyfield-field-girls-nickname').is(':not(:checked)')) {
                    $(document).ajaxStop(function() {
                        $('.views-field-title').show();
                    });
                }

            });

```

**Note**: In the above example jQuery `toggle()` doesn't work, so, I have to put 2 `if(){}` statements for ***Check*** and ***UnCheck***.

# Answer
> 1 votes
You could use Views MediaTable module.

Not sure if this is the exact use case you are after. this will allow the user to select the columns they want to see.

> Views MediaTable integrate the functionality of MediaTable(http://consulenza-web.com/jquery/MediaTable/) into the Views module Table display, allowing the creation of dynamic & responsive Views tables where end users can choose to show or hide certain columns. This module also allows certain table column to behave responsively, hiding the less relevant data in smaller screen sizes.

The js code you used should also do the trick. But the issue you are facing is due to ajax loading. so you will have to put in drupal behavior so it gets called even after the ajax call.

You can check out the below link for more information regarding adding js

Managing JavaScript in Drupal 7

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


title: Preprocess view does not work?

text:
# Question
Title: Preprocess view does not work?
I have a very basic problem: I installed the views module and created a view...and of course the develop module. But why does

```
function bartik_preprocess_views_view(&$vars)
{
  dpm('hi');

}

```

Not givimg me HI in template.php ? If i write that into the bartik\_process\_page() it works...

# Answer
> 0 votes
Add a page display with an URL for your specific view, then on that page it will work and please don't forget to clear the drupal cache.

---
Tags: views
---


# Question
Title: how to return a db_query as an option list and display it
```
<?php

/**
 * Define callbacks that can be used as custom select list options.
 */
function webform_contacts_webform_select_options_info() {
  $items = array();

  if (function_exists('webform_options_contacts')) {
    $items['contacts'] = array(
      'title' => t('Contact List'),
      'options callback' => 'webform_options_contacts',
    );
  }

  return $items;
}

/**
 * Option list containing Contacts.
 * Pull a list of users where status=active and rid=5 from database.
 */
function webform_options_contacts() {
  $items = array();

  $query = db_query("SELECT realname.realname AS realname_realname, realname.uid AS realname_uid, users.uid AS uid, 'user' AS field_data_field_gal_phone_user_entity_type FROM {users} users INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid LEFT JOIN {realname} realname ON users.uid = realname.uid WHERE (( (users.status <> '0') AND (users_roles.rid = '5') )) ORDER BY realname_realname ASC");

  $results = $query->execute();
}

```

I created a custom module for displaying an extra option list. The example provided by *Drupal 7 Webform Cookbook* I used worked; using a hard coded list and it displays fine.

I want to use a db\_query to populate the list. I have this code (shown above) but am unable to see anything displayed. Help! I am sure I am missing the command to properly get this to display as a list.

# Answer
You can make use of `DatabaseStatementInterface::fetchAllKeyed()`, but as you only need 2 columns it would be wise to change your query slightly. Essentially you want to select just one for the identifier, and one for the label. Something like this:

```
$sql = '
    SELECT realname.uid, realname.realname
    FROM {users} users
    INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid
    LEFT JOIN {realname} realname ON users.uid = realname.uid
    WHERE users.status <> :status AND users_roles.rid = :rid
    ORDER BY realname.realname';

$args = array(':status' => 0, ':rid' => 5);

return db_query($sql, $args)->fetchAllKeyed();

```

That will return an array with the 1st column (uid) as keys and the 2nd column (realname) as values, which you can use verbatim as options for a form element.

You don't *have* to return just 2 columns from the query, as `fetchAllKeyed()` allows you to specify the index for both key and value; but as you're not using the data for anything else, it makes sense to avoid the overhead of the extra columns.

Slightly unrelated: you shouldn't call `exceute()` on the return from `db_query()`, as the query has already been executed by that point. You can either use one of the helper methods like `fetchAllKeyed()`, or iterate directly over the values, e.g.

```
foreach (db_query($sql) as $row) {
  // ...

```
> 1 votes

---
Tags: webforms, database
---


title: Issue with menu caching in Drupal 6

text:
# Question
Title: Issue with menu caching in Drupal 6
I have implemented `hook_menu_link_alter` so that a menu link is altered for some authenticated users, but not for all. My implementation of `hook_menu_link_alter` changes properties of the link (HTML attributes), not the destination of the link. The thing that I'm changing is adding an HTML class and other attributes for some users, and not for others. A 3rd party JavaScript that is also loaded reacts differently depending on the attributes.

In Drupal 6 I must clear the cache so that the menu links are rebuild and so that the changes that I have in the hook are applied.

However, that also means that the modified link in stored in the cache. So if another user then logs on who doesn't need the change, then this user also sees the change because it was cached?

I know that a solution could be to have 2 menu's and use PHP code to decide which one is shown to which user, but this is not what I want. I'm building this in a generic module that is available from drupal.org, so I don't was to go duplicating menu's in other people's websites. Another solution could be to rebuild the menu cache after every logon, but I fear that this is quite resource intensive.

Does anybody have advice on how this can be handled?

# Answer
Your idea to rebuild the menu cache on each login would certainly be resource intensive, but it would moreso just not work either as the cache is system wide and isn't somehow custom cached across page loads of a user, so, once someone logged in, it would be rebuilt and then accessible to both that as well as any other currently logged in user. Then, when the next user logged in, it would be rebuilt for all to use by everyone logged in, etc etc etc.

But, you could rather easily as you intimated do this with php inside a new `page callback`, eg, something along the lines of...

```
if ( /* users we are looking for is TRUE */ ) {
  // use our new callback
} else {
  // call original callback
}

```

By doing it inside the callback, you wouldn't be duplicating menu paths, eg, not having `module/callback1` and `module/callback2` but rather `module/callback` in itself would do things differently based upon your new logic...much like how going to `user` as an anonymous user presents a login page, but going to it once logged in presents your profile.

ADDITION:

Given additional commentary, you most probably could overload/overuse the capabilities of hook\_translated\_menu\_link\_alter() to accomplish this, eg, something like:

```
function YOURMODULE_menu_link_alter(&$item, $menu) {

  if ( /* whatever is true for your $item */ ) {
    $item['options']['alter']=TRUE; // Flag this link as needing an alter at display/run time.
  }

}

```

and then

```
function YOURMODULE_translated_menu_link_alter(&$item) {

  if ( /* whatever is true for your $item */ ) {

    // do whatever you want to do to it, eg...

    if ( /* this is a special user */ ) {
      $item['localized_options']['attributes']['class']='foo';
    }

  }

}

```
> 0 votes

---
Tags: 6, routes, caching
---


# Question
Title: How to handle a lot of simple unique URLs (for click's statistics)?
I need to create a lot of simple unique URLs (for click's statistics).
Each such URL consist of several parameters (project\_name, unique\_ID, etc).

Examples:
example.com/project1\_id35 or
example.com/project1/id35 or
project1.example.com/id35 ...

I plan to use Rules to decipher these URLs and to save it to database.

But how Drupal site can catch all such URLs?
It's really hard to make aliases for every case.

May be mod\_rewrite can help?
Or is there any useful module for such task?

PS. It seems mod\_rewrite the best solution.
PPS. Another possible solution: override 404 page.

# Answer
A great module to aliases auto-generation is PathAuto. It will allow you to define patterns to your url's using tokens, things like:

**article/\[title-raw\]**

will generate:

**www.example.com/article/my-blog-post**

Once you install the module, go to:

Administration \> Configuration \> Search and metadata \> URL aliases, in the "Patterns tab" (admin/config/search/path/patterns).
> 0 votes

---
Tags: 7, subsites
---


# Question
Title: Implement boolean search in apache solr search
I am working on Apache solr search. I want to implement boolean search in apache solr search.

On google i found following article and many more articles.

I have also seen the hook\_apachesolr\_query\_alter but i have no idea how to implement the apache solr alter function.

If any one have prior information how to implement it, please guide me to achieve it

# Answer
> 0 votes
Here is a basic example of adding an extra parameter to the search query using the hook\_apachesolr\_query\_alter()

```
/**
 * Implements hook_altersolr_apachesolr_query_alter().
 */
function mymodule_altersolr_apachesolr_query_alter($query) {
  $query->addParam('fq', 'my_field:(value)');
}

```

Check this page for more possibilities on altering the search query: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.interface.inc/interface/DrupalSolrQueryInterface/7

---
Tags: search
---


# Question
Title: How can I provide a checkbox to display name as 'anonymous'?
When users register on my website, they have to fill in their name. However, not everyone wants his/her name to be displayed on his/her profile page. Therefore, I'd like to provide a checkbox "Show as anonymous" during the registration which changes the name to *anonymous* on the profile page. In other words, the checkbox **rewrites** the displayed name, as opposed to Is there a way to let every user can choose (e.g. on registration) whether their field is private or public?, where the field is hidden.

I rewrote the profile pages with **user\_view** in the Pages section and I'm using Panels.

How can I do that?

# Answer
> 1 votes
You can add one more text field to user entity, keep it hidden.While registering the user check if show as anonymous user field is checked save the hidden field value as anonymous else copy the user name field to hidden field.

You can do the above changes in hook\_user\_presave().

Finally add this hidden field to your user view, instead of name field.

---
Tags: 7, entities, panels, users
---


title: Can't create node programmatically

text:
# Question
Title: Can't create node programmatically
I have this code

```
<?php
      $node = (object) array(

        'title' => 'Title',

        'body' => array(

          LANGUAGE_NONE => array(

            0 => array(

              'value' => 'Body Text',

              'summary' => 'Summary',

              'format' => 'filtered_html',
            )
          ),
        ),

        'type' => 'article',
        'language' => LANGUAGE_NONE,

        'uid' => 1,
      );

      node_object_prepare($node);

      $filepath = drupal_realpath('http://ppcdn.500px.org/52335278/cbc55dab399a4bd9caf7a27e9bb3564bc8458f65/3.jpg');

      $file = (object) array(
        'uid' => 1,
        'uri' => $filepath,
        'filemime' => file_get_mimetype($filepath),
        'status' => 1,
      );

      $file = file_copy($file, 'public://');

      $node->field_image[LANGUAGE_NONE][0] = (array)$file;

      node_save((object) $node);

      $path['alias'] = 'our-great-dsk-node';
      $path['source'] = 'node/' . $node->nid;
      $path['language'] = LANGUAGE_NONE;
      path_save($path);

      cache_clear_all();
    ?>

```

But can't understand where to use this code to create nodes programmatically in drupal 7 or how to use this code? To test i saved this as `custom-posts.php` in drupal root directory to see if this code works or not, but it gives a lot errors, so what to include?

# Answer
To bootstrap, try adding the following lines of code to the top of your custom-posts.php file:

```
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
define('DRUPAL_ROOT', '/var/www/drupal7');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Don't forget to update the path to your Drupal root folder.
> 1 votes

# Answer
Drupal is not bootstraped in your php file and its API is not available. Try to create a module and put your code in a hook\_install() to try it out
> 0 votes

# Answer
If you want to add custom code you should better create your custom module.

-- This is how you can create your custom module.

If you want a way to test your php code working or not, you can install devel module, once you install devel module,access yoursitenma.com/devel/php,basically devel opens a testing custom php codes at "devel/php" there you can execute your codes like in your case it is about creating custom nodes.

Try executing your node creating codes either with help of custom module or at "devel/php".As a note it will be better if you test your codes in chunks i.e. simply start with building node without having file field and path alias so your scope of debugging gets limited and clean and then can proceed stepwise.
> 0 votes

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


# Question
Title: How can users write a bio on their profile page?
I'd like my users to be able to write a bio on their profile page. Therefore, I added a long text field called 'Bio' to the user accounts. I created a view that shows the user's bio and wanted to add a link to only let the user edit his/her bio. Unfortunately, I only found a link that redirects the user to a page where he/she can edit his/her whole profile - which isn't exactly what I want.

Did I miss something?

I tried to solve this in another way. I created a content type called 'Bio' and a rule that creates a 'Bio' node with title *My bio* automatically when a user is created. Users don't have permission to add another bio, but they can edit their own 'standard' one. Now, I don't want the title field to be displayed on the edit form, because I'd like the titles to remain *My bio*.

How can I do this?

# Answer
> 1 votes
Re: the second/existing option, if you have a custom module already, could do a `form_alter()` on the node form to remove the title field. Or, you could look into the auto\_nodetitle module that does this for you:

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
>
> When the token module is installed it's possible to use various node data for the auto generated title - e.g. use the text of a CCK field (since 5.x).
>
> Advanced users can also provide some PHP code, that is used for automatically generating an appropriate title.

If instead you wanted to stay/go back to the first option, you could create a menu link/path like `user/%/edit/bio` that presents the `user_profile_form` that has been `form_alter()`ed to show only the bio field based upon the fact that it was called from this new path.

---
Tags: 7, nodes, users
---