# Question
Title: Get the uri/path value of an image in the field template
I have created a custom field template for an image - field--field\_images.tpl.php with the following code:

```
<?php
$url = file_create_url($field_images['uri']);
$url = parse_url($url);
$imglink = $url['path'];
?>
<div id="slideshow">
  <?php foreach ($items as $delta => $item): ?>
    <div data-thumb="<?php print render($imglink); ?>" data-src="<?php print render($imglink); ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" ></div>
  <?php endforeach; ?>
</div>

```

currently `$imglink` returns the value of the root folder "www". I need to find a way to get the path to the image file associated with the field e.g "http://www.example.com/sites/default/files/image.jpg" any help with this would be greatly appreciated.

UPDATE:

I think I'm almost there. Here is the code in my field-field\_images.tpl.php file:

```
<?php foreach ($items as $delta => $item): ?>
  <div data-thumb="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = image_style_url('thumbnail', $img_src); print ($link); ?>" data-src="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = file_create_url($img_src); print ($link); ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" ><?php render($item); ?></div>
<?php endforeach; ?>

```

and you can see the output here: http://www.kfpa.co.za/dev/?q=node/2

The one problem is that it loops through and creates the correct number of elements for the uploaded images, but when it creates the URLs it's only creating for the item as specified for by 'x' in `<?php $img_src = $element['#object']->field_images['und'][x]['uri'];` i.e if I change 'x' to '2' the third photo displays. How do I change this code so that it finds the correct URL for corresponding image in the loop?

# Answer
> 0 votes
you want file\_create\_url().

Note: Usage of drupal\_realpath() is discouraged.

Similar question: What is the alternative to drupal\_realpath()?

# Answer
> -1 votes
There is drupal\_realpath

> Returns the absolute local filesystem path of a stream URI.

```
drupal_realpath($uri)

```

Also there is image\_style\_url

```
image_style_url($style_name, $path)

```

---
Tags: 7, entities, media, uri
---


# Question
Title: How can I modify the advanced search form when my hook runs too early?
I'm using hook\_form\_FORM\_ID\_alter to modify the content of the form on the search page — I want to remove the "phrase" and "not" fields, and restrict the "only of the types" checkboxes to a hand selected list of types.

I have the following code, which is being called and which I think *should* work:

```
function MYMODULE_form_search_form_alter(&$form, &$form_state, $form_id) {
    unset($form['basic']);
    unset($form['advanced']['keywords']['phrase']);
    unset($form['advanced']['keywords']['negative']);
    unset($form['advanced']['type']);
    $form['advanced']['type'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Only of the type(s)'),
        '#options' => array(
            'blog' => 'Blog entry',
            'event' => 'Event',
            'news' => 'News article'
        )
    );
    // print_r($form);
    // die;
}

```

Except node\_form\_search\_form\_alter gets to the search form *after* my form alter hook runs, so I don't get a chance to modify any of the form elements that it's adding.

I'm running Drupal 7.22.

How can I modify the advanced search form when my module hook runs before the hook that defines the advanced search form?

# Answer
> 5 votes
Changing the module weight will work, but sometimes that can cause problems with the order in which *other* hooks in your module are invoked.

Drupal provides `hook_module_implements_alter()` for exactly this sort of situation, so that you can target the order a *specific* hook is run in:

> Alter the registry of modules implementing a hook.
>
> This hook is invoked during module\_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

The code might look something like

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move MYMODULE to the end of the list.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

```

Once you clear the cache your module's implementation of `hook_form_alter()` will be invoked last (unless of course another module is implementing `hook_module_implements_alter()` and altering the order again. But that's a different story).

I personally prefer this method as it's just a simple code change, no need to maintain any changes to the system table in the database.

I'm not sure how well that works with a form\_FORM\_ID\_alter hook (never tried it), but with this method you can at least make sure that only the weight for `hook_form_alter()` need be updated.

Actually looking at the code for `drupal_alter()`, changing the conditional to `if ($hook == 'form_search_form_alter')` would probably work.

# Answer
> 1 votes
Hooks are ordered by module's weight. Easiest way is to simply use Modules weight module and order them as you please:

> We always need to modify modules execution order, and some could write a code that execute a query to modify the weight of a module in system table, some might go straight to his favorite SQL client and modfiy the record directly, This module provide admin interface for users/people has the access to modules page to reorder the module weights as they want, it provide a drag/drop functionality to order the contributed modules execution.

That's easy, but not portable. To make it more portable, use hook\_install():

```
function your_module_name_install() {
  db_update('system')
    ->fields(array('weight' => your_preferred_weight))
    ->condition('name', '[your_module_name]', '=')
    ->execute();
}

```

or follow any other way outlined in the docs on Drupal.org.

---
Tags: hooks, search
---


# Question
Title: How to export private images from Drupal
I want to export private images from Drupal to an external client. How to I authenticate an external client to access private files from Drupal DB?

# Answer
You can use file\_create\_url($uri) to create an externally accessible url for the file.

If used with private file mode files, you will need to implement hook\_file\_download

You might also be interested in the Services module, to expose an API for the files, which can provide authentication methods such as Drupal session and OAuth authentication.
> 3 votes

---
Tags: media, database
---


# Question
Title: Image styles thumbnail, medium, large to default dimenssions
My drupal create thumbnail of my uploaded image (thumbnail, medium and large). I don't want to have redimensioned images, I want original size.

PS: drupal create 3 images per uploaded image, so, for me are lots of nodes.

How can I stop drupal from creating these?

# Answer
Go to Configuration -\> Media -\> Image Styles (or analogous path in non-7 versions). By default you have 3 styles there, the ones you mentioned. You can edit them to suit your needs, but deleting them is not supported - to many modules uses them.

On the other hand, styled image files are supposed to be created on first access. You shouldn't have them on your file system until something really needs them, so to get rid of those files simply turn off everything that uses them, and purge `/sites/*/files/styles` directory.
> 1 votes

---
Tags: media
---


# Question
Title: Custom pager "Showing X - Y of Z results"
I have some entities queried from an external solr server using custom code and Search API, and I'm listing them 10 per page.

I have created a pager for the page using `pager_default_initialize()` and `theme('pager')`.

I wanted to insert a text into the pager div that says "Showing X - Y of Z results". I can do this manually by overriding the `theme_pager()` function, but I was wondering is there a drupal native function or some setting which you can pass to theme\_pager that does this?

I suppose in short I want the Views 3 equivalent of "Full pager", instead at the moment I'm only able to produce the "Mini" pager.

# Answer
In views you can use the below php function and place it in header with php filter

```
<?php
global $pager_page_array, $pager_total_items, $pager_total;
$my_view = views_get_current_view();
$items_per_page = $my_view->pager['items_per_page'];
if ($pager_total[0] == 1) {
  echo t('Showing <b>!pager_total_items</b> results',
    array('!pager_total_items' => $pager_total_items[0])
  );
} else {
  $start = 1 + ($pager_page_array[0] * $items_per_page);
  $end = (1 + $pager_page_array[0]) * $items_per_page;
  if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
  echo t('Showing !start-!end of <b>!pager_total_items</b> results',
    array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0])
  );
}
?>

```

See the below is result
> 1 votes

---
Tags: 7, theming, paging
---


# Question
Title: Field type that is an integer, but accept some strings that means no value is provided?
I have a field named "Price" that should allow anything from 0 - no maximum value, so I set it as an Integer and set 0 for the minimum value (and put a suffix to show up for the price).

However, the field contented is generated by parsing a JSON feed, and the feed owner sometimes puts "on demand" for some items, meaning the price can be negotiated on demand or the price is private and only shared when a client shows enough interest to buy.
The Feeds JSONPath Parser module parses the text string and doesn't import the fields with text for the Price field as it's not an Integer. Therefore resulting in a blank field input.

Should I replace all empty values with a 0 and then on view results set 0 to be rewritten to the "on demand" text? Or is there another way that I should explore?

I need to keep the Price field as an Integer since I use it for a range filter in my view.

# Answer
> 1 votes
If you have only one possible non-integer value, leave it as integer, just make it optional (not required). As far as I understand Feeds JSONPath Parser, non-integer value will simply get omitted, giving you no value for this field - exactly consistent as in fact you don't have that price.

Then in your template files check if it's set. If it isn't, show "on demand" string, with a link to make a demand or, well, anything you need.

---
Tags: entities
---


title: Rate widget won't display

text:
# Question
Title: Rate widget won't display
I am trying to use the rate widget in Drupal 7, and everything looks like it should work correctly, however it isn't displaying.

I'm on one of the node types it should appear under, it does not show up.

I used to have Fivestar installed, could that be an issue?

Here's a screenshot of the nodetypes I've selected

Any help would be appreciated, I can't find anything I've done wrong or that would prevent it from showing up.

# Answer
If everything else fails, you could create a custom block and render the rate widget programatically. This gives you more freedom anyway. Similar approaches are explained here: Rendering the Fivestar widget
> 0 votes

# Answer
I was just having the same issue. Using a custom tpl.php for the node seems to fix it.

Cheers,
> 0 votes

---
Tags: 7, rating
---


# Question
Title: How to pass values directly from THEME_NAME.info to THEME_form_system_theme_settings_submit()
Does anyone know a smarter way to load given settings from the THEMENAME.info file for the submit function only, than to create another "ghost"-form calling theme\_get\_setting() ? I would like to prevent the ghost form, since there is no input needed.

I only need some settings from the info file in the submit state.

# Answer
You do not need to use a form to save these values. `variable_get()` and `variable_set()` functions will make it much easier to set the value and retrieve it.

However, if you still want to pass the information via the theme's .info file, you can do as follows:

**Add your custom variables to the .info file**

EX: my\_awesome\_theme.info file:

```
name = my_awesome_theme
core = 7.x
dragons_exists = 1
how_to_catch_a_dragon[] = "Be a dragonlord"
how_to_catch_a_dragon[] = "Tell him to surrender"

```

Drupal will ignore these extra stuff during normal module/theme scanning.

**To get the value, you can it like this:**

```
$data = drupal_parse_info_file('sites/all/themes/my_awesome_theme.info');

```

You can use functions like `drupal_get_path()` to get the correct path. `$data` will contain the values from the .info file. For example, the above .info file will yield

Note that `drupal_parse_info_file()` doc mentions that you should NOT use this method to store arbitrary data.

> Parses Drupal module and theme .info files.
>
> Info files are NOT for placing arbitrary theme and module-specific settings. Use variable\_get() and variable\_set() for that.

**Update:** If you only need to pass some variable **from the form**, and not necessarily from the .info file, just store the value in `$form_state`. As long as you don't overwrite some existing values, `$form_state['values']` for example, it will work just fine.

Also, consider using a form element of `#type => value`. User will not see anything at all, not even a hidden form element. You can access this value from `$form_state['values']` nevertheless.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How send argument to Services Module (Views+Contextual filters)
I'm using the Services Module to make a request from one website to a drupal website (The services module calls a view).

For this I'm using jQuery:

```
$.ajax({
    url: 'http://test.url/rest/viewname',
    success: function(){ alert('hi'); }
});

```

This works FINE !

Now I added a "Contextual Filter" to the View, to show only nodes of a specific user. My question: How can I send the uid with jquery?? I tried a lot of ways:

```
$.ajax({
        url: 'http://test.url/rest/viewname/555',
        ...
    });

```

**Error 404!**

```
$.ajax({
        url: 'http://test.url/rest/viewname?args[uid]=555',
        ...
    });

```

**Argument ignored!**

```
$.ajax({
        url: 'http://test.url/rest/viewname?arguments[0]=555',
        ...
    });

```

**Argument ignored!**

```
$.ajax({
        url: 'http://test.url/rest/viewname',
        data: { uid: '1' }
        ...
    });

```

**Argument ignored!**

... and much more :D

Can somebody helo me?

# Answer
When making a jQuery ajax request to a Drupal Services 3.x module REST API endpoint, define the *request type* of your ajax request like this.

```
(function ($) {
  var request = $.ajax({
    "url" : "http://test.url/rest/viewname/555",
    "type" : "GET"
  });
}(jQuery));

```

Usually a RETRIEVE request would be done using the *request type* GET, but for an ACTION, like the `taxonomy_term` Resource action `selectNodes` (This method returns all nodes with provided taxonomy id.), provided in Services 3.x, you would set the *request type* to POST. All RESTful services use POST for ACTIONs. In this case, your jQuery Ajax request would look like this:

```
(function ($) {
  var request = $.ajax({
    "url" : "http://test.url/rest/taxonomy_term/selectNodes",
    "type" : "POST",
    "dataType" : "json",
    "data" : { "tid" : 555, "pager" : 0 }
  });
}(jQuery));

```

Each of the resource operations in a REST API use a specific HTTP Method or *request type* (e.g., GET, PUT, POST, or DELETE). You need to use the correct one or it wont work. The Drupal Services 3.x module adheres to these strictly.

To learn more about REST API request methods and how they relate to resource operations, take a look at the Using HTTP Methods for RESTful Services on the REST API Tutorial site.
> 2 votes

# Answer
thank you for the help!

I figured out the problem: to show only nodes from a specific user, it's not enough to add "Author ID" as a exposed filter! You have to add the "Author" relationship, and then you have access to much more filters: choose "User: The user ID (raw)" and check "Exposed ...". If you then scroll down to the point "More" you can set a "Filter identifier" (eg: uid)

After doing this you can call:

http://test.url/endpoint/path?uid=123

I hope I can help someone!
> 1 votes

---
Tags: services, views
---


# Question
Title: Show warning for viewing only some nodes
I am developing one website where I have one content type (News). Now, some of news content type nodes is adult and must to have age confirmation popup (just warning text, accept and decline button).

Any suggestion how to do that?

# Answer
> 0 votes
If you have registered users, you might do it with a role. This would have the benefit of not having to show this more than once.

Other than that, (this is just an idea, I haven't tried it), you could write a small module which implements `hook_node_access()` .

What you could do in this function is:

1. allow the user to view the node if there's an `adult=true` GET variable
2. disallow the user to view the node if there's an `adult=false` GET variable
3. redirect the user to your own YES/NO form when there's no `adult` variable in GET, appending your current path as a `destination` GET path, which is then used as the `action` target for the form, which itself uses the `GET` method and has an options box with the `name` of `adult`

I have no idea how easy it actually is to pull this off, but it seems quite reasonable.

Tell me whether you've done it and if it worked well, that'd be interesting.

EDIT: References you should read to accomplish this task, as you mentioned you are totally new to this.

1. Learn the basics about creating a new D7 module
2. Learn what hooks are
3. Learn how to create a new page with a path with the `hook_menu()` hook
4. In the callback function for `hook_menu()` provide the yes/no-form: Learn about the Drupal form API . Maybe get started with this tutorial on forms and complete it with the given API link.
5. Learn about `hook_node_access()` here and what to return. In this function, do what I mentioned in the list above and complete your functions.

I hope I could help you in any way, and trust me I know how hard it is to get started.

---
Tags: nodes, javascript
---


title: Generate page for each json entry

text:
# Question
Title: Generate page for each json entry
I'm new to Drupal. I want to customize the search module in order to show results from an external JSON. I was able to insert JSON data in the search page, but now I want to generate a page for each result. Something like blog posts. I'm using the latest Drupal 6 Version.

Please give me some ideas how can I generate the pages for each Drupal result.

Anticipated thanks!

# Answer
> 0 votes
I've used Feeds JSONPath Parser module to parse a JSON feed and insert the objects as a specific content type (e.g. blog posts).

It works well but I'm unsure about your search results, you might just have to set the template to link to each of the content nodes by getting the node based on a specific field that you know will be unique for all of your nodes? e.g. title?

If you don't want to actually store the parsed data as content, and just want to display them as a page, then you'll need to use the `hook_menu()` function. I've linked to API 6 as you noted you were using D6.

---
Tags: 7, search
---


# Question
Title: Auto add image to node listing from node body field
Hi I have news content type, where are fields Title(textbox), Body(text with CKeditor) and Summary Image(multimedia asset). Is it possible to auto add first image from Body to summary image field?

# Answer
> 0 votes
Install the Token Filter module. That'll tell you what tokens available and from them choose the field that you want to display in the node body. So when you save the node the token will replace with the field value you want.

---
Tags: nodes, media, entities
---


# Question
Title: How to delete content type menu item in .install file on module uninstall /disable
I have a module that adds a content type in the .install file. When I disable the module how do I remove the content type entry from the menu?

# Answer
Using a `hook_uninstall()` in your .module you can implement.

```
/**
 * Implements hook_uninstall().
 */
function YOURMODULE_uninstall() {

  // List custom content types that you want to delete
  $custom_ctypes = array(
    'blog',
  );

  // Go through each and unlock the content type
  foreach ($custom_ctypes as $ctype) {
    db_query("UPDATE {node_type} SET `custom` = 1, `locked` = 0 WHERE `type` = :ctype", array(':ctype' => $ctype));
  }

  // Clean Drupal cache; this is necessary for the "Delete" link to appear
  drupal_flush_all_caches();

}

```

Now you'll see the delete link on the menu and you can delete the content type. I think it's the only way you can delete the content type with fields.

But you can try using the function below too, afaik it will not delete the content fields:

```
/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  // delete the content type
  node_type_delete('CONTENT_TYPE_NAME');
  variable_del('node_preview_CONTENT_TYPE_NAME');

  // node type rebuilds
  node_types_rebuild();

  // rebuild the menus
  menu_rebuild();
}

```
> 1 votes

---
Tags: installation
---


# Question
Title: List all nodes related to a term which is related to another one
I searched many times how to list all nodes related to a term which is related to another one, but without success...

Can you help me ?

Actually I want to do something like this:

My page (where a term is defined) \<- A term linked to the previous defined one \<- The nodes related to this term.

Thank you for the help!

# Answer
> 0 votes
If you don't have Views installed, install the Views module.

1. Create a taxonomy view
2. Add filter to filter your taxonomy.
3. Add a relationship to other taxonomy you want.
4. Add the relationship to nodes.

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


# Question
Title: file field on form in view is ajax-enabled ONLY if rendered as part of page, not retrieved through ajax
We are using the popup module to render views within a page.

One of the views has a file field for uploading. The popup module can render the popup as part of the page and then display the popup or pull the data in through an ajax call.

If the views is pulled in as part of the rendering of the page, the field has ajax enabled and works correctly.

However, when the view is pulled in through ajax, the field does not have ajax enabled and fails to function.

There are dozens of such popups on the page and it is simply not practical to have all the popups pre-rendered (not to mention the inefficiency of it).

I have tried pulling in just one popup to check whether its just some missing javascript files but while the solitary popup works as expected, the other ones still fail to function.

Digging into the popup module, the bit of code to retrieve the view is exactly the same regardless of whether it's being pulled in as part of the page, or separately through ajax.

from popup.api.inc

```
function _popup_view($attributes, $return = FALSE){

  $title = FALSE;
  $body = FALSE;

  if (module_exists('views')){

    $view = views_get_view($attributes['view']);

    $display = $attributes['display'] ? $attributes['display'] : 'default';
    $args = isset($attributes['args'])
      ? explode(',', $attributes['args'])
      : array();

    if ($view){
      $view->set_arguments($args);
      $view->set_display($display);
      $body = $view->preview();

      $computed_title = $view->get_title();
      $title = $attributes['title']
        ? $attributes['title']
        : ($computed_title
            ? $computed_title
            : @$view->display[$display]->display_options['title']
          );

    }

  } else {
    $body = false;
  }

  $title = $title ? $title : 'View';
  if ($return == 'title'){
    return $title;
  }

  if ($return == 'body'){
    return $body;
  }

  return
    popup_element(
      $title,
      $body,
      $attributes
    );

}

```

The relevant javascript section:

```
  var placeContent = function(data, destination){

    thisObject.body.unbind('showing', fetchContent);
    var close = $('.popup-close-button', destination);

    if (close.length){
      close.siblings().remove();
      destination.append(data);
    } else {
      destination.html(data);
    }

    Drupal.attachBehaviors(destination);
  }

```

The popup module has a mechanism for rendering drupal forms view a popup and load that via ajax as well. This too does not work.

I should state that regular forms do work without any issues. I have views being rendered via ajax popup that have other controls (submit buttons just now) which work without any issues.

However, if I add a file form field into any of those forms, it breaks even the original controls. I believe this may be related to the form changing to a multipart mime form.

This leads me to the conclusion that there is something specific about the file form field that fails when being retrieved through ajax.

Manually adding the file.js has had not impact (I was thinking that attachBehaviours may not be working correctly)

Any help to resolve this will be greatly appreciated.

# Answer
Turns out it was a bug in the popup module.
> 0 votes

---
Tags: 7, views, forms
---


# Question
Title: form_set_error() field not highlited red
When validating a field manually from my form a error is displayed but the field doesn't get red. For the first parameter i used the name of the input element. DRUPAL 7

```
if($form_state['values']['panes']['webform_nid31'][0]['contact_person'] == '') {
    form_set_error('panes[webform_nid31][0][contact_person]', t('You must select a name for this group of settings.'));
  }

```

# Answer
> 7 votes
If your form element is defined like that:

```
$form['panes']['webform_nid31'][0]['contact_person'] = array( ... );

```

your form\_set\_error call should look like that:

```
form_set_error('panes][webform_nid31][0][contact_person',
                t('You must select a name for this group of settings.'));

```

You need to set full path to element, without outside `[` and `]`. You could have many "contact\_person" fields in one form, just in different branches of a form tree. Using only last index would made setting errors ambiguous, thus it's not supported. At least officially. Might work, but only as an undocumented feature.

Formatting this string is described in API:

> Parameters
>
> $name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo\]\[bar\]\[baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

Last but not least, actual output is defined in theme, it might well be something other than red border if theme author decided so.

---
Tags: 7, forms
---


# Question
Title: How to pull active user name from drupal 6
Is it possible to pull the active user name or active ldap user from my drupal site, and store this in a separate DB, as i would like to use it because the login limits who can access the site, but I want to know who is submitting x,y,z data into my forms? so at the top of the form maybe a field that pulls their username?

# Answer
> 0 votes
Drupal 6 supports multiple DBMS connections easily in `settings.php` (to the same type of DBMS, eg 2 Mysql DBs, not 1 MySQL and 1 SQLServer).

You can use a function like hook\_user to track who has logged in and feed that username into your 2nd database using the database api and for instance the `db_query` function. You also likely need db\_set\_active.

**EDIT**

I'm not sure exactly what your trying todo. You can always use php's ldap functions to talk to ldap and look for info on the "user" (if they're not logged in yet I have no clue what you'd grad from ldap ...). You could always use hook\_form\_alter to assign additional submit handlers on any default drupal form to perform custom tasks.

Having used ldap\_integration for D6. You should realllly think about moving the site to D7 as the new ldap module is pretty nice and lets you save off ldap queries as re-runnable things :).

---
Tags: 6, users
---


title: Rendering the Fivestar widget

text:
# Question
Title: Rendering the Fivestar widget
I am trying to render the Fivestrar widget programmatically. I have tried the following code, without success:

```
$settings = array(
  'content_type' => 'parce',
  'content_id' => $nid,
  'stars' => 5,
  'autosubmit' => TRUE,
  'allow_clear' => FALSE,
  'required' => FALSE,
  'tag' => 'vote'
);

print drupal_render(drupal_get_form('fivestar_custom_widget', $field_rating['0'], $settings));

```

I do get the widget form to print, but on submission the votes don't register; plus in this way I do not have the vote summary.

Am I missing something?

# Answer
> 1 votes
In a node template you can use the following code.

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

```

### Reference

# Answer
> 0 votes
You should be able to just add:

```
  <?php print fivestar_widget_form($node, 'name of the vote tag'); ?>

```

Just replace "name of the vote tag" with your vote tag or exclude that part if you only use the default

# Answer
> 0 votes
Try this, its working for me,

```
   $values = array('user' => $user->uid, 'average'=>60, 'count' => 5);

   $settings = array(
    'content_type' => 'user',
    'content_id' => 2,
    'stars' => 5,
    'autosubmit' => TRUE,
    'allow_clear' => FALSE,
    'text' => 'smart', // options are none, average, smart, user, and dual
    'tag' => 'vote',
    'style' => 'dual', // options are average, dual, smart, user
    'widget' => array('name' => 'default', 'css' => 'default'),
  );

   $form['custom_five_star'] = drupal_get_form('fivestar_custom_widget', $values, $settings);
   return $form;

```

# Answer
> 0 votes
In order for this to work on nodes and be able to submit values, you will need additional fields.

```
$settings = array(
  'content_type' => 'profile2',
  'content_id' => $profileView->pid,
  'entity' => $profileView,
  'stars' => 5,
  'field_name' => 'field_profile_rating',
  'autosubmit' => TRUE,
  'allow_clear' => FALSE,
  'langcode' => 'und',
  'text' => 'none', // options are none, average, smart, user, and dual
  'tag' => 'vote',
  'style' => 'average', // options are average, dual, smart, user
  'widget' => array( 'name' => 'oxygen', 'css' => drupal_get_path('module', 'fivestar') . '/widgets/oxygen/oxygen.css' )
);

print render(drupal_get_form('fivestar_custom_widget', $profileView->field_profile_rating['und'][0], $settings));

```

---
Tags: 7, rating
---


# Question
Title: field_attach_form not working as expected
I created an entity like this:

```
<?php
/**
* Implement hook_entity_info()
*/
function fy_teacher_entity_info()
{
    $entity['fy_teacher'] = array(
        'label' => t('teacher'),
        'controller class' => 'TeacherController',
        'base table' => 'fy_teacher',
        'uri callback' => 'fy_teacher_uri',
        'fieldable' => TRUE,
        'entity keys' => array(
            'label' => 'name',
            'id' => 'tid'
        ),
        'bundles' => array(
            'teacher' => array(
                'label' => t('teacher'),
                'admin' => array(
                    'path' => 'admin/structure/teachers',
                    'access arguments' => array('administer teachers')
                ),
            )
        ),
        'static cache' => TRUE,
        'view modes' => array(
            'full' => array(
                'label' => t('Full content'),
                'custom settings' => FALSE,
            ),
            'teaser' => array(
                'label' => t('Teaser'),
                'custom settings' => FALSE,
            ),
        ),
        'views controller class' => 'EntityDefaultViewsController',
    );
    return $entity;
}
?>

```

And this is the form I created to add/edit this entity.

```
<?php
/**
* teacher add/edit form
*/
function fy_teacher_form($form, &$form_state, $teacher)
{
    $form_state['fy_teacher'] = $teacher;
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#default_value' => $teacher->name,
        '#weight' => '-5',
        '#required' => TRUE
    );

    field_attach_form('fy_teacher', $teacher, $form, $form_state);
    //Save button
    $form['buttons'] = array();
    $form['buttons']['#weight'] = 100;
    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
        '#submit' => array('fy_teacher_form_submit')
    );

    // Delete button if on edit page
    if ($teacher->tid) {
        $form['buttons']['delete'] = array(
            '#access' => user_access('administer teachers'),
            '#type' => 'submit',
            '#value' => t('Delete'),
            '#submit' => array('fy_teacher_form_submit_delete')
        );
    }

    $form['#validate'][] = 'fy_teacher_form_validate';
    debug($form);
    return $form;
}
?>

```

I can add fields in the backed (admin ui) of this entity. But somehow the fields I added there aren't showing up.

# Answer
> 1 votes
Turns out that the bundle name must be same as entity type.

```
<?php
...
        'bundles' => array(
            'fy_teacher' => array(
                'label' => t('teacher'),
                'admin' => array(
                    'path' => 'admin/structure/teachers',
                    'access arguments' => array('administer teachers')
                ),
            )
        )
...
?>

```

For anyone who has this issue,

In your hook\_entity\_info, under entity keys, simply add the bundle property. to get the above example to work, simply change the entity keys array to :

```
<?php
'entity keys' => array(
            'label' => 'name',
            'id' => 'tid',
            'bundle' => 'property_name' //The name of the property that contains the bundle name for the entity.
        ),
?>

```

for hook entity info reference, see https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_entity\_info/7

---
Tags: 7, entities
---


# Question
Title: display a node in the sidebar region of another node
I'm a huge fan of annotating content in the margins of my real paper books.

In drupal 7, I want to be able to annotate a book page content type by showing a child of that page in the space beside the main page.

Has anyone done anything like this before in Drupal? Any links?

You might describe it like putting comments next to the page but I would prefer to use child pages if at all possible.

Thanks for any suggestions or help.

# Answer
You could in your template file just render the comment section in your sidebar.
> 0 votes

# Answer
I think you might have heard about Views module, you can create a views block to get the child node and display it on the same page using Views.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: When to share fields between content types?
I have a content type with a geolocation field on it, and I also want to add this as an extra field to users. Is it okay to share the field between these? Or should I create two different fields?

# Answer
> 2 votes
Generally if you happend to have same Field settings (Cardinality etc) you can re-use the same field. But if you want different Field settings (Not widget settings) you have to use different field.

If you have huge number of users(couple of millions) or contents it'll not be a best solution to re-use same field, because field\_date\_\* and field\_revision\_\* tables will end up having a lot of data and that might give you a bottleneck on performance.

---
Tags: entities
---


# Question
Title: Remove user entities on module uninstall
I am using the following code to delete all the nodes and clean up on uninstall of my custom module. How can I do the same thing for my user entity?

```
    function wl_project_uninstall() {
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(
    ':type' => 'wl_project'
  ));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }
  node_delete_multiple($nids);
  foreach (array_keys(_wl_project_fields()) as $field) {
    field_delete_field($field);
  }
  node_type_delete('project');
  // Purge all field information
  // http://api.drupal.org/api/function/field_purge_batch/7
  field_purge_batch(1000);
}

```

# Answer
You can load all user uid's and call user\_delete
> 0 votes

---
Tags: 7, entities
---


title: How to render custom view mode in d7

text:
# Question
Title: How to render custom view mode in d7
I'm trying to render nodes with a custom view mode, having another tab for each node in the same place than "Edit", "View", etc. So I have declared my custom view mode with hook\_entity\_info\_alter, my new "tab" with hook\_menu, with a page\_callback pointing to a custom function that should return the node according to my custom view node. It works great, but the node title is rendered too. How can I remove the node title ? Here is the code. Thanks!

```
   /**
   * Implements hook_entity_info_alter().
   */
   function test_custom_view_mode_entity_info_alter(&$entity_info) {
     $entity_info['node']['view modes']['another_teaser'] = array(
       'label' => t('Another teaser'),
       'custom settings' => TRUE,
     );
   }

   /**
   * Implements hook_menu().
   */
   function test_custom_view_mode_menu()
   {      $items['node/%node/another-teaser'] = array(
           'title' => 'Another Teaser',
           'page callback' => '_test_custom_view_mode_display_content',
           'page arguments' => array(1),
           'access arguments' => array('access content'),
           'type' => MENU_LOCAL_TASK,
       );

          return $items;
   }
   /**
   * Custom page callback hook_menu().
   */

   function _test_custom_view_mode_display_content($node) {
     $node_viewed = node_view(node_load($node->nid), 'another_teaser');

     return array(
              'content' => array(
                'node' => $node_viewed,
              ),
            );
   }

```

# Answer
> 1 votes
I think you need to render send the element as html out put since there is no any theme function defined. See how this output process here.

So your return array should be:

```
 return array(
          '#markup' => $node_rendered
        );

```

---
Tags: routes, theming, entities
---


# Question
Title: Can't access value of dropdown modified by Ajax
I have two dropdown fields, #2 is modified by Ajax based on #1 selection. When I try to access #2 value in the submit handler, I get an empty result. I've checked this against the docs and examples and I can't see what am I doing wrong here?

The code:

```
function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = get_meeting_types();
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
        '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
    ),
  );
  $form['meet'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="meetlist-div">',
    '#suffix' => '</div>',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  return $form;
}

function admin_select_meeting_type_form_submit($form, &$form_state) {
    drupal_set_message('You selected:' . $form_state['values']['meet']);
}

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, $form_state) {
     if ($form['meet_types']['#value']) {
        $dispmeet = array(); // truncated for brevity, my array processing is done here
        $form['meet'] = array(
           '#type' => 'select',
           '#prefix' => '<div id="meetlist-div">',
           '#suffix' => '</div>',
           '#title' => t('Select meeting:'),
           '#values' => array_keys($dispmeet),
           '#options' => $dispmeet,
           '#required' => TRUE,
        );
        return $form['meet'];
     }
}

```

# Answer
You shouldn't build the form element in your callback. You want something like this:

```
function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = drupal_map_assoc(array('conference' => 'conference', 'event' => 'event'));
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
    '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
      'method' => 'replace'
    ),
  );
  $form['meet_container'] = array(
    '#prefix' => '<div id="meetlist-div">',
    '#suffix' => '</div>',
  );
  if (!empty($form_state['values']['meet_types'])) {
    $form['meet_container']['meet'] = array(
      '#type' => 'select',
      '#title' => t('Select meeting:'),
      '#options' => drupal_map_assoc(array('test', 'test2')),
      '#required' => TRUE,
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );

  return $form;
}

function admin_select_meeting_type_form_submit($form, &$form_state) {
    print_r($form_state['values']);
    die();
}

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, &$form_state) {
  if ($form['meet_types']['#value']) {
    return $form['meet_container'];
  }
}

```
> 0 votes

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


# Question
Title: Change OG Group River of News Per Group Basis?
Hello i was wondering the best way on how to go about this. I was thinking of creating a text field for my group content type and changing the url and then adding differant block views to urls like-

blog/\* forum/\* etc

Blog will show a blog view and a forum view on forum. I dont really want to mess about with my urls though.

I dont really want to have differant Group Content Types either.

What would be the best if i could have a text select list on the Group Content Type

blog forum etc

and the view will change depending on the choice.

Can anyone think of a way of doing this? I think i need to bring in some relatonship for my new text field but itdoesnt seem to be happening for me.

Thanks

# Answer
> 0 votes
heh heh i bloody done it!

Relationships OG membership: OG membership from Node (OG membership from node) OG membership: Group Node from OG membership

Filter criteria (Group node from OG membership) Content: Placetype (= Blog)

---
Tags: views, organic-groups
---


# Question
Title: Creating a "scrapbook" node type using an entity reference field
I'm building a site that includes two node types, "scrapbook" and "press clipping". A user can create multiple scrapbooks which are either public or private, and they can also add press clippings to a public pool.

Each scrapbook includes an entity reference field that allows multiple press clippings to be referenced from each notebook. This works fine, but the only way I can add a reference from a notebook to a press clipping is by editing the scrapbook. I want to include a dropdown on each press clipping that allows the user to select one of the scrapbooks they have created and add the press clipping to that scrapbook.

What's the best way to achieve this result?

# Answer
> 1 votes
Personally, I'd move the entity relationship field to the press clipping content type, so you get the convenient dropdown there, and use the reverse relationship, or contextual filter when building a view

---
Tags: 7, entities
---


# Question
Title: I am unable to create a variable in template.php that I later want to use in node--content-type.tpl.php
In template.php I have created the following function.

```
function mytheme_preprocess_node__post_esl_material(&$variables){
  $variables['linking'] = 'yes baby';
}

```

In node--post-esl-material.tpl.php I am trying to print `$linking`, but it is not working. The reason I am trying this is because I heard from an expert in Drupal saying:

> Template files are usually used to change the CSS. You do not want to put too much PHP logic here. The PHP logic is typically included in your template.php file.

Therefore the objective, after getting the above code to work, would be to:

1. Create a `$article` variable in template.php.
2. Swap the following code from `node--post-esl-material.tpl.php` into template.php.

```
if (empty($content['field_article'])) {
  echo '';
}
else {
  echo '<div class="article">';
  echo '<h4>ARTICLE</h4>';
  echo '<div class="field_article">';
  print render($content['field_article']);
  echo '</div>';
  echo '</div>';
}

```
3. Print `$article` in `node--post-esl-material.tpl.php` and hence, have the PHP logic within template.php.

I am using Drupal 7 with the Stark theme.

# Answer
> 0 votes
I have found the mistake. I was using mytheme\_preprocess\_node($variables) twice within the template.php. I have included $variables\['linking'\] = 'yes baby'; within the first function and deleted the second one and know it works fine. Thanks for your help.

# Answer
> 0 votes
These are the steps I would take to resolve (re-trying after each step)

1. Clear theme registry cache - /admin/config/development/performance - Clear Cache
2. Use the more general function `mytheme_preprocess_node($variables)`, clear cache, try again

If the more general function works, your issue is likely that you have incorrectly named the template, try:`kpr($vars['theme_hook_suggestions'])` if you have the Devel Module installed. If not, you should. Otherwise you can print\_r($vars\['theme\_hook\_suggestions'\]). Is your template included in there?

---
Tags: nodes, theming
---


# Question
Title: Is there a way to insert "0000-00-00 00:00:00" in a datetime database field?
Is there a way to insert "0000-00-00 00:00:00" datetime database field?
Should I change the database field's default value to "0000-00-00 00:00:00"?

I got replies on Stack Overflow, and it works with plain PHP, but it gives an error with Drupal.

# Answer
In Drupal 7 DB API, support for the `datetime` type was removed. This means that you must use use `mysql_type` or `pgsql_type` if you want this functionality. Below is an example of of to declare this schema provided your database is MySQL. By setting `not null` to `FALSE`, you can store an empty value (`''`), which is equivelent to `'0000-00-00 00:00:00'`:

```
'mydate_date' => array(
  'description' => t('My date field.'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

```

Note that to make the schema portable, you should provide a fallback type (`varchar`) for the case that the database is *not* mySQL.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: Drupal 7 Views Exposed Filter - How to Select all Taxonomy terms Upon adding new terms?
Whenever I add new taxonomy terms I have to manually go into my exposed view filter to have them show up in the dropdown box when filtering. Is there a way to just select all terms with what im filtering by?

# Answer
You have the answer in the attached image itself.

Just Un-select the **Limit list to selected items** then save the configuration. Now the all the terms for that selected vocabulary will be listed automatically.

When you selected **Limit list to selected items** options, only the selected terms alone will be exposed to the user.
> 4 votes

---
Tags: 7, views
---


# Question
Title: Is a content type needed by a custom module?
I want to write a custom module for my drupal website to get some information from users and process them. because my form fields are complex so I have decided to write my own module to generate form instead of default add content in drupal.

Should I have create a content type for storing data or I can create my data structure for storing data ?

# Answer
> 1 votes
You can create you own data structure but I think your life will be a lot easier if you create a new content type or an entity. You can alter the form in the way you need it or get it and render it wherever you want. You also have validation and submit handlers.

---
Tags: 7, nodes
---


title: Is there a module for repeated content?

text:
# Question
Title: Is there a module for repeated content?
I recently faced a need of reusing some content, creating content templates (not in the usual meaning of the word).

I have content that is created periodically, a product for instance, which differs from another by one or two fields, all of the rest stays the same, so I thought of reusing content.
Have you ever seen a module that would accomplish that?

# Answer
> 3 votes
If you are talking about the actual content then check out the replicate and the replicate ui modules. They allow you to duplicate any entity. Much more powerful than the node clone module which only supports nodes.

If you are talking about cloning the content type or product type then look at the bundle copy module.

---
Tags: 7, nodes
---


# Question
Title: simplenews-newsletter-body.tpl.php won't be overridden
My newsletter is almost ready, where it not that the node title ends up in the sent testmail as well. So I figured if I would just override the `simplenews-newsletter-body.tpl.php` I followed the guidelines from this page.

In my simplenews configuration I just checked just the generic content type that simplenews generated. In that same configuration page, I chose 'newsletter' as the taxonomy term attached to it. This makes the filename `simplenews-newsletter-body--newsletter.tpl.php`

The idea to just delete the following line from the copied file: `<h2><?php print $title ?></h2>`

The tutorial I mentioned says to paste in into the custom theme folder directly. I was assuming not in the templates folder. I tried both though while flushing cashes at least twice after each try. Still getting the darn title in my test mail.

UPDATE: I discovered that the filename needs to be the term ID of the simplenews newsletter, being a number. I looked up the `tid` and changed the `tpl` filename accordingly - in my case making it `simplenews-newsletter-body--110.tpl.php`. Of course the needed flushing of cashes. Didn't help either.

# Answer
The file may need to go in the admin theme folder, if you're using admin theme/sections, and not in the regular theme folder. Worth a shot.
> 1 votes

---
Tags: 6, theming, emails
---


# Question
Title: Addresses Module - Province (State) Used to Be a Drop-Down
I am having trouble with the addresses module (version 6.x-1.12) running on my Drupal 6.28 site. Recently the addresses module stopped showing a drop-down menu for the Province (State) field on my custom content type. I am not certain when this happened, or what caused this change. I did some major upgrades to the site, tested everything, and thought this was working after the upgrade.

This above image shows what I'm talking about. This is from my profile, in case anyone cares about the confidential data I am showing the world.
The above image shows the configuration options for the addresses module I have installed. I don't see any options to make it so that the province is a drop-down, despite the fact that the module info page says it has all the provinces for all the countries it supports...?
The above image shows the address field configuration options for my custom content type using the address field. It's called a uprofile or user profile, and stores additional information about the user.

Thank you very much for taking the time to look at my question. I tried to be as complete as possible. If you want to try to create an account to see what I am talking about (or to be an extra in a movie filmed in New Mexico!) the site is here.

# Answer
A quick look suggests that you put in a patch to the module that didn't get re-rolled into the module after your update as when I installed the module on a testbed it didn't work until I did :)

Anyways, if you look at https://drupal.org/node/244471 and scroll on down to comment #63 you'll see the patch.

If you want to just edit up the code directly, you want to change

```
  // Invoke addressfieldapi to allow modules to add their own addresses fields.
  // Then update these fields with the global settings for each field instance.
  $extra = module_invoke_all('addressesfieldapi', 'form', $fields, $values);
  foreach (element_children($extra) as $ename) {
    if (isset($settings[$ename . '_label'])) {
      $extra[$ename]['#title'] = t($settings[$ename . '_label']);
    }
    if (isset($settings[$ename . '_desc'])) {
      $extra[$ename]['#description'] = t($settings[$ename . '_desc']);
    }
    if ('textfield' == $extra[$ename]['#type'] && isset($settings[$ename . '_size'])) {
      $extra[$ename]['#size'] = $settings[$ename . '_size'];
      // $extra[$ename]['#attributes'] = array('class' => 'text');  // REMOVE OR COMMENT THIS LINE OUT

      // ADD THE FOLLOWING:

      if (isset($extra[$ename]['#attributes']['class'])) {
        $extra[$ename]['#attributes']['class'] .= ' text';
      }
      else {
        $extra[$ename]['#attributes'] = array('class' => 'text');
      }

      // THIS IS THE END OF THE NEW CODE

    }
  }

```

around line 253 in `addresses.module`. That made it work for me anyway.

Oh, if you are interested, the reason it didn't work is AJAX couldn't find the class of the province field, as further on up the chain it was being added, but then overwritten here.
> 2 votes

---
Tags: 6
---


# Question
Title: Should you use multi-site or multiple Drupal instances to host different content for subpath sites?
I want to host a Drupal 7 site that effectively has four different silos of information. The architecture will look like this:

* example.com - Blog site with content about the parent company
* example.com/foo - Informational site about sub-company "foo"
* example.com/bar - Informational site about sub-company "bar"
* example.com/fubar - Informational site about sub-company "fubar"

The top site will pretty much be a blog with navigational elements directing people to the sub-sites. The three sub-sites will essentially be the same structure, but have slightly different CSS (different color schemes) and have different information. Logins can be separate, because we actually want to be able to peel away one of the subsites to sell as an asset, if need be.

I'm wondering what the best way to do this would be. Multi-site should keep it easy to update, because the modules and core should be upgraded in lockstep. However, I can't seem to get multi-site to work for these subpaths.

Is multi-site the best way to go here? Or should I just host four different instances of Drupal, one for each site?

(Note, I saw a question about subsites just after I posted this, but it seems that subsites is only available for Drupal 6. Please correct me if that is wrong!)

# Answer
> 2 votes
Subsites should work for Drupal 7 as well (assuming this is what you're working with). I've found these instructions helpful in the past: http://drupal.org/documentation/install/multi-site

If the company subsites you are running are under one parent company where there is one body of management (a common decision maker), then subsites makes sense. If they are different companies which may want very different functionalities for their sites, then it may not be wise to combine them into subsites which rely on the same code.

# Answer
> 0 votes
The Domain Access module may fit your bill, but it is more geared towards subdomains and not subdirectories. It is worth looking into, though, if you want to have a common database.

If I were you, I would try to use subdomains instead of subdirectories regardless of the approach you take. In the long run it will probably make life easier for you when you want to split a site off.

# Answer
> 0 votes
Did you ever get the answer to your questions about which to use? I'm looking at it the other way. I have multiple sites, all in the same hosting account, and in separate folders. Each has it's own domain name and it's own install of Drupal. I'm considering whether I should consolidate them to a multi-site installation.

What did you wind up doing? I did find a good article that discusses how to take a multi-site to a standalone site (which you would need of you used multi-site and then sold one of the sites): http://technopoetic.com/2012/04/convert-a-drupal-multi-site-installation-to-a-single-site/

As far and when to use which? I still don't know. I hate having to install and update the same modules over and over. I've never done a multi-site install before and I'm sure that I'm torturing the web server with all of the instances of Drupal (however, they are just php files).

If you have a single admin for all, I suppose multisite is the way to go. With multiple instances of Drupal, I can easily move any of then indepenantly.

Let me know what you decided and how it went.

# Answer
> 0 votes
If you go with multi-site and then break the site...every site is broken. At least if you have multiple installs of drupal and then screw one up, then only one is gone.

People like me have to consider the mistakes we make.

---
Tags: multi-sites
---


# Question
Title: How to validate links before moving to different location
This would be most simple functional question in Drupal 7. Now below mentioned things are mandatory to do and cant change the functionality. 1) I have created a custom block in module. 2) I have included form like below:-

```
function usercontent_block_view($delta='')
{

   $block = array();
   switch($delta)
   {
     case 'user_front_page' :
       $block['content'] = drupal_get_form('genre_all_login');
     break;
   }
   return $block;
}

```

3) Now I have some other content in block but which put me in trouble is shown below:-

```
function genre_all_login($form) {
  $form['new_user'] = array(
  '#type' => 'item',
  '#markup' => l('Add New User','http://www.google.com'),
    );
    return $form;
  }

```

4) So it includes a link which will move me to Google once clicked. 5) Now I want to validate certain content inside the block before user navigates to Google.So if the condition doesn't match then I will stop the user by showing an error message and hence user cannot traverse to Google.

Please tell me if it is possible or should I use different technique to handle this scenario.

# Answer
You can achieve this using a client side validation. Like below,

1. Add an ID attribute to the external link

```
$form['new_user'] = array(
  '#type' => 'item',
  '#markup' => l('Add New User','http://www.google.com', array('attributes' => array('id' => 'external-link'))),
);

```
2. Add a JavaScript code to validate and preventi the click.

```
jQuery(document).ready(function() {
  jQuery('#external-link').click(function(event) {
    // Perform your validation. If the validation fails prevent events default behavior.
    validated = false;
    if (!validated) {
      event.preventDefault(); // You can also use return false instead of prevent default.
    }
  });
});

```

Hope this helps :)
> 0 votes

---
Tags: 7, forms, blocks, navigation
---


# Question
Title: Backup table from custom module using backup and migrate
I have a module that allows a user to add to a custom table in bulk via a custom form. But before they do so I'd like to backup that table to the private folder. Does anyone know if it is possible to create a new profile in the Backup and Migrate module and save a table using code in a custom module?

So what I'd like to do is programmatically create a Backup and Migrate profile in my modules .install file. Then in my custom form submit function, trigger the backup using that profile.

# Answer
I've had a look at the Backup and Migrate code and I've come up with a solution, one that works for me at least.

I've created a function that gets the default profile data, then alters that to save only the tables I want. It seems to work well but if anyone can see any possible problems with this solution please do let me know.

The function:

```
<?php
/**
 * @param $tables
 *  An array of table names that will be backed up.
 * @param $filename
 *  Text prepended to the date when naming the backup file.
 */
function _MYMODULE_backup_custom_tables($tables, $filename = 'custom-backup') {
  module_load_include('module', 'backup_migrate');

  // get default profile settings
  backup_migrate_include('files', 'profiles');
  $settings = _backup_migrate_profile_saved_default_profile();

  // set the destination to our private folder
  $settings->destination_id = 'manual';
  $settings->source_id = 'db';

  // get a list of all tables from the database
  $schema = drupal_get_schema();
  ksort($schema);
  $drupal_tables = array();
  foreach ($schema as $table => $table_schema) {
    $drupal_tables[$table] = $table;
  }

  // remove from the database table list the tables we would like to save
  foreach ($tables as $table) {
    unset($drupal_tables[$table]);
  }

  // alter default filters so only the tables we want will be backed up
  $settings->filters['destinations']['db']['nodata_tables'] = array();
  $settings->filters['destinations']['db']['exclude_tables'] = $drupal_tables;

  // change the filename so we can identify the backup in the directory
  $settings->filename = $filename;

  // backup tables
  backup_migrate_perform_backup($settings);
}
?>

```

The function can then be used like this:

```
<?php
// the names of the tables we want to save
$tables = array(
  'custom_table_one',
  'custom_table_two',
);

// the text to use when naming the backup file
$filename = 'my-custom-backup';

_MYMODULE_backup_custom_tables($tables, $filename);
?>

```
> 1 votes

---
Tags: 7, backups
---


# Question
Title: Unable to transfer php logic from node--post-esl-material.tpl.php to template.php
If I use the following code in template.php and print `$link` in node--post-esl-material.tpl.php, everything works fine; I get "hey baby."

```
function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $vars['link'] ='hey baby';
   }
}

```

However, if I use the following code and print `$link` in node--post-esl-material.tpl.php, it doesn't print anything.

```
function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $xyz = '';
      if (empty($content['field_link']))
         $xyz .= '';
      else {
         $xyz .= '<div class="link">';
          $xyz .= '<h4>LINK</h4>';
           $xyz .= '<div class="field_link">';
            $xyz .= $content['field_link'];
           $xyz .= '</div>';
         $xyz .= '</div>';
      }
      $vars['link'] = $xyz;
   }
}

```

I cannot get the PHP logic to work. Can anyone see a mistake within the code?

# Answer
The following code works:

```
function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $xyz = '';
      $node = $vars['node'];
      $field_link = field_view_field('node', $node, 'field_link');

      if (empty($field_link))
         $xyz .= '';
      else {
     $xyz .= '<div class="link">';
       $xyz .= '<h4>LINK</h4>';
         $xyz .= '<div class="field_link">';
           $xyz .= drupal_render($field_link);
         $xyz .= '</div>';
     $xyz .= '</div>';
      }

      $vars['link'] = $xyz;
   }
}

```
> 0 votes

# Answer
I think that the problem is that $content is not defined there. You have it only inside the template file but not in the preprocess hook.
> 2 votes

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


# Question
Title: Which other methods for building html content are out there?
I am searching for opinions about the construction of static pages in Drupal.

Imagine this page as a PSD or PNG: https://www.paypal.com/br/webapps/mpp/quanto-custa-empresa

It's a static page, but it's not just text, it has a somewhat rich layout. I don't think a regular node with WYSIWYG is the right way to do a page like this.

So, imagine you already have the template built, the side menu, the header, footer, etc, but you want more control over the content (middle) layout.

These are the ways I know for building this kind of "rich content":

---

## Create the HTML page in a decent editor, then paste the HTML on the node body when you're finished.

Pros:

* Practical for extremely simple pages

Cons:

* Lose version control
* If you do node-specific CSS, which is pretty much necessary for this kind of page, you might get into trouble if you can't maintain the node id between installations
* Needs php input format in order to print images relatively
* Requires back and forth from IDE every time something changes

---

## Node-\[id\].tpl.php template

Pros:

* Version control
* Allows you to keep working on the IDE

Cons:

* When doing node-specific CSS, which is pretty much necessary for this kind of page, you might get into trouble if you don't have a way to maintain the node id between installations
* Same thing for the whole page. It will go blank if you don't keep track of the node ID.

---

## hook\_menu + hook\_theme invoking a custom template for the wanted path

Pros:

* Version control
* Allows you to keep working on the IDE

Cons:

* Requires custom module and a little more effort
* Does not provide caching by default like a node does (performance hit wouldn't be that great for this, however)
* You lose some node juicy stuff (can't remember an example right now)

---

So, are there any methods people are using I'm not aware of? Maybe with panels? Context? Please let me know!

# Answer
> 0 votes
If this is a one off landing page, I'd go with option 1.

I would never do 2 because I also deal with different installs (dev/stage/prod) and that would break on me.

For option 3 I usually use a different flag in the data other than URL, but I've occasionally used this method. Usually I have a 'Use Template' field that points at a taxonomy, and I can make various theming decisions off of that (including but not limited to the tpl I use)

If this is a layout you think you'll see again, I'd use Panels. Especially if you want this to be editable by people who don't know code.

You can specify very generic to very complex layouts. You basically specify a layout in a tpl file with regions that can get content added to them. The content can be nodes, blocks, views whatevs.

It has a bit of a learning curve on the dev and the content editor side, but it's pretty good.

**With your node specific CSS**, I would recommend adding a "Custom CSS" field to content types that are going to have special layouts. You could do this to what I call a "Custom Page" content type which I use to simply paste in HTML, or add it to Panel Nodes or other customizable node types.

In the theme you'll need to hide($content\['field\_custom\_css'\]); in the node preprocessor and then retrieve the value of the field and run drupal\_add\_css() on the sucker.

You can use file field to allow people to upload CSS, or what I do is specify the URL of the file so I can just re-up the file while I'm working with FTP and don't have to re-up through the drupal interface every time I have a change.

By default drupal\_add\_css doesn't let you add CSS files that aren't on your domain so if you make the user specify a URL (meaning they'd have to have FTP access to get something in there) it's a fairly secure implementation.

Pretty sure there's a way to allow css that's not on your domain, but you'd want to make sure that nefarious parties aren't able to do damage with that field if you decide to go that route.

Custom CSS has been HUGE in doing one off pages like this for all of the promotional pages my group does at work.

Hope that helps!

---
Tags: theming
---


title: Getting only the login field

text:
# Question
Title: Getting only the login field
i got a `user-login-block.tpl.php` to customize user login block of Drupal 7. here is that code:
**user-login-block.tpl.php:**

```
<div id='user-login-block-container'>
  <div id='user-login-block-form-fields'>
<?php print $name; // Display username field ?>
<?php print $pass; // Display Password field ?>
<?php print $submit; // Display submit button ?>
<?php print $rendered; // Display hidden elements (required for successful login) ?>
  </div>
  <div class='links'>
<a href='/user/register'>Create an Account</a> | <a href='/user/password'>Forgot Password</a>
  </div>
</div>

```

this works; here is the screenshot:
but i want to print only the **username field**, **password field** and the **submit button** so i can easily position them, using css, adding custom label etc..
Also delete the blue marked default drupal 7 links.. any idea? thanks..

# Answer
In your theme's template.php file:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */

function YOURTHEMENAME_form_user_login_block_alter(&$form) {

    unset($form['links']);
    return;

}

```

In this function you have access to the form as an array. Usually I enable devel module and do a dsm($form) . In your case dsm() will not work because you need to be logged in to be able to see the output. I used var\_dump($form) to see the form and used unset() function to remove the links.
> 1 votes

# Answer
You need to define theme overriding for user login form via custom module.

```
/**
 * Implements hook_theme().
 */
function [modulename]_theme($existing, $type, $theme, $path) {
  return array(
    'user_login' => array(
      'render element' => 'form',
      'template' => 'user-login-form',
      'path' => drupal_get_path('module', '[modulename]') . '/theme',
    ),
  );
}

function template_preprocess_user_login(&$variables) {
  $form = &$variables['form'];
  // So here you should define required variables
  $variables['name'] = $form['name'];
  unset($form['name']);
  // and so on ...

  unset($form['links']); // Removes links
  // don't forget $rendered variable.
  $variables['rendered'] = $form;
  unset($variables['form']);
}

```

Then you should create template file for login form named user-login-form.tpl.php and put them into \[modulename\]/theme folder.

Don't forget use render() function to render form element's.

Hope, that what you are looking for.
> 1 votes

---
Tags: 7, theming
---


title: User registration page edit

text:
# Question
Title: User registration page edit
I want to add some div's and hrefs to user registration form. any ideas? I'm using ajax login/register module to get user login/register form in ajax windows. and i have no idea how to add some divs and hrefs to register form.

# Answer
> 1 votes
Assuming you're using Drupal 7.

Using hook\_form\_FORM\_ID\_alter and a custom module you can achieve it. Like below,

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['links'] = array(
    '#type' => 'item',
    '#markup' => l('some links','http://www.example.com'),
  );
  $form['additional_markup'] = array(
    '#type' => 'item',
    '#markup' => '<div></div>',
  );
}

```

# Answer
> 1 votes
In other hand you can use Display Suite. It provide you great solution to customize things. With it you can create new registration fields the way you want it and then you can customize de display...

---
Tags: users
---


title: Adding <div>'s on the user login page

text:
# Question
Title: Adding <div>'s on the user login page
The following code is adding `<div>`'s and link to the form action. How can I add them before the form?

```
function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
  $form['bigletters'] = array(
    '#type' => 'item',
    '#markup' => 'Big letters',
  );

  $form['smallletters'] = array(
    '#type' => 'item',
    '#markup' => 'Small letters',
  );

  $form['links'] = array(
    '#type' => 'item',
    '#markup' => '<a href="http://example.com"></a>',
  );
}

```

# Answer
> 2 votes
If you need the form elements you are adding to appear before the other ones, you should use the #weight property, and give them a negative value, since the default value is zero. Differently, the form elements you add to a form via `hook_form_alter()` are normally appended to the form, with the exception of when there is a form element with a positive #weight value higher than the #weight value you assigned to your form element.

user\_login() doesn't set the weight of its form elements. The following code should work.

```
function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
  $form['bigletters'] = array(
    '#type' => 'item',
    '#markup' => 'Big letters',
    '#weight' => -10,
  );

  $form['smallletters'] = array(
    '#type' => 'item',
    '#markup' => 'Small letters',
    '#weight' => -8,
  );

  $form['links'] = array(
    '#type' => 'item',
    '#markup' => '<a href="http://example.com"></a>',
    '#weight' => -6,
  );
}

```

If the code doesn't work, then there is probably another module that alters the weight of the other form elements.

---
Tags: users, forms
---


# Question
Title: Why are there module files like [modulename].pages.inc?
I start to learning moding Drupal and I have a look for the current ones. There are files like \[modulename\].pages.inc or \[modulename\].api.inc and I can't find why it exists? I read that base files are only \[modulename\].module, \[modulename\].info, \[modulename\].install in Drupal book.

Can somebody explain me these files or post names all this kind files?

# Answer
It's just a convention used for separating logic out of the main .module file.

The \[modulename\].pages.inc file typically contains page callback functions (those defined in `hook_menu()`). Since these functions aren't used in every page request there's no point including them, so they're auto-included from the `file` property defined in `hook_menu()` when needed.

You'll probably come across \[modulename\].admin.inc too, which typically contains callback functions for admin pages.

\[modulename\].api.php is another convention that Drupal core uses (and subsequently a lot of contrib modules use) to show examples of the hooks they provide, and usually how to use them.

There are other \[modulename\].\[group\].inc files that can be auto-included when another module implements `hook_hook_info()`:

> Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.
> 7 votes

---
Tags: 7
---


# Question
Title: How to show language switcher only on home page
In my multilanguage site i am using Language switcher (User interface text) and I have it located in block called "Help". This block is shown in the middle of the site, where I want it. But I want it to be displayed only on homepage. I tried to hide by the restriction of a content type. But I wasn't successful.

# Answer
> 2 votes
Set block visibility to only show on `<front>`

---
Tags: nodes, blocks
---


# Question
Title: How do I provide a page manager page override for my custom entities using ctools plugins
I have a custom entity type implemented, this is essentially identical to what the Model module provides, with extra integrations.

I'm wanting to use panels and page manager to template my entity pages, much like how page manager provides the node\_view which overrides the node/%node path, I want to override my custom entity paths.

What ctools plugins and hooks do I need to implement to gain this functionality?

# Answer
We can achieve this quite easily by using node\_view as a guide. First though you must implement hook\_ctools\_plugin\_directory() in your module file to register the ctools plugins:

```
/**
 * Implements hook_ctools_plugin_directory().
 */
function my_entity_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'page_manager' || $owner == 'ctools' || $owner == 'panels') {
    switch ($plugin_type) {
      case 'tasks':
      case 'content_types':
          return 'plugins/' . $plugin_type;
      break;
    }
  }
}

```

This tells ctools that we are implementing plugins under the plugins directory inside our module folder and the plugins will be in their own directories. Since I am only implementing "tasks" I want to only return for that plugin type. The "task" plugin type is what we will use to implement our custom entity view.

After implementing this we just have to create the .inc file to implement our task. The file must be named name\_of\_plugin.inc, so for this we will use "my\_entity\_view.inc"

And here's the code for that, note that function names are made up of the following keys: module\_name\_plugin\_name\_hook(). I found it quite easy to follow this code, the hook\_my\_entity\_task\_tasks() is what all the other callbacks hang off. After implementing this, clear cache and your override should appear in /admin/structure/pages

```
<?php

/**
 * @file
 * Handle the 'my_entity view' override task.
 *
 * This plugin overrides my_entity/%my_entity and reroutes it to the page manager, where
 * a list of tasks can be used to service this request based upon criteria
 * supplied by access plugins.
 */

/**
 * Specialized implementation of hook_my_entity_task_tasks(). See api-task.html for
 * more information.
 */
function my_entity_my_entity_view_page_manager_tasks() {
  return array(
    // This is a 'page' task and will fall under the page admin UI
    'task type' => 'page',

    'title' => t('my_entity template'),

    'admin title' => t('my_entity template'),
    'admin description' => t('When enabled, this overrides the default Drupal behavior for displaying my_entitys at <em>my_entity/%my_entity</em>. If you add variants, you may use selection criteria such as my_entity type or language or user access to provide different views of my_entitys. If no variant is selected, the default Drupal my_entity view will be used. This page only affects my_entitys viewed as pages, it will not affect my_entitys viewed in lists or at other locations. Also please note that if you are using pathauto, aliases may make a my_entity to be somewhere else, but as far as Drupal is concerned, they are still at my_entity/%my_entity.'),
    'admin path' => 'my_entity/%my_entity',

    // Menu hooks so that we can alter the my_entity/%my_entity menu entry to point to us.
    'hook menu' => 'my_entity_my_entity_view_menu',
    'hook menu alter' => 'my_entity_my_entity_view_menu_alter',

    // This is task uses 'context' handlers and must implement these to give the
    // handler data it needs.
    'handler type' => 'context',
    'get arguments' => 'my_entity_my_entity_view_get_arguments',
    'get context placeholders' => 'my_entity_my_entity_view_get_contexts',

    // Allow this to be enabled or disabled:
    'disabled' => variable_get('my_entity_my_entity_view_disabled', TRUE),
    'enable callback' => 'my_entity_my_entity_view_enable',
    'access callback' => 'my_entity_my_entity_view_access_check',
  );
}

/**
 * Callback defined by my_entity_my_entity_view_my_entity_tasks().
 *
 * Alter the my_entity view input so that my_entity view comes to us rather than the
 * normal my_entity view process.
 */
function my_entity_my_entity_view_menu_alter(&$items, $task) {
  if (variable_get('my_entity_my_entity_view_disabled', TRUE)) {
    return;
  }

  // Override the my_entity view handler for our purpose.
  $callback = $items['my_entity/%my_entity']['page callback'];
  if ($callback == 'my_entity_page_view' || variable_get('my_entity_override_anyway', FALSE)) {
    $items['my_entity/%my_entity']['page callback'] = 'my_entity_my_entity_view_page';
    $items['my_entity/%my_entity']['file path'] = $task['path'];
    $items['my_entity/%my_entity']['file'] = $task['file'];
  }
  else {
    // automatically disable this task if it cannot be enabled.
    variable_set('my_entity_my_entity_view_disabled', TRUE);
    if (!empty($GLOBALS['my_entity_enabling_my_entity_view'])) {
      drupal_set_message(t('Page manager module is unable to enable my_entity/%my_entity because some other module already has overridden with %callback.', array('%callback' => $callback)), 'error');
    }
  }

  // @todo override my_entity revision handler as well?
}

/**
 * Entry point for our overridden my_entity view.
 *
 * This function asks its assigned handlers who, if anyone, would like
 * to run with it. If no one does, it passes through to Drupal core's
 * my_entity view, which is my_entity_page_view().
 */
function my_entity_my_entity_view_page($my_entity) {
  // Load my task plugin
  $task = page_manager_get_task('my_entity_view');

  // Load the my_entity into a context.
  ctools_include('context');
  ctools_include('context-task-handler');

  // We need to mimic Drupal's behavior of setting the my_entity title here.
  drupal_set_title($my_entity->label);
  $uri = entity_uri('my_entity', $my_entity);
  // Set the my_entity path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  $contexts = ctools_context_handler_get_task_contexts($task, '', array($my_entity));

  $output = ctools_context_handler_render($task, '', $contexts, array($my_entity->id));
  if ($output != FALSE) {
    //my_entity_tag_new($my_entity);
    return $output;
  }

  $function = 'my_entity_page_view';
  foreach (module_implements('my_entity_override') as $module) {
    $call = $module . '_my_entity_override';
    if (($rc = $call('my_entity_view')) && function_exists($rc)) {
      $function = $rc;
      break;
    }
  }

  // Otherwise, fall back.
  return $function($my_entity);
}

/**
 * Callback to get arguments provided by this task handler.
 *
 * Since this is the my_entity view and there is no UI on the arguments, we
 * create dummy arguments that contain the needed data.
 */
function my_entity_my_entity_view_get_arguments($task, $subtask_id) {
  return array(
    array(
      'keyword' => 'my_entity',
      'identifier' => t('my_entity being viewed'),
      'id' => 1,
      'name' => 'entity_id:my_entity',
      'settings' => array(),
    ),
  );
}

/**
 * Callback to get context placeholders provided by this handler.
 */
function my_entity_my_entity_view_get_contexts($task, $subtask_id) {
  return ctools_context_get_placeholders_from_argument(my_entity_my_entity_view_get_arguments($task, $subtask_id));
}

/**
 * Callback to enable/disable the page from the UI.
 */
function my_entity_my_entity_view_enable($cache, $status) {
  variable_set('my_entity_my_entity_view_disabled', $status);

  // Set a global flag so that the menu routine knows it needs
  // to set a message if enabling cannot be done.
  if (!$status) {
    $GLOBALS['my_entity_enabling_my_entity_view'] = TRUE;
  }
}

/**
 * Callback to determine if a page is accessible.
 *
 * @param $task
 *   The task plugin.
 * @param $subtask_id
 *   The subtask id
 * @param $contexts
 *   The contexts loaded for the task.
 * @return
 *   TRUE if the current user can access the page.
 */
function my_entity_my_entity_view_access_check($task, $subtask_id, $contexts) {
  $context = reset($contexts);
  return my_entity_access('view', $context->data);
}

```
> 5 votes

---
Tags: 7, entities, chaos-tool-suite
---


# Question
Title: REST request through Actions and Triggers
In Drupal, I can define a Advanced Action in `Administration>Actions` , but the available options do not have a `Send REST request` option, how do I achieve what I want?

In my case, I want my remote service to know about a new node is being created, so I need to send the nid to my service.

I've thought of one dirty hack though, which is to use `Redirect to URL` and send my request through URL:

My server will receive the data it needs(which is the nid), and redirect the user back to their content using \[node:id\].

But like I said, this is more of a hack, is there a proper way of doing this?

# Answer
> 1 votes
I think the Rules HTTP Client module will suit you:

> This module adds an action wrapping of drupal\_http\_request to use Rules for making http requests. It has many general uses, because the Hypertext Transfer Protocol is the foundation of web data communication.

---
Tags: actions
---


# Question
Title: Need to know if user is coming from frontpage using jquery
On a Drupal 7 site I need some jQuery-animation on a page, only if user is coming directly from frontpage. My programming skills are very limited and need some help on that. I found something with parent.history.back()-function, but I don't know if and how I can use that in an if-statement. Any help is very appreciated

# Answer
> 0 votes
```
jQuery(document).ready(function($) {
  var referrer =  document.referrer;
  if (referrer == 'http://domain.tld/') {
    // Make whatever you like
  }
});

```

---
Tags: javascript
---


# Question
Title: Why is is_dir() called over 4000 times per request?
I installed XHPROF to check how I could improve my code. I noticed that Drupal calls `is_dir()` over 4000 times on nearly every request, and this takes about 800ms.

>

Why does this happen? Is there any way to speed that up?

I have already disabled the automatic register rebuilt, but it didn't decrease the number of times `is_dir()` is called.

# Answer
When you uninstall a module, you need to first disable it from admin/modules and then uninstall it from admin/modules/uninstall. The same goes for themes, which should be first disabled from admin/appearance.

If you, for example, delete the module without disabling the module, Drupal will continue to search for the module in the file system, which can result, among other errors, in the issue you are experiencing.

See also Avoid re-scanning module directory when multiple modules are missing.

To understand which module has been deleted without first uninstalling it, you will need to run the `SELECT name, filename FROM system WHERE status = 1;` query and compare that list of module with the modules present on the site directory. All the enabled modules and themes should be present.

There's also a hook implementation Martin\_Dresden posted on Drupal 7 abysmally slow: file\_scan\_directory called \> 1000 times per page load that may help with debugging. I provide here a slightly modified version.

```
function MYMODULE_init() {
  $startingtime = microtime(true);
  $o = '<p>Checking for dead modules ...</p>';
  $result = db_select('system')
    ->fields('system', array('filename'))
    ->condition('status', '1', '=')
    ->execute();
  $n = 1;
  $m = 0;

  foreach ($result as $row) {
    $path = DRUPAL_ROOT . '/' . $row->filename;

    if (!file_exists($path)) {
      $o .= "#$n $path<br>";
      $m++;
    }

    $n++;
  }

  $timedif =  round(microtime(true) - $startingtime,3);
  $o .= "Total of $n active modules registered in database. $m dead entries found.<br>";
  $o .= 'Query Time: ' . $timedif . ' seconds';

  drupal_set_message($o);
}

```
> 20 votes

---
Tags: 7, performance
---


# Question
Title: Print from drupal to a printer over the internet
Hope someone can shed some light on this. I've been asked to develop an ecommerce site in which once the order goes through a receipt will be sent some order details over the internet to a printer without the need of a computer in the middle. This is for a takeway restaurant so I do not know what kind of printer I could use either. Has someone faced a similar problem and could point me in the right direction?

# Answer
> 1 votes
You can create batch script on remote PC that connects with your site database and check if it required to print something. Then generate document from database data, and print it from command line.

---
Tags: commerce
---


# Question
Title: How to add tabs to a form without a module
I want to add horizontal tabs (not vertical tabs as shown in examples) as shown on the site : http://www.nseindia.com/ (Get Quotes on the top). I tried using menu modules like superfish and nice menu's it didn't solve my purpose.

I want to add this form with tabs via code and this is what I'm using for adding form to my block:

```
/**
 * Create the form.
 */
function getQuotes_search_block_form($form, &$form_state) {
  $form['keys'] = array(
    '#type' => 'textfield',
    '#title' => 'Get Quotes',
    '#default_value' => t('Enter Script name/Code /ID'),
    '#size' => 35,
    '#maxlength'=> 255,
    '#attributes' => array(
         'onblur' => "if (this.value == '') {this.value = 'Enter Script name/Code /ID'}",
         'onfocus' => "if (this.value == 'Enter Script name/Code /ID') {this.value = ''}",
         ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
    '#states' => array(
         'visible' => array(
            'input[name="keys"]' => array('filled' => TRUE),
          ),
    ),
  );
  return $form;
}

/**
 * Create the form submit handler.
 */
function getQuotes_search_block_form_submit($form, &$form_state) {
  $id = $form_state['values']['keys'];
  if ($id && $id != 'Enter Script name/Code /ID') {
    drupal_set_message(t('The form has been submitted'));
    drupal_goto('custom/node/search/' . $form_state['values']['keys']);
  }
}

/**
 * Create the search results menu callback.
 */
function mymodule_menu() {
  $items['custom/node/search/%'] = array(
    'page callback' => 'mymodule_do_search',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Create the search results callback function.
 */
function getQuotes_do_search($keys) {
  // set the page title
  drupal_set_title('FAQ search results');
  // get the search results
  $results = module_invoke('node', 'search_execute', $keys . " type:faq");
  return theme('search_results', array('results' => $results));
}

/**
 * Create the search form block.
 */
function getQuotes_block_info() {
  $blocks['faq_search'] = array(
    'info' => t('FAQ Search Block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function getQuotes_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'faq_search':
      $block['title'] = 'Custom FAQ Search';
      $block['content'] = drupal_render(drupal_get_form('getQuotes_search_block_form'));
      break;
  }
  return $block;
}

```

How do I add the horizontal tabs?

# Answer
> 3 votes
You don't say what you want in the other tabs but if you want tabbed blocks I would recommend using the quicktabs module.

It will allow you to create a quicktabs block that contains your custom block as one tab, and any other block/view/node in other tabs.

It will be far easier than making it custom. It is a very widely used and stable module.

---
Tags: forms, blocks, routes
---


# Question
Title: How can I make the pager work with EntityFieldQuery if I am redirecting?
I need to use pagers and understand them better to do so.

I have a module that produces custom forms gathering data for specific searches that then select that data using EntityFieldQuery, returning the nodes the user wants which I format as teasers and send back to an EmptyPage page. This works fine. When I add a pager, I only get the same records each time. I have tried adding a pager to the EntityFieldQuery, but I see in step through debugging that the query only has the limit number of records.

Because of the redirect, it doesn't appear to come back through the module on refresh. I have included some of my comment outs to illustrate some of what I've tried.

```
function ssti_search_digest_form_submit($form, &$form_state){
if (isset($_GET['page'])){
    $thispage = $_GET['page'];
} else {
    $thispage = 0;
}
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'weekly_digest')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created','DESC')
  ->fieldCondition('field_article_type','value', 'Digest','=')
//      ->pager(10,0)
  ->range(0, 50);
$keyword = trim($form_state['values']['keyword']);
if (strlen($keyword)>0){
    $query->fieldCondition('body','value', "%$keyword%", 'LIKE');
}

$states = stateslist($form_state['values']['state']);
if (count($states)>0 && ! isset($states['0'])){
    $query->fieldCondition('field_states','value', (array) $states, 'IN');
}

$tmp_q = $_GET['q']; // Store the current value of $_GET['q'].

$results = $query->execute();

$_GET['q'] = 'content/sstisearchresults/'; // Change the value of $_GET['q'] to the "correct" path you want the pager to link to.
if (isset($results['node'])) {
    $form_state['redirect'] = array('content/sstisearchresults',);
   $rows = $results['node'];
    $nodes = node_load_multiple(array_keys($rows));
    $output = node_view_multiple($nodes,'teaser');
    $output['pager']['#markup'] = theme('pager');
} else {
    drupal_set_message('No results found');
}
$_GET['q'] = $tmp_q; // Return $_GET['q'] to the proper value.
}

function ssti_search_digest_form($form, &$form_state){
$options = array('1' => t('Enabled'), '0' => t('Disabled'));
$form['search'] = array(
'#type' => 'fieldset',
'#title' => t(ssti_search_title_callback('digest')),
);
$form['search']['keyword'] = array(
'#type' => 'textfield',
'#title' => t('Keyword'),
'#size' => 30,
'#maxlength' => 64,
'#description' => t('Enter keywords to search for in title and text'),
);
$form['search']['state'] = ssti_search_state_select_input();
$form['search']['start'] = ssti_search_date_select_input('start',strtotime('-1 months'));
$form['search']['finish'] = ssti_search_date_select_input('finish');
$form['search']['formtype'] = array(
'#value' => 'digest',
'#type' => 'hidden',
);
$form['submit'] = array('#type' => 'submit', '#value' => t('Perform Search'));

return $form;
}

```

And to cover the used modules, there are four forms that are presented separately in QuickTabs which is on an EmptyPage. Only one of the forms is submitted and processed and the output of the submit is sent to an EmptyPage. Everything works nicely except the pager, which displays correctly, but no matter which "page" you pick, you get the first page.

# Answer
> 0 votes
The answer is that there are too many moving parts and the pieces needed to be separated. What I finally did was to let the form(s) handled the gathering of information, pull the information from the form submit and send it to another page for displaying results, where the entity field query handles the paging on its own page. The form submit code looks like this

```
function ssti_search_digest_form_submit($form, &$form_state){
form_state_values_clean($form_state);
$options['query']['searchtype']='digest';
foreach ($form_state['values'] as $retkey=>$retval){
    if (isset($retval) && ! is_null($retval)){
        if (is_string($retval) && ! strlen($retval)>0){continue;}
        $options['query'][$retkey]=$retval;
    }
}
drupal_goto('content/sstisearchresults',$options);
}

```

sstisearchresults is set as a page\_callback in the same module and is used by each of the four forms. That code (simplified) is below.

```
function ssti_search_advanced_results() {
$query = new EntityFieldQuery();
//choose between the content type based on sending form
switch($_GET['searchtype']){
    case 'supplement':
        $searchtype='funding_supplement'; break;
    case 'resource':
        $searchtype='resource_center'; break;
    case 'mep':
        $searchtype='meparticle'; break;
    case 'digest':
    default:
        $searchtype='weekly_digest'; break;
}

$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $searchtype)
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created','DESC');

// set filters for passed parameters

if (isset($_GET['keyword'])){
    $keyword = trim(check_plain(($_GET['keyword'])));
    $query->fieldCondition('body','value', "%$keyword%", 'LIKE');
}
if (isset($_GET['state'])){
    $states = $_GET['state'];
    if (count($states)>0 && ! isset($states['0'])){
        $query->fieldCondition('field_states','value', (array) $states, 'IN');
    }
}
// other parameter checks for all possible parameters
// setup pager
$query->pager(10,0);

$results = $query->execute();
if (isset($results['node'])) {
   $rows = $results['node'];

    $nodes = node_load_multiple(array_keys($rows));
    $output = node_view_multiple($nodes,'teaser');
    $output['pager']['#markup'] = theme('pager', $query->pager);
    return $output;
} else {
    return t('No results found');
}
}

```

I had to remove the EmptyPage callback for the results page (conflict) and all is well. The pager really does do what it is supposed to do, but it can get confused (or at least I can) depending on where the pager is being set up. By separating the "gather parameters" from the "display results" pieces, it all came clear and now works. In addition, all of the code for creating the query is in one spot for easy maintenance.

---
Tags: paging, database
---


# Question
Title: Creating QuickTabs programmatically not working
I'm trying to create some QuickTabs programmatically like it's documented on the website, but for some reason, my code bellow doesn't generate QuickTabs at all!
What do I do wrong or am I looking at the wrong documentation here?

```
function quicktabsmenu_block_info() {
  $blocks['quicktabsmenu'] = array(
    'info' => t('Dynamic QuickTabs menu'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function quicktabsmenu_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'quicktabsmenu':
       //set tab content
        $block['subject'] = t('Syndicate');
        $block['content'] = _create_quicktabs();
        return $block;
      break;
  }
  return $block;
}

function _create_quicktabs() {
  $tabs['tabcontent'] = array(
    'title' => t('Tab 1'),
    'type' => 'freetext',
    'text' => t('Free text'),
  );
  $quicktabs['qtid'] = 'my_new_quicktabs';
  $quicktabs['tabs'] = $tabs;
  $quicktabs['style'] = 'Zen';
  $quicktabs['ajax'] = FALSE;;
  $var = theme('quicktabs', $quicktabs);
  return $var;
}

```

# Answer
Well, after some thinking and searching, I managed to solve my own question. All I needed was this:

```
$tabs = array(
   $tabs[] = array(
      'title'   => t('Tab one'),
      'type'    => 'node',
      'nid'     => '24',
      'weight'  => 0,
    ),
    $tabs[] = array(
      'title'   => t('Tab two'),
      'type'    => 'node',
      'nid'     => '23',
      'weight'  => 1,
    ),
);

// Configure the QuickTabs options
$quicktabs_options = array(
   'style'   => 'Bullets',
   'ajax'    => FALSE,
);

$quicktabs_name = 'dynamic_quicktabs_menu';
$quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
return $quicktabs;

```
> 3 votes

# Answer
So, where have you added this code (I'm new to drupal so would appreciate if you could tell me the filename where this code is to be added)
> 0 votes

---
Tags: 7, blocks
---