# Question
Title: How to access node from hook_html_head_alter()?
I want to add an `og:url` tag to the `<head>` so that the correct image shows up when my page is shared on Facebook.

I've found the `hook_html_head_alter()` hook which looks like I can add something to the head. I don't see how I can access the node object though when inside this method. I want to check if this page is for a certain Content Type. If it is that type, then look at some of the data on that node to determine which image to put in the `og:url` tag.

# Answer
Drupal alter hooks, the group of hooks including hook\_html\_head\_alter(), are not thought to add values, but to alter the values provided by another module. If you need to add a tag to the `<head>` of a node page, you should:

* In a module, implement hook\_node\_view(), check `$view_mode` is not equal to `'teaser'`, and possibly other values for which you cannot provide the tag you want to add. Alternatively you can implement hook\_entity\_view(), which is called for every defined entity; if you just want to add the tag to nodes, you should rather implement `hook_node_view()`.
You can also implement hook\_preprocess\_node(), which is invoked every time a node is shown, or `hook_preprocess_page()`, which is invoked for every page, including the page containing the node edit form. In `hook_preprocess_page()`, you need to verify `$variables['node']` is not empty; if it empty, it means the page is not about a node.
The alternative is implementing hook\_init(), but that hook is not invoked for cached pages.
* In a theme, implement `hook_preprocess_node()`, or `hook_preprocess_page()`.

In all the cases, you need drupal\_add\_html\_head() to add the tag, and menu\_get\_object(), when you don't have the node object, which is available in `hook_node_view()`, `hook_preprocess_node()`, and `hook_preprocess_page()`. You would need to call `menu_get_object()` in `hook_init()`, for example.

Notice that `menu_get_object()` called without arguments returns a node object, if the page is about a node, and its path is similar to node/\[node ID\], or starts with that string; if the page page is, for example, page/node/\[node ID\] (where page/node/\[node ID\] is not a path alias), then `menu_get_object()` doesn't return a node object; in the example path I used, you should use `menu_get_object('node', 2)`.
> 4 votes

# Answer
To answer your question you could use menu\_get\_object() inside `hook_html_head_alter()` to get the node object, as in `$node = menu_get_object();`.

As for solving the actual problem it would probably be more suitable to use drupal\_add\_html\_head() and template\_preprocess\_node():

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'sometype') {
    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => 'og:url',
        'content' => 'http://example.com/example',
      ),
    );
    drupal_add_html_head($element, 'og_url');
  }
}

```

Like kiamlaluno pointed out in his answer it's also possible to use some other preprocess/hook functions and you may want to do additional checks (looking at the view mode and page url for example - the arg() function may be useful with the latter) to make sure the tag is only added to the pages you want.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: How to specify subdirectory for uploads in files dir when adding file field to content type via module?
This question is related to: https://drupal.stackexchange.com/questions/39884/how-to-create-file-field-instance-based-on-file-field-info-in-custom-module

If I don't specify directory I can upload file.

However if I try do it I am getting error:

> The upload directory public://osw\_majatkowe\_m for the file field field\_osw\_majatkowe\_m\_file could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

osw\_majatkowe\_m is my content type stored in $type variable.

Code:

```
    $instance = array(
            'field_name' => $ct_info['file_field_name'],
            'entity_type' => 'node',
            'label' => 'Plik',
            'bundle' => $type,
            'required' => false,
            'settings' => array(

                'file_extensions' => '',
                'file_directory' => $type,
                'uri' => 'public://'.$type,

            ),
            'widget' => array(
                    'type' => 'file_generic',
            ),
    );

    field_create_instance($instance);

```

I want to have files for content type is seperate directory in sites/default/files.

# Answer
> 0 votes
It seems to me that your directory does not exists (or at least is not writable). You can make a function to test/create your custom folder:

````
function create_directory($folder) {
   // Constructs a URI to Drupal's default files location given a relative path
   $dir = file_build_uri($folder);
   // Checks that the directory exists and is writable.
   // Indicate if the directory should be created if it does not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only (FILE_MODIFY_PERMISSIONS)
   $res = file_prepare_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
   if (!$res) {
     watchdog('file system', 'The directory %directory does not exist or is not writable.', array('%directory' => $dir), WATCHDOG_ERROR);
   }
   return $res;

}

````

Then call this function with $type as parameter: create\_directory($type);

---
Tags: 7, files
---


title: Are conditional Flags possible?

text:
# Question
Title: Are conditional Flags possible?
Say I have two Flags attached to content; for example a "mark public" flag & "mark private" flag or a "like" flag & "dislike" flag, basically opposites. Is it possible to have the first flag automatically unflag itself conditionally whenever the second flag is flagged? This is basically like using Flags as radio buttons; only one can be selected at once and the other is automatically turned off. Otherwise when using Rules to determine if particular content was flagged "Public" or Private", is difficult since users can flag the same content both "Public" and Private" at the same time.

This could be easily achieved with only one Flag. But this doesn't translate well to a "like", "dislike" flag scenario, since users can only choose to like something but not specifically to dislike. A voting module would be a good alternative for this case however the only one currently available for D7 is the Rate Module which provides ratings for only nodes and comments, not as flexible as Flag module. I have tried implementing Rules to check for if one flag is flagged make the other unflagged, but it does not work.

Any suggestions as to how to tackle this?

# Answer
> 1 votes
to do this you could use the Rules module. I tried to do a similar thing before, it works but is a little awkward. You only need an event and action, a condition isn't really needed here:

Event: "Name of flag" has been flagged, Action: Unflag "Name of second flag"

For the second flag you would obviously do the opposite:

Event: "Name of second flag" has been flagged, Action: Unflag "Name of flag"

Now if someone flags a node with "Like" the "Dislike" flag is almost automatically unflagged, and vice versa (I think you get the concept here). "Almost" is because while flagging works dynamically the unflagging via rules only works after page reload, in my experience at least. So to a user it will look like you can both "Like" and "Dislike" things, but after reload only the last flag will stay.

---
Tags: flags
---


# Question
Title: Adding different containers to different parts of content from a node
How would I go about restructuring certain elements from a node so they are within different containers. E.g. If I had a node with 8 different fields and I wanted 4 of them to be rendered within a list, 2 of them within a certain div and the last two in a table. How would I do this?

Should I do it in hook\_node\_view\_alter() and restructure the build array with nested containers, and if so, wouldn't this be quite expensive for large nodes compared to telling the rendering array to nest, according to some conditions, as it is structured? If so where would I do this?

Should I do in a post\_render function or?

# Answer
The Field Group module will allow you to group fields into containers you may then be able to alter some of the mark up with the Fences module.

It does sound like you need more control so if those modules don't work you'll have to get your hands dirty in some code. The template files node.tpl.php and field.tpl.php should give you all the control you need over the mark up.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: Is there any way to reset a node's properties?
I would like to know if there is a way to reset a node's properties/fields?For example node's body, title,attachments, so as to re write the contents of the page.

# Answer
> 0 votes
In your theme folder you can override the default output using custom template files.
Let's say you want to modify the output of a standard 'Page' (the machine name for this content type is 'page' -- you can check it in /?q=admin/structure/types).
Go to your theme folder (under /sites/all/themes) and add/modify 'node--page.tpl.php' file.
A standard node template file will have something like:

````
<?php print render($title_prefix); ?>
<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
</h2>
<?php endif; ?>
<?php print render($title_suffix); ?>

````

This piece of code is used to show the title of the current content. You can delete (or comment) the entire code and your title won't appear when you display this page.
To hide the entire content (including custom fields attached to this content type) simply comment (or delete) this line:

````
print render($content);

````

After that, you can add your custom code to display anything in place of the original title (or content) for this page.

You can find an extensive tutorial on working with custom themes here: Theming Guide

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


title: using drupal sessions during hook_boot

text:
# Question
Title: using drupal sessions during hook_boot
When a user calls the front page of our site we want to check the country from which the user is surfing and redirect the user directly to the country specific front page.

We chose to use the hook\_boot() callback to implement this.

Now we have the problem that we want to save the state "is\_redirected" into a global variable that will still be available when the redirected page is loading and is calling our hook\_boot() again in order to prevent redirect loops.

We thought about using session management, so we loaded the drupal session code with

include\_once(DRUPAL\_ROOT . '/includes/session.inc');

The question is now, what is the next step after loading session.inc, do we have to call "drupal\_session\_initialize()", add a custom entry into the superglobal $\_SESSION variable and this custom entry + our session will be available after the redirect?

Thank you in advance!

# Answer
> 4 votes
`hook_boot()` is invoked too early to use the session, as Drupal has not yet initialised the session. Furthermore, `hook_boot()` has been removed from Drupal 8. `hook_init()` is not invoked for cached pages, but there is a trick to avoid the page is cached: Call drupal\_page\_is\_cacheable(FALSE) in `hook_init()`.

The function that actually stores the current page in cache is drupal\_page\_set\_cache(), which contains the following code.

```
  if (drupal_page_is_cacheable()) {
    $cache = (object) array(
      'cid' => $base_root . request_uri(),
      'data' => array(
        'path' => $_GET['q'],
        'body' => ob_get_clean(),
        'title' => drupal_get_title(),
        'headers' => array(),
      ),
      'expire' => CACHE_TEMPORARY,
      'created' => REQUEST_TIME,
    );

    // Restore preferred header names based on the lower-case names returned
    // by drupal_get_http_header().
    $header_names = _drupal_set_preferred_header_name();
    foreach (drupal_get_http_header() as $name_lower => $value) {
      $cache->data['headers'][$header_names[$name_lower]] = $value;
      if ($name_lower == 'expires') {
        // Use the actual timestamp from an Expires header if available.
        $cache->expire = strtotime($value);
      }
    }

    if ($cache->data['body']) {
      if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
      }
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
    }
    return $cache;
  }

```

When `drupal_page_is_cacheable()` returns `FALSE`, the page is not cached; `drupal_page_is_cacheable()`, when called without arguments, returns the value of the parameter passed to the function in a previous call.

As `hook_init()` is invoked before `drupal_page_set_cache()`, calling `drupal_page_is_cacheable(FALSE)` causes the current page not to be cached.

I would call `drupal_page_is_cacheable(FALSE)` strictly when necessary, which in you case means when you are sure you need to set `$_SESSION['is_redirected']`.

Notice that a page is served from the cache when there isn't any session enabled. The function called to get the page from cache (\_drupal\_bootstrap\_page\_cache()) contains the following code.

```
  // If there is no session cookie and cache is enabled (or forced), try
  // to serve a cached page.
  if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
    // …
  }

```

If then you need to clear the cache for the front page, you can use the following code.

```
cache_clear_all(url('<front>', array('absolute' => TRUE)),  'cache_page');

```

The other alternative to `hook_boot()`, and `hook_init()` I can think of is `hook_exit()` which is called also for cached pages. The only reason I would not use it is that it is invoked after the current page is rendered, which means that when you redirect the user to a different page, the user would wait for two different pages to be rendered (the one rendered before the redirect, and the one to which the user is redirected).

If you are going to use `hook_exit()`, you need at least to call `drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION)`; if then you need specific functions, you need to change bootstrap phase, such as with `drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL)` when you need a function defined from another module.

Remember that with `hook_boot()` you cannot call functions defined from other modules, as they are not yet loaded; you can only use PHP functions, and a very strict number of Drupal functions, which at least includes the functions defined in bootstrap.inc.

# Answer
> 0 votes
I have implemented same functionality in one of my sites using init hook instead.

```
function hook_init(){
 if(drupal_is_front_page()){
  $ip = ip_address();
  $cc = geoip_country_code($ip); // From GeoIP Module
  // Now check $cc with countries supported by the site
  if(array_search($cc, $country_specific_sites){
    // $country_specific_sites is an array of countries supported by the site
    // redirect !
  }
 }
}

```

To avoid infinite redirection all conditions is wrapped in `drupal_is_front_page()`. Alternatively you can declare this as a different function and call it from `page-front.tpl.php`

---
Tags: redirection, sessions, bootstrapping, location
---


# Question
Title: Hyphens or underscores when referencing a path alias in Drupal 7 templates?
I have a hyphenated path alias in my site and I need to reference it in a template hook, but it seems hyphens get converted to underscores in templates, so I'm wondering how I would go about outputting the code correctly.

My function is something along the lines of if my path alias is "change-directory" then use the "page\__change-directory" template. So my question is, would it be "change-directory" or "change\_directory" in my template?

# Answer
When a hyphen is used in a template filename, or template suggestion, the hyphen is replaced with an underscore. That is done in theme\_get\_suggestions(), and drupal\_find\_theme\_templates() which use, respectively, the following code.

```
// Remove slashes or null per SA-CORE-2009-003 and change - (hyphen) to _
// (underscore).
//
// When we discover templates in @see drupal_find_theme_templates,
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.
$arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);

```

```
// Transform - in filenames to _ to match function naming scheme
// for the purposes of searching.
$hook = strtr($template, '-', '_');
if (isset($cache[$hook])) {
  $implementations[$hook] = array(
    'template' => $template,
    'path' => dirname($file->uri),
  );
}

```

Whenever you are adding a theme template suggestion, or you are looking for a template file to use, you should replace hyphens with underscores, in the same way Drupal does.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Login button not showing after upgrade to PHP 5.3
I upgraded our web server to PHP 5.3 as a bit of software requires it, and suddenly the login button on one of our Drupal websites has disappeared! Submit buttons from other Drupal forms have disappeared too.

I've looked in the source code of the page, and the form is indeed missing a submit button.

Is this a known problem? If not, how might I diagnose the error?

# Answer
To diagnose the problem, make sure you display all errors (notices included) and that they reported somewhere (log, watchdog, ...), it should be a function incompatibility. Usually it is about parameters that are passed by reference for certain native functions or something like that (introduced in PHP5.3).

Then when you have identified the problem, open an issue on the module project (I bet it will be a contrib module or one of your custom module) so that the module maintainer can update it.

Drupal 6 is relatively old and versions prior to 6.14 are not working with PHP 5.3. Make sure you have the latest version, see also http://drupal.org/requirements/#php.
> 1 votes

---
Tags: users
---


# Question
Title: How to integrate content type to webform Drupal 7?
I have a content type called "student".

now I want to set that content type as select option component in webform.

Are there any way to do so? thanks,

# Answer
> 2 votes
Tvphong, I think that the best way to go about doing this is by using a custom module so that you can then integrate that content type within the select list of preloaded options.

Perhaps this link can serve you well in this.

What I ended up doing is a slight tweak of this. So my custom module looks something like this (which is for location content types):

```
<?php

/**
 * Reference:  http://eureka.ykyuen.info/2012/04/11/drupal-7-dynamic-select-options-for-webform/
 * The following piece of code is based on the blog post above
 */
function webform_options_webform_select_options_info() {
 $items = array();

 if (function_exists('get_location_titles')) {
  $items['location_titles'] = array(
    'title' => t('Location titles'),
    'options callback' => '_get_location_titles',
    );
 }

 return $items;
}

function _get_location_titles() {
 $options = array();
 $type = "location";

 $result = db_query('SELECT nid, title FROM {node} n WHERE n.type = :tname', array(':tname' => $type));
 foreach ($result as $row) {
  $options[$row->nid] = $row->title;
 }
 return $options;
}

```

---
Tags: 7, nodes, webforms
---


title: insert new term as tag on node submit

text:
# Question
Title: insert new term as tag on node submit
I want to add a term to the the node whenever it is submitted or edited. I have the term id of the term I want to add. My first approach of putting this code inside the custom node submit function is not working.

```
function module_custom_submit_function($form, &$form_state) {
   $nid = $form_state['nid'];
   $node = node_load($nid);
   $term_id = '73';
   $node->taxonomy[] = $term_id;
   node_save($node);
}

```

This does not insert the taxonomy term with ID equal to 73.

My second approach was to put query inside the submit function. Though this made changes to the database, the taxonomy terms were not added as tags on the website for the corresponding node.

```
function module_custom_submit_function($form, &$form_state) {
  $query = db_select('node', 'n');
  $query->fields('n', array('created', 'sticky'))
   ->condition('nid', $nid, '=');

   $result = $query->execute();
   foreach ($result as $record) {
     $time = $record->created;
     $sticky = $record->sticky;
   }

   db_insert('taxonomy_index')
   ->fields(array('nid' => $nid, 'tid' => $term_id, 'sticky' => $sticky, 'created' => $time))
   ->execute();
}

```

Are there any corrections, or alternative ways?

This approach seems to be working for now. I just added this to the submission handler.

```
   $node = node_load($nid);
   $term_id = '73';
   $node->field_tags[$node->language][]['tid'] = $term_id;
   node_save($node);

```

# Answer
It looks like you're using code from Drupal 6 in your first example, but from your second you must be using Drupal 7...`$node->taxonomy` isn't used in Drupal 7, taxonomy terms are related to entities via fields instead.

Your second example isn't working because the `taxonomy_index` table is just an index table relating nodes to terms...the hard-link between those two entities is actually contained in the field reference, which you haven't updated.

If I could offer a different approach, it would be to use `hook_node_presave()`. Using that method you can simply add another term id to the list of selected terms from the form, and rely on the node/field API to commit the changes and update the cache on your behalf.

```
function MYMODULE_node_presave($node) {
  $term_id = 73;

  // In reality you'd want to loop through the existing field values and check to
  // avoid duplicates; this is just an example to actually set the value.
  if ($node->type == 'mytype') {
    $node->field_term_reference_field_name[$node->language][] = array('tid' => $term_id);
  }
}

```

As an added benefit this will also work for any nodes that you add programatically, not just those added/edited through the node form.
> 4 votes

# Answer
You first need to add a taxonomy term reference field to your content type (i.e. field\_page\_terms) and then add the term like this:

```
$node = $form_state['node'];
$node->field_page_terms[LANGUAGE_NONE][]['tid'] = 73;
node_save($node);

```
> 0 votes

---
Tags: taxonomy-terms, forms
---


# Question
Title: Converting hard-coded menus to using the Menu module
* I have a site built in Drupal 7 with the navigation hard-coded in template.tpl.php. How do I go about switching this over to use the menu module instead?
* I've already have the menu recreated in the site's main menu. How do I make my theme display the Drupal menu rather than my hard-coded one?
* Is it correct to copy my current theme, create a new theme from that, swap out the hard-coded menu with some PHP code (where do I get that?), adjust the styles, and then activate the new theme?

One thing particular to my theme is I have menu drop-downs (secondary menus) that display when you mouseover the primary-level nav using JavaScript image swaps. I would have to recreate this menu in CSS.

# Answer
> 1 votes
You only need to create a new theme if the site in question is in production and you are not able to set up a development version of the site make your changes to the existing theme. In that case, you will want to create a copy of your theme with a different theme name and make sure to update the name of your MYTHEME.info file as well as any function names in your theme's template.php file.

Whether or not you do the above, the rest of the process should be the same either way.

* **Create a backup of the template file where the menu is hardcoded.**
* **Create a block region where the menu currently is.** There are two parts to this step: First you will need to add the following line to the MYTHEME.info file to let it know that the region exists:

```
regions[menu] = Menu

```

You'll want to make sure that there is not already a region with the same machine name. If there is, you may want to change it to something like:

```
regions[menu_top] = Top Menu

```

Next, you'll need to replace the hard-coded HTML for the menu with the code to display the region, something like:

```
<?php if ($menu): ?>
<?php print $menu ?>
<?php endif; ?>

```
* **Clear caches.** This forces the theme registry to be rebuilt and your new region will be show up.
* **Add the menu block to the newly created region.** Visit /admin/structure/blocks and find the block that is automatically created for the menu that you have recreated using Drupal's menu system and drag it into the "Menu" region that you just created.
* **Superfish.** This is one of the better drop-down menu solutions, IMO. You'll want to follow the module instructions for getting it set up. This module creates additional blocks that you can assign your menu to. This will alter the previous step because you will add the superfish block and then assign the menu in the superfish block settings.
* **Profit!**

# Answer
> 0 votes
1) I suggest checking out the Nice Menus and Superfish modules that should be relatively good choices for creating drop-down menus in Drupal. There's a brief comparison of them here. They should have enough documentation available to help with the implementation as well. If needed you can search the web for additional modules which may be more suitable depending of your requirements (like DHTML Menu, JQuery menu).

2) If you need customization to a degree where these modules are more of a hindrance than help then check out the Menu Block module and the Menu API page to help you get the menu displayed and then add your custom css/javascript to it.

You don't necessarily need to create a new theme for these changes until you want to preserve the version with the hard-coded menu as a separate theme. In most cases it's probably enough to do the changes in a development environment and when it's ready move the changes to the production site.

# Answer
> 0 votes
* If you don't need anything else that is in your template.php file, you can just rename your current template.php file to something like template.php.old (just in case you need it later) and create another blank template.php file. Don't forget to clear your caches.

or

* If you have other code in your template.php file that you need you can comment out or delete the lines that pertain to your menu. (I recommend commenting them out, just in case) Again don't forget to clear your caches.

As far as drop down menus, I have used and really like the Superfish Module

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


# Question
Title: Hitting a download link and displaying text in the same menu item page callback (7)
I have a menu item for one of my content types that I want to be able to package up some different files, create a .zip file, link to start a download and then display some text which will describe what the user needs to do with the .zip file.

Here is my menu declaration:

```
        'title' => 'Download Icon',
        'description' => 'Package up the selected icon as a zip file and download it',
        'page callback' => 'download_icon_page_callback',
        'page arguments' => array(1),
        'access callback' => 'download_icon_access',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
        ),

```

And here is my page callback that doesn't work for obvious reason:

```
function download_icon_page_callback()
{
    // some code to compile my .zip file
    drupal_goto('path/to/my/file.zip');
    return t('Here are some inustrctions!');
}

```

So this above function can link to the file compiled .zip with a drupal\_goto but since this a redirect the return t will not ever go through. Is there anyway I can hit both of these in a single page callback? Also, is there a better way to display formatted text from the menu item instead of just doing a return t() from my page callback?

# Answer
A particularly low-tech solution using meta refresh (which should work cross-browser):

```
function download_icon_page_callback() {
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'refresh',
      'content' => '5', // Timeout in seconds
      'url' => '/path/to/my/file.zip'
    ),
  );

  drupal_add_html_head($element, 'download_icon_refresh');

  return array(
    'instructions' => array(
      '#markup' => t('Some instructions')
    ),
    'backup_link' => array(
      '#markup' => l('Click here if the file download does not automatically start.', 'path/to/my/file.zip'),
      '#prefix' => '<p>',
      '#suffix' => '</p>'
    )
  );
}

```

Although returning a string from a page callback function works fine (the return is run through `render()` which accepts a string or render array), returning a render array is preferred as it gives other parts of the system the chance to alter the output while it's still in a structured manner. The documentation for render arrays is a great place to start if you haven't used them before.
> 3 votes

---
Tags: 7, files, routes
---


# Question
Title: Does the Drupal FAPI support more than one AJAX callback?
I am using **FAPI's AJAX** property to save nodes asynchronously. When the associated **AJAX callback** gets called, it gets passed the $form and $form\_state parameters respectively. I then simply call `drupal_render($form)` from the AJAX callback and voilá, the node edit page is refreshed asynchronously. This works well.

**The problem that I am having is that I am only replacing the form, but I also want to replace the page title**. The page title is not part of the node edit form; so I could change the node title on the edit form, but the page title would remain stale when saving and refreshing the form (note: the edited title does get saved into the db). I cannot target an element sitting higher in the DOM hierarchy because (ie, by changing pointing the wrapper to the body) because the AJAX callback is only aware of the form's contents.

`drupal_render($form)` works great, but I have the fear that if I where to point the **wrapper** to the body (or somewhere near it) and render the whole page, that this would have unintended consequences (such as skipping certain rendering steps, resulting in incomplete DOM data). That's why I thought of maybe adding a second AJAX callback to the form submit action: one for handling the form itself, another AJAX callback for handling the page title. **Do you know if having more than one callback is possible? Can you think of a way of targeting two separate wrappers using FAPI's AJAX? Do you know if the path (instead of callback) property provides a solution for my problem?** If path does work feel free to augment your answer with a short example.

Please limit answers to functionality supported by Drupal core. I am not interested in third-party modules that use their own javascript logic (ie, ctools, etc).

Sample code:

```
// Add ajaxified save button in hook_form_FORM_ID_alter (foo_form_node_form_alter).
$form['actions']['ajax_save']['#type'] = 'submit';
$form['actions']['ajax_save']['#access'] = TRUE;
$form['actions']['ajax_save']['#value'] = 'Save';
$form['actions']['ajax_save']['#submit'] = array(0 => 'foo_node_form_submit');
$form['actions']['ajax_save']['#weight'] = 9;

$form['actions']['ajax_save']['#ajax'] = array(
  'wrapper' => $form['#node']->type. '-node-form',
  'callback' => 'foo_ajax_callback',
  'method' => 'replace',
    'effect' => 'fade',
);

...

function foo_ajax_callback(&$form, &$form_state = null) {

  $commands = array('#type' => 'ajax', '#error' => FALSE, '#commands' => array());
  $output = drupal_render($form);
  $commands['#commands'][] = ajax_command_insert(NULL, $output);
  // Prepend status messages to the node form.
  $commands['#commands'][] = ajax_command_prepend(NULL, theme('status_messages'));
  // Update the title on the page.
  $commands['#commands'][] = ajax_command_insert(NULL, $output);

return $commands;
}

```

# Answer
Yes, you can solve it with core Drupal AJAX framework. You are already using `$commands`, you just need one more custom command.

Javascript code to provide new command:

```
(function ($) {
  Drupal.ajax.prototype.commands.change_title = function(ajax, response, status) {
    // Update the <head><title> element.
    document.title = response.data;

    // Update the page title.
    response.data = response.prefix + response.data;
    this.insert(ajax, response, status);
  }

})(jQuery);

```

PHP code to call this command:

```
  $commands['#commands'][] = array(
    'command' => 'change_title',
    'method' => 'html',
    // Selector targets Drupal 7's default theme <h1> title (Bartik 7.12).
    'selector' => 'div#branding h1.page-title',
    'data' => check_plain($form_state['node']->title),
    'settings' => NULL,
    'prefix' => '<em>Edit '. node_type_get_name($form_state['node']). '</em> ',
  );

```

Original idea is taken from here.
> 6 votes

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


# Question
Title: Multiple file upload controls on same form via FAPI not possible?
My research seems to be indicating that only a single file control widget is possible per form when creating said form with the Forms API.

Is this true? Still?

I'm operating in D6, I don't want to use CCK because I want to keep my custom content type within a single DB table, but I do want to be able to upload multiple files - in separate form controls which lie in separate fieldsets from one another (logical context of what the file is for).

If one uses the CCK based upload options (such as those outlined here: How to upload multiple files at once?) as soon as multiple uploads are enabled, the content type's DB table gets fragmented by having the CCK upload control's data moved to its own DB table. **I don't want that.**

Is the only alternative to write some AJAX/AHAH logic handling this in the background, with the FAPI's file handling basically useless here?

# Answer
> 2 votes
I will recommend you to use:

```
print_r($_FILES);

```

This placed inside the form function submit will let you know if the files are been upload it into the temp directory and what are their names. Also check the file upload field name as sometimes when you copy and paste code you might be re-using the same name and this is creating the overwriting.

Last, but not least in your custom module try adding a single upload file field and test it if it work, then add a second and try it and so on.

---
Tags: forms
---


title: How is JavaScript included in Drupal 7?

text:
# Question
Title: How is JavaScript included in Drupal 7?
My site is built on Drupal 7, and a number of my `.js` scripts are throwing this exception: `Uncaught TypeError: Property '$' of object [object Window] is not a function`. After some research, I think this is related to the new jQuery namespace update, but since we didn't write the scripts, I'd rather remove them than make changes.

I've traced the references to the `$scripts` variable in `html.tpl.php`, but haven't been able to trace back any farther. I've examined `.info` files for additions to `scripts[]`, `drupal_add_js()`, `drupal_add_library()`, preprocess and process function calls, and found nothing.

Has anyone had similar issues with removing JS file references, and could you give me a rundown on Drupal's script inclusion process? I found the methods above digging through docs and help sites, but I'm still not clear on how it all comes together (i.e. if scripts\[\] variable additions are added before drupal\_add\_js() calls, etc.).

# Answer
> if scripts\[\] variable additions are added before drupal\_add\_js() calls, etc

The JavaScript files used by a theme, and defined with `scripts[]` directives are added in \_drupal\_theme\_initialize(), using the following code.

```
  // Do basically the same as the above for scripts
  $final_scripts = array();

  // Grab scripts from base theme
  foreach ($base_theme as $base) {
    if (!empty($base->scripts)) {
      foreach ($base->scripts as $name => $script) {
        $final_scripts[$name] = $script;
      }
    }
  }

  // Add scripts used by this theme.
  if (!empty($theme->scripts)) {
    foreach ($theme->scripts as $name => $script) {
      $final_scripts[$name] = $script;
    }
  }

  // Add scripts used by this theme.
  foreach ($final_scripts as $script) {
    drupal_add_js($script, array('group' => JS_THEME, 'every_page' => TRUE));
  }

```

`_drupal_theme_initialize()` is indirectly called from theme(), l(), contextual\_preprocess(), and ThemeRegistry::initializeRegistry().

As each JavaScript file added to a page has its own group, with its own weight, it doesn't generally have importance which file is added first. If you really need to be sure a file is included before another one, you should define its group, and its weight, consider that files are included following this order:

* First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme
* Then by group
* Then by the 'every\_page' flag, with TRUE coming before FALSE
* Then by weight
* Then by the order in which the JavaScript was added
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Call to undefined function field_attach_load() on a newly migrated site
I am moving a site over to a different server to test.

I am getting the following error:

> Call to undefined function field\_attach\_load() in my-path-to-root/my-site/includes/entity.inc on line 320

If I try accessing http://www.example.com/randomstuff, I get this error:

> Fatal error: Call to undefined function user\_access() in /home/borsodas3/digipowers.devserver2012.com/modules/overlay/overlay.module on line 130
>
> Fatal error: Call to undefined function node\_access\_needs\_rebuild() in /home/borsodas3/digipowers.devserver2012.com/sites/all/modules/taxonomy\_access/taxonomy\>\_access.module on line 598

`phpinfo()` returns following information for the two sites:

The Drupal status report from the site I am migrating FROM looks like this:

> Info
> Drupal 7.8
> **OK** Access to update.php Protected
> **Error** CTools CSS Cache Unable to create
> The CTools CSS cache directory, ctools/css could not be created due to a misconfigured files directory. Please ensure that the files directory is correctly configured and that the webserver has permission to create directories.
> **OK** Configuration file Protected
> **OK** Credit card encryption Credit card data is encrypted during checkout for maximum security.
> **OK** Cron maintenance tasks Last run 26 min ago
> You can run cron manually.
> To run cron from outside the site, go to mysite.com
> **OK** Database system MySQL, MariaDB, or equivalent
> **OK** Database system version 5.1.57-log
> **OK** Database updates Up to date
> **OK** Date API System date settings
> The timezone has been set to America/New\_York. The first day of the week has been set to Monday. The medium date format has been set to to F j, Y - g:ia.
> **Error** Drupal core update status Not secure! (version 7.12 available)
> There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately! See the available updates page for more information and to install your missing updates.
> **OK** File system Writable (public download method)
> **OK** Fitvids library Installed
> Fitvids Javascript Library. Download it from here, copy it to the module directory, and rename it to jquery.fitvids.js.
> **OK** GD library PNG support bundled (2.0.34 compatible)
> **OK** GD library rotate and desaturate effects bundled (2.0.34 compatible)
> **OK** Images Product image support has been automatically configured by Ubercart.
> **Error** Module and theme update status Not secure!
> There are security updates available for one or more of your modules or themes. To ensure the security of your server, you should update immediately! See the available updates page for more information and to install your missing updates.
> **OK** Node Access Permissions 1832 permissions in use
> If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions. Rebuild permissions
> **OK** PHP 5.3.2 (more information)
> **OK** PHP extensions Enabled
> **OK** PHP memory limit 300M
> **OK** PHP register globals Disabled
> **Warning** Unicode library Standard PHP
> Operations on Unicode strings are emulated on a best-effort basis. Install the PHP mbstring extension for improved Unicode support.
> **OK** Update notifications Enabled
> **Info** Upload progress Not enabled
> Your server is capable of displaying file upload progress through APC, but it is not enabled. Add apc.rfc1867 = 1 to your php.ini configuration. Alternatively, it is recommended to use PECL uploadprogress, which supports more than one simultaneous upload.
> **OK** Web server Apache/2.2.3 (CentOS)
> **OK** cURL Enabled

# Answer
I had this same problem today and I fixed it by simply running the update script:

The update script is located in the root folder of your Drupal 7 install. eg.

> www.mynewlymigratedtoserver.com/update.php

One other thing you should probably know, you have to be logged in to run the update script, you can login right? No, you can't! That's ok, there's a work around.

In your settings.php (usually /sites/default/settings.php) there is a line (231 for me) that says this:

> $update\_free\_access = FALSE;

This variable determines if the update script can be used by anyone, not just logged in people. Set it to **TRUE** and you'll be able to run the update script. You'll want to set it back to false when you're done.

If that didn't work try this
> 1 votes

---
Tags: 7
---


title: Transfer fieldgroups through features

text:
# Question
Title: Transfer fieldgroups through features
I need transfer fieldgroup through features, but always when I add field group into feature I see status "overriden". How I can add fieldgroup into features correctly? This fieldgroup added for taxonomy vocabulary.

This problem described in this topic http://drupal.org/node/1619154 but it not works for me :(

I use Drupal 7.14, field\_group 7.x-1.1, features 7.x-1.0, CTools 7.x-1.0

# Answer
I found problem - features is not paste this line include\_once('my\_feature.features.inc'); into my\_feature.module
> 0 votes

---
Tags: features, entities
---


title: Archive using date other than "created"

text:
# Question
Title: Archive using date other than "created"
I have a custom content type of "Press Release." I would like to make an archive listing of the press releases, based on a "release date" field in the content type. The archive view built into views uses the "content: created" date, and I can't figure out how to make it work with this other date instead. (This is Drupal 7.)

Any help would be appreciated. Thanks.

# Answer
You have to install the Context module and make sure the the Date Views and Date Context modules are also enabled. Then your date fields will appear in the format:

Field: Date (field\_machine\_name)

Contextual filters based on these fields have the same formatting options as those based on node creation date.
> 1 votes

# Answer
## Basic directions follow -- apologies if you've already done this!

1. Edit View.
2. Under "Sort Criteria", click Add.
3. Locate the field you want to sort by and add it by clicking the checkbox next to it and then next. Set it to Sort Descending so newest items are first.
4. Click "Content: Post Date" and delete the field by clicking the "Remove" button.

## Still doesn't work?

You might have the "release date" field as text instead of a UNIX timestamp or otherwise. I'm not sure how well a simple string will sort -- you might need a date field instead.
> 0 votes

---
Tags: views
---


# Question
Title: order of execution of hook_node_presave and custom submit function
Does hook\_nood\_presave execute before or after a custom form submit handler in the same node ? and I need to perform some action after the node contents have been saved in the database. So, where should put this code ?

# Answer
> 2 votes
In the core system `hook_node_presave()` is only ever invoked once, from inside `node_save()` itself. In the context of a node add/edit form it's called by the original form submit handler, which unless you've explicitly engineered otherwise, will be run before the call to your custom submit handler.

Similar to your other question the submit handler isn't really the best place for this logic, as that code will literally only run when a form has been submitted (not when a node has been added programmatically for example).

After `node_save()` has saved the node data to the database, it invokes one of two other node hooks...`hook_node_insert()` and `hook_entity_update()` (obviously depending on the current operation).

One of those hooks will be called after the data has been committed to the db so will be perfect for your needs.

---
Tags: forms, hooks, nodes
---


# Question
Title: How to specify default formatter for custom field widget?
I created a custom field widget implementing hook\_field\_widget\_info(), created a custom formatter implementing hook\_field\_formatter\_info() and also implemented hook\_field\_formatter\_view() to generate the formatter's display.

Everything works as intended (validation, persisting values, formatter) with one glaring exception: I can't figure out how to make my widget use my formatter by default.

Every time I add a an iToggle field I need to manually change its formatter in Manage Displays for that content type.

Any ideas?

Here's my code:

```
function itoggle_field_field_widget_info() {
 return array(
   'itoggle' => array(
    'label' => t('iToggle Widget'),
    'field types' => array('list_boolean'),
    'settings' => array('display_label' => 1),
    'behaviors' => array(
      'multiple values' => FIELD_BEHAVIOR_CUSTOM,
    ),
  ),
);
}

function itoggle_field_field_formatter_info() {
  return array(
    'itoggle' => array(
    'label' => t('iToggle Widget'),
    'description' => t('Displays the field as an iToggle Widget'),
    'field types' => array('list_boolean'),
  ),
);
}

```

Thanks!

# Answer
So basically, as per Dave Reid's answer, it can't be done nicely.

That doesn't mean it can't be done at all (sort of), I found a decent workaround:

Implement hook\_field\_info\_alter() and alter the default\_formatter of the Field Type. Sure, its kinda rude because we update it for all ther Widgets of that Type, even ones that have nothing to do with our formatter.

That said, this is a very particular case (booleans) and it's safe to display the Widget regardless of the value. Also its just as easy to go to Manage Display and change the formatter back to the old one. It's a lot less disappointing than enabling an iToggle Widget and not getting the formatter. I think in this case the gains outweigh the losses!
> 1 votes

# Answer
Short answer is you can't. You can only specify a default formatter for each field type itself in hook\_field\_info():

> default\_formatter: The machine name of the default formatter to be used by instances of this field type, when no formatter is specified in the instance definition. This formatter must be available whenever the field type is available (i.e. provided by the field type module, or by a module the field type module depends on).
> 1 votes

# Answer
Not sure how you defined your fields. I created them in my .install file instead of using the classic hook\_field\_info. In my case for some reason hook\_field\_alter doesn't work. So i had to define my own field type:

```
function MYMODULE_field_info_alter(&$info) {
$info['MYFIELD_TYPE']['default_formatter'] = 'MYFORMATTER';
}//THIS WORKS

```

otherwise defining on an existing field type like 'text' would interfere with other custom types:

```
function MYMODULE_field_info_alter(&$info) {
$info['text']['default_formatter'] = 'MYFORMATTER';
}//THIS WORKS

```

Let me know if you have a better solution. There might be a way to define it at creation type but dunno how to yet but so far all the solutions I tried were douchebags.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to programmatically create file entity reference on entity
Example with "normal" entity reference.

```
$node = node_load($nid);
$node->field_reference = array(
  $node->language => array(0 => array(
    'target_id' => $other_nid,
  ))
);
node_save($node);

```

Now I want to do the same, but on a File entity field instead. Examining an attached file with devel, the field looks *mostly* like a plain

```
$file = file_load($fid);

```

object, but there's some more data on it, so I'm guessing I will hit problems down the road if I just stick the $file on to the ref, instead of figuring out the proper API call.

# Answer
The file entity module wraps around the core file field, which defines only three field columns that you need to worry about providing:

* *fid* (file id)
* `display` (boolean indicating if the file is displayed or not)
* `description` (self-explanatory)

You can safely ignore any other values that you find on the field as they'll be discarded anyway when it comes to committing the field data.

If I remember rightly it's the core file module that adds the extra data to the field, which is essentially the file object converted to an array. If you're seeing any other 'foreign' values in there they're probably coming from the `file_entity_field_load()` function.
> 1 votes

---
Tags: files
---


# Question
Title: Drupal commerce: Save into a customer profile field
im trying to save into a customer profile field. Reading it out is no problem:

```
if(!empty($order_wrapper->commerce_customer_billing->field_shop_annotations)) {
$annotations = $order_wrapper->commerce_customer_billing->field_shop_annotations->value();
}

```

But saving into gives me an error message. Here's my code:

```
// Save annotations
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$annotations = $form_state['values']['annotations'];

$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

$profile = commerce_customer_profile_load($profile_id);

if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {
   // This gives me the error message:
   $profile_wrapper->commerce_customer_billing->field_shop_annotations->set('muh');
}

```

Everthing works fine except the set method inside the if clause. I also tried:

```
$profile_wrapper->commerce_customer_billing->field_shop_annotations->value = $annotations;

```

# Answer
> 2 votes
ok i got it:

```
$annotations = $form_state['values']['annotations'];
global $user;

// load oder
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

// get profile id
$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

// load customer profile
$profile = commerce_customer_profile_load($profile_id);
if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {

       // set the value of the field and save the profile
       $profile_wrapper->field_shop_annotations->set($annotations);
       $profile_wrapper->save();

}

```

---
Tags: commerce
---


title: Panels overlay capability

text:
# Question
Title: Panels overlay capability
I'm building with D7 and looking for an easy way to build a page rendered into an overlay.

Wouldn't it be awesome if Panels could be configured to spit out it's contents into an overlay -perhaps the core admin overlay.

Has anyone seen anything like this? Is it worth building?

# Answer
> 0 votes
In Panels under Settings -\> Basic for your page there is a checkbox with the label "Use this page in an admin overlay." that you can use for this.

---
Tags: panels, modal-dialogs
---


# Question
Title: How can I show a single block only if the user is on iOS?
I have a *Picture* content type that allows users to upload picture files, something that iOS does not support. Since Apple in 2012 can't support something my first computer running Netscape Navigator was able to do in the early 1990s, I'd like to give a message to iOS users that they will have to e-mail me the photos instead.

I installed the Browscap module but it only detects the user agent; it doesn't do anything by itself. On Drupal 6 I used Mobile Tools, but it has yet to see a stable release for D7.

I only want to show a single block on a single content type to iOS users, so I'm looking for the simplest possible solution.

# Answer
My dull ax dealing with this same issue boils down to a little module helper function along the lines of:

```
function _MODULE_is_iOS() {
  if (strpos($_SERVER['HTTP_USER_AGENT'],'iPad')  !== FALSE ||
      strpos($_SERVER['HTTP_USER_AGENT'],'iPhone')!== FALSE ||
      strpos($_SERVER['HTTP_USER_AGENT'],'iPod')  !== FALSE) {
    return TRUE;
  } else {
    return FALSE;
  }
}

```

and then using that within my block hooks, eg,

```
if (_MODULE_is_iOS()) {
   $block['content']= // whatever I need for iOS
}

```

or from within the Block Admin PHP visibility area if in a pinch.
> 2 votes

# Answer
I've used mobile tools with D7 and it works really well.

Having said that, why not make a .tpl.php for your block that checks the user agent?
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Changing a redirect depending on selection
Using drupal 7 how can I make a selection alter where a page is then redirected to ? I need the value selected by a drop down menu to be part of the destination url for the redirect. For instance if I had the following for a drop down menu:

$form\['changethis'\] = array( '#type' =\> 'select', '#options' =\> array( 'one' =\> 'one', 'two' =\> 'two', 'three' =\> 'three', ),

Selecting option 'two'would send the page to www.mypage.com/two

Any help would be great I have experimented with an ajax request and hook\_menu\_alter , but no luck so far.

# Answer
> 2 votes
You can add your own submit handler to your form. In the submit handler function you will be able to access the value that was entered by the user.

The code could look something like this (to be put in a custom module).

```
    /**
    * Implementation of hook_form_alter()
    */
    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
      if($form_id == 'MY_FORM') {
        // Adds our own custom submit handler to the form MY_FORM
        $form['#submit'][] = 'MYMODULE_MYFORM_custom_submit';
      }
    }

    /**
    * Custom submit handler for MY_FORM
    */
    function MYMODULE_MYFORM_custom_submit($form, &$form_state) {
      $form_state['redirect'] = 'my-path';
      $form_state['rebuild'] = TRUE;
    }

```

Replace 'my-path' with the value the user entered. Look inside $form\_state\['values'\] to find it. Don't forget to check that the value is valid so no funky stuff is done here :)

Good luck.

---
Tags: redirection
---


# Question
Title: How do I override a function from a module?
Firstly, sorry if this answer is covered elsewhere. I've done a lot of searching and can only find info on overring theme functions and hooks.

I am using a module that builds a price table for Drupal Commerce items. There is a function that formats the table headers:

```
/**
 * Helper function that takes care of the quantity displayed in the headers of
 * the price table.
 */
function commerce_price_table_display_quantity_headers($item) {
  // Set the quantity text to unlimited if it's -1.
  $max_qty = $item['max_qty'] == -1 ? t('Unlimited') : $item['max_qty'];
  // If max and min qtys are the same, only show one.
  if ($item['min_qty'] == $max_qty) {
    $quantity_text = $item['min_qty'];
  }
  else {
    $quantity_text = $item['min_qty'] . ' - ' . $max_qty;
  }
  return $quantity_text;
}

```

As you can see, this is not a theme function where I can override it in template.php but I can to tweak some of the output.

Obviously I don't want to edit the module itself in case it gets updated in the future, so, **how can I redefine this function so I can chop and change a few things?**

*My work so far...*

So far, I have tried to create it as a seperate module with a few subtle changes to show if it's working or not, but it's not overriding any of the output.

**Info file**

```
; $id$
name = Price Table: Tweaked Display
description = A different layout for the price table as shown on the product display nodes
package = Commerce (contrib)
core = 7.x

dependencies[] = commerce_product
dependencies[] = commerce_price
dependencies[] = commerce_price_table

```

**Module File**

```
 /**
 * Override of the helper function that takes care of the quantity displayed in the headers of
 * the price table.
 */
function commerce_table_tweak_display_quantity_headers($item) {
  // Set the quantity text to unlimited if it's -1.
  $max_qty = $item['max_qty'] == -1 ? t('Unlimited gnhh') : $item['max_qty'];
  // If max and min qtys are the same, only show one.
  if ($item['min_qty'] == $max_qty) {
    $quantity_text = $item['min_qty'];
  }
  else {
    $quantity_text = $item['min_qty'] . ' - this is working - ' . $max_qty;
  }
  return $quantity_text;
}

```

# Answer
It's Drupal...there's always a way, but the amount of time it will take to do might make you think twice :)

If you look a bit further up the food chain so-to-speak you'll see that this function is exclusively used by `commerce_price_table_field_formatter_view()`, which declares a field formatter that is used for the `commerce_price_table` field type.

With that in mind, you can quite easily implement your own field formatter, assign it to the `commerce_price_table` field type, and use as much custom code as you want, all the time keeping in line with best practices.

Basically you need to implement `hook_field_formatter_info()`:

```
function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_commerce_multiprice_default' => array(
      'label' => t('MyModule Price chart'),
      'field types' => array('commerce_price_table'),
      'settings' => array(
        'calculation' => FALSE,
        'price_label' => t('Price'),
        'quantity_label' => t('Quantity'),
        'table_orientation' => t('Orientation'),
      ),
    ),
  );
}

```

And then implement `hook_field_formatter_view()`, `field_formatter_settings_form()` and (optionally) `hook_field_formatter_summary()`.

For each of these functions just take the code from the same function in the contrib module, and make the changes where you need to.
> 12 votes

# Answer
Seems, you can’t override this function because it doesn’t use theme or hook workflow.

The only way - is to directly change `commerce_price_table_display_quantity_headers()` function. Then create a patch with you changes.

Later if you update the Commerce module - you will need apply your patch.
> 2 votes

# Answer
I think Eugene’s answer is correct that you can't do it without overwriting directly.

However, what I have found useful is that if it’s absolutely necessary to do this, move this module from your `sites/all/modules/contrib` directory to `sites/all/modules/custom` dir so that you can be aware of and keep track of the fact that you made custom changes.
> 2 votes

---
Tags: 7, commerce
---


title: Add a class to panel page body element

text:
# Question
Title: Add a class to panel page body element
How do I add a class to a panel page's body element without having to add it manually in the variant configuration section? I want all panel pages to have a body element with the class 'panel-page'. Is there some kind of hook like hook\_panel\_page()?

# Answer
You can use menu\_get\_item() to inspect what generated the page and add a class to the body element in template\_preprocess\_html(). I saw the code first in the Zen theme, where they also add a class if the page was generated by Views. Link to Zen template.php

```
    function MYTHEME_preprocess_html(&$variables, $hook) {
      // Store the menu item.
      $variables['menu_item'] = menu_get_item();
      if ($variables['menu_item']) {
        switch ($variables['menu_item']['page_callback']) {
          case 'page_manager_blog':
          case 'page_manager_blog_user':
          case 'page_manager_contact_site':
          case 'page_manager_contact_user':
          case 'page_manager_node_add':
          case 'page_manager_node_edit':
          case 'page_manager_node_view_page':
          case 'page_manager_page_execute':
          case 'page_manager_poll':
          case 'page_manager_search_page':
          case 'page_manager_term_view_page':
          case 'page_manager_user_edit_page':
          case 'page_manager_user_view_page':
            // Is this a Panels page?
            $variables['classes_array'][] = 'page-panels';
            break;
        }
      }
    }

```
> 2 votes

# Answer
To override the default template, copy panels-pane.tpl.php from panels \> templates to your theme, and clear the cache. Then, manually add the CSS classes you need in your template file.
> 0 votes

---
Tags: 7, hooks, panels
---


title: Why are cache queries so slow?

text:
# Question
Title: Why are cache queries so slow?
I noticed that some of the queries to retrieve data from cache tables is really slow (\> 100ms). For example:

```
SELECT cid, data, created, expire, serialized FROM cache_views WHERE cid IN ('views_data:en')

SELECT cid, data, created, expire, serialized FROM cache_field WHERE cid IN ('field_info_fields')

SELECT cid, data, created, expire, serialized FROM cache_bootstrap WHERE cid IN ('system_list')

SELECT cid, data, created, expire, serialized FROM cache WHERE cid IN ('entity_info:en')

```

Most of those tables only have 10-100 records total. Why would they be so slow?

# Answer
> 4 votes
I don't know this for a fact but I think it's because the serialised objects contained in the `data` column are pretty large.

I just checked a production site of mine and the `data` column for `views_data:en` contains a serialised string that is **572824** characters long. I kid you not! Imagine loading that on each page request (fortunately that doesn't happen in my case).

The main `cache` table on the same website is currently at 1.4MB, with just 16 records in it.

On another, less-than-a-week-old dev site, the `cache_form` table is at 6.3MB, with just 142 records.

I know 1.4MB and 6.3MB aren't large amounts of data as such, but if you take into account the fact that it has to be processed and passed from MySQL to PHP I think that's where you'll find the bottleneck.

# Answer
> 1 votes
I just wanted to point out also \_field\_info\_collate\_fields() memory usage, which affects memory usage and performance when you have hundreds or thousands of fields/field instances. With Entities everywhere, Profile2 module, Drupal Commerce, etc., many sites now have more than a few hundred field instances, and this quickly becomes a bottleneck. One of my sites has more than 6MB of serialized data in the field\_info\_fields row for cache\_field.

Some sites with lots of fields/instances, views, etc. may encounter similar issues (from WSODes when clearing caches (from a PHP memory exhausted error) to slow page loads when caches are not yet built).

---
Tags: 7, caching
---


title: Views displaying node reference fields

text:
# Question
Title: Views displaying node reference fields
Will the view chosen (in the advanced settings) of a node reference in a content type get overridden by another view if the node reference field is shared between two (or more) content types?

In more detail: I am working with a Drupal site that has a content type that contains a node reference field. One of the things it asks you when creating the content type is - which views are used to reference the node. I am trying to create another content type that shares the same field as the first one, and it therefore will also be a node reference. BUT, when I create this new content type, it again asks which view I want to use. If I chose a different one will it override the view in the first content type, since they share a common field?

# Answer
In Drupal 7 you can have different field settings for different content types. This was not possible in Drupal 6.
> 0 votes

---
Tags: views, nodes
---


title: hook_node_presave () showing error

text:
# Question
Title: hook_node_presave () showing error
When I am inserting a new article there is an error -

> Notice: Undefined property: stdClass::$field\_tags in hook\_node\_presave() (line 344 of D:\wamp\www...)

The code for line 344 is-

```
function mltag_node_presave($node) {
...
$count = count($node->field_tags[$node->language]); //line 344
..
}

```

This error only shows up when **adding** a new article, and **not** when **editing** an article. The line 344 is just to count the number of term-ids in the textfield for tags. Any suggestions ??

EDIT - field\_tags is the name of the default Tag textfield added in the add-article page

# Answer
> 0 votes
I think you need to do an isset($node-\>field\_tags\[$node-\>language\]), if it is empty $node-\>field\_tags\[$node-\>language\] will not exist. Could you check if it is only articles with the empty field\_tags that are affected?

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


# Question
Title: How to have a node creation form on a separate node creation form?
I'm on d7 and creating a "how to" site where users create a topic and add individual steps to it. I have a topic content type and a step content type and I connect them together by having an entity reference field on the steps so they reference the topic. I'm looking for a way to have an "add step" form on the topic creation page that will add a step and automatically reference the topic that I am creating. The field collections module gives me some of this functionality, but it makes it all in the one node being created. I need it to be separate content type because I want other users to be able to add steps to the topic after its been created, as well as commenting on specific steps and flagging. Any suggestions? Thanks.

# Answer
> 0 votes
Check out References dialog also. The module extends entity reference field by adding links to add, edit and search (which links are available can be configured) for references through a dialog.

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


# Question
Title: How to pass a db_query as an array instead of a string?
I am having a bit of trouble converting my module db\_query argument to pass as an array as oppose to a string. The module is D6 and I am trying to port it D7. Here is the snippet:

```
$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {field_config_instance()} nfi
    INNER JOIN {field_config()} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = '%s' AND nf.active = 1 AND nf.locked = 0", $type_name);

```

And here the updated version as suggested below, but I am still getting a PDOException error:

```
$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {field_config_instance()} nfi
    INNER JOIN {field_config()} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = ':type_name'  AND nf.active = 1 AND nf.locked = 0", array(':type_name'=>$type_name));

```

The full error is as below, line 49 is the line starting "WHERE" or the entire bottom line basically:

PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '() nfi INNER JOIN field\_config() nf ON nfi.field\_name = nf.field\_name ' at line 2: SELECT nfi.field\_name, nfi.label FROM {field\_config\_instance()} nfi INNER JOIN {field\_config()} nf ON nfi.field\_name = nf.field\_name WHERE nfi.type\_name = ':type\_name' AND nf.active = 1 AND nf.locked = 0; Array ( \[:type\_name\] =\> page ) in cck\_private\_fields\_get\_content\_private\_fields() (line 49 of C:|... common.inc).

Any suggestions welcome. When I manage to finish this module I'll be submitting it to Drupal.org so everyone can use it.

# Answer
There are three errors in that query:

* The database tables are not field\_config\_instance(), and field\_config(), but field\_config\_instance, and field\_config. Parentheses have a particular meaning in SQL, and putting them after a table name causes an error message.
* The field\_config\_instance table doesn't contain any "label" field. See the schema definition given in field\_schema().

```
$schema['field_config_instance'] = array(
  'fields' => array(
    'id' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'description' => 'The primary identifier for a field instance',
    ),
    'field_id' => array(
      'type' => 'int',
      'not null' => TRUE,
      'description' => 'The identifier of the field attached by this instance',
    ),
    'field_name' => array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    ),
    'entity_type' => array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    ),
    'bundle' => array(
      'type' => 'varchar',
      'length' => 128,
      'not null' => TRUE,
      'default' => '',
    ),
    'data' => array(
      'type' => 'blob',
      'size' => 'big',
      'not null' => TRUE,
      'serialize' => TRUE,
    ),
    'deleted' => array(
      'type' => 'int',
      'size' => 'tiny',
      'not null' => TRUE,
      'default' => 0,
    ),
  ),
  'primary key' => array('id'),
  'indexes' => array(
    // Used by field_delete_instance().
    'field_name_bundle' => array('field_name', 'entity_type', 'bundle'),
    // Used by field_read_instances().
    'deleted' => array('deleted'),
  ),
);

```
* Drupal 7 placeholders aren't wrapped between quotes, when they are for strings.

The following query should not return any error.

```
SELECT nfi.field_name FROM {field_config_instance} nfi
  INNER JOIN {field_config} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = :type_name  AND nf.active = 1 AND nf.locked = 0

```
> 1 votes

# Answer
If this is for Drupal 7, you should name your array items and placeholders.

```
$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {field_config_instance()} nfi
    INNER JOIN {field_config()} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = ':type_name' AND nf.active = 1 AND nf.locked = 0", array(':type_name'=>$type_name));

```

In Drupal 6, `db_query()` doesn't take an array as second argument.
> 0 votes

---
Tags: entities
---


# Question
Title: Configuring Commerce in an existing drupal install
I'm running drupal 7 and would like to add the Commerce module to my site and am having problems with basic functionality. I've created a product display with views, but I'm unable to figure out how to add an 'add to cart' button to item listings, as well as how to add a checkout page.

Just about everything that I've found suggests using kickstart from a clean installation but that isn't an option for me. The documentation seems to be missing gaps of information relating how to set up blocks which normally would be included in commerce kickstart.

What is a good place to start learning about the basic module so I can get my cart up and running?

# Answer
> 5 votes
I would recommend that you install and play with Kickstart 2 in order to study best practices and find out what contrib modules you need for the most common Drupal Commerce features.

To install Drupal Commerce on any existing Drupal site, start by first installing its dependencies, and then activating Commerce modules in the order indicated here. Also, make sure that you activate all the Commerce UI modules. This should get you to the point where you can create basic products, orders, and a checkout workflow.

You should first learn about the separation between product displays and products here. In short, you need to create a new node type, let's say "Product display". For it to act as a product, you need to add a "product reference" field and configure it to suit your needs. Make sure that on the "Manage display" section of your Product display you have selected the "Add to cart form" format for your product reference field. Your view should display products with add to cart forms as long as you configure it to display nodes of type "Product display" with the correctly configured view mode.

After you understand the concept, I fully recommend installing Inline Entity Form. It will spare you the effort of explaining the above concept to your clients, and make their life much easier.

---
Tags: views, 7, commerce
---


# Question
Title: "Call to undefined function fivestar_widget_form()" error
I am getting the following error - it's related to the fivestar module. As far as I can tell, it is using an obsolete function call (used in Drupal 6)

```
Fatal error: Call to undefined function fivestar_widget_form() in /home/SITENAME/public_html/sites/all/modules/contrib/views_php/plugins/views/views_php_handler_field.inc(202) : runtime-created function on line 5

```

The problem is that I've looked at all references to the widget in the template files, tried to change them.

I've tried the following, as said here, but I keep getting the error.

```
print render(fivestar_widget_form($node));
print render($content['field_vote']);
print drupal_render($content['field_vote']);
print drupal_render(fivestar_widget_form($node));

```

What could be causing the error?

# Answer
There's no function called `fivestar_widget_form()` in the Drupal 7 version of Fivestar (I've just grepped the module folder).

It's likely that function is a CCK hook remnant, CCK having been incorporated into the core Field module in Drupal 7, and all of it's functions renamed.

As far as I know there's no easy way in Drupal 7 to use a field widget form as a stand-alone form so you might have to look for another way around this problem.
> 1 votes

# Answer
This might help if you still need it - I was just running into the same issue, banging my head against the wall until I finally found the solution (for me). For some reason, the Fivestar field had gotten set to hidden under full content in "Manage Display" for my content type. I'm pretty sure it defaulted to this, even though the "Default" display did not have it hidden. When I changed it to display "As Stars", I could use

```
print render($content['field_vote']);

```

in my node--\*.tpl.php file.
> 0 votes

---
Tags: rating
---


title: Drupal 7.x & GoDaddy Cron Jobs

text:
# Question
Title: Drupal 7.x & GoDaddy Cron Jobs
Has anyone successfully gotten cron jobs to work with GoDaddy shared hosting and Drupal 7.x?

This sort of thing is EASY if you have access to use wget or cURL but GoDaddy for some reason blocks access to their own shared servers through tools as wget and cURL. Why I don't know.

We are stuck with having to use

```
/web/cgi-bin/php "$HOME/html/drupal/cron.php"

```

but as described here: http://drupal.org/node/251481

that is bad since Drupal doesn't go through its bootstrap process and certain vars are not initalized. I also get the classic:

```
Status: 404
Content-type: text/html
No input file specified.

```

when I use this method. There is also the fact that D7.x requires a cron\_key parameter passed along \_cron.php?cron\_key=XXXXXXXXXXXXX

Anyone have a solution...besides get the hell off GoDaddy?

# Answer
> 2 votes
Yes, I crated a cron.sh script and uploaded it on my server with the following content:

```
#!/bin/bash
# run drupal cron
echo "Start"
START=$(date +%s)
echo "Running Drupal Cron"
wget -O - -q -t 1 "http://<your-domain>.com/cron.php?cron_key=<your-key>"
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Total Time: $DIFF seconds"
echo "End"

```

I went into the GoDaddy hosting account and entered the cron command:

```
bash /home/content/00/00000000/cron.sh

```

NOTE: You will need to know the path of the location where the script resides on the server. If you are using ssh you can get the path by typing "pwd" in the ssh command line.

---
Tags: 7, cron
---


title: Point subdomain to root drupal install

text:
# Question
Title: Point subdomain to root drupal install
I have been tasked to flush out the content on a drupal site that utilizes the domain access module for multiple subdomains under one DB.

* I have gone to structure-\>domains and added all the domains but when I try to visit them I get server not found.
* I have found that I need to direct the DNS to each url? I am still a little unsure of how this works. Is there a way to do this without accessing the host like through the .htaccess file or settings.php or httpconfig? I need to **"configure all domains to the primary VirtualHost's ServerAlias, or else point all relevant DocumentRoots to my single installation of Drupal."**

Can someone please help me get these last two subdomains pointed to the root install of drupal so the site actually shows up? Is this possible to do without editting the httpd.config file as I don't have access to the server files.

Thanks

# Answer
The Domain Access module has quite thorough documentation.

For your specific issue, you want the Before installing section, which covers the necessary Apache configuration. In short, you're right that you want to configure all domains to point at a single docroot--once that is set up, Domain Access will properly handle which content is available on specific domains.
> 1 votes

---
Tags: domain-access
---


# Question
Title: Is it true that CCK has no API to work with from other modules?
A colleague of mine was trying to import some huge data (from Excel) into a drupal 6 project with pure PHP and MySQL. The result is supposed to be few content-types(CCK), thousands of nodes(CCK nodes I mean),some vocabularies and few other things.

Seeing him trying to decipher the tables involved, I suggested instead of trying to reverse-engineer what CCK is doing, he should use CCK API. The problem is I couldn't find any such thing as CCK API!

Despite my heavy search to no avail, I can't in any right mind believe this to be true. I say, to myself, perhaps I can't find it ?

So how do you add a content-type, a CCK node etc etc Pragmatically ? How do you utilize CCK in PHP code ? not from the user interface ?

# Answer
> 5 votes
No, it's not true.

CCK does its field processing when node API hooks are invoked, so when you (or another system process) call `node_save()`, CCK will run through the node object and save any field values it needs to.

For example, this code would load a node, change the value of a field called `field_my_field`, and then save that to the database:

```
$node = node_load($nid);

$node->field_my_field[0] = array('value' => 'Some new value');

node_save($node);

```

There are also CRUD functions in `includes/content.crud.inc` which will come in handy to create fields and instances on the fly.

# Answer
> 4 votes
Clive's answer is spot-on in regards to how to use CCK programatically. However, the question specifically mention content migration from spreadsheet data, and for that the Feeds module is a really useful tool.

The Feeds module provides a user interface for importing content from a few different types and sources of structured data including RSS feeds, XML and CSV files. In this situation, you would save the data in Excel as a CSV file and create a custom Feeds importer that maps the columns of the CSV to different fields and attributes of a specific node type. Be sure to read the very thorough documentation to learn the details of using this module.

---
Tags: entities
---


# Question
Title: Embed view and set filter from CCK field
I created a view with 3 filters. I embedded the view in my tpl.php file for the content type. My question is, how can I set some filter with the value from a CCK field?

This is the code I use:

```
$view = views_get_view('view_name');
$view->set_display('default');
$view->filters[2]['value'] = $node->field_name[0]['value'];
if (!empty($view)) {
    print $view->execute_display($display_id , $view_args);
}

```

# Answer
> 2 votes
You should use arguments instead of filters on your view. That way you can use views\_embed\_view.

Just add an argument to the view with the same field you would use as a filter. That adds a where condition to the views query in a similar way as a filter would do.

Then pass on the CCK field value as the third argument on your template file like this:

```
print views_embed_view('view_name', 'default', $node->field_name[0]['value']);

```

# Answer
> 0 votes
you could always use like this:

`views_embed_view($name, $display_id = 'default', 'your first arg', 'second arg', 'so on', 'so forth');`

---
Tags: 6, views
---


# Question
Title: how to ignore the validation of hidden form fields in the user registration form?
I am having a problem regarding the validation of the hidden fields.

I have some some fields that are hidden and only visible if a specific field is selected.

And I marked those those hidden fields as required. So I want to validate those fields only if they are visible and not validate if they are hidden.

I tried the client side validation module but the problem is if I enter the visible required field values then upon submission it also validate those hidden fields.

Any idea?

# Answer
> 3 votes
You need to use #ajax attribute on your specific field to alter the form ( to remove #required for your hidden element ). It lets Drupal re-build the form before submission and core validation. You will need to implement hook\_form\_alter and an ajax callback function.

Here is a workaround.

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register_form'){

        $form['toggle_me'] = array(
            '#type' => 'checkbox',
            '#title' => t('Tick this box to type'),
            '#ajax' => array(
              // #ajax has two required keys: callback and wrapper.
              // 'callback' is a function that will be called when this element changes.
              'callback' => 'ajax_form_alter',
              // 'wrapper' is the HTML id of the page element that will be replaced.
              'wrapper' => 'replace_field_div',
              // Don't show any throbber...
              'progress' => array('type' => 'none'),
             ),
        );

        # This field will be shown or hidden when "toggle_me" is checked or unchecked
        $form['dependency'] = array(
          '#type'       => 'hidden', # initially hidden
          '#title'      => 'Dependency',
          '#required'   => TRUE,
          '#prefix'     => '<div id="replace_field_div">',
          '#suffix'     => '</div>',
        );
        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['toggle_me']) && $form_state['values']['toggle_me'] == 1){
            # when "toggle_me" is checked, show this field and set required.
            $form['dependency']['#type'] = 'textfield';
            $form['dependency']['#required'] = TRUE;
        }else{
            # when "toggle_me" is unchecked, hide this field and remove required.
            $form['dependency']['#type'] = 'hidden';
            $form['dependency']['#required'] = FALSE;
        }
    }
}
/**
 * Callback for toggle_me
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['dependency'];
}

```

The example shows only two new elements ( toggle\_me and dependency ) which are added to user registration form using hook\_form\_alter. When "toggle\_me" is checked, show "dependency" and set required. When "toggle\_me" is unchecked, hide "dependency" and remove required.
If you don't know about ajax form alter, download examples module and check ajax example.

# Answer
> 0 votes
Specify the conditions under which the field is required using drupal\_process\_states(). There's a UI for it, called Conditional Fields, but it does not have a recommended release yet.

---
Tags: 7, users, forms
---


# Question
Title: How can I adjust the position of a cancel button added with hook_form_alter()?
Based on this answer, I added a cancel button to my user picture upload form like this:

```
  $types = array(
    'profile_picture',
  );

  foreach($types as $type) {
    if($type.'_node_form' == $form_id) {
      if(arg(1) == 'add') {
        // If adding node link to node/add screen
        $link = l(t('Cancel'), 'account/manage-pictures', array('attributes' => array('class' => array('form-submit','cancel'), 'id' => 'edit-cancel')));
      }
      elseif(arg(2) == 'edit') {
        // If editing node, link to node view screen
        $link = l(t('Cancel'), 'node/'.arg(1), array('attributes' => array('class' => 'form-submit, cancel', 'id' => 'edit-cancel')));
      }
      $form['cancel'] = array(
        '#type' => 'markup',
        '#markup' => $link,
        '#weight' => 0,
      );
    }
  }

```

However, this causes the red cancel button to be placed at the top of the form instead of the bottom of the form next to the purple save button as shown in the screenshot below.

When I examined the CSS in Firebug, I saw that the save button is under this div: `<div id="edit-actions" class="form-actions form-wrapper">`, while the cancel button is not. Is there a way to place the cancel button under the same div as the save button?

# Answer
Use the following code.

```
$form['actions']['cancel'] = array(
 '#type' => 'markup',
 '#markup' => $link,
);

```

If it doesn't work, check with `print_r()` where the submission buttons are added in the form array. Usually, it's `$form['actions']`, but sometimes can be a different array index.
> 2 votes

# Answer
Use `$form['buttons']['cancel'] = /* … */;`.

*buttons* is just an example; it depends on how the form was created. Some forms call it *actions* or something else. Inspect the form variable to find out where to put your button.

Sometimes the save button won't be in a special div. In that case you only need set the weight to something high in order to get it last.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Selecting the taxonomy terms to use using a textfield to search them
My Drupal 7 site has almost thousand of taxonomy terms. So it is a hard work for my users to pick their desired category from thousand of taxonomy terms.

Is there any way to select a taxonomy term by using a small search box to choose the exact category and sub-category?

# Answer
> 0 votes
You can try using Views to build a custom search with exposed forms. And the use the fields to display terms the way you need it. That is probably the easiest.

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


# Question
Title: Drupal 7 - How to get AJAX response displayed in a ctools modal?
I want to create a ctools modal popup when a button is pressed.

```
function custom_form( $form, &form_state ) {
  $form['btn'] = array(
    '#type' => 'button',
    '#value' => t('add'),
    '#executes_submit_callback' => FALSE,
    '#ajax' => array(
      'callback' => 'custom_callback',
    ),
  );
}

function custom_callback() {
  ctools_include('ajax');
  ctools_include('modal');

  ctools_modal_render( 'Error', 'Error Message');
}

```

I only get the alert message with the un-rendered ajax response. How can get I this response displayed in rendered format in modal?

# Answer
> 2 votes
Checkout Documentation on: http://api.drupal.org/api/drupal/includes!ajax.inc/7 or: http://drupal.org/node/1635198#comment-6120546 on how to render drupal messages.

For more Information about ctools modal you may check: Example to display webforms (webform.module) within CTools modal windows

Or what about a tutorial like: "Ajax modal windows, the easy way"

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


title: Add Fields to the Link Module

text:
# Question
Title: Add Fields to the Link Module
Image here:

I made this with Photoshop. The "URL" field is supposed to be a Link field (the Link module). But it seems that it only provides an optional title field but no way to add fields like this. Or should I create a new node type and add "Quality" and "Provider" fields then reference (the Entity Reference module) that node with this? Seems that adding those two fields are more ideal. Please advise. Thanks.

# Answer
There is a module just for this, where you can add and group fields together, as well as add multiple field groups: Field Collection
> 3 votes

---
Tags: 7, entities, navigation
---


title: How to add content to a main page

text:
# Question
Title: How to add content to a main page
First Drupal site. I have a custom content type of 'books' which I want to add to the 'books' basic page. I literally have no clue how to do this, or what is the best 'Drupal' way of doing this.

# Answer
The default Drupal setup is to display a list of all nodes that have their "promoted to front page" box checked.

If you want to display a single node rather than that list, you can create that page and then change the default front page in admin/configuration/site-information by pasting in that page's path to the front page field.

If you would like to display a list that is different from the default list, (like, you want to add filters or display fields or something) then you can install and use Views to override the default or to create a new page and set it as the main page in site-information settings as described.
> 0 votes

---
Tags: 7, nodes
---


title: Show only objects with the latest date

text:
# Question
Title: Show only objects with the latest date
How can I show objects having the latest post date? I.e. if 1 was posted yesterday, and 2 -- today, then show only 2 but if they both were posted yesterday and all the others before that, then show 1 and 2.

Is it possible with Views?

# Answer
Since there's logic involved (check records based on this date, if there are no results, check the previous date) I would do this with a custom module making use of Entity Field Queries.
> 1 votes

---
Tags: views
---


# Question
Title: List of users who signed-up last month, or last year
I want to get the number of users who signed-up the last month, or the last year.

Is there any module for achieving this? How can I do it using the Views module?

# Answer
> 0 votes
I believe you can create a View of Users. Group by signup date.

---
Tags: views
---


title: Changing Font Options in CKEditor

text:
# Question
Title: Changing Font Options in CKEditor
I've tried a few different methods to change the options listed in the "font" drop-down in CKEditor, to no avail.

First off, I went to Config \> CKEditor \> Profiles \> edit each profile \> Advanced Options \> Custom JavaScript configuration and followed the instructions below, putting something like

```
config.font_names = "Helvetica Neue;Helvetica;Arial;sans-serif;"

```

but nothing changed. I went into the config.js file located at sites\all\modules\ckeditor\ckeditor\ and added the following lines inside the function call:

```
config.font_names = "Helvetica/Helvetica Neue, Hevletica, Arial, sans-serif;"

```

but nothing changed. I then tried removing the prior line in Drupal's Configuration menu but that also didn't help. I've cleared my browser's cache and Drupal's cache, no luck. I've tried Firefox & Chrome, no luck.

Am I missing something or is this a bug? As a last resort, I could go directly into ckeditor\ckeditor\_source\plugins\font\plugin.js and change the font\_names listed there but the documentation I've read indicates my methods above should work, so I'm trying to avoid that.

# Answer
> 1 votes
I tried using the code that you mentioned above, and it didn't work. Then I went back to the basics and checked the official documentation from CKEditor's website so I added something like this:

```
config.font_names =
    'Helvetica, Arial, sans-serif;' +
    'Times New Roman/Times New Roman, Times, serif;' +
    'Verdana';

```

and it worked perfectly.

**IMPORTANT NOTE**: there is no need to go to a file and add the custom code in it. Actually, *it's not even recommended to do that*. What you should do, is go to the configuration options of CKEditor in your admin area (admin/config/content/ckeditor) press the "edit" button for the profile that you want to add this option to, and add the code from above in the "Advanced Options" -\> "Custom JavaScript configuration".

Save the edits and you are good to go.

P.S: I didn't even need to clear the cache. The effects were visible instantly.

# Answer
> 2 votes
Solution: It took me quite a while to figure this out. Let us say you want to use Verdana as the default font. Here is what you can do:

1. Open contents.css and change the font tag:

font-family: Verdana;
2. In the application/page where the output will be published, add this style:

.entry-content {font-family: Tahoma;}

That's it! Now you have change the default font successfully. This works for the font size as well. I just finished developing this question2answer site, http://banatbanat.com, which utilizes CKEditor and this tiny issue kept me awake for two days!

---
Tags: wysiwyg, theming
---


title: Empty space on top of the page

text:
# Question
Title: Empty space on top of the page
I coded some modules (basically only PHP and no alter of Drupal functions), and on mysterious way, two of my modules are producing an empty quote on top of my meta tags in the body.
This causes a 20 empty pixels on top of my page, and destroys my slider.

As mentioned, two modules are producing this; I figured out that the first module produces this when I use `include_once("config/rewards.inc");`. If I comment it out, everything works fine. `include_once("config/rewards.inc");` is already included in one of my other modules, but I used `include_once`, to include it, obviously, only once.
`include_once("config/config.inc");` doesn't produce this error.

This is a screenshot of Firebug (the arrow point at the margin).

In my first module, the problem happens when I uncomment the line containing `require_once("config/rewards.inc")`.

```
<?php
//      *****************************************
//      **      Donate Script for Trinity      **
//      **             by Leandros         **
//      *****************************************

//module_load_include('inc', 'donatescript', 'rewards');
//module_load_include('inc', 'donatescript', 'config');
require_once("config.inc");
//Produce problems (for some reason I dont know ^^)
//require_once("config/rewards.inc");

if(user_is_logged_in()){
global $user;
global $donatepoints;
$userip = $user->hostname;
$userid = $user->uid;
$username = $user->name;
$usernameuc = strtoupper($user->name);

//$GLOBALS['reward_items'] = $tab_rewards;
//$GLOBALS['reward_texts'] = $reward_texts;

//Get Variables from config.inc for realmd DB
$db = $realmd_DB['1']['3'];
$host = $realmd_DB['1']['0'];
$dbuser = $realmd_DB['1']['1'];
$dbpassword = $realmd_DB['1']['2'];

//Connect to realmd DB
$connect = mysql_connect($host, $dbuser, $dbpassword) or die (mysql_error());
mysql_select_db($db, $connect) or die (mysql_error());

//query overall donatepoint value
$donate_points_select = mysql_query("SELECT points FROM donate_points WHERE id='$userid'");
while($row = mysql_fetch_array($donate_points_select)) {
    $donatepoints = $row['points'];
}

if($donatepoints == 0) {
    $GLOBALS['donatepoints'] = 0;
} else {
    $GLOBALS['donatepoints'] = $donatepoints;
}

//mysql_query("INSERT INTO `donate_points` (`id`, `name`, `points`) VALUES ('$userid', '$usernameuc', '$donatepoints')");

//Close DB connection
mysql_close($connect);
}
?>

```

# Answer
I found the error in the second module: It was because the opening `<?php` tag had a tab before it.

I fixed the second module, too. I don't know which produced the empty space, but I created for every file I used a new file and pasted my code into, renamed the module and enabled it. Everything now works.
> 1 votes

# Answer
First of all, it is better practice (in Drupal) to use this in your .module file

```
/**
* Includes necessary files for YOUR_MODULE_NAME module
*/
module_load_include('inc', 'MODULE_NAME', 'rewards');
module_load_include('inc', 'MODULE_NAME', 'config');

//you don't need the trailing .inc in rewards as drupal adds it in this function.

```

This will allow you to load the file only once (using require\_once see module\_load\_include ).

So, try this 'Drupal Way' instead of include\_once. If that still gives you the weirdness with the extra space, perhaps post the code of rewards.inc (unless it contains sensitive info, which should be redacted).
> 0 votes

---
Tags: 7
---