title: Drupal Views for 2 Title Styles

text:
# Question
Title: Drupal Views for 2 Title Styles
**Mock:** **Site**: http://www.mastersfunds.com.php5-23.dfw1-2.websitetestlink.com/funds-and-performance/equity-fund

**Brief:** The mock has the title with 2 font styles. The first part is in blue text and the fund/ticker is in a smaller, light gray font.

Is there a way to use VIEWS to display the TICKER font/html directly after the Title as displayed in the mockup? What VIEWS settings would I use?

# Answer
I think as a relatively new Drupal developer, you could benefit tremendously from getting to know CCK. This will allow you to have flexibility with how fields are laid out and ensure that page layouts remain consistent.

The way you've approached the task, I can think of two ways to get that ticker to show: using jQuery and using a theme function. If you know about `template.php` and theme overrides, I'd recommend that route. Otherwise, this should be doable with jQuery:

Using jQuery:

Place this in a js file:

```
$(function() {
    $('#block-quicktabs-fundsperformancetabs h2').append('<div class="ticker">MSILX, ETC</div>');
});

```

And in your stylesheet

```
.ticker {
    text-transform: uppercase;
    color: #CCC;
    font-size: 11px;
}

```

Be sure to include your js file in your theme's info file.

```
scripts[] = js/custom.js

```

This has the downside of being 'in the code' instead of editable by the client, but that's where CCK would come in.
> 1 votes

# Answer
Views is a tools to query and display data (most of the time nodes). While views is pretty flexible, its main and well documented usages are blocks and pages with data from the database. We don't have that much information, but it doesn't seems like you need to query your database to build a list of items to be displayed. You are rather looking for a way to display the fund/ticker information right after the title of the page.

IMHO, the proper way to do it is to have a `hook_preprocess_HOOK` implementation for the `block.tpl.php` template to retrieve the tickers information and store in the `$variables` array received as argument. Then in this template, display the information right after the title. The tricky part would be retrieving the tickers since you won't have that much information about the block context while in the `hook_preprocess_HOOK` implementation.

In your custom module `.module` file or in your theme's `template.php`

```
function MODULE_preprocess_block(&$variables) {
  $tickers = get_ticker_from_some_context();
  // Use a custom theme hook to format the tickers
  $variables['tickers'] = theme('tickers', $tickers);
}

```

In your `block.tpl.php`

```
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
  <?php if !empty($tickers):?>$tickers<?php endif;?>
<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>
</div>

```
> 1 votes

---
Tags: views, 7
---


title: Synchronize two drag-able tables

text:
# Question
Title: Synchronize two drag-able tables
I have two tables on a page that the row positions need synchronized when a row is drug. One table is the master table and is the only place that the actual dragging can take place.

Basically, what needs to happen is when the user drags a row in the master table, the changes in position need to be duplicated to the child table.
I've been poking around with the `onDrop` custom handler function, but I am about at my wits end.
I'm not willing to hack tabledrag.js, as my custom module will be deployed on a system that I don't manage.

I'm sure someone else has faced this same issue. Are there any suggestion for a solution?

# Answer
> 1 votes
Are you using the Draggable Views module? If so, you can set the child table to use the sort order of the dragged table, and possibly trigger an ajax refresh when the order of the master table is saved.

---
Tags: 6, javascript, theming
---


title: Drag function in Blocks is Gone

text:
# Question
Title: Drag function in Blocks is Gone
In one of my Drupal installations I suddenly noticed I can no longer drag and sort the order of my blocks. The image shows on the left the admin with now drag handles and a screenshot of another admin with the handles.

What could have happened? I think its AJAX/JavaScript related.

# Answer
> 2 votes
It's definitely js related, most likely a conflict/error from something in the theme or a contributed module. If you switch to a core theme, are the blocks draggable? If not, it's probably a module (or a script coming from somewhere else, like a block).

If you need to change block position ASAP, you can temporarily disable your browser's javascript, which should then cause the weight positioning drop-downs to appear, which you can use to adjust the order.

---
Tags: blocks
---


# Question
Title: How to post xml data in drupal_http_request? I have curl code of it
This is following curl code

```
    $ch = curl_init(); //initiate the curl session
    curl_setopt($ch, CURLOPT_URL, $url); //set to url to post to
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // tell curl to return data in a variable
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlrequest); // post the xml
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // set timeout in seconds
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $result['xml'] = curl_exec($ch);

```

How do I change the following code to use `drupal_http_request()`?

# Answer
> 7 votes
Seeing how drupal\_http\_request() is used in \_xmlrpc(), something like this should do it.

```
// The path to send the request
$url = "http://example.com/API_PATH_HERE";
// Example of valid xml code;
$xmlrequest = "<showId>0</showId><tag>123</tag>";

$response = drupal_http_request($url, array(
  'headers' => array('Content-Type' => 'text/xml'),
  'data' => $xmlrequest,
  'method' => 'POST',
  'timeout' => 10
));
// If there is no error return data
if (empty($response->error)) {
  $result['xml'] = $response->data;
}

```

---
Tags: http-request
---


title: Javascript assumed conflict with Drupal

text:
# Question
Title: Javascript assumed conflict with Drupal
I have a website, where I have been trying to build a form with server side and client side validitations of the input fields. More or less I have been achieving progress. Then I put my code from my testing enviroment to the drupal based website, to see how many tweaks do I need to make. Needless to stay lot of things fell apart. Most important at the moment is that my javascript checks if the input field has the correct information, if it does, it colors the input field and changes the helper thex accordingly. This got fully broken on the site. I read a lot and I assumed this may be cause drupal uses an older JQuery that which I was testing with. So with a little help in another question here I invoked the noConcflict and I used the newer jquery with my code. Sadly this did not fix my problem.

The html of the site is located here: http://www.htconsulting.hu/test/form The javascript: http://www.htconsulting.hu/form/validation.js

Ps.: After the noconflict, my popup Jquery UI broke as well, so I hope to find a possible solution outside using noConflict, or solving the popup window now...

# Answer
> 2 votes
You should use the jQuery provided by Drupal and try to work with what Drupal provides (JavaScript, Form API, Theme system, etc.) instead of trying to work without it or, worse, against it. The jQuery update module allow you to use updated jQuery releases in Drupal. That would be 1.6.2 for Drupal 7 and 1.3.2 for Drupal 6. Drupal 7 also provides jQuery UI while for Drupal 6, the jQuery UI module should be used to provide it. This way you can avoid compatibility issues between different version of the same library, unnecessary workarounds and fixes over fixes.

Also, you shouldn't use `$(document).ready()` in Drupal, but add your function to `Drupal.behaviors` as explained in the Drupal JavaScript API guide (also available for Drupal 6). And off course, for the form generation, validation and submission server-side code, you should use the Form API.

Keep in mind that your are trying to add a form to a Drupal site, not to a stand alone simple PHP script that doesn't already provides all the (server-side) API your need.

# Answer
> 0 votes
The problem appears to be that when you load jquery the first time, you call no-conflict and assign it to `$jq`. You then load jquery again, re-assigning `$` to this 2nd jquery (same version by the way) and after that you load jquery ui. This means that jquery ui is going to attach to the most recently loaded jquery (the one still using `$` and not `$jq`). So `$("#dialog").dialog()` should work, but `$jq("#dialog").dialog()` will not, because `$jq` does not have ui, `$` does.

From looking at this page, there is no need for `noConflict` at all, since both versions of jquery you are loading are 1.6.2.

# Answer
> 0 votes
Shameless pug, we created a module todo this, see http://atix.be/docv, the only thing we don't support for the moment is to display the errors in a popup, but feel free to open an issue

---
Tags: javascript
---


# Question
Title: User Relationships view showing each relationship more than once
I'm trying to display a users relationships through Views(3). I'm getting duplicates for accepted relationships. Also, the current user show's up under his/her own relationships. Here's what I got so far:

---

*Format*: Unformatted list
*Show*: Fields
**Fields**
*User*: Name
*User*: Picture

**Filter criteria**
*User*: Active (Yes)
(rtid) *User relationships*: Requester or Requestee is current user (True)

**Sort criteria**
*User*: Created date (desc)

*Block name*: None *Access*: Permission | View user profiles

**Contextual filters**
*User relationships*: Requester user // I've tried (rtid) here with the same result

**Relationships**
*User relationships*: Requestee user
*User relationships*: Requester user
*User relationships*: RTID

*Use AJAX*:Yes

# Answer
You can exclude current user from view by passing argument of current logged in user id and check exclude this argument from view.

You can avoid duplicates by enable distinct in basic settings.
> 1 votes

---
Tags: views, users
---


title: Streaming video integration

text:
# Question
Title: Streaming video integration
I'm looking for a solution for streaming video in Drupal 6. Ideally, I'd like to be able to have users upload video via a content type, convert and encode it, then have the published version be linked to a streaming server (like DSS). I want to host the streaming server myself and ideally I'd like it to be free.

I've never heard of it, but it seems there is also something called Kaltura that might work.

Anyone have experience in this realm? Know of something simple I could integrate?

The best I option I can see so far seems to be to display the video via jw player and write something custom to upload videos to the streaming server from those that are uploaded via drupal.

# Answer
> 0 votes
I did more research on this and I came up with an "easy", Drupal integrated solution. Hopefully this will help inform someone else looking for similar. My approach is as follows:

Convert videos to mp4 (H264) format and upload them natively to Drupal. In my case I plan on using the JW Player module. This will allow me to upload and embed videos using JW Player natively in Drupal.

I could have also used Flowplayer for this (and the flowplayer module).

I ended up deciding to use psuedo HTTP streaming for my video files (mp4). I could have used a streaming server, but it would have required more integration work. Here's a good article on the various streaming servers available.

In order to support psuedo streaming (basically, splitting up a video via HTTP), I am going to use an IIS 7 module for it. IIS is probably a less frequent case for Drupal, but there are modules for the web server of your choice available here.

# Answer
> 1 votes
I have used Navicast (but not a free) platform to develop a webtv module for Drupal 6. It is based on Output APIs. There are few limitation with the platform APIs that I reported. Navicast Studio a desktop application build around their input APIs used to upload video and adjust video properties. The platform has built in tagging system to categorize videos. Comments on video contents is also managed by the platform.

I used it with Flow Player API module.

I developed Web TV around my own entities.

---
Tags: 6, media
---


# Question
Title: Linking slideshow thumbnail to slideshow views content
I have a view containing pictures from a content type "Slideshow". When I click the Slideshow title in a view containing the slideshows, it takes me to the slides from that slideshow. However, I want to get rid of the title and be able to click the picture instead of the title so I can do the same thing. Could you please tell me how I could do that?

# Answer
> 1 votes
You will earn time by coding a small hook\_block() that calls your JavaScript plugin for your slideshows. Then, you will be able to configure easily your module and your link. Views can be really harmful when you try to do things like slideshows.

Just pick a jQuery plugin from the ones listed on 13 Super Useful jQuery Content Slider Scripts and Tutorials and the rest of the job will be easy.

# Answer
> 0 votes
If I understand your problem correctly you should be able to go to your view, edit the image field (the one that shows the Slideshow thumbnail), find the heading 'Link image to' and change it from the default 'Nothing' to 'Content'.

---
Tags: views
---


# Question
Title: Given a node object how can I detect if it's first term (or term in a chosen vocabulary) contains a taxonomy image?
Using php code and a node object, how can I detect whether or not the node's first term (or term in a chosen vocabulary) has a taxonomy image? Any help appreciated.

# Answer
`taxonomy_image_display` returns an empty string iff the term has no image.

Given a node `$node`, the terms are stored in `$node->taxonomy` as an array indexed by term ID (see `taxonomy_nodeapi($node, $op = 'load')`).
> 1 votes

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


# Question
Title: Which drupal hook to implement to react on module installation?
I have module A installed that defines some custom hooks. Module A wants to be notified when another module B is installed, so that it can inspect and see if module B implements its hooks (for building a cache of some info for example).

Is there a hook like "hook\_module\_enabled($module\_name)" ?

# Answer
You should do it the other way around.

When your module is enabled, it should check for other modules that has implemented it's hook and call them to build up the cache you need.

Then you could create an API function for other modules to call when their module is activated.

It makes more sense to build it like that. You never know when the cache is reset anyways, so you can never rely on having a complete cache data all the time anyways.

Another solution would be to build the cache when it's needed. It doesn't make sense to build the cache data before it's actually needed. The normal thing to do with cache in drupal is to check if the cache data is there, if it's not create it and save it in the cache for next time. That would spare you the headache of trying to know all.

To answer your question, there is to my knowledge not a way to hook into the process of modules being installed / enabled.

**Update:**
For Drupal 7 there have actually been created a hook to react on modules being enabled: hook\_modules\_enabled()
> 5 votes

# Answer
You should generally check for modules implementing hooks when you actually call the hooks, not before, by calling module\_implements() (to get a list of modules that implement the hook) or module\_envoke\_all() (to directly run the hook on all implementing modules).

That said, you can also tell modules that implement your hook that they need to notify your module when they're installed. content\_notify() does this for CCK, for example.
> 2 votes

---
Tags: 7
---


title: How can I un-subtheme a theme?

text:
# Question
Title: How can I un-subtheme a theme?
I've been developing a custom theme as a Zen subtheme, but I've made so many changes and new files that nothing from the original Zen theme is being used.

However, my new theme is still connected to the Zen theme and requires that it is installed on the server.

How can I detach the Zen parent theme and have my subtheme stand alone?

# Answer
> 5 votes
Remove “base theme” declaration from YOURTHEME.info

---
Tags: 6, theming
---


title: Using Blocks vs Template Edit

text:
# Question
Title: Using Blocks vs Template Edit
I have a banner and some social media buttons added through a template edit. I was wondering if it would be better to put it in a block or leave it as is. My goal is better performance.

# Answer
> 3 votes
Technically putting things straight into a template may have better performance.

However if you create a static block and make sure it is cachable on the whole site the difference will be negligible. There are many other ways to improve performance and this is right a the bottom of the pile.

There are many other things that you can do to improve performance. Taking the view of the site as a whole. The flexibility that a block gives you may give you may outweigh the performance gains you achieve.

---
Tags: 6, blocks, theming
---


# Question
Title: How do I add a child to an HTML Tag render element?
I need to reproduce this with render elements:

```
<div id="parent">
<div class="child"></div>
<div class="child"></div>
</div>

```

Can't figure this one out!

# Answer
Please see the drupal API page on this.

A simple example could be:

```
// Shows how #prefix and #suffix can add markup into an array.
t('Using #prefix and #suffix') => array(
  '#markup' => '<div class="child"></div><div class="child"></div>',
  '#prefix' => '<div id="parent">',
  '#suffix' => '</div>',
),

```

or you could use children

```
t('using children demonstration') => array(
  '#markup' => '',
  'child1' => array('#markup' => '<div class="child"></div>'),
  'child2' => array('#markup' => '<div class="child"></div>'),
  '#prefix' => '<div id="parent">',
  '#suffix' => '</div>',
),

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to “filter” out one specific user in a view?
I’ve a question regarding some of my blocks which I’ve made in views (using Drupal 6 and Views 2). One of the users on the site is the sites “manager” and so this user of cause writes a lot of posts, comment on a lot of posts and “likes” a lot of posts.

In some of my blocks I display the most contributing users and this “manager” is almost always on top of the list and I would like to display the most contributing users, but “ignore” this user.

My views are very simple and basic created. For example in one I list the most commenting users right now (that be, the last 24 hours) and I sort according to the comment count. In this example, how do I “filter” out the one user?

Thanks

Sincere
\- Mestika

# Answer
In your view filter out the user:

1. **Add relationships:** Node revision: User
**Label:** user
**Require this relationship:** (checked)
2. **Add filters:** User: Name
**Relationship:** user
**Is not one of:** manager
> 5 votes

---
Tags: views
---


# Question
Title: How to programmatically create a node when a payment is successful
I have a content type, and with the help of the UC node checkout module, I am able to successfully add the content to cart once it is created by the user. When the user checked out and had made a successful payment, I want to create another node of another content type.

```
function gy_mod_uc_checkout_complete($order, $account) {
  if ($order->order_status == 'payment_received') {
    exit();
  }
}

```

The above is not getting fired; I always get it as "in\_checkout." I tried doing it using the Paypal sandbox.

Does anyone have a suggestion on how I should write the code I need?

# Answer
Looks like `hook_uc_checkout_complete()` is called while the order is still in "in\_checkout."

You might want to consider using Ubercart's *Conditional actions* module and add an action for "Trigger: Customer completes checkout"; it allows you to execute actions based on a range of conditions. You can then either execute custom PHP code to create the node, or implement the `hook_ca_action()` (see "ubercart/ca/ca.ca.inc" for reference).

As to how to programmatically create a node, you can either use node\_save() or drupal\_execute(). There's quite a few tutorials around that you can use as guidance.
> 2 votes

---
Tags: 6, ubercart
---


title: Use variable from template.php in block

text:
# Question
Title: Use variable from template.php in block
I have a custom table in the Drupal DB, which I need to retrive and use on a few places on the site I'm creating. And I don't like to run soo much PHP in blocks, so I thought that I could get the table value I need, using PHP in template.php in the theme-dir and then just call the variable from a block, using PHP.

That didn't work.. Why and how should it be done?

template.php:

```
$sub_count = db_query("SELECT count FROM {sub_count}")->fetchField();

```

block:

```
<?php $sub_count; ?>

```

# Answer
You need to use a preprocess function. Take a look at template\_preprocess\_block(). In your template.php you can use:

```
function YOURTHEME_preprocess_block(&$variables) {
  $variables['sub_count'] = db_query("SELECT count FROM {sub_count}")->fetchField();
}

```

and can print into the .tpl.php file as you did above.

A few good articles to learn more about preprocess functions are

As a basic overview of preprocess functions, from the second article:

> Preprocess functions only apply to theming hooks implemented as templates. The main role of the preprocessor is to set up variables to be placed within the template (.tpl.php) files. Plain theme functions do not interact with preprocessors.
>
> Notes:
>
> * Preprocessors are also used for providing template suggestions.
> * In versions 5 and below, the function \_phptemplate\_variables served the same purpose. It has been deprecated in 6.
> * Prior to Drupal 6.7, for your theme to have its preprocessors recognized, the template associated with the hook had to exist inside the theme. When a default template exists, copy it to your theme and clear the registry (or you should really be upgrading to a later version of Drupal anyway for security reasons, at which point you don't have to worry about this).
> 2 votes

---
Tags: theming
---


# Question
Title: Show specific gmap in block based on node id
I am trying to show a gmap for a specific location, using the content: mapping coordinates for gmap in a view in drupal 7. The map itself shows fine in content for the page view, but if i clone it to block it shows all maps for that content. I cannot figure out how, without using php, to filter by the current node.

For example, node id 2 has coordinates so show the map for that node in the view for the block. and only node 2, not nodes 3,4,5,7.

I am really trying to do this using views and block and not php code in blocks.

# Answer
Add an argument to the view, the argument is the node ID, then you'll be able to retrieve fields and information only for the viewed node.

Example: http://through-my-eyes.be/portfolio/events/2011/04/07/drupal-government-days-2011
> 1 votes

---
Tags: 7, views, blocks, google-maps
---


# Question
Title: Users can't use a name in comments that is equal to the username of a registred user
I have a Drupal 7.7 installation for which I'm activating comments using the standard Comments module. Everything works just fine except for a annoying quirk.

The admin username is "Christoffer", and for some reason anonymous users can not use the name "Christoffer" for their comments. If I add an additional character or change the spelling it works but it seems that an anonymous user cannot have the same name as a registred user. Can I allow it somehow?

Thanks

# Answer
> 3 votes
It is not possible. The form validation handler for the comment form (comment\_form\_validate()) doesn't allow to the anonymous users to choose a username that has been already used by a registered user. The function contains the following code:

```
  elseif ($form_state['values']['is_anonymous']) {
    // Validate anonymous comment author fields (if given). If the (original)
    // author of this comment was an anonymous user, verify that no registered
    // user with this name exists.
    if ($form_state['values']['name']) {
      $query = db_select('users', 'u');
      $query->addField('u', 'uid', 'uid');
      $taken = $query
        ->condition('name', db_like($form_state['values']['name']), 'LIKE')
        ->countQuery()
        ->execute()
        ->fetchField();
      if ($taken) {
        form_set_error('name', t('The name you used belongs to a registered user.'));
      }
    }

```

The code avoid the confusion there could be between anonymous users that reports the link to their homepage and an authenticated user, when the anonymous users would use a username already in use.

To remove that limitation (which I don't think it's a good idea), you should implement hook\_form\_comment\_form\_alter() to add your own validation handler (with `$form['#validate'][] = 'mymodule_comment_form_validate'`, or similar code. Your form validation handler should be a copy of the one used from the Comment module, except the part that reports an error when an authenticated user is already using that username.
There is another problem, though; the form validation handler used by the Comment module contains the following code:

```
  if (!empty($form_state['values']['cid'])) {
    // Verify the name in case it is being changed from being anonymous.
    $account = user_load_by_name($form_state['values']['name']);
    $form_state['values']['uid'] = $account ? $account->uid : 0;
    // …
  }

```

In your case, if an anonymous user would use "Christoffer" as username, and that is already used by an authenticated user, the code would load the user object for the authenticated user, and the comment would be attributed to the authenticated user, not the anonymous user.

There could be also other code in the Comment module that takes the assumption there cannot be two users with the same username, which is a restriction present in Drupal.

---
Tags: 7
---


# Question
Title: How are drush and jenkins used together for continuous integration?
I hear the buzz words, "continuous integration", "drush" and "jenkins" often. Thus, sparking my interest.

How are drush and jenkins used together for continuous integration?

Also, why would you want to use drush and jenkins together?

# Answer
For my projects, I use a build script made of Drush commands in a Jenkins job. I use my Phing Drush Task project to run Drush from a Phing build script. This allow me to leverage the existing Phing tasks (eg. files copy, phplint, etc.). With the help of Drush, this build script

* Downloads all non-custom code (ie. Drupal core and contribs module and themes) with Drush Make to `./dist`
* Expands placeholders in a versioned `settings.php` (ie. replace `${db_host}` with the actual DB hostname) while copying it to the freshly downloaded `./dist/sites/default` folder.
* Copy custom modules and themes to `./dist/sites/all/modules/custom` and `./dist/sites/all/themes/custom`
* Run `phplint` for all files from my custom modules and themes.
* Copy everything under `./dist` to a pre-configured webroot.
* Run `drush site-install testing` and `drush pm-enable simpletest` to install a fresh site using the build code base and able to run SimpleTest.
* Run `drush test-run` to run my custom module test suites.
* Run `drush coder-review`.

Here is a commented build.xml template for Drush usage in Jenkins.
> 20 votes

# Answer
You can use Phing in Jenkins, so you can use Drush through http://drupal.org/project/phingdrushtask (Pierre Buyle on SE.COM)

Custom example:

```
 <drush command='cc' root="${project.drupal.core.dir}" uri="${env.host.name}" assume="yes">
  <param>all</param>
</drush>

```
> 3 votes

---
Tags: drush, deployment
---


title: Building Custom Drupal Form

text:
# Question
Title: Building Custom Drupal Form
I am trying to display a custom form with Drupal 7.

Here is what I am trying:

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

  $items['pay-online'] = array(
    'title' => 'Pay Online',
    'description' => 'Pay Online',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form_generate'),
    'access arguments' => array('access content'),
  );

  return $items;
}

function mymodule_form_generate() {

  $form['first_name'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#attributes' => array('placeholder' => 'First Name'),
  );

// ... etc, more form code

return $form;

```

What I am getting on the screen is a form, but it is not a 'drupal' form. It's just an array of form fields. No form id, etc.

What do I have to do in Drupal 7 to accomplish this?

# Answer
You should replace

```
function mymodule_form_generate() {
  $form = array();

```

with

```
function mymodule_form_generate($form, &$form_state) {

```

I'm not sure if this fixes things for you, but that is the only thing I can see that is out of order.
> 2 votes

# Answer
You should use `return system_settings_form($form)`.

See system\_settings\_form(), and what googletorp reported.
> -1 votes

---
Tags: 7, forms
---


# Question
Title: Is allowing Full HTML (HTML filter on) input for all user roles safe?
Is allowing Full HTML input for all user roles safe as long as I enable the HTML filter?

# Answer
> 5 votes
Only trusted roles and users should have access to Full HTML. You can add some additional allowed tags to the Filtered HTML input format but don't add too many or you risk creating a vulnerability. (admin/settings/filters)

# Answer
> 5 votes
It doesn't really matter what the name of the input format is, if "untrusted" users (see a defintion of trusted roles) are allowed to enter unsafe HTML tags then your site is unsafe.

You can make the Filtered HTML input format unsafe by adding the wrong tags to it or make the "Full HTML" input format more safe by changing its configuration.

I suggest installing the Security Review module and configuring it to know which roles of your site you trust. It will then analyze your input formats to see which are safe and which are not. It also has documentation and links to further resources if it determines that some of your input formats are unsafe. One great resource is the handbook page on configuring input formats for safety.

If you want to make a different input format the default for your admins vs. your regular users, try the Better Formats module.

---
Tags: input-formats, security
---


# Question
Title: Backport of hook_library() for Drupal 6?
I've come to love the hook\_library() of Drupal 7 as an extremely clean way of including assets etc. I'm fully aware of the many different ways to include assets intelligently (including the context\_addassets module) but I'd love a near exact drop in backport for the `hook_library()` that Drupal 7 provides.

Note: Using `mymodule_library()` essentially defines a list of css/js (and their dependant libraries) which can be added in one simple call to drupal\_add\_library()

# Answer
The module that originated the patch that introduced `hook_library()` in Drupal 7 is the jQ module (see Allow to add JS/CSS libraries (sets of files, settings, and dependent libraries). The hooks used by that module are different, but that is the module that is closer to what you are looking for. That module requires you to call a different function, but using `drupal_add_js()` would require you to hack the Drupal core, which is something it is never suggested to do, in the cases where you want absolute compatibility between Drupal 6 and Drupal 7.
> 3 votes

# Answer
There is the Libraries API module available for Drupal 6 which is similar to the native Drupal 7 hook\_libraries.
> 1 votes

---
Tags: 6, hooks
---


# Question
Title: The Batch API won't continue running if the browser is closed correct? Can a batch be run with Drush?
Can the batch API continue to run once the browser closes? If not then can I run a batch with Drush? I have an insane amount of data to migrate and I don't really have time to wait for it to import every item one at a time on my local machine.

Currently I have my batch process setup to import each item (groups, users, blogs, files, etc) one per op call. But I am going to change that to do 50 to 100 per call to improve the speed. But I just ran it last night on just my groups and it took almost an hour to run on almost 800 groups.

This is part of a data migration from multiple websites to one unified site. Thoughts? Suggestions? Can Drush help me out?

EDIT: I have rolled my own export/import scripts for this because of the nature of the migration (multiple Drupal 4.7 sites that are highly customized and with potentially hacked cores to Drupal 6). I already have the exported data file created and ready to go. I am just testing the import portion of this madness.

# Answer
> 3 votes
It seems possible, have you tried: Processing batch jobs with drush.

# Answer
> 3 votes
Sounds like a job for Drupal Queue then. Explore that as an alternative to Batch API. It is included in Drupal 7, and there is a Drupal 6 backport in contrib.

# Answer
> 2 votes
I've successfully used drush with the Batch API in exactly the situation you describe, importing content from multiple sites into one site. The total content imported included 800-some user accounts, a few thousand nodes, etc. The total execution time was something like 30 minutes.

I essentially wrote a number of php scripts, one per content type (or other thing), to load the nodes (or other things) from the source sites' databases and save them using the API. I used the pattern in Processing batch jobs with drush for these scripts, and then used drush commands in a shell script to run them all.

---
Tags: migrations, drush, batch-operations
---


# Question
Title: How do I automatically change the background image of body?
How do I automatically change the background image of body, when I click on a menu link?

I want to obtain the same effect shown in the Drupal Design Camp Boston 2011 site.

# Answer
This is the code that is added directly to the page and is not part of a seperate script.

```
<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { $('body').css( 'background-image', 'url("/sites/default/files/palm1.jpg")' ) });
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { $('body').css( 'background-color', '#2a2f1d' ) });
//--><!]]>

```

The place where you want do this is inside your theme's template.php file under the function `MYTHEME_preprocess_page(&$variables)`

then add something like

```
$script_bg_img = "jQuery(document).ready(function () { $('body').css( 'background-image', `url('/sites/default/files/palm1.jpg')` ) });"
drupal_add_js($script_bg_img);

```

or put the javascript in a separate file, then add `drupal_add_js(PATH_TO_FILE . '/FILENAME');`
> 2 votes

---
Tags: 7, theming
---


title: tpl.php files in subfolders

text:
# Question
Title: tpl.php files in subfolders
I am creating a big Drupal theme with lots of node types and lots of custom templates. Each having a very diffent look and feel. This is something I can not get round because the design was signed off before Drupal was decided as a platform. I wish to organise my files into folders.

```
templates/content_type/node-content_type.tpl.php

```

So for example

```
templates/page/node-page.tpl.php
templates/blog/node-blog.tpl.php
templates/node.tpl.php

```

The problem is drupal only scans for the templates files in the same folder as node.tpl.php.

Is it possible to get Drupal to scan into subfolders? Even if I need to hardcode where to look I don't mind.

Views does something which means it can look in subfolders but I don't know if that is because it defines its own type rather then a core type (node/page).

# Answer
> 3 votes
In D6, any custom templates (from core, such as node or page) must be in the same folder as the base tpl file in order to use the auto-recognition of theme files.

You may be able to specify additional template files (in D7 they're called theme hook suggestions) in a preprocess function in your theme's template.php. See the first code example at http://drupal.org/node/249726 to get you started.

---
Tags: 6, theming
---


# Question
Title: How to add classes to image fields set to Unlimited and a "rel" attribute to the <a> tag that wraps them
I have an image field set to Unlimited and I have some questions on how to display them:

1. How do I display only the first image while all the rest are hidden (has `class="hide"`)?
2. Add a `rel="something"` attribute to each `<a>` which wraps `<img>`

**Answer to #1 found!** After several tests, simply capture the field by adding this to your `field.tpl.php` file. This will insert the `hide` class to all succeeding images after the first one.

```
<?php if( $element['#field_name'] == 'field_gallery') : ?>
  <div class="<?php print $classes; ?>" <?php print $attributes; ?>>
    <div <?php print $content_attributes; ?>>

      <?php $i = 0; foreach ($items as $delta => $item) : ?>

        <div class="field-item <?php if($i > 0) print 'hide '; print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
          <?php print render($item); $i++; ?>
        </div>

      <?php endforeach; ?>

    </div>
  </div>
<?php endif; ?>

```

# Answer
> 0 votes
Don't you want to use a module like Views Slideshow: Dynamic Display Block to produce what you're looking for ?

If not you should create a specific template for your field using a name like `field--field-name.tpl.php` (Drupal 7 Template Suggestions), put it in you theme folder and customize it.

You can use theme\_imagecache() if you're on Drupal 6 or theme\_image\_style() on Drupal 7.

```
$img = theme('image_style',
             array('style_name' => 'thumbnail',
                   'path' => $content['field_image'][0]['#item']['uri']
                  ));

```

Then you wrap your images in a using l():

```
$attributes = Array('rel' => 'rel_text');

echo l('yourpath', $img, array('html' => TRUE, $attributes));

```

---
Tags: media
---


# Question
Title: Force nodes created by Feeds module to be published even if nodes are unpublished by default
How can I do this? Force nodes created by Feeds module to be published even if regular nodes are unpublished by default.

# Answer
Implement `hook_nodeapi()` for the 'presave' operation to set the node status to published if there is a new one created by Feeds:

```
function MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op === 'presave' && empty($node->nid) && !empty($node->feeds_node_item)) {
    $node->status = 1;
  }
}

```
> 3 votes

# Answer
Making nodes published is not a problem, the question is how are we going to tell the nodes created by Feeds. The quickest options are

1. a separate node type for imported content, or
2. a hidden field that only gets set via Feeds mapping

Assuming none of the quick solutions would fit your scenario, the only actual way to tell Feed-created nodes is the `feeds_node_item`. After importing a node, it will contain a record for the node, with `nid` column set to the node id.

Making use of the Rules module, the whole trick is just a matter of an *Execute custom PHP code* for condition to check if the record is there for the newly created node:

*Add new rule*

**Event:** After saving new content

*Add a condition*

**Select the condition to add:** Execute custom PHP code

*PHP code*

```
<?php
$a = db_fetch_array(db_query("select count(*) c from {feeds_node_item}
                              where nid = %d", array($node->nid)));
return $a['c'] != 0;
?>

```

*Add an action*

**Select an action to add:** Publish content
> 2 votes

# Answer
I've done something similar to expose the user status as a mapper; see the patch proposed in Add user status to FeedsUserProcessor, which would be similar.
> 1 votes

---
Tags: 6, nodes, feeds
---


# Question
Title: Editing content redirects to apache test page?
Everything in the site works except for when saving it redirects to an apache test page. Any ajax request returns an error and the apache test page as debug text? Any idea? php 5.3 all requirements met.

*Clarification* For example: When editing content and clicking save I am taken to an apache test page. The url display in the browser is site.com?q=node/1/edit&destination=admin/content If I refresh the page and send the postdata again I get the apache start page.
If I load that page (like put the cursor in the URL bar and hit enter) it goes to the content edit screen but nothing is saved.

All forms that submit post data it seems do not work. I dont have this problem anywhere else on the server.

# Answer
> 1 votes
This was an issue with mod\_security. Disabling it fixes the problem...but is not advised.

---
Tags: nodes
---


# Question
Title: Is there a module for user level permissions?
I know that permissions are controlled by admins. I want regular users to control a different set of permissions, for example my users will have pictures, friends list, personal information in there profile. I want them to be able to create groups and limit access so certain groups can see certain content. Is there a module for this or do I need to put on by big boy paints and start coding?

# Answer
Yes! Check out the Role Delegation module. Here is a quote from its project page:

> ... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
> 2 votes

---
Tags: 7
---


# Question
Title: Avoid admin users editing other admin users
I'm in a Drupal 7 installation, trying to find a way to avoid admin-users to edit other admin-user's account.

I've created a role for 'content administrators' and this users tasks involve user administration, but I don't want them to be able to edit other content administrators or admin accounts.

I wasn't able to find an option for this or a module providing the functionality and I'm a bit lost about how this can be achieved.

In D6 I guess could use hook\_user() to catch an edit and check the target role in order to allow that edit or not, but this hook is gone on D7. The closest thing is hook\_user\_alter(), but this is called after the edit, so I can't use it.

Any pointers?

# Answer
Just use the User Protect module.

This module provides various editing protection for users. The protections can be specific to a user, or applied to all users in a role.

Note: User Protect has a complicated configuration -- please take the time to read the very extensive module help before using it!

The following protections are supported:

```
username
e-mail address
password
status changes
roles
deletion
OpenID identities
all edits (any accessed via user/X/edit)

```

When a protection is enabled for a specified user (or the protection is enabled because the user belongs to a role that has the protection), it prevents the editing operation in question that anyone might try to perform on the user--unless an administrator who is permitted to bypass the protection is editing the specified user. The module will protect fields by disabling them at user/X/edit.

User administrators may be configured to bypass specified protections, on either a global or per-administrator basis.

These protections are valid both when trying to edit the user directly from their user/X/edit page, or using the mass user editing operations.

The module also provides protection at the paths user/X/edit and user/X/delete, should anyone try to visit those paths directly.
> 8 votes

---
Tags: users
---


# Question
Title: How can translations 'inherit' CCK values of the node in the default language
I've got a CCK content type called 'projects' with about 10 fields, including an ImageField that allows for multiple images.

There are two languages defined for the site: English (the default), and Chinese.

The projects have been created in English by the client.

Now, they want to add translations for all the projects into Chinese. So, I've:

* enabled content translation
* created a new 'project' node (e.g., node/234) and populated just the title and body fields (all the other values are the same between both nodes)
* gone back to the original English node and added node/234 as the translation

The problem of course is that when I go into the Chinese translation for the page, the field values for the original node aren't there, so at the moment, the site editors would have to re-add the values all over again.

Is there a module or Drupal setting for addressing this issue, or would it be better to, say, create a module to run a query that populates the fields in Chinese translations with the values from its sister English node? I'm not adverse to writing such a module, but if there's a solution already, of course that would be better.

# Answer
I've found a solution that works for my needs. There's probably a better way:

Modules used: Views Bulk Operations, Node Clone, Views Bonus Pack, Language Assign, Feeds

Assumptions: you have a CSV file or MySQL database with translations of your pages in another language. It's not necessarily to have this - it just makes things faster.

* Install the Node Clone module and Views Bulk Operations (VBO) module. Add this patch to expose the Clone feature to VBO.
* Clone the nodes you need in VBO. This will append 'Clone of' to the title of each cloned node.
* Set the language of the new nodes, again using VBO and Language Assign.
* Install the Views Bonus Pack to get CSV export functionality. Create a View that uses the CSV Feed style, and add the title field and any other fields you need translated. Add a filter that displays only fields where the title starts with 'Clone'.
* Export the nodes using the View created in the previous step.
* Now, you can either manually add your translations to the CSV file by replacing them with the relevant translations, or you can use your new CSV as a reference file to add the right node ids to your original CSV with the translations. Basically, at the end of it, you have a file like this:

--\>

```
| Node ID | Original Title | Chinese Title  | Body         | Some other field |
| 234     | Hey You        | ????           | Blah, blah   | Blah ...         |

```
* Now, you can install the Feeds module, override the default CSV import, changing only the mapping and content type to use. Map the field 'Node ID' to the node ID (or the original title to the node title), and change the Update options to 'Update node.'
* Go to http://yoursite.com/import. Do your import. I did, and now I'm happier.
> 1 votes

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


title: Custom html output of form

text:
# Question
Title: Custom html output of form
I want to theme a form in drupal. I know I can add and remove things to the form using `hook_form_alter()`, change the text etc. Great!

I also want to add some custom html to the form. For example adding a div with some text between two form elements.

I want to do this on the comment form. The comment form has the ID comment\_form. So I need to add it to the theme registry.

```
function mytheme_theme() {
    $items = array();
    $items['comment_form'] = array('comment_form' => array('arguments' => array('form' => NULL)));
    return $items;
}

```

So I then need to add a function to be called

```
<?php
  function mytheme_comment_form($form) {
    // stuff goes here
  }
?>

```

How do I affect the html in this function and render it on the page?

# Answer
> 3 votes
You can add the html in your form\_alter, just use `'#type' => 'markup'.`

---
Tags: 6, forms
---


title: Hiding body in teaser display

text:
# Question
Title: Hiding body in teaser display
For CCK fields you can set the display to be hidden for teaser display and shown when in full node display. How can I do the same for a node's body field as it's not listed on the display settings page?

# Answer
> 1 votes
I don't know of a module that would provide a user interface you could use to achieve what you're after. It is quite simple, however, to put together a tiny module and implement hook\_nodeapi('view') to remove the `body` part from the node content before it is built for display.

The most basic example would be the following, removing the body part from all nodes' teasers:

```
function YOUR_MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'view' && $a3 /* teaser */) {
    unset($node->content['body']);
  }
}

```

Just pop a function like this into your module and adjust the `if` condition as needed.

---
Tags: 6, entities, nodes
---


title: views on top of other views

text:
# Question
Title: views on top of other views
I have a content type called News. There are three taxonomy terms for this content type (In the News, Success Stories, Events)

I want a page that shows each taxonomy term, with the newest three nodes summary, respective of that term, underneath it.

For Instance:

**IN THE NEWS:**

january 5th, 2001 blah blah blah blah blah

february 5th, 2002 blah blah blah blah blah

**SUCCESS STORIES:**

March 1, 2011 blah blah blah

Jan 2, 2012 date blah blah blah

**EVENTS:**

march 1, 2010 blah blahb lah

may 3, 2011 blah blah blah

Is there a way to do this using Views alone or should I make a separate view for each section and use Panels to show the three views?

Any suggestions would be helpful.

# Answer
> 1 votes
You can use Views attachment to put them all together. See example at http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments

# Answer
> 0 votes
You do not need separate views. I suggest using the same view with different displays (that differ only in the filter).

The natural solution would be to set the term field as the grouping field in the Style settings. But this does not work for you, because it does not allow you to specify how many items to display in each group. If you are unlucky, all recent nodes belong to a single term, so no nodes for the other terms would be displayed.

# Answer
> 0 votes
In Drupal 7 you can put other views in the header and footer area of a view. This means you could create three views (one for each type) and in the `Success stories` place the `in the news` in the header and `events` in the footer.

I haven't checked out the Drupal 6 version of views-3 but think that the same is possible.

---
Tags: views, panels
---


title: List of CCK fields under a group field

text:
# Question
Title: List of CCK fields under a group field
For a section of our site, we need to show fields, even if they are empty. A helpful suggestion has been to edit content-field.tpl.php and remove the following part.

```
<?php if (!$field_empty) : ?>
<?php endif; ?>

```

But I don't want all empty fields to show up; only a handful that are under a Field Group in my custom content type should be shown.

I'm looking for a way of saying, "Show all fields under group X in content type Y."

Does such a thing exist?

# Answer
> 1 votes
CCK uses `theme_fieldgroup_fieldset` by default to render field groups. The single argument to that function usually contains all the fields that belong to that field group (apart from a rendered representation of those fields). So if you could override how to theme your specific field group, you would be done.

One way is to override this function in your theme: add a function `foo_fieldgroup_fieldset` to your theme (if your theme is called `foo`). Note that this function is then used for all field groups. The function would have to decide on its own whether to show or hide empty fields. See Overriding themable output for more details.

A different way would be to use a template file for rendering field groups. You would have to implement `hook_theme` for this to work (either in your theme or in a module). Advantage of this is, that preprocess functions are executed before rendering the field group. Preprocess functions allow you to add template suggestions, so you could have a custom template for one field group and a default one for others.

Also: have a look at the Theme developer module. It tells you for each item on a Drupal page which theme functions, templates and preprocess functions where involved in the rendering and how you could override the output.

---
Tags: entities
---


# Question
Title: How can I get a user_reference type field working that allows me to enter names that don't exist on the site as well as ones that do?
So essentially I want a text field to operate in a similar fashion to the facebook tagging text field. By default I would be looking up other users on the site. So user reference field is obvious. However if the user isn't found I'd still like to keep the text they entered as they are just entering someone's name. Obviously I could just go and code this I'm just wondering whether anyone has done or seen this done before?

# Answer
> 1 votes
Autocomplete username looks like it does the auto complete bit for user registration. It's fairly simple. And could probably be adapted for your UI needs. image annotate looks like it does something similar, but without the ajax.

If you end up making it and publishing it, you can always post it here as an answer.

---
Tags: 6, entities
---


# Question
Title: How to use JQM theme and jQueryMobile plugin with Drupal?
I'm developing a mobile web site with Drupal 7 and i want to use jQuery mobile. I've found many plugins, but just one available with drupal 7 (jQuery Mobile module). I have also a jQuery mobile theme (jQM Theme). My problem is that doesn't work (there is just html, no css and jquery mobile displayed). Is there someone who used this plugin and theme ? Or could you give me an efficient way to create a mobile web site with Drupal 7 ?

Thanks, Gen

# Answer
Please make sure you've read the readme properly. The module requires that certain files be patched and you have the libraries in the correct place.

I have had jQuery Mobile theme working but found that it was far from usable so built my own simplified theme.
> 1 votes

---
Tags: 7, theming, javascript
---


# Question
Title: how to apply CSS for a Custom Block/View
Like your tutorial a lot. I am really brand new into Drupal and PHP and i am trying to learn to apply and suggest product for my work. Recently, i have installed Drupal 7 and installed many modules to play with. I have looked over online tutorial and i have few drupal7 books, but i haven't find any answer about my needs.

My question is, suppose i create a simple block to display a list of news items how can i apply css for this block. Where can i add css codes? Is there any specific css file in a certain directory?

Please let me know if you can help me on that. if you already have a question thread opened or answered before, you can point me the url. i couldn't find the answer yet.

# Answer
It depends on what theme you're using. The core Drupal themes are stored under /themes/. If you have a custom theme, it should probably be installed in /sites/all/themes/. Different themes may name their main CSS file differently, but look for .css files within your theme's directory or a subdirectory beneath it.

From there, you'll need to know what ID or class name is associated with the particular block. You can right click in somewhere in the block and choose "Inspect Element" to examine the source file. Or for even more power, I'd recommend installing the Firebug extension for Firefox. You can find out more about Firebug in this screencast.

For more complicated theming, I'd recommend also installing the Theme Developer module. It will allow you to see what theme file or function is currently outputting a specific area of the page, as well as what files or functions can be used to override it. See the screencast for more detailed information.
> 3 votes

# Answer
Give the Code per Node module a look, this allows you to add custom css and js to any node / block. Here is an excerpt about it from the module's project page:

> ... makes it possible to add custom CSS and Javascript per **node**, per **content type**, per **block**, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.
> 2 votes

---
Tags: blocks
---


# Question
Title: Disable default view when offering module is disabled
I have the User IP Log that displays the logged data using a default view defined in the module; when the module is disabled, the view page becomes broken, throwing PHP warnings and notices.

I would like to disable the default view when the module defining it is disabled, to fix the PHP warnings I get. Is it the right way of handling this? If it is so, what API could be used for disabling the default view defined by a module?

# Answer
> 1 votes
`hook_disable()` is what you are looking for:

> Perform necessary actions before module is disabled.
>
> The hook is called every time the module is disabled

Remember to do inverse actions with `hook_enable()`, which is used when a modules is enabled, install hooks don't fire when a module is re enabled.

Also if you need to track enable/disabling of another module you can use `hook_modules_disabled()` and `hook_modules_enabled()`

(it looks like you found it, but adding an answer for others is always good).

---
Tags: 7, views
---


# Question
Title: Some files are deleted from the files table after CRON execution
I am using `hook_form_alter()` to add a file upload field to the taxonomy term form. The form itself and the submit are working well. From the submit callback i save the uploaded file using `file_save_upload()`. This also works well, the is saved in `sites/default/files` and in the `files` database. I have noticed that when Drupal CRON is executed the files i saved are deleted, but the other files (from CCK for example) remains in the table. Files are also deleted from the `sites/default/files` directory.

Here is my code :

```
/**
 * Implementation of hook_form_alter()
 */
function community_form_alter($form, $form_state, $form_id) {
  switch($form_id) {
    case 'taxonomy_form_term':
      // get the current image if any
      $image = variable_get('community_term_image_'.$form['tid']['#value'], '');
      // load file
      if($image) $image = field_file_load($image);
      $form['identification']['image_preview'] = array(
        '#type' => 'markup',
        '#value' => $image ? theme_imagecache('community-section-title', $image['filepath']) : '',
      );
      $form['identification']['image'] = array(
        '#title' => t('Category image'),
        '#type' => 'file',
      );
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['#submit'][] = 'community_term_form_image_submit';
    break;
  }
}

function community_term_form_image_submit($form, &$form_state) {
  $dir = variable_get('file_directory_path', 'files');
  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    // If the term currently contains a picture, we remove it prior to saving
    // the new one
    $current_image = variable_get('community_term_image_'.$form_state['values']['tid'], '');
    if($current_image) {
      $current_image = field_file_load($current_image);
      db_query('DELETE FROM {files} WHERE fid = %d', $current_image['fid']);
      file_delete($current_image['filepath']);
    }
    variable_set('community_term_image_'.$form_state['values']['tid'], $save->fid);
  }
}

```

# Answer
> 3 votes
`file_save_upload()`:

> The source file is validated as a proper upload and handled as such. The file will be added to the files table as a temporary file. Temporary files are periodically cleaned. To make the file permanent file call file\_set\_status() to change its status.

You need to use file\_set\_status() to change the status of the file.

```
  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    file_set_status($save,FILE_STATUS_PERMANENT);
    ...

```

---
Tags: forms, files, cron
---


# Question
Title: How can I create an excerpt for each of a node's taxonomy terms?
Rather than create a single node excerpt/ preview used across all Views for a taxonomy term, how can I create individual excerpts for a selection of taxonomy terms used to describe a node?

For example, if I have a node about a hotel that is family-friendly and has business facilities (both of which are also taxonomy terms), when I display a list of 'family-friendly' nodes I would like to display an excerpt with a short description of the family-friendly features of that hotel, whilst when displaying a list of nodes for hotels with 'business facilities', I would like to display excerpts with short descriptions of the business facilities at those hotels.

I've found the Excerpt module, but this only appears to provide a minor modification to how Drupal's existing excerpt feature works.

# Answer
> 1 votes
This is an interesting feature. I have never seen a module which does it.

If you look at the Open Calais module, you can see some custom extensions to the way taxonomy works. While it doesn't do what you want precisely it may be a good guide for you.

In short, you can assign meta data to a node-term relationship which contains your excerpt. It would require a custom module and a fair amount of coding.

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


title: Copy view mode custom settings

text:
# Question
Title: Copy view mode custom settings
On /admin/structure/types/manage/article/display I can enable custom display settings for various view modes. But what if I want one custom view mode to be almost identical to another? Is there a way to copy the settings of a certain view mode to another view mode?

# Answer
> 3 votes
There isn't any built in way of doing this. I'm sure you could make a custom module that could do this, but it wont exactly be trivial.

What makes this a bit tricky, is that the information is store many different places. Each field has it's weight stored in the `field_config_instance` table, which holds general information about the field, like widget settings etc. The weights for all the extra fields for the entity/bundle is saved as a key to the `field_bundle_settings` variable that can be accessed with `variable_get`.

If you want to explore this you can take a look at the `field_ui_display_overview_form_submit` function which is responsible for saving the display info.

# Answer
> 1 votes
Have a look at Display suite in combination with Features, it will allow you to export your custom settings

---
Tags: nodes, entities
---


# Question
Title: How to display cck node fields' values at the search result page?
I need to display some specific cck fields such as Telephone Number, Address, etc. at the search result page.

As I see the `search-result.tpl.php`, there is no `$node->...` So how can I get the node fields into search result page?

# Answer
> 1 votes
---

**\[SORTED\]**

wow, that simple :)

**search-result.tpl.php**

```
<?php if ($result['node']->field_name[0]['value']): ?>
  <h4><?php print($result['node']->field_name[0]['value']); ?></h4>
<?php endif; ?>

```

# Answer
> 3 votes
In your theme, you can use `template_preprocess_search_result()`

```
function YOURTHEME_preprocess_search_result(&$variables) {
  if ($variables['type'] == 'node') {
    $node =& $variables['result']['node'];
    //Do something here
  }
}

```

Or, you can also implement `hook_nodeapi()` in a custom module for `$op = 'search result'`. The result of `hook_nodeapi($node, 'search result')` is available in `$info_split` in the `search-result.tpl.php` template.

# Answer
> 1 votes
We had to create a custom search once. We created a custom module that allowed not only writing a custom query to the database but also choose the kind of amount that gets displayed. We hooked into `hook_search` with the module. To give you an idea:

```
function yourmodule_search($op = 'search', $keys = NULL) {

switch ($op) {
   //some code, basically a stripped version from what the API shows us
    case 'search':

      $find = do_event_search($keys); //the actual search

      // Load results.
      $results = array();

      foreach ($find as $item) {

        //iteration and adding certain elements to $resuls needned by Drupal
      }
      return $results;
  }
}

```

The interessting part for you is the retrival of the search results as done by `do_event_search`:

```
//all data comes from a queries to the database
$search_result[] = array ('link' => trim($link),
                    'snippet' => trim_text(i18n_get_lang() == "en" ? $row->description_en : $row->description_de),
                    'head' => trim_text(i18n_get_lang() == "en" ? $row->title_en : $row->title_de),
                    'type' => $type
                );

```

As you can see, `snippet` holds the text that should be displayed on the search pages and we select a certain `$row` from a custom database. The API example shows all fields that are needed for displaying the results properly.

# Answer
> 1 votes
Another possibility is to use Display Suite, it allows you to override the node indexing as well as the display of the search results

# Answer
> 0 votes
you could use the template\_preprocess\_search\_result(&$variables) function (copy it from the search module and place it in your theme's template.php file) - and use the $variables variable (var\_dump it) to retrieve your node info and print it

---
Tags: search, nodes, entities
---


title: template for a view?

text:
# Question
Title: template for a view?
I created a view which is viewable at `http://mysite.com/branch-locator`. The view is being displayed by my page.tpl.php. How do I override this and use a new template file called branchlocator.tpl.php to display my view?

# Answer
How specific do you need to be with the name of your template file? You should be able to create a page--branch-locator.tpl.php that gets picked up by Drupal's auto-detection mechanism. At least, that would have worked in D6 (minus the extra hyphen after page).
> 2 votes

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


# Question
Title: Define image cropping in new image style
When creating a new image style, is there a module which can let you define where to start the cropping? I think Drupal only crops from the very center. What if for this specific image I want the cropping to being from the top left? Or better yet, provide some gui which can let me crop the area manually like in fb.

# Answer
You mean like image field crop
> 4 votes

# Answer
There are many options to choose from in Drupal for image cropping. Here is a quick comparison.

* **EPSA Crop**

Allows a user to choose coordinates for different presets on an image. If a user defines coordinates EPSACrop will override the Imagecache process and will set new coordinates.
* **Image Javascript Crop**

With this one you define one or more presets in imagecache using the 'javascript crop" action, a new 'javascript crop' link appears underneath the image on the node edit screen, and the resulting popup window will display those presets. This screen shows the original image and initially applies the initial crop settings defined in the preset you select, e.g.: crop 50%-50%, center-center. However, you can then choose a different area of the original picture you want to crop, dragging an overlay box over the image, altering the size etc.
* **Imagefield Crop**

When the user uploads an image, the image is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking 'preview' or 'submit', the image is cropped and the result is saved instead of the original image.
* **Imagefield Focus**

This module allows to scale and crop images focusing on their important portions.
* **Image Editor**

Bring Photoshop-like functionality into your Drupal website! Create/edit any images online in the powerful and feature-rich image editors and save resulted images back to your site! This project integrates several popular online image editing services into Drupal:Pixlr editors: Pixlr Editor and Pixlr Express, Picnik, Simple HTML5 editor from Aviary: Aviary Feather, Advanced Aviary editors: Aviary Phoenix; Aviary Raven (vector editor - not working yet); Aviary Peacock; Aviary Falcon, Sumo Paint, FotoFlexer and Open-source HTML5 PaintWeb editor.

*On a side note, (this is not what you were really asking, but) anyone coming to read this post looking for similar functionality directly in IMCE can use the IMCE Crop module which adds image cropping functionality to IMCE through its UI. And for kicks, if your looking for the ability for users to be able to do manual cropping on their avatars, use Avatar Crop. Or just to force Image presets on Avatars, use Image Cache Profiles.*
* **Manual Crop**
> 6 votes

---
Tags: 7, media
---


# Question
Title: How can I check if a node references a Drupal Commerce product?
Is there a short function in Drupal Commerce API that returns TRUE (or something else) if a given node references a product?

# Answer
There isn't a short function, though that's not a bad idea for a feature request. However, it's not that difficult using the Field Info API to determine if a given node contains a product reference field. One method would be using field\_info\_instances().

With this function and your node object, you can retrieve an array of all field instances on your node with the following code:

```
$instances = field_info_instances('node', $node->type);

```

You would then need to loop over the returned instances and use `field_info_field($instance['field_name'])` to load the field info array and see if the type of any given field is commerce\_product\_reference. If so, then you know the node can *at least* refer to a product... but that doesn't mean a reference is actually established.

For that you'd need to make sure the node contained data for that instance. That could be as simple as checking `if (!empty($node->$instance_name))`, but it'll depend on how you're actually building / using these reference fields.

One simpler way to find if a product reference instance is on the node is possible if you know your reference field's name. For that you can use field\_read\_instance() with the following code to return the info array of the instance or FALSE if it doesn't exist for the given node type:

```
$instance = field_read_instance('node', $field_name, $node->type);

```

Hope those help, and feel free to open an issue in the Commerce issue tracker for any related helper functions under the "Developer experience" component. I suggest you spend time getting to know the Field Info / CRUD APIs, as they'll be very helpful to you in your Drupal 7 development.
> 4 votes

---
Tags: commerce
---


# Question
Title: How do I force Breadcrumb to use a menu other than Main Menu?
I am trying to force breadcrumb to follow the structure of a menu other than Main Menu.

I have configured the content type to use the new menu to add links, which are displayed correctly in the sidebar menu. However breadcrumb just displays Home \> (current\_page).

Where is this configured? Is it hard coded?

Any advice appreciated.

Cheers Paul

# Answer
Menu Breadcrumb

By default, Drupal will use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.

As an added bonus, it also allows you to Append the page title to the breadcrumb (either as a clickable url or not) and hide the breadcrumb if it only contains the link to the front page.
> 2 votes

---
Tags: 7, routes, breadcrumbs
---


# Question
Title: View that only shows content that have a certain date?
I have a view that I am using to list events, specifically "today's events." it was relatively easy to create it, say that I want it to sort by time, but what I am wondering, is how can I filter it to only show events that are happening on the day that it is displaying. I am using the date module's CCK in order to create the date. I would assume that I would use the date start time, but I can't figure out how to filter that start date.

# Answer
Filter by the start date with granularity of day. When you setup the filter, you can specify operator `Is equal to` and in the Date default field use the keyword `now` to default to the current date at runtime.
> 3 votes

---
Tags: 7, views, datetime
---


# Question
Title: Receive link from row in views-template file
I changed a views-template and wanted to link all elements together. Is there a different way as getting the link via regular expressions?

# Answer
Have you try the option in the field to "Reqrite the output" ?

First of all, you select "Exclude from display" in the fields you want to group together, then in the last field you rewrite its output using patterns. This allow you to put HTML or text before your fields for example something like this:

```
<strong>Address</strong>
City: [field_city_value]<br />
Country: [field_country_value]

```

Then you also have the option to "Output this field as a link" which allows you to give your group of field a link. This option also provides a way to rewrite the link with patterns.
> 2 votes

---
Tags: views
---


# Question
Title: Problem with Drupal 6 built in "normal" caching - users getting data several days old on front page
I have a site running Drupal 6. I was having performance problems so I turned on Drupal's built in "normal" level of caching performance -- which claims to not have any side effects.

Since I enabled this feature (about 3 days ago) I have users reporting that they are not seeing the latest content -- specifically the latest posts on the front page appear to be from several days ago. I believe this is happening both for logged in users, and anonymous users. I have not yet seen it happen as either a logged in user or an anonymous user.

What might be causing this and what steps can I take to troubleshoot it?

# Answer
A couple of things to look at:

1. Adjust the Minimum cache lifetime set at on admin/settings/performance to something better suited to your users.
2. Make sure you have cron tasks in place to rebuild that cache on a regular interval. You can do it using Poormanscron in D6 (Built in core in D7).
3. Disable any server-side performace/caching mechanisms, such as APC, memcache, varnish etc...
4. Disable any extra Drupal caching mechanism, such as Boost.
> 1 votes

---
Tags: caching, performance
---


# Question
Title: What will be the url to show all content type posts?
OK i have created a content type. But what will be the url that will show the list of all posts in specific content type? Basically I want to make a link or a menu item that will show all posts in specific content type but off course paginated.

# Answer
> 1 votes
If you are referring to a URL that every user with permission to view published nodes would see, then a Drupal fresh installation doesn't have such a URL. There is a URL that only users with the permission to administer nodes can see, and that shows the list of all the nodes, which can then be filtered by content type and other criteria.

For a URL that is accessible to anybody, you need to use a third-party module, such as Views, as Nigel already reported. Using Views Bulk Operations (VBO), you can create a page that is very similar to the page to administer content, but that is visible to any user having less restrictive permissions. Being a view, it can be customized as every view; in particular, the filter criteria are the usual exposed filters used by Views.

# Answer
> 6 votes
You will have to use the Views module to create list filtering for a specific content type.

The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Traditionally, Drupal has hard-coded most of this, particularly in how taxonomy and tracker lists are formatted.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content. You need Views if:

1. You like the default front page view, but you find you want to sort it differently.
2. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
3. You use /tracker, but you want to restrict it to posts of a certain type.
4. You like the idea of the 'article' module, but it doesn't display articles the way you like.

Views can do a lot more than that, but those are some of the obvious uses of Views.

Here is a series of awesome tutorials on Views (**I am not affiliated with the author(s)**)

---
Tags: nodes
---


title: Views contextual filters for NULL value

text:
# Question
Title: Views contextual filters for NULL value
How do I use a contextual filter to find all nodes with field\_abc that has a null value?

# Answer
1) Views PHP Filter is good to go when you have 'not that many' query results in total. The thing is that it loads node's object and it's not the best choice if you opt for better performance, but still it's okay for quick views filters creation.

2) Create new Computed field and store any flag (1/0 is quite enough) as its value. The flag itself will indicate if the field X has any content and then it can be used by Views for filtering.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to prevent a field with thousands of files from loading on Edit operation?
I have a process running that renders a PDF to PNGs and attaches those PNGs to a file field. There is one PDF's results per node, but there we have a bunch of PDFs with 10,000+ pages. We've found that this results in the operation of loading an edit form to eat quite a lot of memory (a node with 12,000 attached files ate up all 4GB of RAM on our server before Apache killed the process for taking up too much memory).

Does anyone have any ideas how we might prevent the field from loading? It looks like I could hack file\_field\_load() to not perform its task given the user is on an edit page and the troubled field is expected but it would be cool if there was a solution that wasn't a hack.

The stack trace when the troubled field is set to not display is:

```
 1. {main}()  /index.php:0
 2. menu_execute_active_handler()  /index.php:18
 3. call_user_func_array()  /includes/menu.inc:348
 4. node_page_edit()  /includes/menu.inc:0
 5. drupal_get_form()  /modules/node/node.pages.inc:15
 6. drupal_process_form()  /includes/form.inc:121
 7. form_builder()  /includes/form.inc:406
 8. form_builder()  /includes/form.inc:930
 9. form_builder()  /includes/form.inc:930
10. _form_builder_handle_input_element()  /includes/form.inc:889
11. imagefield_widget_value()  /includes/form.inc:1020
12. filefield_widget_value()  /sites/all/modules/contrib/imagefield/imagefield_widget.inc:207
13. field_file_load()  /sites/all/modules/contrib/filefield/filefield_widget.inc:215
14. _field_file_cache()  /sites/all/modules/contrib/filefield/field_file.inc:51

```

And when the field is set to display:

```
1. {main}()    /index.php:0
2. menu_execute_active_handler()    /index.php:18
3. call_user_func_array()    /includes/menu.inc:348
4. node_page_edit()    /includes/menu.inc:0
5. drupal_get_form()    /modules/node/node.pages.inc:15
6. drupal_process_form()    /includes/form.inc:121
7. form_builder()    /includes/form.inc:406
8. form_builder()    /includes/form.inc:930
9. form_builder()    /includes/form.inc:930
10. form_builder()    /includes/form.inc:930
11. _form_builder_handle_input_element()    /includes/form.inc:889
12. process_weight()    /includes/form.inc:1063

```

# Answer
> 2 votes
Would it be enough to deny editing rights to that field using Content Permissions?

# Answer
> 1 votes
Per my comment, use hook\_nodeapi() when $op == 'load' as a place to unset() that field to prevent it from being built in the form code.

# Answer
> 0 votes
You could try to hook\_form\_alter the edit form for that content type, but I am not sure it will happen too late in the process.

This post can provide guidance: https://stackoverflow.com/questions/1067782/drupal-form-alter

It would essentially start out as

```
function module_form_alter (&$form, &$form_state, $form_id)
{
  if (isset($form['#node']) && $form_id == $form['#node']->type .'_node_form') {
  }
}

```

You would need to add logic to check for your content type, and then unset the necessary elements.

I am not 100% sure if it will leave the fields as-is when you do this, though, so test first on a safe copy of your site.

---
Tags: 6, entities, files
---


title: Modify Default search to phrase search

text:
# Question
Title: Modify Default search to phrase search
Is there a way to change the default search settings of the built in search module to default search to phrase match?

Phrase search as in by default terms would be searched with exact match:

`"foo bar"` over `"foo" "bar"`

The client doesn't seem to like the way the out of the box search works.

# Answer
Even if it's kind of hacky you could do a hook\_form\_alter, set a submit function before the default one and look at the form input. Then wrap it with "" if it's not there already.

So what you need is

* a custom module
* hook\_form\_alter
* Register a '#submit' function
* Alter the value $form\_state\['values'\]
> 2 votes

---
Tags: 6, search
---


# Question
Title: Matching values between two different fields, each of which have multiple values
I have a content type with an imagefield and a link field. Each of those fields accepts four values; so the user uploads four images and types four URLs in each node.

I want to use Views to create a block based on that node that displays the first image linked to the first URL; the second image linked to the second URL; etc. I don't want to use CCK 3 with Multigroup (if possible) because it seems to sometimes cause weird behavior in Views, Contemplate, etc.

Given the existence of Delta fields, "Group multiple values", etc., it seems like this should be possible. But I can't make it work. Is it possible? Or should I bite the bullet, use CCK 3, and hope it's not confusing as all get-out?

# Answer
> 1 votes
You shouldn't use delta for such thing as data sometimes get reordered in the tables (ex: for node reference, the nid gets reordered regarding the title of the node referenced).
So I'll recommend you to create 4 fields for images and 4 for the URL and eventually put them in groupfields.

Also to make things prettier you can theme your form and put each group of field in a row using div or table.

Have a look at Theming Forms in Drupal 6 for information regaring form theming and the official documentation: The theme registry for special cases.

Another nice tutorial: http://www.akchauhan.com/theme-drupal-form/

---
Tags: views, 6, entities
---


# Question
Title: Issue a Conditional Redirect in Drupal 7
I have a custom payment form that redirects to a 'Thank You' page on success. The page is just a Page type node, so someone can control the content of the page.

What I wanted to do was add a little extra, and prevent the page from being seen unless they had just come from the form.

I tried using 3 functions. hook\_node\_view, hook\_node\_view\_alter, and hook\_init.

I thought the first two would allow me to check the node path or nid, and redirect if I needed to, but they did not seem to be called. Additionally, I tried

```
mymodule_init() {
  global $user;
  krumo($user);exit;
}

```

That was not being hit, either. The rest of the module works fine, custom menu item, custom form, validate/submit/mail hooks. I am stumped.

How can I check a node value when loading, take action, and furthermore, why is hook\_init() not dumping/exiting?

# Answer
You should not use `hook_init`, but `hook_boot` as you want to perform the check when caching is turned on. That would also be the best explanation as to why your `exit` doesn't work. That or you forgot to clear cache after implementing the hook. (All hooks are cached in D7)
> 0 votes

---
Tags: 7, hooks, nodes
---


title: D7 Unique page/profile per user

text:
# Question
Title: D7 Unique page/profile per user
I am working a lot with views and panels to figure this out but i cant.

When user register account i want for him to be able to make his own profile visible to everyone. Profile is 1 page user can create with custom content type (maybe there is something better to use?) with info from taxonomy vocabulary, random text, a gallery and a calendar. Since there is lot of info to write in i want to separate this in few steps. So i would like to divide page in few regions that look same for all users. Gallery on left side, taxonomy terms and random text in middle, calendar on right side or in block. Each region editable by user who made it. All info on that specific page must be only from user that created it (only userA pictures, userA calendar, userA random text on. All on 1 page).

I worked a lot with panels and views but i have no idea how to make all of this in a way that all info created by 1 user is on 1 page, viewable by everyone on that page.

I managed to use views to collect info from all users in 1 field/block/page so i know some basics. Also used panel to divide for example /home in more regions to.

Cheers!

# Answer
This should really be pretty simple if you have created the Views properly.

You need to make the views select only the content that the user provided through an argument, fx uid = 5 would should show content user with uid 5 created.

Then it's just a matter of creating a panel page that has the uid in the url, fx `user/[uid]/profile` and pass the uid to the views when you insert them on the page, which then will display the correct content.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to display additional fileds I've added to a page - the way I want them?
I've added some additional fields to the content type - Page. But now when the page is rendered it displays all of them as well - just lists them at the bottom of the content. But that's not what I want - I do not want them to display at all, I just want to use them elsewhere in PHP code. There should probably be a hook for this, but I still just can't get my head around the whole thing. Please?

# Answer
Hiding additional fields is easy, just notice **Display Fields** tab at the **Manage Fields** page for the specified content type (page in this case). There you can easily exclude additional fields from being automatically appended to the $content.

In order to show fields the way you want them use **themename\_preprocess\_page** hook and check $vars\['node'\] object for the particular fields.
> 2 votes

# Answer
I found that often you need a lot more control than just using render($content) gives you. Maybe you want fields in a different order, or wrapped specifically in DIVs or other tags. Personally I hated letting Drupal just dump out the entire array in a TPL file.

I'm in the middle of a huge Drupal project and find myself often pulling items out of the content array individually:

```
print $content->field_name

```
> 2 votes

# Answer
As jayarjo says, you want to use the *Display Fields* tab.

One caveat here is the difference between *Display Fields* and the *Exclude* option.

If you set a field to **not** display, the HTML won't be generated, but the data will still be available for other uses.

If you instead check the *Exclude* option, the field won't be passed to your theme at all: no HTML, no data.
> 1 votes

---
Tags: theming, nodes, entities
---


# Question
Title: How do I set up a Drupal view with two relationships?
I have "Event," "Session," and "Download" content types. Events can have many sessions, and each session can have many downloads. I have used node references to link the downloads to the sessions, and sessions to the events. Can I create a view of the downloads which will show session information and also the event information? I know I can use a relationship to link two node types in a view, but can I do it for three node types?

I'm using Drupal 7, and Views 3.

# Answer
> 3 votes
I found my answer at Multiple Node Relationships?

> The answer is to go to the Relationships section and add two relationships, each for your node references. You'll find them under the 'Content' group. When adding the second relationship, select it to use the first relationship so that they chain. That will get you "base" node being the lowest level child, the first relationship is that node's parent, and the second relationship is the grandparent.
>
> Then, add the Node: title field 3 times. Set 1 to use no relationship, 1 to use the first relationship, and 1 to use the second. Preview your view. That should get you the basis for what you want. Add sorts, filters and other fields to taste.

---
Tags: views
---


title: Add an extra delivery address

text:
# Question
Title: Add an extra delivery address
I'm a Drupal novice and struggling to build a webshop with Drupal Commerce. It's really starting to work out, but I've still have some problems regarding overriding and restyling themes.

Is it possible to add an extra delivery address form to the Drupal Commerce address field module (different billing, delivery addresses with checkbox to show delivery address)?

How can I restyle the address form? Is there a template file for it, or does it have to be done through CSS?

It would be really usefull if somebody could help me with some information or maybe some kind of guideline.

# Answer
> 2 votes
The customer information is stored as commerce\_customer entity. By default it has an address field attached to it. For multiple addresses, you could either allow multiple values on the field, and use some theming to display one as billing and the other as delivery.

The other option would be to add a new address field and use that for delivery/billing. With `hook_form_alter` you could add custom elements to the form, like the checkbox and JavaScript effects.

You have a few options if you want to customize your address field form. You can implement `AddressFieldForm`, the default looks like this:

```
/**
 * Default address handler.
 */
class AddressFieldForm_default implements AddressFieldForm {
  public function form($address, $field, $instance, $langcode, $items, $delta, $element) {
    $required = $delta == 0 && $instance['required'];

    $form['thoroughfare'] = array(
      '#title' => t('Street'),
      '#type' => 'textfield',
      '#required' => $required,
      '#default_value' => $address['thoroughfare'],
    );
    $form['premise'] = array(
      '#title' => t('Residence, building, ...'),
      '#type' => 'textfield',
      '#default_value' => $address['premise'],
    );
    $form['sub_premise'] = array(
      '#title' => t('Floor, stairway, ...'),
      '#type' => 'textfield',
      '#default_value' => $address['sub_premise'],
    );
    $form['dependent_locality'] = array(
      '#title' => t('Suburb, post box, ...'),
      '#type' => 'textfield',
      '#default_value' => $address['dependent_locality'],
    );
    $form['postal_code'] = array(
      '#title' => t('Postal Code'),
      '#type' => 'textfield',
      '#size' => 5,
      '#required' => $required,
      '#default_value' => $address['postal_code'],
    );
    $form['locality'] = array(
      '#title' => t('City'),
      '#type' => 'textfield',
      '#size' => 30,
      '#required' => $required,
      '#default_value' => $address['locality'],
    );

    // All the other fields are unsupported by this handler.
    foreach (array('administrative_area', 'sub_administrative_area') as $field) {
      $form[$field] = array(
        '#type' => 'value',
        '#value' => '',
      );
    }
    return $form;
  }
}

```

This is what addressfield uses to internally handle different address types. Using `addressfield_mapping_alter` you would be able to overwrite the default mapping, or create a mapping for your own country:

```
function module_addressfield_mapping_alter(&$mapping) {
  $mapping['default'] = 'AddressFieldForm_my_custom_default_form',
  $mapping['DK'] = 'AddressFieldForm_dk', // Add for Denmark which doesn't exist yet
}

```

In addition to this, you have all the usual tools, like `hook_form_alter` and adding a custom theme function to render the form like you which. You should be aware that addressfield makes heavy use of AJAX to replace form elements when changing country.

# Answer
> 1 votes
The Commerce Shipping module now defines a default "Shipping information" customer profile type that can function as your shipping address. It isn't fully featured at this point as far as copying addresses and such goes, but it should be a quicker start for most people.

---
Tags: commerce
---


title: Theming views that use node row style

text:
# Question
Title: Theming views that use node row style
I have a view that uses node rows. I looked at views-view-row-node.tpl.php and it only contains 4 lines. I tried to override the theme by using my node.tpl.php code in a new file but got this warning:

> Invalid argument supplied for foreach() in /home/public\_html/sites/all/themes/templates/overrides/views-view-row-node--taxonomy-term-attachment.tpl.php on line 36.

How can I use a modified version of node.tpl.php to theme a certain display of my view?

# Answer
> 2 votes
You probably missunderstood the two different templates here

* The node template(node.tpl.php): This is for rendering a specific node
* views template This is for wrapping the node + comments

So all you have to do is to use the node.tpl.php to theme a single file.

---
Tags: views, 6, theming
---


# Question
Title: $form array in views-exposed-form.tpl.php has #printed set to true?
I'm not doing anything to it in any other functions, but every #printed is set to TRUE when it reaches the .tpl. Any ideas why this is?

# Answer
> 1 votes
#printed is set by drupal\_render, so if the actual form element is rendering into a string the $form has #printed, try it out on any other drupal form theming.

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


# Question
Title: Latest tweets from a specific user (bonus: rotating slideshow)
I want to display the latest 3 tweets on my homepage from my Twitter account for all users. A rotating slideshow of the tweets would be cool and it looks that with the Twitter module it might be possible but I can't get it working.

I have tried Twitter Block (http://drupal.org/project/twitter\_block) but that is still under development and it seems the only thing not working with it is display a specific user (which is what I need).

I have searched far and wide, tried and tested a lot of modules and cannot find one that actually allows this. Does anyone have anything to point me at? Tutorial, walkthough, functioning module?

# Answer
Here's how I would implement this:

1. Use Feeds to aggregate your tweets to a custom content type, map tweet id to node title and tweet body to node body.
2. Create a View to display x amount of tweets from the custom content type.
3. Use Views Slideshow to rotate the content.
> 3 votes

---
Tags: 7, blocks, social-network
---


# Question
Title: Does anonymous can access current node? How to check it in my module?
I need to do something witn current node by my module only if anonymous users can view this node. How to check it?

By default I use `$node->status == 1`, but some other modules can change anonymous access rights also for published nodes.

# Answer
Also, for development especially, Devel module's Devel Node Access submodule provides a block that you can display that shows, on any given content page, all the user access permissions/grants provided, and even displays a few users and the access they would be given if they tried accessing the page, editing, deleting, etc.

Check it out: http://drupal.org/project/devel

Also, just a short bit ago, Larry Garfield posted an excellent overview of node access in Drupal 7 (applies almost without any adaptation to the Drupal 6 systems as well).
> 2 votes

# Answer
If your node is not visible by anonymous users, they will be served a 403 access denied page. So I'm pretty sure that your node won't be loaded so you can certainly do something on hook\_node\_load() and be assured that anonymous will see it.
Have a look at hook\_node\_access() if you want to control access for your nodes.
> 0 votes

# Answer
To check if the anonymous user can access a node you can use node\_access(), using the value returned from drupal\_anonymous\_user() as last parameter; the first parameter is "view" as you want to check if the anonymous users can view the page.

Anyway, this is not necessary if you want to show a value in a node when the user who is viewing the node is the anonymous user. In this case, you simply use code similar to the following one; in the case the anonymous user doesn't have access to the node, the part inside the IF statement will not be executed.

```
global $user;

if (empty($user->uid)) {
  // The user is anonymous.
}

```

If you want to show data about the anonymous users that are visible to other users too, and show those data only if the anonymous users can view the node, then I would use the `node_access()` method.

`$node->status` is equal to 1 when the node is published, and 0 when the node is unpublished. You cannot use it to determinate if the anonymous users can view it, as anonymous users could have the permission to view the unpublished content they created, or there could be a module that implements an extra permission that determinate if an unpublished node can be seen from users who are not administrator users, nor the node's author. The same is true for other users too: If a node is unpublished, it doesn't mean that node cannot be seen from every users.
> 0 votes

---
Tags: 7, users
---