# Question
Title: Prevent Search Results Being Truncated - Drupal 7
Is there a way to prevent Drupal from truncating the search results?

That is, I do not want the search results shortened with a "..." added to the end of the result. I would like the full text.

Cheers in advance.

# Answer
Yes, there is. Copy the `/modules/search/search-result.tpl.php` file into your `theme` directory. Then modify it like this:

```
  <?php /* this is just so it will be easier to access the body of the node */ ?>
  <?php $node = $variables['result']['node']; ?>
  <li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?></a>
  </h3>
  <?php print render($title_suffix); ?>
  <div class="search-snippet-info">
  <?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>>
    <?php /* this part is modified, you could display different data then the body */ ?>
    <?php print $node->body[$node->language][0]['safe_value']; ?>
  </p>
  <?php endif; ?>
  <?php if ($info): ?>
    <p class="search-info"><?php print $info; ?></p>
  <?php endif; ?>
</div>
</li>

```

**Note** Like I said in the comment, it's easy to display content from some other field, not just the body. To see what data you have to play with do:

```
 <?php echo '<pre>';
       print_r($variables);
       echo '</pre>';
 ?>

```
> 2 votes

# Answer
You can rewrite the snippet by preprocessing the search results. Replace test in the module name below with the name of your module and you'll be good to go. I don't really know my way around D7 yet, but I think the 'und' part of the node array implies that you're only using one language on your site.

```
function test_preprocess_search_result(&$variables) {
  $variables['snippet'] = $variables['result']['node']->body['und'][0]['safe_value'];
}

```
> 2 votes

---
Tags: search
---


# Question
Title: Are there modules for managing inline images?
I would like to include inline images in my posts. Is there an easy way to:

* find (and delete) unreferenced images
* find which content references a given image
* (ideally) keep things working if I decide to rename an image file
* don't show the uploaded images except where referenced manually ("Image" field seems to show all linked images below the post)

# Answer
After days of searching, I believe the closest there is is the Media module. It goes in the right direction on all counts, but seems to be a long way off "complete".

I haven't found any other modules that even remotely approximate what I'm after.
> 1 votes

# Answer
You could try Insert module along with an image field. When you using this you would hide the images in the display settings and then put whatever ones you want inside the posts. They have a recommended release for D7 as well. This really only solves putting inline images in your posts. As far as keeping track of them there really isn't much of an alternative than Media module.
> 1 votes

---
Tags: 7
---


# Question
Title: Print all the pages in the same level in a book
I am have a book like this

About Us

> --Overview
> --Vision
> --Mission

I want there to be menu like this in the left side when the user is in any of there page.

> --Overview
> --Vision
> --Mission

Now the links are visible when in About Us page, thats the main parent page. I have spend 2 hours already in google and drupal documentation but no use.

# Answer
This should work out of the box if you add the book navigation block to a region.

EDIT:

Sorry, I didn't realise that I was on on of the book pages so the book block expands in this case but not on non book pages. The way around this is to use Menu Block and create a menu block that starts at your About Us. Make sure you go into the advanced options of the menu block and select `Expand all children of this tree`.
> 0 votes

---
Tags: 7, navigation, nodes
---


# Question
Title: Some module is adding info below 'Nice Menus'
I believe some module is somehow hooking into nice menus and adding a div of content below the menu. However I can't for the life of me find out which one.

Here's what I know:

There is a content type called 'nice\_menu\_addition'. When creating an item of that content type you chose which menu item you would like it placed beneath, and it shows up there. However, I can't find ANY modules anywhere, or any theme info that shows where this is being done. Any suggestions as to where to look?

# Answer
> 2 votes
suggestion from average drupal guy.... try using the module\_implements() with watchdog method to check the available hooks from nice menu or menu docs that can cause the change and track the module...hope it helps you in some way

# Answer
> 0 votes
Would Theme Developer give you the module function that was generating the spurious info?

---
Tags: 6
---


# Question
Title: What can I remove after install of Drupal 7
What files and folders can I remove after I have installed Drupal 7 My installation uses SQLite In order to make the total package as small as possible I have removed unused themes from the root themes directory but what else can I remove? Can I remove modules from te root modules directory that I will not be using e.g. Aggregator, Forums etc?

# Answer
> 2 votes
Theoretically, yes if it's not enabled you can remove it... but why? You're not really saving a lot of space.

# Answer
> 0 votes
Yes, you can! But...before removing any modules, follow certain precaution steps first (backup, disable modules).

Please see http://drupal.org/node/250783 on more information on uninstalling modules.

One thing I would also consider is to remove or at least lock http access to all \*.txt files in the main D7 installation folder for security purposes.

---
Tags: 7, installation
---


# Question
Title: How to export pseudo fields display configuration to code
How can I export the configuration of pseudo fields as set from the display configuration for my entities types and their bundles ? When exporting a *normal* fields instance (with Features) its display settings, for each available view mode, are exported with it. But I cannot find how to export the settings for the pseudo fields such as the *History* field of a User entity and the *File* field for a File entity.

# Answer
Strongarm will do this because `field_bundle_settings()` stores the settings in a huge variable called `field_bundle_settings`. There is a patch to move it into several variables, but it'll be variables nonetheless.

Edit: I guess the core source code counts as "official source", doesn't it?
> 7 votes

# Answer
Have you tried Display Suite? It allows for that and much more. It might be overkill, but it just solves your issue AND is exportable in features.

See mortendk post on Display Suite, particularly his slides.
> 1 votes

---
Tags: entities, features
---


title: User Registration Module for Drupal

text:
# Question
Title: User Registration Module for Drupal
Drupal uses email for user registration purpose. Instead of the out-of-box Drupal user registration that requires user to specify a username and email address, I want a full-fledged user registration form ( with captcha, user profile etc, like yahoo or gmail registration) for my website.

Is there a module that does that?

# Answer
> 24 votes
There are a couple of options for this.

To get profile fields the most common solution is the profile module included in Drupal core. Go to `Administer > Site building > Modules` and enable it under core-optional. Then you can configure the Profile module at `Administer > User settings > Profile` and in the settings you can say whether the fields will show during registration or not.

To get a captcha during registration you will need one of a couple of modules:

I prefer HCaptcha because it works very well and even can earn you some money, but it sends your content to an external site to do some verification.

There is also Captcha which provides integration with other options.

# Answer
> 11 votes
The typical choice for this is to use a combination of content\_profile to create the user profile as a node, content\_profile\_registration, a component of content\_profile, to create such a profile at registration using such a full-fledged node edit form, and possibly auto\_assign\_role if you have multiple types of users with distinct profile types.

For the captcha part, Mollom is an interesting service, as Greggles suggested, but you might also want to consider reCaptcha, which is good too at even doubles as a public service.

# Answer
> 8 votes
It would appear that the recommended process now is creating fields. From the Drupal site:

> The Profile module is deprecated in Drupal 7. It is kept around only to provide an upgrade path for Drupal 6 sites that used it. Use of the Profile2 module or creating fields directly on the user entity is recommended in Drupal 7.

# Answer
> 1 votes
ReCaptcha for sure.

You can also have the simple core profile fields show up in registration if you want to stay lean. Though this often requires you to theme user\_profile.tpl.php if you want that page public.

PS: The Email Registration module may be of user, as well as LoginToboggan.

# Answer
> 1 votes
With regards "full-fledged user registration form", you can go to Admin \>\> Use Management \>\> Profiles then create/customize your fields and make sure that you tick the "Visible in user registration form" option.

# Answer
> 0 votes
If I edit `user_profile.tpl.php` then I can easily maintain registration part as I want.

```
<?php
   // Validate the username:
   if (user_access('change own username') || user_access('administer users') || arg(1) == 'register') {
     if ($error = user_validate_name($edit['name'])) {
       form_set_error('name', $error);
     }
     else if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
       form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
     }
     else if (drupal_is_denied('user', $edit['name'])) {
       form_set_error('name', t('The name %name has been denied access.', array('%name' => $edit['name'])));
     }
   }
?>

```

---
Tags: users
---


title: Dynamic section-specific submenu

text:
# Question
Title: Dynamic section-specific submenu
I have a problem that's driving me bananas on Drupal 7.

My need is very simple. I have a site with a bunch of communities with URLs like

http://domain.example/community/communityname

All of these communities have similar structures with pages like "learning", "blog" etc. which are at URLs such as

http://domain.example/community/communityname/learning

I need to create a navigation menu for each of these communities without actually creating a separate menu item for each. How can this be achieved?

I tried doing this with hook\_menu and even after 3 hours of relentless googling and fiddling about I just can't seem to get this working.

Any help is much appreciated.

Here's my non-working code:

```
function mymodule_menu(){
    $items = array();
    $items['community/%mymodule_arg/learning'] = array(
        'title' => 'Learning',
        'page callback' => 'mymodule_view_page',
        'page arguments' => array(1),
        'menu_name' => 'menu-community-menu',
        'type' => MENU_NORMAL_ITEM,
        'access callback'=>TRUE
    );
    return $items;
}

function mymodule_arg_to_arg($arg) {
    return (empty($arg) || $arg == '%') ? "community-a" : $arg;
}

function mymodule_view_page($context) {
    return drupal_goto("community/" . $context . "/learning");
}

```

If I replace the wildcard from the items array key and replace it with a static string, the code works. Also if I just return a string from `mymodule_arg_to_arg()` it works. But I just can't seem to make it dynamic.

# Answer
You seem to me trying to make it more complicated as necessary. You can simply use the arg function http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7

in your example domain http://domain.example/community/communityname

arg(0) = community;

arg(1) = communityname;

so why not just use arg(0) and arg(1) in your dynamic link url
> 1 votes

---
Tags: 7, routes, hooks
---


# Question
Title: What alternatives exist for Autologout in D7
Since the autologout module isn't ready for prime time for D7, what are some alternatives out there?

Is there any snippet out there already that can be used in a sample custom module that will logout users for x minutes of inactivity?

**Update 1**: The suggested snippet here keeps D7 from crashing, but does not logout the user.

Thanks!

# Answer
We ended up working with a third party, and they helped with getting the version for D7 to work. Look at #19 comment in the issue queu.
> 0 votes

# Answer
You can just lower the cookie lifetime in your `settings.php` file as a temporary solution.

> Set session cookie lifetime (in seconds), i.e. the time from the session is created to the cookie expires, i.e. when the browser is expected to discard the cookie. The value 0 means "until the browser is closed.

```
ini_set('session.cookie_lifetime', 2000000);

```
> 1 votes

---
Tags: 7, users
---


# Question
Title: Content profile image (CCK imagefield) instead of default drupal picture
tried what igorik said on drupal.org == http://drupal.org/node/609454#comment-2172258 Placed user-picture.tpl.php in my theme directory and replaced code inside it:

```
<div class="picture">
<?php print $picture; ?>
</div>

```

to:

```
<?php
$img_url = $content_profile->get_variable('profile', 'field_photo');
print l(theme('imagecache', 'msg_profile_pic', $img_url), 'user/' . $account->uid );
?>

```

but all what im getting after these actions is WSOD... set to display errors true in index.php, but still can't see any errors. Help me guys! Thanks

# Answer
To find out errors in WSOD you can look at you Apache Error Log, in Ubuntu you can execute `tail -f /var/log/apache2/error.log` and you will see the php error.

It's pretty sure the problem come from $content\_profile which doesn't seem to be instanciated and thus don't carry the whole content profile object. You can load it using content\_profile\_load.
> 1 votes

# Answer
You might want to look at the ImageField Avatar module which is able to automatically synchronize images from a content\_profile CCK ImageField to the core drupal user picture field.
> 0 votes

# Answer
By default, `$content_profile` variable is `NULL` in `user-picture.tpl.php` file, while you don't explicitly load its contents with content\_profile\_load() function or make this variable available in this template too. (Citing from the official readme about the places where this variable is available: "The $content\_profile variable is available in the page, node, comment, user\_name, user\_profile, user\_signature, search\_result and some other templates.")

I think it's a better solution to create your own `user-profile.tpl.php` (you should copy it from `/modules/user` directory to your own theme's `templates` directory, and delete theme registry cache after that), where the `$content_profile` variable is already set, and print the customized user profile picture in this one.

When you use the Content Profile module's `get_variable()` function, you usually get an `array` or `NULL` (if the variable doesn't exist).
If it's an image field (and you query its content with e.g. `$content_profile->get_variable('profile', 'field_photo');`), the content of the variable looks something like this:

```
array (
  0 =>
  array (
    'filename' => 'default_avatar1.gif',
    'filepath' => 'sites/default/files/imagefield_default_images/default_avatar1.gif',
    'filemime' => 'image/gif',
    'source' => 'default_image_upload',
    'destination' => 'sites/default/files/imagefield_default_images/default_avatar1.gif',
    'filesize' => 5711,
    'uid' => '1',
    'status' => 1,
    'timestamp' => 1320633662,
    'fid' => '54',
    'default' => true,
    'nid' => '446',
  ),
)

```

So in your case, you should rather do something like this (in the appropriate place in `user-profile.tpl.php` file):

```
$user_profile_photo = $content_profile->get_variable('profile', 'field_photo');

print l( theme('imagecache', 'msg_profile_pic', $user_profile_photo[0]['filepath'], 'just a test image', 'test image'), 'user/'.$account->uid, array('html' => true) );

```

Of course, `'field_photo'` must be a valid CCK field (previously set in Content Profile's fields), and `'msg_profile_pic'` must be a valid ImageCache preset.
Just tested, it works on my site.
> 0 votes

---
Tags: nodes
---


# Question
Title: How do I exclude a single menu item from the home page?
I have a menu that displays on every page, and the top link for that menu is the "Home" link. The clients do not want this menu item to appear when a user is viewing the home page, but wish it to be there at all other times. How can this be accomplished? There's no way I see to set an excluded page for menu item links.

# Answer
I ended up putting the home link in a separate menu/block, then set that block to not display on the page.
> 0 votes

# Answer
Here is one method, and I must confess it may not be the absolute best. This method works for a menu that is not inside a block.

In your page.tpl.php use the following snippet:

```
if (drupal_is_front_page()) {
  foreach ($primary_links as $key => $value) {
    if (in_array('Home', $value)) {
      unset($primary_links[$key]);
    }
  }
}

```

The snippet will hide the element that contains the value 'Home' in the 'title' attribute.

Place that snippet before this chunk of code (so that $primary\_links is modified before it is printed out):

```
<?php if (isset($primary_links)) : ?>
   <?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
<?php endif; ?>

```
> 5 votes

# Answer
You could also do it with CSS. Get the class for the front page - which might be something like .page-front - and the class for the menu item - which might be something like .main-menu ul li.first - and hide it.

So your CSS would look sort of like this -

```
.page-front .main-menu ul li.first {visibility:hidden;width:0px}

```

That'll blank out that one menu item and move the rest over seamlessly.
> 2 votes

---
Tags: routes, navigation
---


title: Creating Code Snippets

text:
# Question
Title: Creating Code Snippets
I'm attempting to use Drupal as creating a pretty versatile code snippet site for storing all of my and others goodness. Yeah I know, sounds a bit familiar, but stick with me. What I'm having a hard time grasping is the best way to handle this in terms of both functionality and security.

At its simplest form, I'm thinking I'd create a Code content type with some taxonomy attributes, language type, etc. and then the actual 'body' of the node will be the code snippet itself. What I'm struggling on is, do I allow unfiltered text through here so anything and I mean anything can be put in and then on the node display just wrap the body in a code or pre block? I think then I could just wrap that with Google Prettify and bam, code snippets.

Am I way off with this? Is there something I'm missing with how that could conceptually work? In terms of security, it seems a single code or pre block from any code actually rendering sounds a bit scary - is that how normal code snippet sites work?

I've been fumbling around with ideas in my head, so any help to either lead me in the right direction or slap some sense into me would be greatly appreciated. Thanks!

# Answer
I would definitely encourage you to look at the http://drupal.org/project/geshifilter input filter

From the page:

At the time of this writing the GeSHi library supports highlighting for **more than 200 programming languages and configuration syntaxes**, including: ActionScript, Ada, Apache Log, AppleScript, ASM, ASP, Bash, C, ColdFusion, C++, QT, C#, CSS, D, Delphi, Diff, DOS, dot, Eiffel, Fortran, Groovy, Haskell, HTML, INI, Inno, Java, Javascript, LaTeX, Lisp, Lua, Motorola 68000 Assembler, Matlab, mIRC Scripting, MySQL, Objective C, OCaml, OpenOffice.org Basic, Oracle 8 SQL, Pascal, Perl, PHP, PL/SQL, Python, QBasic/QuickBASIC, Rails, Microsoft Registry, robots.txt, Ruby, SAS, Scheme, Smalltalk, Smarty, SQL, TCL, Text, Visual Basic, vb.net, VHDL, XML, X++.

There is a stable D7 and D6 version.
> 2 votes

---
Tags: nodes, input-formats
---


# Question
Title: Call User Profile Field in Node Template
I have a field in my user profile of byline (field\_byline). I'd like to call this in the node template so that the byline is included next to the author's name (e.g. Posted by Mr. Rogers | Sweater Entrepreneur) I kind of have it working, but not quite there yet. I'm using Drupal 7.10

**Right now, I have this in my template.php**

```
global $user;
  $user = user_load($user->uid);
  $bylines = field_get_items('user', $user, 'field_byline');
  if ($bylines) {
    $vars['field_byline'] = $bylines[0]['value'];
  }

}

```

**And this in my node.tpl.php**

```
if (isset($field_byline) && !empty($field_byline)) :
  echo '<span class="byline">| ' . $field_byline.'</span>';
endif;

```

But, my problem is this only calls the correct byline while viewing the individual node. It breaks on the front page when all the nodes are looped out and only displays the byline of the first user, not the one that wrote the post.

Any help or direction would be much appreciated!

# Answer
> 3 votes
global $user is that of the currently logged in user, not specifically the owner of any specific content.

So what your code was doing was just looping through printing your byline, eg, admin, eg uid 1. What you need to do is grab the uid from the specific user's content, user\_load(THAT-UID) into a variable, and then use that to get the byline into vars\[\] in hook\_preprocess\_node() so it goes to the specific node in question, not the page it is printed on.

(in D6 at least, still learning D7 but I am sure it's pretty similar)

Addition/Edit: In D6, you can get the uid of the node author like this:

```
function hook_preprocess_node(&$vars) {

  $node=$vars['node'];
  $uid=$node->uid;

  $byline= "whatever you need to do to get it with $uid"

  $vars['byline']=$byline;

}

```

just change hook to your theme or module name and you should be on your way. You can now use the byline variable in your node.tpl.php (barring any typos or brainfades of mine above :)

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


title: Content types & ubercart

text:
# Question
Title: Content types & ubercart
I have another question about ubercart. I have a content Type hotel & a content type tript (city trips etc) that people can buy, (just one price). I really don't know if it is possible to add my content type to ubercart so i do not have to add this all again manually. I hope this question is clear.

Thanks

# Answer
I'm pretty sure that if you go to `admin/store/products/classes` and add a class where the Class ID is the same as the machine name of the content type that Ubercart will pick it up as a product type.
> 1 votes

---
Tags: ubercart
---


# Question
Title: How do you get the options from a select form?
As a follow-up to my last question regarding creating a dynamic select using JavaScript and the Forms API, I'm now wondering how do you actually get the options from that select list in a submit function. I've read "How to get All options of a 'select' field?" but I have yet to get it working with my code. Maybe because this person is using a CCK field and I'm using the Forms API which as far as I've read works differently. I've also tried pulling the data from the $form\_state as well as the $form with no luck. Below is my code for a more complete picture of what I'm trying to do:

```
function _jstest_form($form, &$form_state) {
  $form['list'] = array(
    '#type' => 'select',
    '#options' => array('1', '2', '3'),
    '#size' => 4,
  );

  $form['text'] = array(
    '#type' => 'textfield',
  );

  $form['add_button'] = array (
    '#type' => 'button',
    '#value' => t("Add"),
    '#after_build' => array('_jstest_after_build'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('_jstest_submit'),
    '#after_build' => array('_jstest_after_build'),
  );
  return $form;
}

function _jstest_submit($form, &$form_state) {
  //  Do stuff with options from select
}

```

# Answer
> 2 votes
`$form` is the array build on server side, and it is not modified from JavaScript code executed from the browser, as that array is never passed to the browser. That is the reason why `$form['list']['#options']` contains only the values set from the form builder.

The code that retrieves the value of `$form` is the following one, contained in drupal\_build\_form():

```
  // If the incoming input contains a form_build_id, we'll check the cache for a
  // copy of the form in question. If it's there, we don't have to rebuild the
  // form to proceed. In addition, if there is stored form_state data from a
  // previous step, we'll retrieve it so it can be passed on to the form
  // processing code.
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  if ($check_cache) {
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  }

```

When the form is submitted, that code retrieves the value of `$form` used to build the form.

# Answer
> 0 votes
I think if you want to pass the dynamic option list (client side javascript) back to the the server (PHP) then you've got two options:

1. Have another, hidden, field that your javascript sets the value of at the same time that it is adding options to your select;
2. Have your javascript execute a small AJAX callback that will get the server to save the values in the session.

---
Tags: 7, forms
---


# Question
Title: How do I call some function after an AHAH callback that adds a new item?
I've tried

```
'#ahah'   => array(
        "url": "/?q=content/js_add_more/pmemo/field_tracks_disks_chapter",
    "event": "mousedown",
    "keypress": true,
    "wrapper": "field-tracks-disks-chapter-items",
    "selector": "#edit-field-tracks-disks-chapter-field-tracks-disks-chapter-add-more",
    "effect": "fade",
    "method": "replace",
    "progress": { "type": "throbber" },
    "button": { "field_tracks_disks_chapter_add_more": "Add another item" } ,
        'after' : 'myJsFunction'
),

```

But it is not working.

I wasn't able to find any solutions to this problem.

Thanks for any help.

# Answer
> 2 votes
You could handle ajaxComplete jquery event, which is called right after completion of ajax/ahah requests.

---
Tags: ajax
---


# Question
Title: How can I tell which site uses which database?
I have a multi-site Drupal installation that's misconfigured. The settings information has been confused, and I need to map databases to particular sites. I am tasked with cleaning up the mess.

For any given database from a Drupal installation, what tables can I look at to see which site was using it?

# Answer
Big giveaways will be in the variable table, especially the two rows with the names:

* `site_mail`
* `site_name`

As hopefully these are different for each one of your sites.

Perhaps this database query can help you:

```
SELECT * from variable WHERE name LIKE 'site_%';

```
> 6 votes

# Answer
Drupal doesn't save any reference to the domain name in the database.
If the value you set for the site mail, or the site name is different for each domain of the multi-site, then you can look at the content of the "variable" table: The rows for those values are "site\_mail" and "site\_name."
> 2 votes

# Answer
Though also not a foolproof method, the URLs on images and other uses of Insert will sometimes end up with absolute paths w/ domain name.

On Drupal 7 you can try

```
SELECT *
FROM field_data_body
WHERE body_value LIKE 'http%'

```

On Drupal 6, you can try

```
SELECT *
FROM node_revisions
WHERE body LIKE 'http%'

```

Then look at the results.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Adding gmap markers programmatically with a module
I've been researching how to add markers to a drupal 7 gmap for more hours than I feel comfortable admitting. The reason I have to do it through a module and not views is because of client specifications that I won't go into here. The code below is what I have so far, everything I've found seems to point in this direction and it looks right to me. But when I go to the page, no markers show on the map. Can anyone help me out here?

```
function rrs_custom_menu() {
$items = array();
$items['search-by-towns'] = array(
    'title' => 'Search by Towns',
    'page callback' => 'search_by_towns',
    'access arguments'  => array('access content'),
    'type'  => MENU_CALLBACK,
);

return $items;
}
function search_by_towns() {
$query = "SELECT node.title AS node_title, location.lid AS location_lid, location.latitude AS gmap_lat, location.longitude AS gmap_lon, location.name as loc_name, location.street, location.city, location.province, location.postal_code, gmap_taxonomy_node.marker AS gmap_node_marker, taxonomy_term_data.tid AS tid, taxonomy_term_data.vid AS vid, gmap_taxonomy_term.marker AS marker
    FROM
    {node} node
    LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
    LEFT JOIN {location} location ON location_instance.lid = location.lid
    LEFT JOIN {gmap_taxonomy_node} gmap_taxonomy_node ON node.vid = gmap_taxonomy_node.vid
    INNER JOIN {taxonomy_index} taxonomy_index ON node.nid = taxonomy_index.nid
    INNER JOIN {taxonomy_term_data} taxonomy_term_data ON taxonomy_index.tid = taxonomy_term_data.tid
    LEFT JOIN {gmap_taxonomy_term} gmap_taxonomy_term ON taxonomy_term_data.tid = gmap_taxonomy_term.tid
    WHERE (( (node.status = '1') AND (node.type IN  ('listing', 'town')) AND (taxonomy_term_data.vid = '3') ))
    ORDER BY tid desc";

    $result = db_query($query);
    $marker = array();

    foreach ($result as $res) {
        $text = '<div class="location vcard"> <div class="adr"> <span class="fn">'.$res->loc_name.'</span> <div class="street-address"> '.$res->street.' </div> <span class="locality">'.$res->city.'</span>, <span class="region">'.$res->province.'</span> <span class="postal-code">'.$res->postal_code.'</span> </div> <div class="map-link"> <div class="location map-link">See map: <a href="http://maps.google.com?q='.$res->gmap_lat.'+'.$res->gmap_lon.'">Google Maps</a></div> </div> </div>';

        $marker[] = array(
            'latitude' => $res->gmap_lat,
            'longitude' => $res->gmap_lon,
            'markername' => $res->marker,
            'offset' => 0,
            'text' => $text,
            'opts' => array(
                'title' => '',
                'highlight' => 0,
                'highlightcolor' => '#FF0000'
            )
        );
    }

    $map_array = array(
        'id' => "auto1map",         // id attribute for the map
        'width' => "685px",        // map width in pixels or %
        'height' => "480px",      // map height in pixels
        'latitude' => '36.10237644873644',    // map center latitude
        'longitude' => '-80.8758544921875',  // map center longitude
        'zoom' => 8,              // zoom level
        'maptype' => "Map",       // baselayer type
        'controltype' => "Small"  // size of map controls
    );
    $map_array['markers'] = $marker;

  $output = theme('gmap', array(
      'element' => array(
        '#type' => 'gmap',
          '#gmap_settings' => $map_array,
          '#input'  => FALSE,
          '#theme'  => 'gmap',
          '#children'   => '',
          )
        )
    );

return $output;
}

```

# Answer
> 1 votes
I wouldn't even get that fancy. Just use drupal\_add\_js to send an array of markers to a page, then call drupal\_add\_js to call your basic javascript that instantiates your map. Gmap hasn't been updated for V3 of the Google Maps API (so you need to go get a key, and you need to update the key when you move sites) and I've found that it's easiest, especially if you only need it on one page, to just call your own stuff.

EDIT: Maybe an example will help.

I had to do something similar where I wanted custom markers based on a set of results. In my preprocess I did:

```
  foreach($variables['results'] as $key => $result) {
    $store = node_load($result);
    $markers[$key] = array(
        'latitude' => $store->field_lat[0]['value'],
        'longtitude' => $store->field_lon[0]['value'],
        'title' => $store->title,
    );
  }
  $settings['markers'] = $markers;

  /* Add in the settings first */
  drupal_add_js($settings, 'setting');
  /* Then add in the javascript to instantiate map */
  drupal_add_js($module_path . '/map.js');

```

Then in my map.js:

```
Drupal.behaviors.map = function(context) {

  var initialZoom = true;
  mapInit();
};

function mapInit() {
  /* Get the markers variable set in PHP */
  var markers = Drupal.settings.markers;

  var myOptions = {
    mapTypeId : google.maps.MapTypeId.ROADMAP,
    scrollwheel : false,
    draggable : false,
    disableDefaultUI : true
  };
  var mapElement = document.getElementById("map");
  var map = new google.maps.Map(mapElement, myOptions);
  /* Loop through my markers and add them to the map */
  $.each(markers, function(index, value) {
    var latlng = new google.maps.LatLng(value.latitude, value.longtitude);
    bounds.extend(latlng);
    var marker = new google.maps.Marker({
      position : latlng,
      map : map,
      title : value.title
    });
  });
}

```

# Answer
> 0 votes
Try using the jMapping jQuery plugin instead because it uses semantic markup to create a Google map. There are a ton of reasons to use this over gmap -- first and foremost you can leverage Google Maps JavaScript API V3. Also, jMapping has a callback that refreshes the map. This way you can have an event handler that listens for a change in zoom or map center location and use the lat / lng parameters to query the Drupal database that uses the super simple Ajax macro system in Drupal 7 to return the semantic data wrapped in a div element to the page which can trigger a jMapping refresh callback.

I didn't get that fancy because I'm going to first use Apache Solr to run the proximity search. I built a module that is hosted on Github that uses jMapping, it's a little dated because Geofield and Apache Solr Location for Drupal 7 hadn't been created yet which are now better than my system.

My implementation can be found on http://windwardguide.com if you want to see it in action. It uses Views of course

Here is the Views template for printing a row of information that contains the map information in the $metadata variable. Super easy to work with.

```
<?php
  $photo_count = trim(strip_tags($fields['field_photo_count']->content));
  $review_count = trim(strip_tags($fields['field_review_count']->content));

  $data = array();

  $data['lat'] = trim(strip_tags($row->field_data_field_address_field_address_lat));
  $data['lng'] = trim(strip_tags($row->field_data_field_address_field_address_lng));
  $data['path'] = trim(strip_tags($fields['path']->content));
  $data['nid'] = trim(strip_tags($row->nid));
  $metadata = array();
  if (!empty($data['nid']) || !empty($data['lng']) || !empty($data['lat'])){
    $metadata = array(
      'id' => $data['nid'],
      'point' => array(
        'lng' => $data['lng'],
        'lat' => $data['lat'],
      ),
    );
  $fields['metadata']->content = json_encode($metadata);
  }
?>

<?php if ($fields['metadata']->content): ?>
  <li id = "nid-<?php print $data['nid'] ?>" class="map-location" data-jmapping='<?php print $fields['metadata']->content ?>'>
    <a href="<?php print $data['path']?>" >
        <?php if (!empty($fields['field_logo']->content)): ?>
          <div class="map-logo"><div class="ml-level-1">
          <?php print $fields['field_logo']->content?>
          </div></div>
        <?php endif; ?>
      <h3><?php print $fields['title']->content ?></h3>
      <div class="fivestar-rating">
        <span class="description">Average rating: </span>
        <?php print $fields['value']->content ?>
      </div>
      <div><?php if (isset($fields['proximity'])):?><?php print $fields['proximity']->content ?><?php endif;?></div>
      <div class = "reference-count">
       <span class = "photo-count">Photos (<?php print $photo_count ?>)</span>
       <span class = "review-count">Reviews (<?php print $review_count ?>)</span>
      </div>
    </a>
  </li>
<?php endif; ?>

```

---
Tags: 7, google-maps
---


# Question
Title: ubercart - Add sku to a product catalog title via tokenizing it or adding it to a view?
I'm looking to add the sku in the product catalog view.

Thus producing this:

`[title][sku]`

Is there a way to tokenize it? I've looked around each field. It seems as the sku is not exposed in views as a field.

# Answer
I can see SKU in views, see the screenshot below, so not sure if I'm missing something obvious about the question.
> 1 votes

---
Tags: views, 6, ubercart
---


# Question
Title: Auto resize iframe from different domain?
I already post a question regarding this issue but I haven't got any solid answer(s). Since we are not allowed to communicate inside the iframe due to "Same Origin Policy", which I almost give up due to all responses that there is no way to re-size the height of an iframe coming from different domain.

Being eager to solve the problem I searched for solutions and I found this easyXDM which looks like a solution to my problem. Any of you guys have an idea about this. In addition to that I read this post also.

I also tried this one but it keep refreshing the page and keep looping to add height. Looking forward to hear from you guys.

# Answer
I'd hate to say it, specially as the author of easyXDM, but http://consumer.easyxdm.net/current/example/resize\_iframe.html is kinda *the* way to do it if you need cross-browser (and especially IE6) support. If you're fine with only supporting more modern browsers, then using postMessage directly is not that hard.
> 1 votes

---
Tags: javascript, theming
---


# Question
Title: How do I add a webform to my Event content type View
I'm using the Date module to create custom Event content types. I'm using Webform to create registration forms for each event. I've created a View that displays events in a table based on start date/end date. I would like to add a link to the corresponding webform to the event in the View. Is there a way to do that? (Using D7 with all modules updated.) I thought I would need a relationship, but the webform is not available.

# Answer
Could you use a node reference field on the event?

Example:

1. Create your registration webform and save it.
2. Create your Event node, and in the node reference field select the Webform that will book your event.
3. In your table view you should be able to link to this referenced node.
> 1 votes

---
Tags: 7, views, webforms
---


# Question
Title: How to make author name hyperlinked to it's profile
For my site this is the sample page. Users are submitting articles and I (as admin) am creating myself a new page node and pasting the user article into it. At the same time I'm changing the author name to that of user's.

I've two questions:

* The author name( in this page it is some "clifflowe") is not hyperlinked to the user profile but when I see in as admin it is hyperlinked. How to make it hyperlinked for all users?
* Secondly after I create a new article page and simply change the author name with that of another user, will that user get any added permission on this article? Who is the original owner of this article then?

# Answer
To the first question: users (anonymous or authenticated) need to have the "View user profiles" permission.

To the second: the user you set will be the original owner. The fact that admin created it is not stored in the node anymore.
> 1 votes

---
Tags: 6, users
---


# Question
Title: Can you use the features module to replace existing functionality
Say I have an existing content type and related view on a site. Can I install Features and convert that content type and view into a feature.

I want to start using Features for better portability.

# Answer
> 3 votes
Yes, you can. You can install features, then export all the things you want to change. Install the feature on a copy of the site you are working on, and export again, after you made the changes. (and reinstall again to that copy site, until you are satisfied).

Then copy your feature to your production site, enable, and revert the feature (revert in this case means, making sure the feature behaves like defined in the feature, hence upgrading).

Good luck!

---
Tags: features
---


# Question
Title: How do I add custom primary menu using CSS and HTML
I have a Drop down mega menu using a CSS file and a HTML file. I want to use this instead of the Drupal primary menu. I have been advised to change the HTML in the page-header.inc file but I don't know how to do this?

On looking at the page-header.inc file, do I place the code under the file or in the header? I have no idea! Do I have to change this section?

```
<?php if (isset($primary_links)) : ?>
    <?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
<?php endif; ?>

```

Any advice would be great, I'm new at this.

# Answer
You could alter the menu attributes using template.php file and its functions exclusively for menu.
> 1 votes

# Answer
Since menu provides hooks, I think it's better to create a custom module a use hook\_menu to customize your menu rather than editing directly your template file. This may also help you. You can also use Menu CSS Name for that.
> 0 votes

# Answer
If I understand well your question, I think that an alternative could be add the html of your menu to a block (using a block you can handle where and who can see your menu):

(`full html` is a feature less strict to use html tags)

the CSS rules can be handled from a CSS file using the `html.php.tpl` in modules \> system file. copy/paste `html.php.tpl` file inside your template directory and edit it to add your tag to call CSS. Also is possible for your test, add your CSS with your html menu:

```
<style type="text/css">
....
</style>
<!-- now your html menu -->
<div>
....
</div>

```

I hope information be useful.
> 0 votes

# Answer
There are quite a few options, such as the valid suggestions above.

As you already have the HTML and CSS, the easiest way is to insert it into a page template, such as `page-front.tpl.php` for the Front page only or `page.tpl.php` (you'll find this in your theme folder).

You should place your html in within the `<body>` tag, preferably within the `<div id="main-menu" class="navigation">` element should you want it there, and amend your `theme.info` to include a new stylesheet or else insert the css into sytle.css (again found in your theme folder).
> 0 votes

---
Tags: 7, theming, navigation
---


# Question
Title: Specify what the Facebook "Like it" button shows on Facebook
On our website we have a Facebook "Like it" button, which works fine, but if someone "likes" us, Facebook shows an ugly picture.

As we want Facebook to link to the same content on every page, also on pages which are not driven by a node but by a view, this makes Drupal node based meta tags and open graph useless, is it?

How can we tell Facebook what to show about our website?

# Answer
Check out this page for more information about this: http://developers.facebook.com/docs/opengraph/
> 0 votes

# Answer
You can also look into the Open Graph meta tags module which allows you to specify which fields Facebook looks at when constructing its likes.
> 3 votes

# Answer
Following Lance's suggestion we tried to add the og meta tags. Unfortunately it looks like facebook is not looking at them. Any ideas?

```
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:og="http://ogp.me/ns#"
    xmlns:fb="http://www.facebook.com/2008/fbml"

...
<head>
...
    <meta property="og:title" content="Adventskalender.be | Pülss Production GmbH"/>
    <meta property="og:url" content="http://www.adventskalender.be"/>
    <meta property="og:image" content="http://www.adventskalender.be/pp_logo.png"/>

    <meta property="og:site_name" content="Adventskalender.be"/>
    <meta property="fb:admins" content="105102305182"/>
    <meta property="og:description"
        content="Öffnen Sie ihr Fenster und gewinnen ein iPad 2."/>

...

</head>
<body
...

```
> 0 votes

---
Tags: 7, views, social-network
---


title: qTip2 and Drupal 6 troubleshooting

text:
# Question
Title: qTip2 and Drupal 6 troubleshooting
I am currently trying to implement a tooltip using the jQuery extension, qTip2. I have installed both of the files included in the extension (jquery.qtip.min.js and jquery.qtip.js in my /theme/js/ location, and their appropriate CSS sheets in /theme/css) and declared them in my theme's .info.

At the moment, I'm trying to write a function that displays the tooltip "Hello World" whenever someone hovers over an element of with the attribute #T6roll. I have the following as a script in my /sites/js/ location:

```
Drupal.behaviors.magds = function (context) {
  // Sounds, if using class "sound", these "#T1roll, #T2roll, #T3roll, #T4roll" can be removed, ul.dropdown li a,
  $('ul.links li a, .sound, #T1roll, #T2roll, #T3roll, #T4roll').mouseover(function(){$.fn.soundPlay({url:Drupal.settings.magds.themeAbsolute+'flash/mouseover.wav',playerId:'embed_player',command:'play'});$("#sound").html("mouseover.wav");}).mouseout(function(){$.fn.soundPlay({playerId:'embed_player',command:'stop'});});

  // IE helpers
  if ($.browser.msie && ($.browser.version < 8)) {
    $('#main-menu li').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
  };
};

/*
 * implements jquery.qTip.js
 */

 (function($){
    $(document).ready(function() {
        $('a#T6roll).qtip({
            content: 'Hello World!',
            position: { target: 'mouse'}
        });
    });
 })(jQuery);

```

However, the site does not seem to be executing this. Is there any ideas as to what might be the cause of this? At first, I thought that it might be the qtip syntax, but I kept it as simple as can be to debug and it's not functioning.

# Answer
After doing some research, it turns out that there is active development being done in the jQuery\_Update module. Specifically, you may reference this post .

The issue with the jQuery\_Update module is that it would only update your Drupal 6 jQuery install to v. 1.3.0. With the patch that is applied in the aforementioned post, you are able to update all the way to jQuery 1.7.

An alternative to this solution would have been to load jQuery from another location and use the noConflict() function. Drupal has some excellent documentation regarding this.
> 1 votes

---
Tags: 6, javascript
---


title: Is db_query() closing connections?

text:
# Question
Title: Is db_query() closing connections?
I recently build a web site with a small-medium profile of user access (around 150.000 pageviews/month) and sometimes, in the middle of the day I get the following error:

> PDOException: SQLSTATE\[08004\] \[1040\] Too many connections in lock\_may\_be\_available()

The Drupal application is hosted with the MySQL on the same server, with an 2 CPUs Intel Xeon Quad Core and 8 GB of RAM.

I'm new on the Drupal world, and someone recomended me to use `db_query()` to throw my queries to the database. I don't know if this is the best pratice or even if this is the root of the problem. Can anyone help me?

# Answer
> 4 votes
You need to make sure the number of MySQL connections (max\_connections in my.cnf) is greater than the number of PHP processes (pm.max\_children if you use php-fpm, or MaxClients if you're using Apache mod\_php).

The default for Apache is often 300, and the MySQL default is only 100, so you can run out of connections pretty quickly if these values aren't tuned.

# Answer
> 0 votes
Actually, lock\_may\_be\_available() is using `db_query()`; if that would not cause the error you are seeing, then you should not see it when `lock_may_be_available()` is called.

It is suggested to use `db_query()` when the query that is being executed doesn't need to be altered from other modules; in that case, it is preferable to use db\_select().

If you look at the code of `db_query()`, and `db_select()`, you will notice that both call `Database::getConnection` to obtain the database connection. The cause of that error is surely not the use of a function instead of the other.

```
function db_query($query, array $args = array(), array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }

  return Database::getConnection($options['target'])->query($query, $args, $options);
}

```

```
function db_select($table, $alias = NULL, array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->select($table, $alias, $options);
}

```

---
Tags: 7, database
---


# Question
Title: How can I implement Schema.org on my Drupal 6 site?
I can't seem to find a straight-forward answer to implementing this - http://googleblog.blogspot.com/2011/06/introducing-schemaorg-search-engines.html \- on my Drupal site.

I've found lots of Drupal discussion about microformats, RDF and RDFa, as well as support for RDF in Drupal 7 core, but I can't find a module that will help me to take advantage of Schema.org in Drupal 6.

As a non-developer, how can I easily start to work with Schema.org on my Drupal 6 site?

# Answer
> 2 votes
I would imagine that this isn't going to be possible anytime soon, if at all.

> The module leverages the native RDFa layer present in Drupal 7 core. Doing the same in Drupal 6 is impossible or would involve a lot of patching. In any case, I won't have any resource to work on a Drupal 6 version of this module.

Taken from here.

Although this is in a post requesting a backport of the schema.org module, the reasoning behind why the maintainer can't do it would apply to anyone else.

# Answer
> 4 votes
Anyone coming across this looking for this in Drupal 7 (I know the question is for D6), see the Schema.org module. Using this module sites administrators can specify what schema.org terms they want to associate with their content types (e.g. Art Gallery, House, Event, Person, etc.) and their fields (description, participants, etc).

Although this project is syntax agnostic, the schema.org types and properties selected by the site administrator will be used as part of the native Drupal 7 RDFa markup.

You can also use the Microdata module. Microdata is a module which takes care of embedding schema.org terms in HTML per the microdata spec. Core does it via the RDFa 1.0 spec. There is a UI for schema.org in microdata so that it does not have to depend on other modules for the UI (Drupal core does not include such UI).

---
Tags: 6
---


# Question
Title: External anchor link or map for attached images
I'm looking to wrap the attached images (part of the content type) in an anchor. Typically we are putting together pages that are cross promotions so they go out to other non-Drupal sites

For now we are putting the images in via HTML with the a and img tags on the ones we need external links for. Now we are using views to have a grid page, block, views slideshow but these manually input images are not visually promoted in these new views.

Some had suggested having the link below the image in text (using the link module) but that solution is confusing users who see our standard 'click here to book' and 'book now' phrases on the image.

Simply how can I wrap the image with a link? (with or without the link module, which doesn't wrap)

# Answer
You can copy the templates views uses to your theme and modify them so that a field returned in the view is used to theme another. Views has this built in in its latest versions, but only allows divs, spans, etc, and you want an anchor. Check out Exposing Individual Fields on Output for Styling here for an example of what I am talking about. There they wanted to just wrap an in a div to set the color, but you could use the same concept to wrap it in an anchor.
> 1 votes

---
Tags: nodes, media, navigation
---


# Question
Title: How do I create e-products, and store order id+uid in my own tables in case of successful purchase via PayPal
On a website I'm developing, there's a plan that **users could buy some "online" products (or e-products) cheaply via PayPal, and than give these products to each other as a present.**
For example, one user could buy a star (or more) for 1€, and send this star to another user he/she likes as a gift.
So nothing would be shipped, nothing would be downloaded.
I already have Ubercart set up with a PayPal Sandbox API key (there will be other products too), so I can see that online transactions seem to work successfully for products that can be shipped.

1. **How can I create products that can not be shipped, can not be downloaded, just simply purchased and registered, assigned to a given user (like an "online" product, which users can utilize on an online surface)?**
I could create a "star" product in my Ubercart webshop, let users buy it, and than check this type's stuffs in Ubercart tables.
2. **After a successful purchase, how could I check the order id (for the "star" product), and store the purchase process in my own tables** to let users present these "online" products to each other (there would also be a field to whom it was sent) and register when this whole thing happened, and that one user already took this opportunity?
(To let you understand why it's needed: there would also be a little icon on the site indicating that users already have e.g. 12 stars that could be virtually given to another user; besides, there would be another icon indicating the user got a star from another user \[which user gave it, and when\]. I would also like to generate an own unique code for these stars to utilize them later for example for a draw!)

Any good ideas are appreciated. Ask if anything isn't quite clear!
Thank you in advance!

# Answer
> 1 votes
OK, solved it with Conditional Actions!

1. I created a new product class on `/admin/store/products/classes` site. Let's call it "`My Stuff`" (class id: `my_stuff`).
2. The previous step created a new content type with the "`My Stuff`" name. So I went to "**Create content** \> My Stuff" (`/node/add/my-stuff`).
3. I left *"Product and its derivatives are shippable."* **UNCHECKED** (as I didn't to be shipped). **Gave it an own SKU**, sell price, description, uploaded an image, etc. as usual. OK, product created.
4. Went to "**Conditional actions**" (`/admin/store/ca` ; don't forget to enable this module), "**Add a predicate**" (`/admin/store/ca/add`).
5. Gave it a title, set "**Customer completes checkout**" trigger, gave a description, set my own class, set status to Enabled, pushed "*Save predicate*" button.
6. Under "Conditions" tab, selected "**Check an order's products**", pushed "*Add condition*" button.
7. Under "**Product models:**", I selected the SKU given in step 3.
8. Clicked on "**Actions**" tab. Selected "**Execute custom PHP code**", pushed "*Add action*" button.
9. Here I could "play" with the **`$order` and `$account` variables** in my custom code, and this was the key. This way I could loop through `$order->products` array (with `for` or `foreach`), reach the customer's user id via `$order->uid` (or `$account->uid`), read quantities (in the loop, with e.g. `$order->products[$product_index]->qty`, where `$product_index` is the actual index of the loop steps) and save them in my own database tables with `db_query()` function. Everything needed could now be saved in my own tables where they could be handled the appropriate way, so everything works fine now. I'm happy.

---
Tags: users, 6, ubercart, payment-gateways
---


title: Create a rent product

text:
# Question
Title: Create a rent product
I'm using the Drupal Commerce module to build a Website to manage two Flats **to be rented by days**.

The visitor select one of the two flats and then select a date (let's say it the day: 15 January 2012) and make the payment for it.

After the payment the date of 15 January 2012 will not be available to be sold again until this day has passed (the 16 january).

I first thought of creating a product type called: **Day to rent** with a field called: **date** and then creating 365 'Day to rent' products, each one for each one of the days of the year, setting the field 'date' to the corresponding date.

Then, using the calendar module and views I would show the products in the calendar allowing the visitor to click in the 'add to cart' for the day they choose.

I'm a Newbie with the module, and I now see that I cannot get 'products' inside a view. Then, my idea fails.

Now I think that I should add the field called: date to the 'Product display' instead of the product itself, but I am not sure.

Before wasting hours, I just need to know if is there any way I can accomplish this with the commerce module. Do I need an affiliated module? Do I need to develop a new module? What is the best approach to do it?

# Answer
> 2 votes
Drupal Rooms module is a perfect solution to this. It is a booking and room management solution for hotels, vacation rentals and B&Bs. It integrates directly with Drupal 7 Commerce.

---
Tags: commerce
---


# Question
Title: Create videoplayer shortcode module for drupal 7
I have a custom player I made (Using flowplayer) and would like to make a short code for the id of that player. For example, when the user pastes \[myplayer 12345\], it will display that player with the appropriate video.

Can anyone point tell me how to do this in drupal? I know in wordpress it's simple like this:

```
add_shortcode('myplayer','myplayer_video');

    function myplayer_video($attr) {

    $output = '<iframe width="448" height="282" src="http://mysite.com/embed/' . $attr[0] . '" frameborder="0" allowfullscreen="false"></iframe>';

    return $output;
}

```

My understanding is I need to make a module and I have looked at many tuts on making modules in drupal, but none on how to access the content field and diplay something or php code.

# Answer
> 1 votes
I'd look at the Custom Filter module.

# Answer
> 0 votes
Wordpress shortcodes are implemented as filters, which pretty much have a direct analogue in Drupal, which also happen to be called filters.

If you want to implement this yourself, you could have to create a custom module and then implement hook\_filter\_info in Drupal 7 or hook\_filter in Drupal 6.

There are also some module, like @Jimajamma mentions that let you do everything from the UI.

You may also want to check out the Flowplayer module to see if it fits your needs. Normally, though, I either make my own shortcodes or custom field handling, instead of using this module.

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


title: Easy theming of admin-side forms?

text:
# Question
Title: Easy theming of admin-side forms?
I need to provide a backend user with a fieldset to enter technical data, such as value (in an editfield) and unit (selected from a dropbox). Instead of the default row-based layout such as in:

```
Value: [editfield]
Unit: {dropbox|values}

```

I would like to provide:

```
Parameter name: [value editfield] {unit|list}

```

While I know I could set up a suggestion template for that, does anyone know of the easiest way to re-position the fields? Display Suite?

Artur

# Answer
> 1 votes
Try the Arrange Fields module.

> This module lets you drag-and-drop the fields of any CCK content type, Webform, or almost any other form in Drupal into the positions you would like for editing. This makes it super simple to have forms with inline fields, which you can change at any point.

---
Tags: forms, theming
---


# Question
Title: Why do I get a blank page when I create a new node?
It seems there are some problems with the content submission. When I select filtered HTML or full HTML, it shows a blank page after submitting a new node. I turned on the error messages, but I still get a blank page with no error message. When the input format is plain text, all works fine.

How do I resolve this issue?

# Answer
> 2 votes
The White Screen of Death (or WSOD) can be caused by a lot of different things. There is an article about them http://drupal.org/node/158043

Without more information, especially error messages or logs, all answers will be guesses.

Follow the steps in the article above, in order and one by one, to track down your problem. The first step is making sure you can see errors by adding:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

to you index.php or settings.php. Once you do this, you should see what is happening and be able to address it.

That said, the two biggest culprits of WSOD are errors in custom code and hitting the PHP memory limit.

---
Tags: nodes, input-formats
---


title: Drupal 7 - Extract posts and user names

text:
# Question
Title: Drupal 7 - Extract posts and user names
New at Drupal. Trying to extract from MySql the list of the posts with body and user name. Apparently since Drupal 7, the content is stored in drupal\_field\_data\_body. The problem is that it does not contain any user\_id, so I have no clue how to join the two tables. So far I am here:

```
SELECT *
FROM drupal_node node, drupal_node_revision revision, drupal_users users
WHERE 1=1 AND revision.vid=node.vid AND revision.nid=node.nid AND users.uid=node.uid

```

Need to JOIN **drupal\_field\_data\_body**

# Answer
Can I ask why you are not using views for this task?

Views 3 for drupal 7 is a powerful interactive SQL builder. And trivial tasks like this are can be easily sold without even knowing SQL or which tables to join on etc.
> 3 votes

# Answer
For this type of queries, you should use the EntityFieldQuery class that allows to execute queries for all the entities defined in Drupal 7, and from third-party modules.
> 0 votes

---
Tags: database
---


title: Keeping unused elements?

text:
# Question
Title: Keeping unused elements?
I keep a lot of unused elements that I don't bother to delete such as blocks, content types, views, taxonomies etc. Is there any speed benefit of deleting these unused elements? If so which ones?

# Answer
It could help, yes. Your site will be faster, and easier to manage.

* less elements means Drupal uses less memory
* with less elements, it takes less time to read them all (unused elements are still active)
> 1 votes

---
Tags: 6
---


# Question
Title: For a non-english single-language site, is it still best practice to write t()-strings in the theme in English?
On Drupal 7 with the i18n-modules, in what language should your default strings be written in? In modules it's obvious that all strings should be in English (for reuseability) and use t().

But a custom theme will only be used for the specific site. If the site is not in English it seems lika an awkward practice to first write everything in English and then translate to the specific language.

# Answer
If you're 100% sure that you do not need to (re-)use this code in a multi-language environment, now or in the future, you're safe using foreign language strings. Personally, I consider it best practice to always use t() because you never know what's going to happen in the future.

Be aware that strings in code that *are* run through t(), are assumed to be in English, so you have to choose between `t('English text')` or `'Svensk text'`. Never use `t('Svensk text')`.
> 3 votes

# Answer
I personally wouldn't want to use English in the theme if there was no expectation of the site ever using that language. I think it would slow down my initial coding, slow down updating text, and if the site was to need English at a later date, I doubt the quality of the initial translations would be up to scratch (because I was never anticipating them being used live). Having said that, obviously if you are going to use i18n at any point you'll need to follow the rules and use English, similarly if you want to release the theme on d.o (now or in the future), or reuse it in a project featuring i18n. One suggestion: I think I might create a function, eg.

```
function ct($string, array $args = array(), array $options = array()) {
    return t($string, $args, $options);
}

```

And use that in place of `t()`. So to continue from marcvangend you could use `ct('Svensk text')`. This way you get the convenience of using the final language, but you can easily find examples of where you've done so and quickly modify them if you later need to.
> 2 votes

# Answer
There is no difference between using `t()` in modules, or themes; in both the cases, the function expects the string passed as argument to be in English.

Between using `t()`, even when you know the page is always show in a specific language, and using a string that is in the language you know to use, using `t()` is preferable.

Why? Because in the first case, the string would be hardcoded in the code of the theme, which means you cannot change it without to change the code. If the page that you are now showing in a language needs to be shown in a different language, you should change the code of your theme to change the strings. That is exactly what `t()` avoids.
Suppose that the same code is used for more than one site, and in one site one of the string needs to be different. Without using `t()`, you would need two different themes, while using `t()` you would use the same code for both the sites.

It's enough that in the settings.php file you add lines similar to the following:

```
 $conf['locale_custom_strings_en'][''] = array(
   'forum'      => 'Discussion board',
   '@count min' => '@count minutes',
 );

```

The example is for changing the strings used for English, but the same can be done for every language; it's enough you change the "\_en" part in "locale\_custom\_strings\_en" with the language ID for the language you are interested. The first string is in English, and the second string is the translation of the first string in that language.

Suppose that your theme contains `print t('forum')`. Adding that code in the settings.php file, what the user will see, when the currently set language for that page is English, is "Discussion board"; if your theme contains `print 'forum'`, the user will always see "forum," and to change that you need to change the code of your theme.

I could also use the following code:

```
 $conf['locale_custom_strings_it'][''] = array(
   'forum'      => 'Tavola di discussione',
   '@count min' => '@count minuti primi',
 );

```

In this case, when Italian is the language set for a page, and the theme contains `print t('forum')`, what the users will see is "Tavola di discussione."
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Module/Method to cleanup content of Drupal site?
I have been assigned with the task of maintaining a specific Drupal site. The problem is that the person who created the website did not actually think it through. No input filters to be heard of, no restriction for images' placement, plain HTML everywhere.

I'm now on the spot, since I've promised to tidy up the website, and I've just realized how much work will it require. There are articles that are copy+pasted from wikipedia (the WYSIWYG editor kept all the formatting), random websites or (even worse) from MS Word.

I understand that I will have to do some manual editing and check the articles one by one, but I was wondering if there is some kind of a method that someone may have used in a similar situation. Perhaps a module that will cleanup the html of the various nodes?

**Note**: The website is built in Drupal 6, but if you have suggestions for Drupal 7, I guess that I could upgrade.

# Answer
Normally, when I have encountered this, there is too much variety to do much automated cleanup. You can do something like this, though

```
$sql = "
  SELECT n.nid
  FROM {node} n
";

$result = db_query($sql);

while ($row = db_fetch_object($result)) {
  $node = node_load($row->nid, NULL, TRUE); // bypass internal cache
  $node->body = _filter_htmlcorrector($node->body);
  node_save($node);
}

```

Either stick this in a custom menu entry or make a simple script for it. Depending on how many nodes you have, you may need to use the Batch API.

\_filter\_htmlcorrector will fix bad HTML to an extent, and I have also used check\_markup with luck, too. For check\_markup, you just need to figure out the numeric filter number to use.

Other than that, you really do need to play with the processing you do in the loop. This will give yourself a head start, but you still need to edit each article and manually check/fix things.
> 6 votes

# Answer
I guess you need to use Input format in this issue. You need to create filter and set an allowed elements to avoid dirty inputs. In the wysiwyg settings admin/settings/wysiwyg/profile/ID/edit in the Cleanup and Output tab be sure to enable the Verify HTML, Apply source formatting, and Force cleanup on standard paste. If the old nodes are created using Full HTML then you need to apply the above conf in the Full HTML profile...please let us know if that helps you
> 2 votes

# Answer
If the text looks good with Full HTML, why don't just continue to go with that? At lease, you can switch to HTMLPurifier, which gives you total control of the HTML tags/attributes. Thus you could make sure that there is no security issue (no script tags).

Then I think you must manually edit each node, clear format, add custom CSS classes, semantic HTML tags... so that your content will be semantically correct. But I suggest you only do that if it is really needed.

Or, if you just want to remove extra inline CSS/JS, unnecessary class/id attributes, there are many tools to do that, and you should do directly on the database. A 3rd party tool might be faster and more mature. E.g. there is a bug in D6 HTML corrector filter.
> 1 votes

# Answer
I've not been in this situation, so just suggestions here! Obviously back up the db before anything. I'd try and see if you can find a filter that does a decent job of cleaning up (I know you want to clean the DB itself). I'd maybe take the worst offenders and see what markup comes out with a few different HTML correctors (eg htmLawed). If any of them consistently do an ok job, then you can use a drush script, or create an action to use with VBO, to run the filter on the bodies and teasers and then save them back to the db. Then take a look and see the damage :/ Good luck
> 0 votes

---
Tags: 6, input-formats
---


title: Imagecache action for image reflection

text:
# Question
Title: Imagecache action for image reflection
I am using Drupal 7. I would like to display images with reflection effect.

For Drupal 6 there is module "Imagecache Effects" that offers this option.

For Drupal 7 there is "ImageCache Actions" module, but it does not offer reflection effect, but it provides *Custom action effect* for php code.

Can I add reflection with some custom php code?

# Answer
> 1 votes
If you're comfortable with modifying a little your theme, you can use a plugin like Reflection.js for jQuery.

# Answer
> 0 votes
I'm not sure if you know how to add CSS to your theme, but it's pretty straightforward. We've written a blog post about how to add it, here Adding CSS in Drupal Design

The reason I mention it, is that it seems the most practical way of gaining these effects, as not everything aesthetic requires a Drupal module.

Should you want to use CSS3 for example, you can easily achieve the effect you require and you can add a CSS ID or Class to certain images once you have input the required CSS code.

This article is a good tutorial on how to achieve the effect that you require: Create reflection effect using CSS3

In addition, there are jQuery plugins that can help you to create the reflection affect, however the JQuery plugin site is down (under redesign) so I think the CSS3 option is a good solution in the interim.

---
Tags: 7, media
---


# Question
Title: Does Drupal 7 use a publicly-available function to concatenate text in the "text area with summary" widget?
I'd like to make use of functionality similar to the "display summary if filled in, if not display shortened body" that is used by Drupal's text area with summary widget. Is there a publicly available function that will concatenate body text to a certain word length, taking into account that there may be embedded HTML?

# Answer
> 1 votes
The code used to render that field is contained in text\_field\_formatter\_view():

```
case 'text_summary_or_trimmed':
  foreach ($items as $delta => $item) {
    if (!empty($item['summary'])) {
      $output = _text_sanitize($instance, $langcode, $item, 'summary');
    }
    else {
      $output = _text_sanitize($instance, $langcode, $item, 'value');
      $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
    }
    $element[$delta] = array('#markup' => $output);
  }
  break;

```

You are interested in how `$output` is set. \_text\_sanitize() is a function that you can use to write similar code more specific for your case, while text\_summary() is a generic enough function you can use for your own code.

```
function _text_sanitize($instance, $langcode, $item, $column) {
  // If the value uses a cacheable text format, text_field_load() precomputes
  // the sanitized string.
  if (isset($item["safe_$column"])) {
    return $item["safe_$column"];
  }
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
}

```

---
Tags: 7, entities
---


# Question
Title: Is there a way to generate thumbnails within Drupal?
I see that Drupal 7 natively includes the GD toolkit. Looking at the documentation, there are Several Functions available to me that would seem to make it possible to, from an existing image, generate temporary thumbnails. The issue, however, is that any of the resizing methods seem to be destructive, and there is no simple way to copy images. PHP, of course, offers facilities that are low-level enough to handle this...and I'll use those if I have to...but is there a simple, Drupal way to programmatically create a thumbnail to a specified size?

# Answer
> 2 votes
First, create an image style from the Drupal UI, or by implementing hook\_image\_default\_styles in a custom module. An image style contains the resizing and cropping rules for your thumbnail. After that, you can use theme\_image\_style to create the html output for an image using the thumbnail style. Do not call theme\_ functions directly though; call it like this: `theme('image_style', ... )`. The thumbnail will automatically be created in a non-destructive way when it is first requested.

---
Tags: 7, media
---


# Question
Title: How do I create a user relationship to show author name in Views?
I want to show node title and it's author but I'm not able to find how to show the author name. I don't see Content:Author in Relationship.

How do I configure Views to show it?

# Answer
In Drupal 6 you don't need a relationship for the author name of a node, it is directly available in the fields' list.
> 1 votes

---
Tags: views, 6
---


# Question
Title: Help needed with hook_node_submit in custom module to save data
I require some help in my custom module, specifically getting the value of a form element added via ajax in hook\_node\_submit.

First I'll explain the basic module setup needs:

* You have created a content type called 'content'.
* You have created a sample taxonomy vocabulary and added some sample terms to it.
* In the content type you add a term reference field with the name 'field\_terms' for the newly created vocabulary and allow unlimited values (checkboxes).

Now you enable the module and create new content of type 'content'.

Once you select 2 taxonomy terms, a select list appears with the 2 or more selected terms in it, allowing the user to select one of the above selected terms once more (to define a main term from the selected terms - if that makes any sense)

So, in terms of the module I have written this:

1) I use the function hook\_form\_alter() and apply it to only $form\_id == 'content\_node\_form' (content type = 'content').

2) In hook\_form\_alter() I apply '#ajax' to each checkbox for the field\_term checkboxes and create a blank container where the select list will be placed after the callback.

3) I have written the function \_custom\_callback() which gets the selected checkbox term\_ids and term\_names from the field\_terms to create the select list options. It then outputs the select list if 2 or more options have been selected

4) Implement hook\_node\_submit() to grab the data from the $form\_state and move it into the node object (this is where the first errors occur)

5) Implement hook\_node\_load() to load the values when editing the page

6) Impmeneted hook\_node\_insert(), hook\_node\_update() and hook\_node\_delete() to do the db stuff.

But when I submit the form I receive the following errors - due to hook\_node\_submit:

I am unsure how to call my object in the node. My form is called

```
$form['container']['main_taxonomy_term']

```

So I presumed this would be correct:

```
/**
 * Implements hook_node_submit().
 */
function select_main_taxonomy_term_node_submit($node, $form, &$form_state) {

  $value = $form_state['values'];
  // Move the new data into the node object.
  $node->main_taxonomy_term['tid'] = $value['main_taxonomy_term'];
}

```

I have looked and tried but I just can not find any clues how to get the data from $form\_state and into the node object.

Please find attached the module. maybe someone can help me out as this is driving me insane.

Here is the module:

http://www.megaupload.com/?d=181H4B5F

Many thanks in advance.

# Answer
So now I can answer my own question:

In my module I had `$form['container']` defined in the hook\_form\_alter(), but the actual field `$form['container']['main_taxonomy_term']` wasn't defined yet as I was adding it in my callback, so naturally Drupal didn't know about the field when rendering the form.

I restructured the module, moved the `$form['container']['main_taxonomy_term'] = array(...)` into the `hook_form_alter()`, created a new function to get the select options, calling upon it in various circumstances, added some extra checks for the edit node form as the options had to be built from the database values upon first display, but after that use `$form_state` else it wouldn't refresh the list upon editing the checkbox selection...

Oh well, so i finally managed to get it working without error message.

Maybe this is helpful for anyone, or maybe it isn't at all.
> 1 votes

# Answer
After much finagling from my post above, I found myself confronted with your original problem. I had additional fields that were dependent on the clicks of a particular checkboxes field. I was able to grab the value for a `hook_node_insert` function below by making the dependent fields hidden until a check was made on the original. Here is a snippet if it could help anyone:

```
  if (!empty($form_state['values']['subject']) && !empty($form_state['values']['grade'])) {
      $form['topwrap'] = array(
            '#type'     => 'markup',
            '#prefix' => '<div id="gunge">',
            '#suffix' => '</div>',
      );
  }
  if (empty($form_state['values']['subject']) && empty($form_state['values']['grade'])) {
      $form['topwrap'] = array(
            '#type'     => 'hidden',
            '#prefix' => '<div id="gunge">',
            '#suffix' => '</div>',
      );
  }
  $form['topwrap']['topblock'] = array(
            '#type'   => 'fieldset',
            '#title'  => 'Topics',
  );
  $form['topwrap']['topblock']['topics'] = array(
        '#type'     => 'checkboxes',
        '#options' => grab_topics($subjids, $gradids, $strandids),
        '#prefix' => '<div style="background:#FFAA00;">',
        '#suffix' => '</div>',
  );

```
> 0 votes

---
Tags: 7, hooks, ajax
---


# Question
Title: Adapting a superfish menu to what I want
I am getting acquainted with Drupal 7 right now. One of the things that I have consumed a lot of time doing is understanding theming and getting the kind of Menu I want for my website.

I am using a subtheme of Bartik and have a Superfish menu (parent menu : main menu) rendering itself in the Highlighted region.

My grouch is that the menu does not render itself for the full width of the screen. The next is, I need to trigger some design changes to my menu itself which I am not sure how to.

Any leads people?

# Answer
If you need the menu to render to the full width of the screen make sure the containers the menu is in doesn't have any set widths, and then set the main ul to a 100% width. Superfish comes with a lot of default styles that can be hard to override. If you use the Drupal Superfish module, configure your Superfish block and set the 'Style' to none, and make sure drop-shadow is ticked off. If you don't use the module you can do this when you call Superfish with drupal\_add\_js (or in your init.js).
> 0 votes

---
Tags: theming, navigation
---


title: How to display tags inline?

text:
# Question
Title: How to display tags inline?
How can I display tags below an article inline? I have tried using firebug to no avail. I am using Drupal 7 and the zen sub theme.

# Answer
> 2 votes
You can use CSS to style the tags.

If your html output is this:

```
<ul class="tags">
    <li>Tag 1</l1>
    <li>Tag 2</l1>
    <li>Tag 3</l1>
    <li>Tag 4</l1>
</ul>

```

Then use the following CSS to align tags horizontally.

```
.tags li { display:block; float:left; }

```

---
Tags: taxonomy-terms
---


title: Consistent style of user-entered tables

text:
# Question
Title: Consistent style of user-entered tables
Soon I will face a problem of ensuring constant look of tables entered by user throughout the site. I will probably install one of available WYSIWYG editors and allow tables therein.

I would probably want to prepare a set of table templates (with row headers, column headers, row&column headers, with column headers and subheaders, etc...) and would want the user to select appropriate template, determine row&col count, and then just fill in the data.

My task would be ensuring that the tables get appropriate classes upon submit and process them accordingly.

Would you do that with jQuery or with some WYSIWYG editor setup/plugin?

# Answer
Perhaps you can create a wysiwyg plugin to do the job. In my case I used the hook\_wysiwyg\_plugin to create plugins I needed.
> 0 votes

# Answer
I am facing a similar problem and am developing a custom module to act when the specific content type is generated (`hook_node_presave`). My concern is that the more they are required to do to generate the format, the more things will go wrong. All the user has to do is enter the cell contents as delimited rows and the module determines the size of the table and generates all the HTML and class content to match up with the css I have developed for its display.
> 0 votes

# Answer
You can write your own filter format that parse text into HTML. Something like this

```
|table|style=3
|data11|data12|data13|
|data21|data22|data23|

```

About a wysiwyg editor, I suggest CKEditor (I don't know much about TinyMCE, though). It has a good table editor, with predefined styles for row/column/both headers.
> 0 votes

# Answer
There are two different ways to deal with user entered tables (or any other content, btw). You can either write a plugin for your WYSIWYG editor that applies classes to your content under certain circumstances (the client-side solution) or you can get the user input after it's been submitted and apply your own php logic to it (the server-side solution).

Drupal makes it very easy to go server side. It has an input filter feature that preserves the data the user has input but renders its output according to the filters' logic. Bonus: it caches the output.

Try studying filter inputs — Pro Drupal Development, the book, has a short yet complete chapter on it. You can see the API too.
> 0 votes

---
Tags: wysiwyg, theming
---


title: Globals using Drupal with views

text:
# Question
Title: Globals using Drupal with views
I have a module in Drupal for getting the url extention via `$full_url = $GLOBALS['base_url'];` Now, is it possible to make the full\_url global so I can access it in the views module?

When I make a block using views I'm only getting 3 Global option:

* Global: Custom text
* Global: Math expression
* Global: View result counter
* here I want my full\_url variable

# Answer
Views usage of the term "Global" is unrelated to PHP Globals. It means that is it globally accessible to all Views regardless of base type (node, user, taxonomy term).

If you find the need to use PHP in your Views, then you should either look into writing a custom Views handler, or try the Views PHP module.
> 1 votes

# Answer
When you select "node:path" from fields in a view, there is an option to make it absolute.
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to write a CCK widget with more than one input element?
What I am looking for is not CCK flexifield or CCK Multigroup. I am trying to develop a CCK widget that allows me to enter two or more input fields per value, kind of what Doublefield does for Drupal 7. How would I develop that?

# Answer
> 1 votes
Example are taken from Phone Number CCK field. You'll need to

1. implement hook\_field\_settings() to return the field data storage

```
176     case 'database columns':
177       return array(
178         'number' => array(
179           'type' => 'varchar',
180           'length' => CCK_PHONE_PHONE_MAX_LENGTH,
181           'not null' => FALSE,
182         ),
183         'country_codes' => array(
184           'type' => 'varchar',
185           'length' => CCK_PHONE_CC_MAX_LENGTH,
186           'not null' => FALSE,
187         ),
188         'extension' => array(
189           'type' => 'varchar',
190           'length' => CCK_PHONE_EXTENSION_MAX_LENGTH,
191           'not null' => FALSE,
192         ),
193       );

```
2. implement hook\_elements() to display the real input fields, where you create the FAPI inside the function cck\_phone\_process()

```
598 function cck_phone_elements() {
599   return array(
600     'phone_number' => array(
601       '#input' => TRUE,
602       '#process' => array('cck_phone_process'),
603       '#autocomplete_path' => FALSE,
604     ),
605   );
606 }

```

# Answer
> 3 votes
I built something like that for drupal 7. Considering CCK moved into the drupal core in d7, I'm not really sure how much different the code would be for a cck module in d6, but maybe this module will help you

I wrote this module as I had to somehow capture phone numbers, but have them split into country code / area code and number and save them into seperate columns in the database. All other field modules I tried did not allow for this!

That way all numbers can be entered uniformly and thus presented in a uniform way - especially helpful if you use it to store and manage customer information and possibly need to export it to different applications. In my case, some users would enter phone numbers with a dash, other with a slash and others again with nothing seperating values making managing them difficult and displaying them messy.

Rip the code apart and modify it to suit your needs (like only 2 fields):

It's in my sandbox: http://drupal.org/sandbox/tecjam/1320886

in Git: http://drupalcode.org/sandbox/tecjam/1320886.git/tree/e7c97511506ee6e92a44656aa02d31f4e8f69727

I like to comment my code to help myself (sometimes there are more comments than code lol). So figuring out what does what and where should not be a problem at all.

You can always ask if you have any special questions.

# Answer
> 1 votes
I guess I have to thank Jennifer Hodgdon (and Larry Page + Sergey Brin). There is a wonderful guide at Poplarware: http://poplarware.com/articles/cck\_field\_module

---
Tags: 6, entities
---


# Question
Title: How do I separate the "Product" select list & "Add to cart" submit form in a node product display?
I have a node product display which references 2 different products.

When I use the code below, it prints out both the "product select" form + the "add to cart" submit form. How do I print them out separately?

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

```

Alternatively, how do I change the HTML to print this 2 form out? I am looking for a way to theme my product display differently.

# Answer
> 0 votes
I realized that you can't, albeit after several hours of experimenting.

However, you can add a price field (and other fields) to your "add to cart" form by adding a "price" form item element. Follow the instructions here for more details: http://drupal.org/node/1300798#comment-5328550

Tell me if this helps.

---
Tags: theming, commerce
---


# Question
Title: Add extra field on check out page of Drupal 7
All we want is for the customer to have to tell us how they heard about us at checkout page even when they did not make an account.

How do I add this extra field?

We are running Drupal 7 and below are the new modules installed to accomplish this new task:

* addressfield-7.x-1.0-beta2.zip
* commerce-7.x-1.0.zip
* commerce\_extra\_panes-7.x-1.x-dev.zip
* commerce\_fieldgroup\_panes-7.x-1.0-rc2.zip
* field\_group-7.x-1.1.zip

# Answer
I think you can add a new field for your orders in "Store \> Configuration \> Order Settings \> Manage Fields."

Next, using the Commerce FieldGroup Panes module, you can add the new field as a pane in your checkout.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: How to add 'font color' option to Buedit
I have used other text editors but BUEdit is my text editor of choice: lightweight and robust.

However, what I lack in its buttons is a function to enable users to colorize (and hence beautify) their texts. I'd be grateful to know how to do so.

# Answer
You can enrich Bueditor by adding buttons to it. You can find some very well written documentation about how to add buttons to the editor in the official bueditor page.

After you have learned how to create buttons, you can use one of the already implemented buttons for text color. You can find a demo and the actual button code here.

The steps that I followed in a clean Drupal 7 installation:

1. Installed Bueditor
2. Navigated to Configuration - Content Authoring - Bueditor
3. Selected a random editor (e.g. Default) and hit "Edit"
4. Copied the 2 files from the second link in the library folder inside modules/bueditor
5. Added the following lines in "Editor specific library files":

%BUEDITOR/library/bue.style.js

%BUEDITOR/library/bue.colorbox.css
6. I went to the bottom of the page, above the "Save Configuration" button and in the blank button I added a title (i.e. Color), in the "Content" field I added the code from the second link (the code that is marked as: "Button code" (simple copy and paste)
7. In the place of the icon I just wrote: Color
8. Now just hit: "Save configuration" and go to the bottom of the page and check in the demo editor how it works.
> 2 votes

---
Tags: 7
---


# Question
Title: form_set_error highlight offending field?
form\_set\_error supposedly takes the name of the offending form element as the first param.

I have a form element that is named "field\_reviewer\_terms\_of\_service\[value\]" (as taken from firebug). My code that sets the error is:

```
    form_set_error('field_reviewer_terms_of_service[value]', t('You must agree to the Terms of Service.'));

```

The error shows up in the messages, but doesn't highlight the form element itself. What am I doing wrong?

Edited with HTML of form element:

```
<div id="edit-field-applicant-terms-of-service-value-wrapper" class="form-item">
 <label for="edit-field-applicant-terms-of-service-value" class="option"><input type="checkbox" class="form-checkbox required error" value="1" id="edit-field-applicant-terms-of-service-value" name="field_applicant_terms_of_service[value]"> I agree to the <a href="/terms_of_service" target="_blank">Terms of Service</a></label>
</div>

```

# Answer
> 1 votes
Don't put the `[value]` inside, it should work with only

```
form_set_error('field_reviewer_terms_of_service', t('You must agree to the Terms of Service.'));

```

See the documentation for `form_set_error()`.
You may have to use some `[value` inside your field if it is multivalued, see this comment but we need to see the HTML ouput for your field.

---
Tags: 6, forms
---


# Question
Title: How do I access the variables posted in a page callback?
Ok I don't know why I am having such a hard time getting my mind around how to do this. How do you access posted values in your page callback? Something in Drupal seems so hard. All examples just call `drupal_get_form()` but what do I do if I want to display the form and any results from the submit?

```
function stock_quotes_menu(){
    $items['stock-quotes'] = array(
     'title' => variable_get('market-summary-title', 'Stock Quotes'),
     'access arguments' => array('access content'),
     'page callback' => 'stock_quotes_page',
    );

    return $items;
}

function stock_quotes_page() {
    $symbols = isset($_REQUEST['symbol']) ? strtoupper($_REQUEST['symbol']) : '';
    $out = "<pre>".print_r($_REQUEST,1);
    if ($symbols != '') {
        $start = NULL;
        $pos = strpos($symbols, ",");
        /*if($pos == false){
            $start = date('Y-m-d');
        }*/
        $quotes = stock_quotes_fetch_yql_quote($symbols, $start);
        $out = print_r($quotes, 1);
    }

    $form = drupal_get_form('stock_quotes_get_form', $symbols);
    $build['snippets'] = array(
      '#type' => 'node',
      '#title' => '',
      '#prefix' => drupal_render($form),
      '#markup' => $out
    );

    return $build;
}

function stock_quotes_get_form() {
    $form['symbol'] = array(
      '#title' => t('Symbol(s)'),
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#description' => t('Enter Symbols or Symbols seperated by , to get quotes'),
      '#default_value' => !empty($form_state['values']['symbol']) ? $form_state['values']['symbol'] : 'Enter A Symbol',
    );

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

    return $form;
}

```

# Answer
By default, Drupal looks for two functions on form submission (for forms generated with the Form API): {$form\_name}\_validate() and {$form\_name}\_submit();

For what you are trying to do, you need to implement the submit handler, do something with the form values (store to session, database, etc) and then go to page that will display the values of the form. I've mocked up a quick and dirty module so you can see a couple different approaches:

```
function mymodule_menu(){

  $items = array();

  $items['sample_form'] = array(
     'title' => t('Sample Form'),
     'access arguments' => array('access content'),
     'page callback' => 'drupal_get_form',
     'page arguments' => array('mymodule_sample_form'),
  );

  $items['sample_form/success/%'] = array(
     'title' => t('Sample Form | Success'),
     'access arguments' => array('access content'),
     'page callback' => 'mymodules_sample_form_success',
     'page arguments' => array(2), //pass value of field_two to callback function
  );

  return $items;
}

function mymodule_sample_form($form, &$form_state){

    $form['field_one'] = array(
      '#type' => 'textfield',
      '#title' => t('Field One'),
    );

    $form['field_two'] = array(
      '#type' => 'textfield',
      '#title' => t('Field Two'),
    );

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

    return $form;
}

function mymodule_sample_form_submit($form, &$form_state){

  //This is where you process and store submitted values.
  //Lets use variable_set to store the value
  variable_set('mymodule_field_one', $form_state['values']['field_one']);

  //Ok, lets now redirect the user to the success page and pass field_two as an argument
  $form_state['redirect'] = url('sample_form/success/'.$form_state['values']['field_two'], array('absolute'=>true));
}

function mymodules_sample_form_success($field_two){

  $output = 'Value for field one: '. variable_get('mymodule_field_one').'<br />';
  $output .= 'Value for field two: '. $field_two.'<br />';

  //Lets display the form again, rebuilt.
  $output .= drupal_render(drupal_get_form('mymodule_sample_form'));

  return $output;
}

```
> 1 votes

# Answer
You need a submit handler function. Just add a `_submit` to the end of your form function

```

function stock_quotes_get_form_submit($form, &$form_state){
  $symbols = $form_state['values']['symbol'];
  return "You submitted this symbols: " . $symbols;
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: Change block location on page by page basis?
I am working on a custom theme that's inheriting defaults from Bartik. I want to specify that the 'recent content' block should appear in the content area on the homepage, but the left sidebar on article pages.

I see how to specify a specific area for the block on a specific page, but no way to set a different area on a different page or duplicate the block. I'm thinking it might be most logical to duplicate it, so I have front-page recent content and regular recent content, since they might look a little different. But not sure how would I go about doing that?

# Answer
I am assuming 'recent content' is "just" the output of a view, so, if I that is correct, you can create any numbers of blocks with that content by just going into views and clone()ing the display and thus creating another block that could then be placed wherever you want.
> 1 votes

---
Tags: 7, blocks
---