# Question
Title: how do display 404 while the url didn't exits
I add a view contains three display page,and the page urls are:

1. questions
2. questions/my
3. questions/unanswered

but when I visit the url questions/s12dsdd ,It display the questions page list all questions,how to display a 404 page ? I found none settings in views.

of course we can handle it in code,but not a good one....

other desciptions:

> What he asks (I believe) is how to have 3 displays in one view and with \[placeholder\], \[placeholder/versionone\], \[placeholder/versiontwo\] URLs respectively and get a 404 on \[placeholder/somethingrandom\]. The second part of the URL does not seem to be an actual argument such as %nid. It's just a literal representation within the URL of what the display is meant to provide. :) @magtak

# Answer
> 3 votes
Drupal 7 – Show page not found if view argument exists http://eureka.ykyuen.info/2012/02/24/drupal-7-show-page-not-found-if-view-argument-exists/ Posted on February 24, 2012 Assume we have a Views page which does not have a contextual filter setting and the view path is /eureka. If you provide an argument in the url such as /eureka/abc, the argument is ignored and the Views page will return all view rows. But sometimes we may want to show the user a page not found instead of return all rows. This can be done by adding a Global: Null argument in the contextual filter.

1. Add a Global: Null input in the View Contextual Filters settings.
2. Check the Specify validation criteria option and select PHP Code as validator.

if (empty($argument)) { return TRUE; } else { return FALSE; }

Done =)

# Answer
> 6 votes
You can create two views. In one, using questions as URL, you add "Content: Nid" as contextual filter, and use the following settings for that contextual filter.

* In *When the filter value is NOT in the URL*

+ Select *Display all results for the specified field*
* In *When the filter value IS in the URL or a default is provided*

+ Select *Specify validation criteria*
    + As *Validator*, select *Content*
    + As *Action to take if filter value does not validate* select *Show "Page not found"*

The other view, using questions/mine as URL, would use "Content: Author uid" as criteria, and use a default value taken from the user currently logged-in.

---
Tags: views, uri
---


title: how to track user profile page views?

text:
# Question
Title: how to track user profile page views?
I want to track page views to a user's profile page similar to what the core "statistics" module does for node page views.

I don't want to use profile2 for my site, otherwise I could probably use the statistics module.

Eventually I want to use the Google Analytics module to track page views to cached pages as well.

I'm looking for a simple solution/workaround that I can use right now.

# Answer
Have you checked the User Visits Advanced, and the User Visits modules?

The User Visits Advanced module is a module that depends from the User Visits module. It is extremely useful for social networking sites that wish to provide their users with statistics about the number of time a user's profile page is being viewed, and by which users.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Problem in Recurring payment using money scirpts
we offered 20% discount last year and I've just received a recurring payment and it should be for full amount but its the same payment as last year. It just means if people renew their membership we lose on 20% of each membership fee.

Am using MS Core 6.x-1.25 and Drupal Version 6.20

Any one can help?

Thanks

# Answer
If you set it to 'Persistent' in scope, then it will remain discounted for all payments in the series. 'Initial' is what you want, where only the first payment is discounted, sort of like a Trial amount.
> 0 votes

---
Tags: payment-gateways
---


# Question
Title: Only show content in a View if the content has a checked field
On my content type, I have a boolean field which consists of a single on/off checkbox.

I have created a view, which shows all the nodes of that content type. However, I only want the view to show nodes where the boolean field has been ticked. How can I do this?

I thought in Views I could use "Filter criteria \> Content: \[Name of Field\]."
However, when I select this, the only option available is "Select All". If I select this, I get the following error message:

> No valid values found on filter: Content: Show on Main Navigation.

What am I doing wrong?

# Answer
> 4 votes
I tried on my test site, and it happened to me too, for the simple fact I didn't enter any value for *On value*, and *Off value*. Once I entered *Show the node in the view*, and *Don't show the node in the view*, for those fields, the filtered criteria showed those values in *Options*.

If you don't enter any value for *On value*, and *Off value*, the *Options* fields really shows three entries, but the other two are empty strings. They are there, but you cannot see them, and you don't know which value comes first. Is the first row for *On value*, or *Off value*?

# Answer
> 0 votes
I think in the filter criteria you can set the operator manually. See the attached screenshot.

---
Tags: views
---


# Question
Title: How to add Follow Me link inside content type in Drupal 7
My project contains two content types:- Professor and Lecturer. Here the users are student so students can log in using their own credentials.

Now I want to show up a button/link with Text "Follow Me" in Professor & Lecturer Content Type.When User/student will select the link/button then the corresponding Lecturer/Professor will be attached to the student profile and will be visible inside their home page. Similarly that student will be visible in Teacher/Lecturer.

I look at The "Relation" Module in Drupal 7 but my use case don't need to display too many things in the widget. There should be a simple button/link which relate user and content type.

# Answer
> 4 votes
You should try the Flag module for this. It should solve your purpose.

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

# Answer
> 0 votes
I've had a similar case where I needed to attach students to an instructor's class and have instructors print out class lists of attached users.

I used node registration to achieve this effect. And set up the registration parameters during the Content Creation process with node registration set to On by Default.

After, you can make some views with filters to display node registrants as a block and place it wherever you need.

# Answer
> -1 votes
There is Shortcode Module also

> Shortcodes are actually macros to be used in the text of contents. These macros change the text of the content and format the given part through the theme engine.
>
> Shortcode is an API that handles the shortcode macros for text formats. You can add your own shortcode tags via this API. All tags are themeable and new tags can be provided by other modules.

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


title: Custom module and block API

text:
# Question
Title: Custom module and block API
Have followed all the steps at http://www.packtpub.com/comment/reply/7089 to create a custom module.

I am able to create it and it is showing under the Modules and is getting enabled. However as the purpose of this module is to create a new block it is not doing so. Its not showing under the Structure/Blocks. Any reasons?

```
name = First
description = A first module.
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

```

```
/**
 * @file
 * A module exemplifying Drupal coding practices and APIs.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */
function first_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function first_block_info() {
  $blocks = array();

  $blocks['list_modules'] = array(
    'info' => t('A listing of all of the enabled modules.'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function first_block_view($block_name = '') {
  if ($block_name == 'list_modules') {
    $list = module_list();

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Enabled Modules'),
      'content' => $content,
    );

    return $block;
  }
}

```

# Answer
Let you try with this code. Clear performance cache.

```
function example_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Block Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function example_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = example_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function example_contents() {
  return '
    </p><div class="body">
      Hello World, this is a example custom Block
    </div><p>
  ';
}

```

For more info see this http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7
> -1 votes

---
Tags: blocks
---


# Question
Title: Where is the field exclude checkbox in Content type > Manage display in Drupal 7
When editing a content type in Drupal 6, in *"Display fields"*, there was a checkbox to "exclude" field (not just a dropdown for hidden).

Is there something like this for Drupal 7?

# Answer
> 4 votes
Clicking and dragging the 4-arrow handle, you can move the field (which one you want to exclude) under "Hidden" (In Drupal 8 this is now called "Disabled".) in admin/structure/types/manage/{content type name}/display.

---
Tags: entities
---


# Question
Title: Showing fields or content with Views - which is faster?
Say I'm building a view that lists 30 nodes. My understanding is that using fields in the view is faster than content (teaser), because the latter would need to call node\_load 30 times? At least, I think this was the case with D6.

I appreciate the performance of both options depends on number of fields and types of fields used (entity reference, dates etc add query overhead). But does anyone have a general steer on this?

Thanks

# Answer
> 4 votes
In D7 it is the same, because the node (or any other parent entity) needs to be loaded in order for a field to be displayed (that's how Field API works in D7).

# Answer
> 0 votes
Actually as far as I know with cache enabled using teasers is actually faster as teasers can be cached efficiently.

---
Tags: 7, views
---


title: get content which user likes

text:
# Question
Title: get content which user likes
When a user registers in my site, the registration form asks the user on which type of food he likes, the user choses one or more from a taxonomy terms.

A user can also create content and tag them from the same taxonomy terms on the registration from.

Now I want to create a view that gets all food "content" the user likes based on what he chose in the registration form or profile.

# Answer
I would approach this by building a view that has relation to current user selected taxonomies. Then listing content according to that.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Theme the progress bar when in batch API with AJAX
I am looking to create a stylized theme for the progress bar for the batch API screen. I wish to alter the HTML and CSS being displayed in order to do so.

I know how to add the CSS to the page. I am aware of the hook theme\_progress\_bar, but according to the documentation "Note that the core Batch API uses this only for non-JavaScript batch jobs.".

What is the best method for overriding the HTML for AJAX driven batch API jobs?

# Answer
> 2 votes
Ultimately decided to use the hook hook\_js\_alter() in order to replace misc/progress.js with my own version. You can declare your own markup in this file, and also react on progress update (every 1500 ms out of the box).

In case anyone was wondering, this is the outcome of this http://drupal.org/project/nyan

# Answer
> 1 votes
It depends on how much you want to alter it. It can be modified pretty simply with CSS. Are you absolutely sure there's no way to do what you want with CSS only? If you're trying to completely change the way it works, have a look at the ajax.inc file - you'll see this

> * + #ajax\['progress'\]: Choose either a throbber or progress bar that is * displayed while awaiting a response from the callback, and add an optional * message. Possible keys: 'type', 'message', 'url', 'interval'.

It doesn't support a custom "type". So there's not a clean way to do it through the AJAX API itself, but you could theoretically make changes on the client side with a jQuery plugin. A starting point for that would be to override the Drupal.ajax.prototype.success function in misc/ajax.js in your theme.

---
Tags: 7, theming, batch-operations
---


# Question
Title: Show title of article instead of date in a Views block
I'm using the Views module to show a list of the 3 most recent articles posted on a site. I've set the filter granularity to the specific date of posting and it shows three dates with bullet points in the block. What I would I like to do is get rid of the Bullet points, have the date formatted MM/DD/YYYY and then on the line below the date have the link to the article where the link is the title of the article.

I want this to look like this, where TEXT is the title of the article it links to.

# Answer
Try the following steps:

1. Create new date format as you want (MM/DD/YYYY). admin/config/regional/date-time/formats
2. Create Date type and assign your format. admin/config/regional/date-time
3. In views: Select your date type under "Choose how users view dates and times:" when you add your date field under "FIELDS".
4. Add (Content:title)title field (after date field) and Enable the Link this field to the original piece of content checkbox.
5. Bullet point from your css
> 1 votes

---
Tags: views
---


# Question
Title: How to perform join with multiple columns using db_select?
How to perform join with multiple columns using db\_select? Any help?

Here below is the sample, which I'm looking for.

```
SELECT * FROM digitaliq_flds_by_node a
JOIN digitaliq_fld_category b ON
  a.fld_id = b.fld_id AND
  a.fld_collection_id = b.fld_collection_id AND
  a.fld_group_name = b.fld_group_name

```

# Answer
You can use the following code.

```
$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');
$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');
$terms = $query->execute();

```

Calls to `SelectQuery::join()` (like `SelectQuery::leftJoin()`, `SelectQuery::innerJoin()`, and `SelectQuery::addJoin()`) aren't chain-able because those methods don't return a `SelectQuery` object, but the actual alias used for the join. If you execute the following code, you would get an error.

```
$query = db_select('digitaliq_flds_by_node', 'a')
  ->fields('a')
  ->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name')
  ->execute();

```

Strings in PHP are not objects nor they define an `execute()` method.

To verify the code is executing the right SQL query, cast `$query` to a string, and print it. You will get the SQL query that would be executed from your code.

```
$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');
$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');
print $query;

```

With that code, I get the following output.

```
SELECT a.*
FROM
{digitaliq_flds_by_node} a
INNER JOIN {digitaliq_fld_category} b ON a.fld_id = b.fld_id AND a.fld_collection_id = b.fld_collection_id AND a.fld_group_name = b.fld_group_name

```
> 11 votes

# Answer
Try this

```
$query = db_select('digitaliq_flds_by_node', 'a');
$query->join('digitaliq_fld_category', 'b', 'a.fld_id = b.fld_id');
$query->condition('a.fld_collection_id', 'b.fld_collection_id' '=');
$query->condition('a.fld_group_name', 'b.fld_group_name', '=');
$query->fields('a');
$query->execute();

```
> 4 votes

---
Tags: database
---


title: What is Drupal caching based on?

text:
# Question
Title: What is Drupal caching based on?
What does Drupal use for caching? Is this something like APC or memcache? Where does it store cache files?

# Answer
> 3 votes
Out of the box, it's stored in the database, in a number of tables names `cache_[name_of_bin]`.

There are lots of other options if one wants to configure it differently.

1. Memcache
2. MongoDB A nice feature is that mongo supports replication across multiple databases
3. APC
4. Varnish Doesn't replace normal caching, but integrates with Varnish so Varnish can invalidate cache when Drupal does
5. Boost Can generate static HTML files from content.

Also see Lullabots Beginners guide to caching data in drupal 7 (Thanks Chapabu!).

# Answer
> 2 votes
The basic drupal caching uses serialized data stored in database for caching.

If you want to have a look at the tables `SHOW TABLES LIKE 'cache_%';` to get a list of all the tables associated basic drupal caching.

If you want use caching in your module code then have a look at cache\_get and cache\_set functions.

Drupal also has support for APC and memcached by using those respective modules.

---
Tags: caching
---


# Question
Title: Edit the classess applied to a field from outside the field template
I am creating my own Panels Style Plugins.

The styles are applied to a Panel Pane which contains a field.

From the Style, I can add a wrapper DIV to modify the display of the field.

However, I would like to be able to modify the actual class on the field itself (this would negate the need for a wrapper DIV).

In my field.tpl.php file I have placed a PHP variable for the class, but I'm not sure how I can access and modify this variable from outside the field.tpl.php file. Could some one give me some pointers.

Thanks!

# Answer
Check out Semantic Panels. It lets you choose HTML element and classes for wrapper, the field and the label. The module provides the same options that are available to customize the field output in Views.

Here's a screenshot from the user interface when you customize the field.
> 5 votes

# Answer
You should be able to it via hook\_preprocess\_HOOK . Try to dpm($vars), classes should be one of them, you will then be able to change it.
> 0 votes

# Answer
You should be able to use preprocess\_panels\_pane(). I use it to remove the default classes from Panels.

```
function THEME_NAME_preprocess_panels_pane($vars) {
  $content = $vars['output'];
  // basic classes
  $vars['classes'] = '';
  $vars['id'] = '';

  ctools_include('cleanstring');

  // Add id and custom class if sent in.
  if (!empty($content->content)) {
    if (!empty($content->css_id)) {
      $vars['id'] = ' id="' . $content->css_id . '"';
    }
    if (!empty($content->css_class)) {
      $vars['classes'] .= $content->css_class;
    }
  }

  // administrative links, only if there is permission.
  $vars['admin_links'] = '';
  if (user_access('view pane admin links') && !empty($content->admin_links)) {
    $vars['admin_links'] = theme('links', $content->admin_links);
  }

  $vars['title'] = !empty($content->title) ? $content->title : '';

  $vars['feeds'] = !empty($content->feeds) ? implode(' ', $content->feeds) : '';
  $vars['content'] = !empty($content->content) ? $content->content : '';

  $vars['links'] = !empty($content->links) ? theme('links', $content->links) : '';
  $vars['more'] = '';
  if (!empty($content->more)) {
    if (empty($content->more['title'])) {
      $content->more['title'] = t('more');
    }
    $vars['more'] = l($content->more['title'], $content->more['href'], $content->more);
  }
}

```
> 0 votes

# Answer
Seeing as it's just a field that you're trying to alter, have you tried the Field Formatter Class module?

> This module allows site administrators to add classes to the outer HTML wrapper for any field display.
>
> Classes can be specified at the Manage display settings for content types, users and other entities.

On a side note, the Fences module doesn't add classes to your fields, but it is WELL worth knowing about if you want to reduce the markup/div soup that Drupal adds.
> 0 votes

---
Tags: theming, entities, panels
---


# Question
Title: How to add fields in Drupal Registration Form?
I have installed content profile module. I just want some fields in drupal sign up page. I am using Drupal 6. How can I achieve this?

# Answer
After you have enabled the module there will be a new content type called Profile available. Add fields to the content type Profile under admin/content/types.

The fields you add here will show up when the user registers.
> 1 votes

# Answer
Select `Use this content type as a content profile for users` option under your `admin/content/node-type/profile` page. After that go to `admin/content/node-type/profile/profile` and the option `Hide form fields` elements is there to show only few fields on registration page.
> 1 votes

---
Tags: users
---


# Question
Title: Block is not showing up in a custom taxonomy page template
I am using Drupal 7 I have a content type courses. I have a page folder in template folder, with courses.tpl.php file. When i go to courses page it is showing contents from courses.tpl.php. Issues is that courses.tpl.php is not rendering blocks.

I checked region in info file. I cleared cache etc, but block is not rendering. I am not sure, if this page is a taxonomy page. 'footer\_testimonials' is the block i am trying to render in this page, but it is not showing up.

'footer\_testimonials' is showing up in page.tpl.php but not in courses.tpl.php

```
<div id="innerCourse_area">
    <div id="searchbox">
    <?php print drupal_render(drupal_get_form('course_searchbox'));?>
    </div>
    <div id="innerTopRight_info"><?php print $page['page']['course_page_top_ad']['block_1']['#markup'];?></div>
    <div class="clearfix"></div>
    <h4>Popular Courses: <em>Certificate IV in Bookkeeping, Diploma of Accounting, Diploma of Business, Advanced Diploma of Accounting</em></h4>

</div><!--end inner course area-->
<div class="innerRightCol">
<h1>Courses</h1>
<div class="contentInfo">
    Central College Distance Education offers a range of Government and Industry Accredited courses ready to help launch your career.  Remember, Central College has been launching careers for over 30 years.  You may also be interested in our specialty Central College Certificates that will help you better manage your existing business and do it in your own time at your own pace, right in the comfort of your home.

</div>

<?php
//$taxoTerm = course::get_taxonomy_term(1);
$categories = course::getAllCategories();

foreach($categories as $category):?>
    <div class="course_cats">
        <div class="taxo_term"><h3><?php echo $category->name;?> Courses</h3></div>
        <div class="taxo_courses">
            <?php //get courses by taxonomy
                $courses_term = course::courses_by_term($category->tid);
                $i = 0;
                foreach($courses_term as $course):
                $courseObj = course::getCourseByNid($course->nid);
                    $i++;
                ?>
                <li><a href="<?php echo course::courseUrl_alias($course->nid);;?>"><?php echo $courseObj->title;?></a></li>
                <?php endforeach;?>
        </div>
    </div>
<?php
if($i%2==0):
    echo '<div class="clearfix"></div>';
endif;

endforeach;
?>
<div class="clearfix"></div>
</div><!--end innerRightCol-->

<div class="innerLeftCol">
    <h2>Testimonials</h2>
    <div>
<?php print render($page['footer_testimonials']);?>
    </div>
</div><!--end innerLeftCol-->

```

# Answer
> 0 votes
A page.tpl.php template file doesn't get blocks to render; it gets the theme regions to render, which by default are the following ones:

* `$page['help']`: Dynamic help text, mostly for admin pages
* `$page['highlighted']`: Items for the highlighted content region
* `$page['content']`: The main content of the current page
* `$page['sidebar_first']`: Items for the first sidebar
* `$page['sidebar_second']`: Items for the second sidebar
* `$page['header']`: Items for the header region
* `$page['footer']`: Items for the footer region

Themes can define other regions as well.

When you want to show a blocks that has been associated to the "highlighted" region, the page template file needs to contain the following code (or similar).

```
<?php if ($page['highlighted']): ?><div id="highlighted"><?php print render($page['highlighted']); ?></div><?php endif; ?>

```

Without that code, a block that should visible in the "highlighted" region would not be visible.

In a taxonomy term template file, you need to get the block content using code similar to the following one.

```
  global $theme_key;

  $query = db_select('block', 'b');
  $block = $query
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->condition('b.delta', $delta)
    ->condition('b.module', $module)
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->addTag('translatable')
    ->execute()
    ->fetchObject();

  if ($block) {
    $array = module_invoke($block->module, 'block_view', $block->delta);
    drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);

    if (isset($array) && is_array($array)) {
      foreach ($array as $k => $v) {
        $block->$k = $v;
      }
    }

    if (isset($block->content) && $block->content) {
      // Normalize to the drupal_render() structure.
      if (is_string($block->content)) {
        $block->content = array('#markup' => $block->content);
      }

      print render($block->content);
    }
  }

```

You need to know the module implementing the block, and the delta used for that block. It is better to put the code in the preprocess function to set a variable that is then rendered in the template file. As usual, the logic code should be in the template.php file of the theme, or in the module file, and the rendering code in the template file. (Don't confuse the template.php file with the template file.)

Instead of executing that code, it is easier to assign the block you want to show in the taxonomy term page to taxonomy term pages. In the settings page for the block (`admin/structure/block/manage/<block id>/form/configure`) select *Only the listed pages*, and in the textarea enter:

> taxonomy/term
> taxonomy/term/\*

---
Tags: 7, blocks
---


# Question
Title: Language switcher not visible when logged out (Drupal 7)
I'm creating a multilingual website in Drupal 7. I'm using the internationalization and entity translation modules and language detection is set to URL. I use the language switcher (content) from the entity translation module to switch between languages.

Everything works fine as long as I'm logged in as administrator. When I log out, or when I'm just an authenticated user, I can't see the language switcher anymore although the html code is generated. Does anyone what could be the reason for this?

Thank you.

# Answer
> 4 votes
You have to check the permissions on internationalization module; probably you have selected "administrator only".

By the way, read this: Drupal multilingual.

---
Tags: i18n-l10n
---


# Question
Title: Can I use the feeds module to import csv data to 2 different content type?
I have 2 content types, account and contact. I have a .csv file which contains the data.

In the Account table we have:

* name
* street address
* postcode
* city
* province
* country
* created
* lastModified

and in the contact table we have:

* initials
* lastName
* gender
* function
* officePhone
* mobilePhone
* otherPhone
* email

The csv contains all fields from the table like this:

> “name”,“street address”,“postcode”,“city”,“province”,“country”,“initials”,“last name”,“gender”,“function”,“office phone”,“mobile phone”,“other phone”,“email”

Is it possible to use the Feeds module to import the csv, separate the data from the csv file and either append, replace or merge the data in the 2 different content types at once?

# Answer
> 2 votes
Unless anything has changed in the last couple of weeks, I don't think it's possible to set up one feed to import to multiple content types out of the box. There's some discussion here.

That said, someone did mention the Feeds Node Helper module which apparently does allow this feature, although I'm no sure how robust it is.

> Feeds Node Helper is a collection of useful Feeds Import targets and Tampers. This is how book content can be imported and exported between Drupal sites. It provides helpers for the following:
>
> * UUIDs
> * Book parent based UUIDs
> * Book Weights
> * Node Types (by default Feeds just maps to 1 type, this allows multiple)

*EDIT*

If the module doesn't work, I don't see any reason why you couldn't simply set up two feeds that both use the same source CSV file; one for each content type.

---
Tags: feeds, importing-exporting
---


title: How to add a cron task

text:
# Question
Title: How to add a cron task
I am new to drupal, now I have function get\_node\_from\_rss() which the file is inside mysite\sites\all\modules\node\node\_rss\node\_from\_rss.module the function will update node from the rss link every 1 hour. Now, I dun know how to make this function add to the cron task. Can I run it without using cron.php? I search in google, they something like simple change the function name like get\_node\_from\_rss\_cron(), I also putting some code like:

```
$interval = variable_get('get_node_from_rss_interval', 60 * 60);
if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }

```

inside my code, but those still not working for me, Any solution?

# Answer
A *hook* implementation is simply a **my\_module\_name**\_function implentation. Your module's internal name is what you have used in the .module file's name.

So for in this case, it's `node_from_rss` (I'd recommend you to rename the folder name to node\_from\_rss as well so it reduces any confusion).

If you rename your cron function to comply with the above **my\_module\_name**\_function pattern, function name has to be `node_from_rss_cron`

```
function node_from_rss_cron() {
 $interval = variable_get('get_node_from_rss_interval', 60 * 60);
 if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }
}

```

Other than these changes, here are some of the Drupal best practices.

Drupal 7 has a `REQUEST_TIME` constant defined at the beginning of page processing. If this code is for D7, use it instead of time().

drupal\_set\_message() function sets a message to the screen. but cron functions will run without use interaction. You will not see this message unless you are running cron manually at admin/reports/status page.

Avoid placing folders such as 'node' inside sites/all/modules folder. Technically it's completely ok to do so. But I think it will confuse you and others in the long run. Usually we place modules like:

```
sites/all/modules/MY_MODULE/MY_MODULE.module

```
> 3 votes

---
Tags: hooks
---


# Question
Title: How to extend the user registration in Drupal 7
I want to run a set of php code(not drupal code) after the user submits the registration form.

1. user enter details
2. submit the form drupal
3. writes form data to db
4. execute custom code
5. comes back to default registration tanakyou page of drupal

For this how will i extend the default user module of drupal without touching the core user module codes.

can i define a custom module and execute its resources

# Answer
you can add any action you want after user registered by implementing hook\_user\_insert.
> 3 votes

---
Tags: users
---


# Question
Title: drupal 7 lack of understandig location of bartik's color.css
I liked to change some css color styles. I created my own css file and let bartik theme (my enabled theme) know this in its info file. But no changes took effect.
Then i realized, that there are two color.css files. One is in bartik/css/ and the other in sites/default/files/color/. The second one is used. Can someone explain to me, why not all css are just taken from bartik/css. I think i didn't get the concept yet.

# Answer
> 1 votes
The Bartik theme has support for the Color module, which is a module that allows themes to change the color used in their images, or in their CSS style files basing on a schema defined in the theme settings page.

When the selected color set is not the default one, color\_scheme\_form\_submit() generates the files that will be used for the theme. The files you have seen inside the sites/default/files/color directory are the ones generated from the Color module, and that will be used for the theme. The files in the theme directory are the ones used when the color set is the default one.

As side note, if you are editing the files used by a theme that supports the Color module, you need to disable, and then re-enable it, or the files used for the theme could still be the old ones.

# Answer
> -2 votes
This second css file may be cache file. Try flushing your cache and then checking if your changes take effect.

---
Tags: theming, files
---


# Question
Title: How can I implement a shopping cart limit?
> **Possible Duplicate:**
> limit items in commerce shopping cart

I\`m using drupal commerce for my webshop, i want to limit products in the shopping cart which means when the user has a product in his shopping cart he must not be able to add other products. Is it possible ?

# Answer
> 6 votes
Sure it's possible there are several ways of doing it.

The simplest solution would be to add a custom validation handler to the `add_to_cart_form` and raise a validation error if there is something in the cart:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'MODULE_cart_validate';
}

function MODULE_cart_validate($form, &$form_state) {
  $order = commerce_cart_order_load($GLOBALS['user']->uid);
  if ($order) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    if ($order_wrapper->commerce_line_items->value()) {
      form_set_error('', t("You can only have one item in your cart");
    }
  }
}

```

Another option is to remove other items in the cart when you add a new one. This could probably be done with rules, but is more easy to do with code if you know a bit of Drupal and PHP.

---
Tags: 7, commerce
---


# Question
Title: Need help creating a Commerce Order from Commerce Customer shipping profile
I am looking for a way for our admin users on a Drupal Commerce site to look up customer profiles from previous orders, and upon looking at a specific customer profile, provide a button that allows then to create an order for that customer. This use case is for a call center.

So far, I have tried using Button Field to call a rule component but I have having problems writing the rule.

Looking up previous orders and creating a new order with information for the shipping profile attached would also be a viable alternative.

Any suggestions regarding approach or use of modules would be welcome.

Thanks!

# Answer
> 1 votes
Things like this, is much easier to accomplish with a bit of custom code. You could add a form on the order view page, with the order as the context. This can be done by using `hook_commerce_order_view`.

All you really need to do, in the submit handler would be something like this.

```
$old_order //
$new_order = commerce_order_new();
$new_order->uid = $old_order->uid;
$new_order->commerce_shipping_profile = $old_order->commerce_shipping_profile;
commerce_order_save($new_order);
$form_state['redirect'] = 'admin/commerce/order/' . $new_order->order_id . '/edit';

```

The code above is from memory, should be in a form submit handler and is written from memory, but should work, if I remembered correctly. As you can see, it's pretty simple to accomplish.

---
Tags: commerce
---


# Question
Title: Autocompleting line-item fields in Drupal commerce
First off all I'm rather new with Drupal & Drupal Commerce. I'm going to do my best to describe what I have done and tried.

I'm developing a website where people can register (buy) a place in event. One of the things is that on the "add to cart" page they should be able to give some information like name, club, etc.

I added some fields to the line item "Product" like for example a textfield name Club and where I selected the option "Include this field on Add to Cart forms for line items of this type" so that it is shows in my add to cart form.

The problem I now have, is that I want (for a start) autocomplete that line-item field Club using #ajax and a ajax callback.

I started off with a hook\_form\_alter. I dumped (after checking the form id) the $form variable (with dpm()) to look for the Club #textfield so that I can modify it to include #ajax or #autcomplete\_path, but I can't find that element.

The only thing I see is an array line\_item\_fields containing field\_club, field\_name (my fields that I attached to the line item) of the type #container (and I looked for a #texfield node within it, but didn't find it). I tried adding #ajax to it but that didn't work.

To be honest I'm totally stuck now as I don't know how to proceed further with this. Is it even possible to attach #ajax or any other attributes to a line-item field visible in the add to cart form ?

# Answer
> 1 votes
If you change the field from a simple text field into an entity reference field, you can create the different clubs as nodes (seems to make sense, since you could then write info about each club on your site). Entity reference comes with a built in autocomplete.

You could also use taxonmy terms and taxonomy reference field instead if you don't want to create a node for each club. Either way should work just fine, as both have autocomplete built in.

---
Tags: entities, commerce, ajax
---


# Question
Title: Shipping price for different countries using Commerce Kickstart
I'm using commerce\_kickstart distribution.

I need to set different prices for shipping products to different countries. Ex: France -\> 10€, Spain -\> 15€...

I guess I have to create a rule at: admin/commerce/config/shipping/calculation-rules but I don't know to create a condition to check over the selected Country in the Shipping Information filled by the buyer.

I think I saw a video about this at http://vimeo.com/31586256 but i can't find it though.

# Answer
> 1 votes
An easy solution is to create multiple flat rate shipping methods. As each of them is create as a rule, you can add different conditions to them, being the value of the contry in the shipping address.

Commerce shipping with then only present the user for the flat rate shipping that has the correct contry, and the price you setup will then be applied.

---
Tags: commerce
---


title: Add fee to total order balance once

text:
# Question
Title: Add fee to total order balance once
Is there a way to add fee to total order balance once, based on some conditions? The product pricing rules are added for each product. I need this to be a price component, so it needs to be displayed as fee on the total order display (not as an added product!).

# Answer
> 1 votes
This is a bit tricky, since the order total is calculated from the line items. Either you would need to add/remove a line item that has the fee, or you would need to add the price to the order after it has been loaded, using `hook_commerce_order_load`.

I would prefer the line item solution, as it is more robust, but it also requires more work, as you will need to define the line item and either create custom code for adding/removing it.

---
Tags: commerce
---


title: How to Import features back to database

text:
# Question
Title: How to Import features back to database
I have lots of feature modules in my site. I want to `import` it back to database for upgrade purposes. Any idea how can I do that?

# Answer
I used this patch from here - http://drupal.org/node/1014522#comment-5719202

After you patched it you can then use `drush features-import-all --yes` or `drush fia -y` to import features to database.
> 5 votes

# Answer
There is a patch in the works for this, Provide way to Import views/true exportables back to the database. I have given it a quick test and upgrading seemed to work out fine, however, that particular project ended up with building a new site from scratch anyway, so I haven't used it a lot.
> 4 votes

# Answer
You can use the features tools module to import the features from code back to the database.

Note : This will really help the performance of the site.
> 2 votes

---
Tags: 6, updating, features
---


# Question
Title: Views filter: Filter by number of field values
Is there a way in Views to create a filter that shows nodes by number of values for a field? For example, to create a view of nodes, showing only those with two or more terms from a given vocabulary?

# Answer
> 1 votes
did you look if you have access for your designated field to the **"delta"** version of this field ?

This will do the trick.

If you don't, I'd advise to use **aggregate** and **COUNT** values of the field. Will work the same. Create a filter with that field, activate aggregation, count.

---
Tags: views, entities
---


# Question
Title: Why node custom fields weren't saved when adding node programmatically?
On node insert I want to save another node with data taken from first node into other Drupal database. The node in second site has 3 fields: title, image field, is\_public. Both Drupal installation shares same files directories.

Code:

```
$node = new stdClass;
$node->type = GALLERY_IMAGE_TYPE;
node_object_prepare($node);
$node->is_new = True;
$node->language = LANGUAGE_NONE;
$node->title = $file->filename;
$node->uid = 1;
$node->status = 1;
$node->{GALLERY_IMAGE_FIELD_NAME}[LANGUAGE_NONE][] = array(
    'fid' => $file->fid,
    'alt' => $image['alt'],
    'title' => $image['title'],
);
$node->{GALLERY_IMAGE_PUBLIC_FIELD_NAME}[LANGUAGE_NONE][]['value'] = $is_public;
node_save($node);
db_set_active();

```

$node structure before node\_save is similar to node structure created from admin panel and dump on hook\_node\_view:

Dump from hook\_node\_view in second database:

```
[field_file_image] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [fid] => 9
                        [display] => 1
                        [description] =>
                        [upload_button] => Upload
                        [remove_button] => Remove
                        [upload] =>
                        [width] => 415
                        [height] => 332
                        [alt] =>
                        [title] =>
                    )

            )

    )

[field_file_image_is_public] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => 1
                    )

            )

    )

```

Node structure before node\_save:

```
    stdClass Object
    (
        [type] => image
        [status] => 1
        [promote] => 1
        [sticky] => 0
        [uid] => 1
        [created] => 1355514057
        [revision] =>
        [comment] => 2
        [menu] => Array
            (
                [link_title] =>
                [mlid] => 0
                [plid] => 0
                [menu_name] => main-menu
                [weight] => 0
                [options] => Array
                    (
                    )

                [module] => menu
                [expanded] => 0
                [hidden] => 0
                [has_children] => 0
                [customized] => 0
                [parent_depth_limit] => 8
            )

        [language] => und
        [title] => wyoming-rocky-mountains.jpg
        [field_file_image] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [fid] => 13
                                [display] => 1
                                [description] =>
                                [upload_button] => Upload
                                [remove_button] => Remove
                                [upload] =>
                                [width] => 415
                                [height] => 332
                                [alt] =>
                                [title] =>
                            )

                    )

            )

        [field_file_image_is_public] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => 1
                            )

                    )

            )

    )

$node structure after node_save:

stdClass Object
(
    [vid] => 13
    [uid] => 1
    [title] => wyoming-rocky-mountains.jpg
    [log] =>
    [status] => 1
    [comment] => 2
    [promote] => 1
    [sticky] => 0
    [nid] => 13
    [type] => image
    [language] => und
    [created] => 1355514057
    [changed] => 1355514057
    [tnid] => 0
    [translate] => 0
    [revision_timestamp] => 1355514057
    [revision_uid] => 1
    [rdf_mapping] => Array
        (
            [rdftype] => Array
                (
                    [0] => sioc:Item
                    [1] => foaf:Document
                )

            [title] => Array
                (
                    [predicates] => Array
                        (
                            [0] => dc:title
                        )

                )

            [created] => Array
                (
                    [predicates] => Array
                        (
                            [0] => dc:date
                            [1] => dc:created
                        )

                    [datatype] => xsd:dateTime
                    [callback] => date_iso8601
                )

            [changed] => Array
                (
                    [predicates] => Array
                        (
                            [0] => dc:modified
                        )

                    [datatype] => xsd:dateTime
                    [callback] => date_iso8601
                )

            [body] => Array
                (
                    [predicates] => Array
                        (
                            [0] => content:encoded
                        )

                )

            [uid] => Array
                (
                    [predicates] => Array
                        (
                            [0] => sioc:has_creator
                        )

                    [type] => rel
                )

            [name] => Array
                (
                    [predicates] => Array
                        (
                            [0] => foaf:name
                        )

                )

            [comment_count] => Array
                (
                    [predicates] => Array
                        (
                            [0] => sioc:num_replies
                        )

                    [datatype] => xsd:integer
                )

            [last_activity] => Array
                (
                    [predicates] => Array
                        (
                            [0] => sioc:last_activity_date
                        )

                    [datatype] => xsd:dateTime
                    [callback] => date_iso8601
                )

        )

    [cid] => 0
    [last_comment_timestamp] => 1355514057
    [last_comment_name] =>
    [last_comment_uid] => 1
    [comment_count] => 0
    [name] => admin
    [picture] => 0
    [data] => b:0;
)

```

I don't understand why custom fields are wipeout.

**EDIT**

Anyway I switched from node type to entity. The issue still present. I put test code to Drupal installation which is using database called 'gallery':

```
$e = entity_create('model', array('type' => 'image'));
$ew = entity_metadata_wrapper('model',$e);
$ew->field_entity_image_is_public->set(1);
$ew->field_entity_image->set(array(
    'fid' => 12,
    'alt' => 'alt',
    'title' => 'title',
));
$ew->field_entity_image_name->set('image name');
$ew->save();

```

It works ok, but when I try to use similar snipper in other installation:

```
$file = file_load($image['fid']);
unset($file->fid);
$file->uid = 1;
db_set_active('gallery');
file_save($file);
$e = entity_create('model', array('type' => 'image'));
$ew = entity_metadata_wrapper('model',$e);
$ew->field_entity_image_is_public->set(1);
$ew->field_entity_image->set(array(
    'fid' => $file->fid,
    'alt' => $image['alt'],
    'title' => $image['title'],
));
$ew->field_entity_image_name->set($file->filename);
$ew->save();
db_set_active();

```

Custom fields are not stored. Only record in file\_managed table is inserted correctly.

All Drupal installations are on the same server so I thought that I can just switch to other installation database, but now I start thinking about using somekind of web service but it is pointless in this case :/

# Answer
> 4 votes
The quick answer is this - Do a `field_info_cache_clear()` call just before you flip the database and the fields for the node should be set correctly in the target site as well i.e.

```
field_info_cache_clear();
db_set_active('other');
module_list(TRUE); // optional, if the two sites have different sets of modules enabled..
// Do your stuff here..
db_set_active('default');

```

Having said that, let us try to understand the fundamental problem here and why I think it is a bad idea to be doing this in the first place. The problem is *static caching*.

Two different Drupal sites may be different from each other in numerous ways - different set of active modules, themes and entities, different set of fields attached to content types with the same name, different values for variables (configuration) and so on. These differences typically lie in the respective databases that the sites connect to.

Now, when we we flip the database using `db_set_active()` in the middle of the page request, our assumption is that all future method calls will be against the other database. However, this is not entirely true. We forget that a lot of *getter* methods statically cache data fetched from the database during Drupal bootstrap. Examples include `module_list()`, `entity_get_info()`, `module_implements()`, `_field_info_collate_types()`, `_field_info_collate_fields()` and many more. As the bootstrap phase has already passed by the time you flip the database, these static caches of these methods will not be cleared by Drupal automatically and is the responsibility of the developer to do so before flipping.

Not only is it not practical to lookup all methods that statically cache data and are called just before you flip the database, but some of them don't use the `drupal_static()` global store for cached data as well making it tougher to clear their caches elegantly. Now, add contributed modules to the mix and your application becomes extremely unreliable and super hard to debug. The only way you can circumvent this reliably is by bootstrapping the target site also. However, this is both expensive and assumes that both sites are running off the same code-base. (Drupal multi-site)

So, one has to be super careful while flipping the database when a page is being served. I would recommend not making any module/theme API calls and sticking just to the core Database API to simply read/write to/lookup. For your use case, one way I can think of, is to dump information about the node to be created from the source database to a temporary table in the target database and set off a trigger in the target site to fetch entries from that table and create nodes from them locally.

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


title: Is there an API for this?

text:
# Question
Title: Is there an API for this?
I know about user\_access API. I've written a module that should display some information only if the user has specific rights on the taxonomy.

To be more precise:

* we've created a vocabulary, say `books`.
* in this vocabulary `books` we have a lot of terms, say for example `children` and `cooking`
* we've created roles *according to the terms*, i.e. roles like `role for children` and `role for cooking` =\> one role = one term.
* now I've written a module that should diplay a link to 'edit' or 'create' **only** if the user is logged, **and** if he has the rights based on the role (which heavily relies on the taxonomy access rights).

In short: in my `node_view` hook:

* I have to check if it's a node with `books` vocabulary.
* if so, I have to read the associated term (there can be only one), let's take an example: `children`
* if the user is logged in **and** has the permissions of editing nodes with the specific term (`children` here), the I display a text with a link like `edit this book` and another like like `create a children's book`.

This is only the last part that is a problem to me.

Does the user access API call works flawlessly, and takes in account those rights, or do I have some specific calls to do? No API seems available for the taxonomy access control (TAC).

Maybe you have an example somewhere (didn't find one actually)?

# Answer
> 1 votes
Are you actually having a problem with user\_access or just asking before you're trying it? I'm not really following what exactly is your problem.

Taxonomy Access Control should influence what user\_access returns. Or you could just set permissions for "Use contextual links" and let Drupal take care of it with contextual links instead of writing a custom module.

---
Tags: taxonomy-terms
---


# Question
Title: How to cleanup Wordpress media tags after migration?
After migrating from Wordpress to Drupal with the Wordpress Migrate and Migrate modules, content still contains media tags:

```
[[{"type":"media","view_mode":"media_large","fid":"4202","attributes":[{"class":"media-image","typeof":"foaf:Image","style":"","width":"339","height":"305"}]}]]

```

What is the best way to strip them out?

# Answer
Ah found the answer after some digging:

> You have the Media module enabled, so the migration renders image references as media tags - you need to change your filter to interpret the tags

http://drupal.org/node/1859458#comment-6819442

> You have the Media module enabled, correct? And you're saying when you view (not edit) the nodes you're seeing the media embeds (\[\[{"type":"media"," etc.) instead of the image itself? Please go to /admin/config/content/formats and make sure that the text format you've chosen for the imported bodies has "Convert Media tags to markup" enabled.

http://drupal.org/node/1642352#comment-6136596
> 1 votes

---
Tags: migrations
---


# Question
Title: How do I install Commerce Kickstart as a Aegir installation profile
I have been trying to get the most recent version of Commerce Kickstart to install as a profile in Aegir, but I have had no luck. I found the following note on the Aegir project site, and this note in the Commerce Kickstart issue queue. Has anyone gotten this to work?

# Answer
> 1 votes
If you download the .tar.gz from http://ftp.drupal.org/files/projects/commerce\_kickstart-7.x-2.0-rc4-core.tar.gz into your platforms directory on aegir, untar it, and then create a platform with the same name you can build sites using the commerce kickstart profile with aegir. Here are the commands I used:

```
cd /var/aegir/platforms
curl -O http://ftp.drupal.org/files/projects/commerce_kickstart-7.x-2.0-rc4-core.tar.gz
tar xzf commerce_kickstart_7.x-2.0-rc4-core.tar.gz
mv commerce_kickstart_7.x-2.0-rc4 commerce-kickstart
chown -Rf aegir\: commerce-kickstart

```

Then go into Aegir and create a platform. Set the platform directory to this commerce-kickstart directory and don't include a build file. It'll verify the platform and then you'll be able to create sites on there using the Commerce Kickstart installation profile.

Cheers, Diwant

---
Tags: distributions, commerce, aegir
---


# Question
Title: Export news items (including pictures etc.) from Drupal to SQL
I would like to export newsitems from Drupal including images to import them into a whole different database.

Is there any module or whats the best way to create an export from Drupal to a SQL, CSV file?

# Answer
Try Node Export.

> This module allows users to export nodes and then import it into another Drupal installation, or on the same site.
>
> Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.
>
> You will need the same content types for the imports to work (unless using Feeds to import), and ideally relevant compatibility with fields, and modules.

**Node export formats**

The format to export with is configurable, and the Node export package comes with the following formats:

> JSON - JavaScript Object Notation code which is known for being security friendly. (Drupal 7 only)
>
> Drupal var export - A Drupalized PHP array which is similar to var\_export(). (Drupal 7 only)
>
> Node code - A customized PHP array which is similar to var\_export(). (Drupal 6 only) CSV - RFC4180 compliant CSV code. Ideal for viewing in Windows software, and editing data as spreadsheets.
>
> Serialize - Very robust, though not human readable, representation through Serialization using the PHP serialize function.
>
> XML - XML 1.0 representation which is good for machine-readability and human-readability.
> 1 votes

---
Tags: importing-exporting
---


# Question
Title: How to dynamically create a view, and then export to PDF
I'd like to dynamically create a view for each of my content types/items, and then export that View's data to PDF format.

My (Drupal 7) website tracks mileage, gas usage, engine usage, and other items for a fleet of cars. Let's say I want to run a report on Car A. I'd like to have a single view that could pull in only the information for Car A when I click a link on Car A's content page. Then, if I click a link on Car B's page, it would pull in only the information for Car B. The same would be true for Engine A, Engine B, etc. The purpose would be to see a snapshot of the usage of that car, engine, etc.

I use the Entity Reference module to link individual usage content items to each of the "master" content items (cars, engines, etc). The Usage content items have the following fields: the VIN/serial number of the car/engine (which links the usage content item back to the car/engine), miles driven since last visit, gas remaining since last visit, etc. These usage items are the most important thing for this usage report. There will be other fields from the Car, Engine, etc (such as the color of the car, starting mileage, etc) that will appear on the report, but those are really just information; the usage items are key.

Is all of this possible with Views out of the box? Or would I need an additional module to accomplish this?

Thanks!

# Answer
> 1 votes
I was able to get the output that I needed by using the Reference module and the Viewfield module.

1. Created Content type A and content types B, C, and D. B, C, and D are all associated with Content type A via Reference fields.
2. Created contextual/relationshipped views for B, C, and D, relating it to the title field of Content Type A.
3. Created a Viewfield on Content Type A for each of the sub-content types (B, C, and D).
4. Created a View for Content Type A, contextualized with Content:Title, and added the Viewfields to this new View (using reverse relationships with the node referenced field). I then added a PDF Page view using Views PDF, and that did the trick!

I can provide more detail if needed. Just let me know...

# Answer
> 0 votes
Views can do the basic reporting with some tinkering.

Look into these possible modules for outputting a PDF of a report view:

1. Views PDF
2. Print

---
Tags: views, log-messages
---


# Question
Title: Printing out translated Views' variables
I have a View, with its title translated to all enabled languages. When in tpl file I say: `print $views->human_name`, the title printed is stuck at the original language though. Any workaround for that, please?

# Answer
```
$title = $view->get_title();

```

Views' human-readable name is just for developers and is not translated by i18nviews. You might want to get title.
> 1 votes

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


# Question
Title: Setting base_url in a multidomain setup?
I have functionality that relies on having $base\_url set in the settings.php file, but I have a multidomain site in order to keep languages separate.

The sections of my site are www.mysite.com and www.de.mysite.com. If I set base\_url to "www.mysite.com" I get German language content on www.mysite.com.

How do I set the base\_url for a multi-domain, multi-lingual setup so that things like my image style generation can work correctly?

This is a single install, not multisite.

# Answer
It looks like you have 1 site in `sites/www.mysite.com` in your drupal setup and are trying to avoid having `sites/www.mysite.com` and `sites/www.de.mysite.com` ... ? So you're trying to edit 1 `settings.php` file.

You could create the above drupal sub-sites .... or try this less invasive approach.

Create a `sites.php` file if you're using Drupal 7 (you didnt specify your drupal version).

See this documentation page on sites.php It allows you to define configuration folders (where settings.php lives) per site in an array. This file is placed at `DRUPAL_ROOT/sites/sites.php`

```
// contents of sites.php
// URL = folder in sites directory.
$sites['www.mysite.com'] = 'mysite.com';
$sites['www.de.mysite.com'] = 'de.mysite.com';

// make a settings.php with unique $base_url in each directory above.

```

@kalabro's response is basically the same, except this is trumping the auto-discovery behavoir and making the settings directory explicitly set in PHP code.
> 3 votes

# Answer
I guess you need separate settings.php file for each site. You can create special folder for each domain in your `sites` directory and set custom `$base_url` in each settings.php file.

```
.
+-- all
¦   +-- modules
¦   +-- README.txt
¦   L-- themes
+-- default
¦   +-- default.settings.php
¦   +-- files
¦   L-- settings.php
L-- de.mysite.com
    L-- settings.php
L-- ru.mysite.com
    L-- settings.php

```

Documentation about site folders: http://drupalcode.org/project/drupal.git/blob/c5d6e6334fb7a71ecf1dbc7e06a7de8ad9547b27:/sites/default/default.settings.php#l25
> 4 votes

---
Tags: configuration, uri
---


# Question
Title: How to filter a view relating node and user data?
I created a content type called **Vouchers**. This content type has a field called: **Points**.

In the other hand I enabled the http://drupal.org/project/Userpoints module which allows users to get points.

I created 2 Vouchers nodes. One of them has the value 10 for the **Points** field and the other one 15

After, I created a view to show the content type: **Vouchers**. Now I need to add a filter to show the vouchers node only if its **Points** field value is lower than the **User points** value (the current logged user)

Please, look my capture to make this understandable:

# Answer
You can add the same filter programmatically to your view.

```
/**
 * Implements hook_views_pre_view().
 */
function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_view_machine_name') {
    $info = array(
      'table' => 'field_data_field_points', // name of your “Points” field table.
      'field' => 'field_points_value', // name of value field in that table.
      'value' => array('value' => userpoints_get_current_points()), // dynamic part.
      'operator' => '<',
      'id' => 'field_data_field_points_YOURMODULE', // unique id.
      'group' => 100, // new group.
    );
    $handler = views_get_handler($info['table'], $info['field'], 'filter');

    $handler->init($view, $info);
    $view->display_handler->handlers['filter'][$info['id']] = &$handler;

    unset($handler);
  }
}

```

It will automatically join the table and add condition to query.
> 3 votes

---
Tags: views, userpoints
---


# Question
Title: Display a field for a specific amount of time
I'd like to place a small overlay on my video called "New". So I downloaded the date module and added a date field to my video content type.

Anyone know if its possible to then output the date field (which I can style with CSS) only for a certain period of time like a week or two? After a set date the field would not be output.

Thanks guys!

Update: I have found a module called fieldscheduler that will schedule a field, but I cannot schedule a specific node, only all nodes that use that field. So close!

# Answer
Field Formatter Conditions should do what you want with perhaps a little tweaking/Rules manipulation.
> 0 votes

# Answer
I don't know what format your date field uses so you'll have to adjust for that, but something along the lines of

```
if(($content['field_date'] >= $first_date) && ($content['field_date'] <= $second_date)) {
  print render($content['field_date');
} else {
  print($wrong_date_message);
}

```

...where `$first_date` and `$second_date` are the beginning and end of the date window for which you want to display the field, and `$wrong_date_message` is whatever you want to show up there instead when the field isn't displayed.

For more information about date formats in PHP, check out http://php.net/date.
> 0 votes

---
Tags: 7, theming, entities, datetime
---


# Question
Title: Determine Array Key For Field Type Programatically
Different fields have different keys for the actual 'value' of the field. For example a regular text field has:

```
$node->field_my_text_field[$node->language]['value']

```

Whereas if I have a field using the email module, it looks like this:

```
$node->field_my_email_field[$node->language]['email']

```

I'm working on a function that saves a whole bunch of fields, and I want it to be as flexible as possible, it has a loop that looks like this:

```
foreach($person_details as $k=>$detail) {
    $node->{'field_'.$k}[$node->language][0]['value'] = $detail;
}

```

This is no good at the moment since 'value' is hard coded, and I have some fields in there that use 'email' and a few others from various modules.

Is there any way to know in advance what the key should be?

# Answer
> 0 votes
My solution ended up being this:

```
$field_structure = field_info_field($field_name);
$keys = array_keys($field_structure['storage']['details']['sql']['FIELD_LOAD_CURRENT']['field_data_'.$field_name]);

```

This gives an array of all the posible data columns for $field\_name, where $field\_name is something like 'field\_my\_field'.

---
Tags: entities
---


title: Some nodes totally inaccessible

text:
# Question
Title: Some nodes totally inaccessible
A great many of my nodes are not showing up at all on their node page (e.g. mysite.com/node/1234) but they are showing up in views, and they do exist in the database. What could cause a node to be unable to be viewed or edited on its node page, but still show up in Views and the database?

To clarify, "Not showing up at all" means I get a 404. I have cleared all caches.

# Answer
> 0 votes
I tracked it down.

`Node_load()` was dying whenever the query it was trying to run, failed. The query failed because it was joined on the UID of the author, and some users had been deleted. Lists of content that didn't use `node_load()` yielded the node's info without incident.

---
Tags: views, nodes, database
---


# Question
Title: How do i use a renderable array to create a list with children render arrays
I have a function which returns a facebook wall feed. The data comes back fine but the point i'm having an issue with is combining the list children with the list array.

I start out by defining the list without children.

```
   $row = array(
    'item_list' => array(
      '#theme' => 'item_list',
      '#attributes' => array(
        'class' => array('wall-post-list')
      ),
    )
  );

```

After that i jump in to a foreach loop which i'll omit for clarity since it's large. First i create a container which will be inside the li of the list and then stuff that container with children like i did with 'account\_link' which will be rendered as #markup FAPI elements.

```
     $list_items[$interation]['data'] = array(
      '#theme' => 'container',
      '#attributes' => array(
        'id' => array($post['id']),
        'class' => array('wall-post-content', $post['type']),
      ),
      'account_link' => array(
        '#markup' => l('<img class="user" src="http://graph.facebook.com/'. $post['from']['id'] . '/picture" />','http://facebook.com/' . $post['from']['id'], array(
          'attributes' => array(
            'class' => array('picture'),
            'target' => '_blank',
          ),
          'html' => TRUE,
        ))
      ),
    );

```

So after building up what this list item is going to have in it I take the $list\_items and stuff them into $row\['#items'\]. And now this is where my issue is. The array looks perfect almost to perfect... And when it renders to the page i get

```
<li>Array</li>

```

Is there some issue with my approach? or does theme\_item\_list not render out the children of a li and if so how can I get this to render recursively through the whole array?

Full function code here http://pastebin.com/dr3b4CTX

**Correction: seems i was using #theme rather than #type in this situation.**

# Answer
> 1 votes
I think what you are expecting is logical. But from the definition of `theme_item_list()` you can see that it expects value of the `data` key to be just HTML and hence prints it as it is. I could be wrong here and there is probably a `hook_preprocess_*` somewhere that pre-renders each item of the list.

Either way, an approach that should work is rendering your item before adding it to the list by calling `drupal_render()` yourself.

```
// .. your code .. //
$container_elem = array('#type' => 'container' ... );
$render = drupal_render($container_elem);
$row['item_list']['#items'][] = $render;
// .. your code .. //

```

---
Tags: 7, forms, theming
---


title: Drupal using panels with ajax

text:
# Question
Title: Drupal using panels with ajax
I have two questions.

I wish to build a website that will use a three column look. I was told to use panels, I found it easy to use.

My question is I have a menu bar, all menus point into different panels, the reason I do this every page I have has different blocks in it, some of these blocks point to sub-panels. (A., is there a "smarter way" of doing this?)

B., my main question how can I use ajax, so when somebody clicks any of the links on my menus only the panels reload, not the full site?

Regards,

# Answer
> 1 votes
For this to work you might have to restructure some of your blocks into mini panels but you could implement this module, Panels Ajax Tabs. Ajax can now be used when loading content via panels, either as a tab or container.

> Provides the ability to have a tabbed panel-pane that displays mini-panels within it.

If you require more control; instead you could utilize Ctools AJAX. Of course this is a much more hands on approach.

Hope this helps,

---
Tags: ajax, panels
---


title: meta tags not appearing

text:
# Question
Title: meta tags not appearing
I am using Drupal 7, and I have strange problem with meta tags. For some content type even if I enter meta title, meta keywords and description, they don't get effective on page.

Where in for some content type it does reflect the meta information.

How can I narrow down the problem? I have no idea how I can make use of meta tag quick module for my problem because meta information is not getting generated.

How can I debug where the problem exists?

# Answer
> 2 votes
I searched for this a while and found some solutions.

The thing is make sure you have rendered the `<?php print render($page['content']['metatags']); ?>` in page--front.tpl.php

# Answer
> 0 votes
You should try to use the Devel module. This should help you debug and narrow down the problem.

# Answer
> 0 votes
do you use display suite on the content type where you have problem. If yes, you should read this post and apply the patch. You must use the full display and not the default display to get the meta tags on yours pages.

---
Tags: 7, meta-tags
---


title: Ajax upload in Ctools Modal Window

text:
# Question
Title: Ajax upload in Ctools Modal Window
I have node creation form in a popup dialog box. I decided to give it a try using ctools modal window. But I seem to be getting errors when I upload an image into a image field after using browse to select it.

```
Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'node_form' was given in drupal_retrieve_form() (line 795 of /var/www/html/test/includes/form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1193 of /var/www/html/test/modules/comment/comment.module).
Notice: Trying to get property of non-object in comment_form_node_form_alter() (line 1210 of /var/www/html/test/modules/comment/comment.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /var/www/html/test/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /var/www/html/test/modules/menu/menu.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /var/www/html/test/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /var/www/html/test/modules/menu/menu.module).
Notice: Undefined index: field_artwork_image in file_ajax_upload() (line 271 of /var/www/html/test/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /var/www/html/test/modules/file/file.module)

```

Below is my code

```
function portfolio_cust_node_add_modal_callback($js = FALSE) {
  global $user;

  //If people are not using JS. I just tell them "sorry" it is '2012'
  if (!$js) return "Javascript required";
  ctools_include('node.pages', 'node', '');
  ctools_include('modal');
  ctools_include('ajax');

 // Create a blank node object here.
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => 'psuedo_portfolio',
    'language' => LANGUAGE_NONE,
    );

  $form_state = array(
    'title' => t('Add Portfolio'),
    'ajax' => TRUE,
  );
  $form_state['build_info']['args'] = array($node);
  drupal_add_library('system', 'ui.dialog');
  // change this to your type node form
  $output = ctools_modal_form_wrapper('psuedo_portfolio_node_form', $form_state);

  // This means the form has been exectued
  if (!empty($form_state['executed'])) {
    $output = array();
    // Close the modal
    $output[] = ctools_modal_command_dismiss();
  }

  print ajax_render($output);
  exit;

}

```

I am planning to use colorbox module or some other method which uses a iframe instead of how ctools implements the modal dialog.

Any help will be greatly appreciated.

# Answer
> 4 votes
I faced the same problem, and I managed to solve it using merlinofchaos's suggestion. I used `form_load_include()` just after form\_state initialization:

```
  $form_state = array(
    'title' => t('Add new deal'),
    'ajax' => TRUE,
    'node' => $node,
  );

  $form_state['build_info']['args'] = isset($form_state['build_info']['args']) ? $form_state['build_info']['args'] : array($node);
  form_load_include($form_state, 'inc', 'node', 'node.pages');

```

# Answer
> 0 votes
this fixed for me:

http://drupal.org/node/1336212#comment-6049694

Add the following lines to a `hook_menu_alter()` implementation:

```
$items['file/ajax']['file'] = 'node.pages.inc';
$items['file/ajax']['file path'] = drupal_get_path('module', 'node');

```

---
Tags: chaos-tool-suite, javascript
---


# Question
Title: Adding a field without the field_ prefix (Drupal 7)
I am using the organic groups module which adds a field with machine name: group\_audience to the user entity which can be seen at:

```
/config/people/accounts/fields

```

Somehow after install some other modules, this field disappeared. I would like to add it back the field's machine name was simply group\_audience instead of field\_group\_audience.

When I try and create a new field with the Drupal 7 interface builder it always prepends field\_ to any field that is create. How can I create a field that does not have the field\_ prefix?

# Answer
The Organic Groups module has a nifty API method for this. You just need to do a:

```
og_create_field(OG_AUDIENCE_FIELD, 'user', 'user');

```

This first checks if the field exists and creates it if it doesn't, then checks if an instance of the field has been attached to the *user* entity and creates it if it doesn't.

You can check this answer out to understand where and how you can run this snippet from.
> 3 votes

# Answer
You can add fields without prefixes with drush field-create command or by using Remove field name prefix module.
> 2 votes

---
Tags: 7, users, organic-groups, entities
---


title: Print custom user fields

text:
# Question
Title: Print custom user fields
I want to display a custom field, and i've done it with this code

```
<?php
 global $user;

 $user_fields = user_load($user->uid);

 $customfield = $user_fields->field_navnn['und']['0']['value'];

 print  t("Custom field value is " . $customfield. ' ') ;
?>

```

but it dosn't show when im logged out. Thanks

# Answer
> 1 votes
You are using the global variable $user which represents the logged-in user.

> An object representing the user currently visiting the site.
>
> Contains preferences and other account information for logged-in users. When a user is not logged-in, the $user-\>uid property is set to 0.

You could use the user id from the URL on the user profile page by calling `arg(1)`. Here is the possible fix for your code:

```
<?php
 $uid = arg(1);

 $user_fields = user_load($uid);

 $customfield = $user_fields->field_navnn['und']['0']['value'];

 print  t("Custom field value is " . $customfield. ' ') ;
?>

```

I do not concern with your user profile template. This is just for your code fix.

# Answer
> 0 votes
That is because you are doing:

```
      global $user;

```

and loading the fields of user which will load fields of only logged in user.

If you are printing it on user profile , then you can directly do the following in your `user-profile.tpl.php`.

```
  $customfield = $field_navnn[0]['value'];

```

and then print it.

---
Tags: users
---


# Question
Title: Can any of the cache_* be emptied safely?
Sometimes when moving the database it can be too large. Can any of the "cache\_" prefixed tables be emptied without causing problems?

# Answer
With one exception, yes. That exception is `cache_form`. That is not actually a cache table but contains temporary $form\_state information of forms currently displayed on your site. Clearing that table would invalidate these forms and when a user then tries to submit that form, he will get an error message and has to fill out that form again.

Note that `drush sql-dump` and Backup and Migrate automatically leave out the content of these and other tables when creating a database dump with these instead of mysqldump or phpmyadmin.
> 14 votes

# Answer
There's a "false friend" in that list. cache\_form is not a cache table, and emptying it will invalidate all forms active on the site at that moment.

I also don't see a reason why you would use phpmyadmin for this. It is clunky and error prone. "drush cc all" is your friend :)
> 4 votes

# Answer
The purpose of the cache tables is keeping computed values. When a module calls cache\_get(), and it gets back an empty value, then it just executes the code to obtain back the cached values.
All the modules I know automatically execute the code to get the value they were expecting in the cache, if the cache is empty; emptying the cache doesn't cause any problem to the modules using it.
> 3 votes

# Answer
I have done it many times and haven't find any problem by doing it.

Important notice - try to clear **all** cache tables at once. This will prevent Drupal from using invalid cache data.
> 3 votes

---
Tags: database, caching
---


# Question
Title: Custom Views Bulk Operation using Batch API
I am using `Views Bulk Operation` for updating custom value. I created a custom Operation using `hook_action_info`. How can I use `Batch API` with my custom action if I have to Operate on maximum nodes.

# Answer
Go to VBO settings (when editing the view, next to Style: Views Bulk Operations) and for your operation select the "Use Batch API" radio button under "To execute operations".
> 2 votes

---
Tags: 6, views
---


# Question
Title: echo() doesn't output anything for anonymous users
I am working on my own form module for Drupal 7.

I tried to set some default text depending on a cookie was set or not. It works perfectly as long as your are logged in; once you are an anonymous user, it doesn't read/write the cookie.

I tried to debug this by putting in a few calls to `echo()`, and `drupal_set_message()`, but they are only shown when I'm logged in; they don't show for anonymous users. I can't figure out why.

Can anyone help me with this?

This is the code I am using.

```
$serviceType = "";
$serviceName = "";
if (isset($_COOKIE["kms_hoststring_name"])) {
  $serviceName = $_COOKIE["kms_hoststring_name"];
  $serviceType = $_COOKIE["kms_hoststring_type"];
}
drupal_set_message("test");
echo "TEST";
$form['serviceType'] = array(
  '#type' => 'textfield',
  '#title' => t('Service Type:'),
  '#default_value' => t($serviceType),
);

$form['serviceName'] = array(
  '#type' => 'textfield',
  '#title' => t('Service Name'),
  '#default_value' => t($serviceName),
);

//Deletes cookies after use.
echo "TEST1";
if (isset($_COOKIE["kms_hoststring_name"])){
  setcookie("kms_hoststring_name", "", time()-60000, "/");
  setcookie("kms_hoststring_type", "", time()-60000, "/");
  echo "TEST2".$_COOKIE["kms_hoststring_name"];
}

```

None of the `echo()` or `drupal_set_message()` calls output anything for anonymous users.
When I log in, I see the output of those function calls.

# Answer
Drupal have much better tools for debugging than echo. You can sent a message to the watchdog log with the watchdog function. And if you install the devel module you get a few more funcions like dpm() to easily send messages or dd() to write onto the drupal debug log.
> 2 votes

---
Tags: forms
---


# Question
Title: Change the height of the ckeditor text window
If I try to change the height and style of the ckeditor text window with css then I find there are numerous layers to the css which makes it difficult to style. Is there a width and height setting in the settings which I can modify?

# Answer
> 2 votes
You should give this a go...

```
/**
 * Set a class on the iframe body element for WYSIWYG editors.
 * This only works for the WYSIWYG module: http://drupal.org/project/wysiwyg
 */
function adaptivetheme_wysiwyg_editor_settings_alter(&$settings, &$context) {
  $settings['bodyClass'] = 'wysiwygeditor';
}

```

---
Tags: wysiwyg
---


title: Referencing theme from block

text:
# Question
Title: Referencing theme from block
We are complete newbies to Drupal, so please forgive us if this is a stupid question. We have googled and googled and cannot come up with an answer.

Basically, we've got a block that has been placed in a region (Hooray, we got that far!) The problem is that we need to reference an image file that is in the sites/all/themes/\[theme\]/img directory. We have hardcoded this for now, but is there a placeholder that we can put in the block content area that will automatically fill in that path?

Are we going about this in the completely wrong way? We are both very impressed and very overwhelmed with Drupal all at the same time.

Thanks in advance for your help.

# Answer
> 0 votes
If you have image file in each theme folder use option 1,otherwise it is place in particular theme folder use option 2.

1. Better use path\_to\_theme() function to get current theme path.ex: sites/all/themes/test Note: please use php as the input format for your block.
2. use drupal\_get\_path('theme','test') for image is placed only in this theme folder.

---
Tags: blocks
---


title: Flag Friend (D7): add link in block

text:
# Question
Title: Flag Friend (D7): add link in block
I have created a custom block (that resides with path visibility of `users/*`).

I have written some PHP code to allow users to message each other (D7 Privatemsg module):

```
<?php
// Get user object.
if ($account = menu_get_object('user')) {
  if ($url = privatemsg_get_link(array($account))) {
    return l(t('write a mail to this user'), $url, array(
      'query' => drupal_get_destination(),
    ));
  }
}
?>

```

In that same block, I would like to add another snippet to show a Flag Friend link. This would give me one block with two links: one for mail, one for adding/removing friendship.

Does anyone know the PHP code for flagging a friend?

# Answer
> 1 votes
I think the method below should do the trick. Don't think it is available in the `flag_friend` module's API.

```
/**
 * Gets the friend/unfriend link for a given user.
 *
 * Depending on the flagging user's current friend status with the target
 * user, the label of this link will show up as 'Add friend' or 'Remove friend'.
 *
 * @param stdClass $account
 *   Target user object. Defaults to the currenly logged in user.
 *
 * @return mixed
 *   FALSE or
 *   Formatted flag/unflag link otherwise.
 *
 * @see flag_friend_flag_default_flags().
 * @see flag_create_link().
 */
function flag_friend_get_friend_flag_link($account = NULL) {
  if (!isset($account)) {
    global $user;
    $account = $user;
  }
  return flag_create_link('friend', $account->uid);
}

```

Do note that the flagging user is assumed by default to be the currently logged in user which fits your use-case anyway.

Access check happens implicitly. So, if the current user does not have access to friend/unfriend a given target user, then this method will return `FALSE`.

---
Tags: 7, blocks, navigation, flags
---


title: problem with hooking node add/edit form

text:
# Question
Title: problem with hooking node add/edit form
I wanted to hook `node/add/patient-history` form because I wanted to add ajax in that form.

Before adding Ajax I wanted to **get field names correctly**. So I tried this:

```
function ajaxify_form_patient_history_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_history_patient_id']['und'][0]['#value'] = "Hello";
  // I also tried
  $form['field_history_patient_id']['#value'] = "Hello";
}

```

They are not working.

I am not sure if I am taking the **field names incorrectly** or **missing something else**.

Hook name seems to be correct because this one works:

```
  $form['actions']['submit']['#value'] = t('Save History');

```

I found some similar questions on stackexchange but with no answers.

Any advice/links appreciated very much. Thank you.

# Answer
I use this in my module to prepopulate the forms with data when hooking on FORM\_ALTER:

```
$form['field_history_patient_id'][LANGUAGE_NONE][0]['value']['#default_value'] = "whatever";

```

But when defining the form it is enough to do :

```
$form['field_history_patient_id']['#default_value'] = "whatever";

```
> 1 votes

# Answer
Check Why is hook\_form\_alter so messy in d7?.

If you have Devel module installed, you can check your fields with `dpm($form)` in your hook or you can use `echo '<pre>'; print_r($form); echo '</pre>'`.

I hope this will help you to track down your element hierarchy and find out the correct attributes.
> 1 votes

# Answer
You need to set the #default\_value property. `$form['field_history_patient_id']['#default_value']`
> 0 votes

---
Tags: nodes, ajax, forms, debugging
---


# Question
Title: How to make textfield with ['#ajax']['keypressed'] = TRUE trigger only on click and not on blur?
When I specify `['#ajax']['keypressed'] = TRUE` for textfield, trigger runs not only when I click `ENTER` (as it is mentioned in documentation), but also when textfield loses focus (must be `blur` event in JavaScript). So how can I avoid this?

# Answer
> 1 votes
Maybe too late but for the others :

```
['#ajax']['event'] = 'none'

```

---
Tags: ajax
---


title: db_update() with joins

text:
# Question
Title: db_update() with joins
Is there any way to `db_update()` for the following query?

```
UPDATE field_data_field_TEST as ft
left join node as n on ft.entity_id = n.nid
set n.type='test'
where n.type='foo'

```

I tried using `db_update()->join();` but it didn't work.

# Answer
`db_update()` doesn't implement any interfaces that have `join()`/`innerJoin()`/etc. methods so I think you're stuck with using `db_query()` and writing the query string out manually.

```
$sql = "
  UPDATE field_data_field_TEST as ft
  left join node as n on ft.entity_id = n.nid
  set n.type = :type1
  where n.type = :type2";

$args = array(':type1' => 'test', ':type2' => 'foo');
db_query($sql, $args);

```
> 11 votes

---
Tags: 7, database
---


title: Display view block in custom field

text:
# Question
Title: Display view block in custom field
View block need to display in custom field and need to pass nid as a argument for that view block. Help me on this.

# Answer
> 0 votes
Solution: we can use insert\_view module to add view in CCK field.

---
Tags: views, 6
---


title: Huge cache_menu table

text:
# Question
Title: Huge cache_menu table
My Drupal database becomes very huge, it just related to cache\_menu table:

```
~4,291,529 rows and 2.9 GiB

```

What can I do to prevent this? is there any way to change cache strategy for menu items? or simply I should EMPTY this table every week?

# Answer
It has been a bug in Drupal, but should be corrected since Drupal version 7.13. See more details here: http://drupal.org/node/1234830

As a workaround, you can empty (truncate) the cache\_menu table, since it is just a cache table and will be regenerated. Of cource, you'll have a trade-off in performance, in that case.
> 4 votes

---
Tags: 7, caching
---


# Question
Title: On what event does the cron begin its execution?
I have a site which requires periodic tasks to be done (sending content update notification / subscription, etc); which are configured on cron run. The cron run is setup to run after every "3 hours" at *admin \> config \> system \> cron*.

I (user 1) did not visit the site for 10-12 days, while some of the other authenticated users did some activity like commenting / adding content. I have enabled notification emails whenever any user adds / edits any content or comment.

Last night when I logged into the site, I received notifications for the period of 10-12 days (period for which I did not log in to the site). While, as per the expected behavior I should have been receiving the notifications on the cron run after the user activity.

I checked to see the logs, and during this days I can see only the following message under the type "cron"

> Attempting to re-run cron while it is already running.

And strangely, I could see

> Cron run completed.

just before 5 secs of the message:

> Session opened for admin-user.

So, it is clear that I did not receive the notifications because the cron did not run during this period of time.

So, my question is why did the cron not run for these days? What is the exact event which triggers cron to start running? I understand that in Drupal 7 `cron.php` is called along with a token value to run the cron. But who / what does this call? Or do the Admin users need to log into trigger this action?

**UPDATE:** The site is on a dedicated server owned by the company. I have access to it as root user. And obviously don't have a cpanel to it ;-) And I have not set any other application to like crontab? Do I need to do so? If so how?

# Answer
> So, my question is why did the cron not run for these days? What is the exact event which triggers cron to start running?

Poormans cron is D7 default cronjob handler, which invokes cron hooks. But it depends on traffic, when a user visits a page it will check last time at which cron was run, and schedule it to run if needed according to interval set.

Summary : This is not reliable if cron has to be run daily. To do so open up crontab from terminal (`crontab -l` will list the jobs, `crontab -e` will let you edit jobs) Ex:

```
0 0 * * * wget -O - -q -t 1 http://<yoursite>/cron.php?cron_key=<yourkey>

```

Will schedule cron job @midnight daily.
> 3 votes

---
Tags: 7, cron
---


# Question
Title: Showing all results of custom content type in every page
Essentially we have a custom content type called "Slideshow" with "title", "content", and "image" as the three fields. We want our admins to be able to add new elements to the slideshow by simply adding new content with the slideshow content type.

Everything we have tried has failed miserably. All research indicates that we need to create a custom node template named node--slideshow.tpl.php and lay it out how we want (IE place the slideshow divs around our render($content\['field\_slider\_image'\]), etc... but how do we then insert that into our page template?

I apologize if this is a stupid question or if we're going about this in an odd way. The template has already been coded, so we need to be able let our admins add slideshow elements easily and have them show up on the front-end without them editing a "slideshow" block.

I hope someone can help us figure this out.

**Edit** \- Just stumbled upon "views" and that looks very promising because it allows us to set up a 'slideshow' view which automatically pulls in the content of our slideshow content type. If we go that route, how do we format the output?

**Edit 2** \- This slideshow will be at the top of the homepage only. Any other page will have the page title in that spot.

# Answer
> 0 votes
The simplest solution would be to to call views\_embed\_view in the page--front.tpl.php file (page-front.tpl.php in D6).

The more complex solution I would go with, is using Panels everywhere, and expose the View as a content pane.

---
Tags: nodes
---


# Question
Title: How to use field.tpl for rendered node in views3
i have set up a view (drupal 7) with a field that rendered the full node (node referenced field), and i want to get rid off the extra classes and tags wrapped around the fields.

i have copied field.tpl to my templates dir, and no matter what i name it it doesn't effect anything. I have selected that in the field settings in views. and yes, cleared the cache always.

would i name it after the content type. or the view. i even left it at just field.tpl and still nothing.

# Answer
If you want to override the views field template, the correct template file name would be views-view-fields.tpl.php.

You need to copy the template **sites/all/modules/views/theme/views-view-field.tpl.php** to your current enabled theme folder. Then update the file as you need.

Rescan template files in your view theming information. The file **views-view-field.tpl.php** should be highlighted with bold. You may need to fluch the cache. It is a view template to all the fields as a row.

If you want to theme a specific field, you could use **views-view-field--\[field\_name\].tpl.php**. It is the most specific view template. You can check more in Views theming.
> 1 votes

# Answer
The easiest way to find out what the templates should be is to use hook\_preprocess\_field() in your themes template file.

```
/**
 * Implements template_preprocess_field().
 */
function THEME_preprocess_field(&$vars) {

  // Check for template suggestions
  var_dump($vars['theme_hook_suggestions']);

  // Add a less verbose field name class: .field-NAME
  $vars['classes_array'][] = drupal_html_class($vars['element']['#field_name']);

  // Use .field-body instead of .body
  if ($vars['element']['#field_name'] == 'body') {
    $vars['classes_array'][] = 'field-body';
  }

  // Remove some classes from the wrapper <div>.
  $classes_to_remove = array(
    'field',
    'field-label-' . drupal_html_class($vars['element']['#label_display']),
    'field-type-' . drupal_html_class($vars['element']['#field_type']),
    'field-name-' . drupal_html_class($vars['element']['#field_name']),
    'body',
    'clearfix',
  );
  $vars['classes_array'] = array_diff($vars['classes_array'], $classes_to_remove);
}

```

The following has the information you want...

```
$vars['theme_hook_suggestions']

```

See: http://drupal.org/node/1089656

Theres a few examples above to edit/remove classes. You can then remove any wrappers divs and extra markup from the template.
> 0 votes

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


# Question
Title: Node teasers in node object filled with full node body if teaser is not defined
When Editor saves the Node, If teaser field is filled, normally teaser node object is filled with that content. But if Teaser field is not filled, System is populating teaser of node object with body of the Node.

That is kind of weird because i need to detect if node has teaser or not, programatically.

Is there a workaround how i could detect programatically that Node was saved without teaser has been touched ?

# Answer
You can check summary text in node obj.

```
if (empty($node->body['und'][0]['summary'])) {
//do something
}

```
> 2 votes

---
Tags: nodes
---