title: problem with templates in custom module

text:
# Question
Title: problem with templates in custom module
I wrote a simple module that uses `hook_theme()`.

```
/**
* Implements hook_theme().
*/
function test_theme() {
  'upload_page' => array(
  'template' => 'templates/upload_page',
  'arguments' => array(
    'uploadurl' => NULL,
    'options' => NULL,
    'title' => NULL,
    'user' => NULL),
   )
}

```

I still have an error.

> Warning: include(./sites/all/themes/test/templates/upload\_page.tpl.php): failed to open stream: No such file or directory

How do I change this path to ./sites/all/modules/test/templates?

# Answer
> 1 votes
Drupal won't look for the template in a theme path unless

1. You've added this code to a *theme* instead of a *module* or
2. You've put your module in the theme folder instead of sites/all/modules, and then perhaps moved it once installed (less likely I think).

If you've done either of these I'd advise fixing that problem and putting the code/module where it's supposed to go.

If you're too invested at this point, though, you can use the `path` argument to `hook_theme()` to provide a static path to your theme's implementation folder:

```
'upload_page' => array(
  'template' => 'templates/upload_page',
  'arguments' => array(
    'uploadurl' => NULL,
    'options' => NULL,
    'title' => NULL,
    'user' => NULL
  ),
  'path' => drupal_get_path('module', 'test')
)

```

The docs I've linked to are for Drupal 6 as I assume from your code that's what you're using; if you're using Drupal 7, the `arguments` property should be changed to `variables`.

---
Tags: theming
---


# Question
Title: Is it possible to have term permission vocabulary id's match taxonomy vocabulary id's when creating a feature
I am attempting to create a feature to be used in an install profile that exports a vocabulary and the permissions that are associated with the vocabulary. The problem that I am running into is that the vocabulary vid's on my development site do not match the vid's when running an install profile. Features exports the vocabulary and when imported the next available index in the table is used to create the new vocabulary being imported by the feature. Term permissions use the vid, so when you export the permissions with a feature they look something like:

```
// Exported permission: edit terms in 4.
  $permissions['edit terms in 4'] = array(
    'name' => 'edit terms in 4',
    'roles' => array(),
    'module' => 'taxonomy',
  );

```

When I run my install profile the vocabulary I exported is imported with vid 1. So when it attempts to add the permissions for vid 4 it throw an integrity constraint error. I could change the features permissions code to align the id's but this does not bode well when I need to release a new feature that uses vocabularies and their permissions on top of an existing site that already has some vocabularies associated with it. I wanted to check here first before submitting an issue with features. Does anyone know a trick on how to get vocabularies and their permissions exported properly with features?

I was originally using features 7.x-1.0-rc2 then attempted to rectify the issue with 7.x-1.0-rc3 as there are a number of threads with similar issues but not quite the same issue as I am having.

# Answer
> 0 votes
That's not possible in Drupal 7 (and earlier) — permissions are hardcoded to use vocabulary autoincrement IDs, and there's no hook to override them.

This issue proposes switching to using the vocabulary's machine name for permissions in Drupal 8 — please consider reviewing the latest patch on that issue and providing feedback.

---
Tags: 7, features, distributions
---


# Question
Title: Can't find file to patch at input line 11, File to patch:?
I got an error message on module installation simpletest

> SimpleTest could not be installed. Must apply core patch, please see INSTALL.txt. (Currently using SimpleTest code addition Not-found)

Then by the instruction provided by INSTALL.txt I run the command

> ioss@ioss-System-Product-Name:~$ patch -p0 \< /var/www/Drupal/beeone/sites/all/modules/simpletest/D6-core-simpletest.patch

Then I got error below

```
can't find file to patch at input line 11
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|? sites/all/modules
|? sites/default/files
|? sites/default/settings.php
|Index: install.php
|===================================================================
|RCS file: /cvs/drupal/drupal/install.php,v
|retrieving revision 1.113.2.12
|diff -u -p -r1.113.2.12 install.php
|--- install.php    9 May 2010 14:13:31 -0000   1.113.2.12
|+++ install.php    7 Oct 2010 21:55:51 -0000
--------------------------
File to patch:

```

# Answer
> 0 votes
The patch is trying to alter the install.php file that comes with Drupal, but it doesn't find it. That file is normally removed, once Drupal has been installed.

What the command line is prompting for is the name of the file to patch, in the case has been renamed, or moved in a different directory.

Keep in mind that the SimpleTest module should not be installed in a production server, but in a development site.

---
Tags: 6, uri, testing
---


title: store fid of file_load into profile2

text:
# Question
Title: store fid of file_load into profile2
I programmed a multi-step form using the drupal form API. On the first page is a user image file upload using the drupal managed field **managed\_file**. When the form is stepped thru to the end and submitted, the already in the single steps validated data will be stored into profile2, by creating a profile2 object with `profile_create` and set the assign the fields. This all works without problem. But how can I store the FID of the uploaded file to the profile2 user\_image field? A s I saw in mysql, the file FID and the measurements of the image are stored in the field table.

I have this (file\_load code snippet is untested) in the form submit step, where the data gets stored into profile2:

```
$profile = profile_create(array
    'user' => $new_user,
    'type' => 'main'));
$profile->field_firstname['und'][0]['value'] = $user_data_collection['t_1_1'];
// ...
if (isset($user_data_collection['t_1_22'])) {
    $file = file_load($user_data_collection['t_1_22']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    $fid = $file->fid;

    // --- how can I store the FID, x and y measurements of the image?
    // ...
}
// ...
profile2_save($profile);

```

Can somebody give me a hint? I was searching on google but did not find an answer to my question. Thanks in advance!

**Update:** This is how I solved it now. Since I work with an **"managed\_file" Field** in the form, and later for displaying the image file via the `theme()` fct I do not have to care about resizing. This is done due to the image cache / theme fct's with a properly defined image-style.

```
$profile = profile_create(array(
   'user' => $new_user,
   'type' => 'main'));

//...

if (isset($user_data_collection['t_1_22'])) {
   $file = file_load($user_data_collection['t_1_22']);
   // --- Flag that this file is permanent and should not be deleted.
   $file->status = FILE_STATUS_PERMANENT;
   // --- save file object to the database
   file_save($file);

   // --- get original x/y measurements for this image
   $img_info = image_get_info(drupal_realpath($file->uri));
   // --- store fid. x and y to profile 2
   $profile->field_image_user[
      'und'][0]['fid'] = $file->fid;
   $profile->field_image_user[
      'und'][0]['width'] = $img_info['width'];
   $profile->field_image_user[
      'und'][0]['height'] = $img_info['height'];
}

//...

// --- save profile data
profile2_save($profile);

```

So all seems to work and have the solution that I needed.

# Answer
I think you are asking how to save user picture. Users table holds the place for picture.

```
$account = user_load($new_user->uid);
user_save($account, array('picture' => $fid));

```

EDIT

Profile2 module is based on entities using Entity API module. You can use `entity_metadata_wrapper('profile2', $profile->pid)` to get a metadata object. This object will hold the properties (native profile2 fields) and Fields (additional properties plugged in via field api or Field Admin UI)

```
$profile = profile2_load_by_user($account, 'main');
$profile_w = entity_metadata_wrapper('profile2', $profile->pid);
$proflie_w->field_myfield->value(); // This is a read operation
$proflie_w->field_myfield->set('new value'); // This is write operation
$proflie_w->save(); // Finaly save the things

```

You can bypass metadata wrapper.

```
$profile = profile2_load_by_user($account, 'main'); // Loading existing profile instance
OR
$profile = profile2_create(array('user' => $account, 'type' => 'main')); // Providing a new profile instance
$profile->field_myfield = "new value";
$profile->save();

```

NOTE: you can check all your listed properties using foreach operation on the wrapper object. e.g.

```
$profile_w = entity_metadata_wrapper('profile2', $profile->pid);
foreach($profile_w as $key => $obj){
   debug($key) // give you name of your property

```
> 3 votes

---
Tags: 7, users, files
---


# Question
Title: How to add a default Field when creating a Content Type?
I use to add a image field every time I create any content type. Just wondering if is there any way to add this field by default when the content type is created.

I found the http://drupal.org/project/content\_type\_extras module which provides some additional features to content types, but it doesn't include this feature.

# Answer
Not fully what you're asking. But once you have defined your image field you can easily reuse it in any content type. Since defining new content types is not something you do every day, this shouldn't be to much of extra work.
> 1 votes

---
Tags: nodes
---


# Question
Title: Why does view display incorrectly when logged out?
I have a view with a page display configured. When I take a look at the page in the browser, **while logged in**, it displays correctly. When **logged out**, it's a mess: the fields are out of order, the sort order is wrong, the field settings are wrong...

I've built views with this approach dozens of times before and have never experienced this. In fact, I've even built a similar view-based page in the same site with no issues. Any idea what's happening here?!

I've flushed the caches. No role permission settings have been changed beyond the default.

# Answer
Nevermind.

After walking away for an hour or so, coming back and then refreshing the page, **everything is working**. WTF? Does anyone know if this is a Drupal setting somewhere or is it an artifact of the somewhat locked-down instance of Drupal that I have to work with.

Grumble grumble.
> 1 votes

---
Tags: views, 6
---


# Question
Title: Contextual Filters On Block of News Items
Well I inherited a site, I have to make updates too. I have a list of news items, each news item has field I added called section, which lets people know what the section the news article blogs to. The url structure is http://example.com/tv or http://example.com/sports

On those pages, I have a list of news items (right now it's a global list) in a block. I need to adjust that list from a global list to reduce down to a list based on the section you are currently in. So the news list item should only show articles which belong to TV or Sports.

I have been working with the block, adding filters. I have attached an image of what I currently have. The field I have used in the view (sections) is called field\_channel\_section. In the auto preview I can put in TV and it will show me a list of the articles on that section, but on the actual page it shows nothing at all.

What am I doing wrong?

# Answer
Whenever you need to pass a parameter into a View, one should immediately think "Contextual Filter" - in this case, one should exist for field\_channel\_section. Note that blocks don't pass their parameters along the URL by default (as with pages), so you will need to set a default value for the filter criterion based on the URL yourself. Thankfully, this can be done by supplying the default value using PHP in the Contextual Filter settings. The particulars depend on what type of field field\_channel\_section is. If you could clarify, I'd be happy to do the same.
> 1 votes

---
Tags: blocks, views
---


title: How to remove core taxonomy rss feeds

text:
# Question
Title: How to remove core taxonomy rss feeds
I'm creating my own custom taxonomy rss feeds and have added those sucessfully to the head on term pages. Now, however, I need to remove the core taxonomy feed from those pages (currently it shows 2 feeds: the custom feed and the core feed).

Many people have suggested simply using the taxonomy view which overrides the core term and feed displays, but for complex reasons I can't use this solution.

I need to programmatically remove the feed from the head.

The original feed in the page head looks like this:

```
<link rel="alternate" type="application/rss+xml" title="RSS - termname" href="/taxonomy/term/2764/0/feed">

```

My best attempt to remove this is done in template.php and shown below, but it doesn't work:

```
mytheme_preprocess_page(&$variables) {
  //target taxonomy term pages
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric($arg2)) {
    $variables['head'] = preg_replace('/<link rel="alternate" type="application\/rss\+xml" title=".*?" href=".*?">/', '', $variables['head']);
  }
}

```

I probably need to get even more specific on the 'href' portion as well, so it only removes the term feed...but I haven't gotten that far yet.

I also tried adding `$variables['head'] = drupal_get_html_head();` at the end just to reload the head, in case it was necessary, and that doesn't help.

How can I programmatically remove this feed?

# Answer
Have you tried the RSS Permissions module? Here is a quote about it (from the module's project page):

> Set role-based permission settings for blog, taxonomy, aggregator, and main site's RSS feeds. This module does not disable RSS feeds altogether: RSS feeds created through the Views module and others not listed here do not have associated permissions.
>
> RSS permissions module lets you disable some or all RSS feeds based on different user roles, and was created as a stopgap solution for #28337: Add permissions to disable RSS feeds.
>
> This module adds role-based permission settings to blog, taxonomy, aggregator, and main site's RSS feeds.
> 2 votes

# Answer
If you're using D7 hook\_html\_head\_alter is your friend.

something like

```
function my_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if (isset($element['#attributes']['type']) && $element['#attributes']['type'] == 'application/rss+xml') {
      unset($head_elements[$key]);
    }
  }
}

```

Otherwise your attempt seems to be the best solution. Perhaps try ungreedy regex?

```
<link rel="alternate" type="application\/rss\+xml" title="[^"]*?" href="[^"]*?">

```
> 1 votes

---
Tags: taxonomy-terms, theming, feeds
---


title: Proper way to ajaxify links?

text:
# Question
Title: Proper way to ajaxify links?
According to a comment on Drupal's AJAX framework it should be possible to define a link as a render array which Drupal then would turn into an ajaxified link. As far as I understand it, the essential part of this is :

```
$link = array(
  '#type' => 'link',
  '#title' => t('something'),
  '#href' => 'some/path',
  '#ajax' => array(
    'callback' => 'some_callback_function',
    'wrapper' => 'ajax-response-goes-here',
    'method' => 'replace',
    'effect' => 'fade',
  ),

```

However, I'm not quite certain which url the client would use to actually invoke the AJAX request? I know forms use 'system/ajax' to access callback methods from there, but what about this case?

If anyone would have the chance to shed a little light on how to properly ajaxify links, I'd be very greatful!

# Answer
I would be rather suspicious about the '#ajax' way. Try to have a look here : http://api.drupal.org/api/examples/ajax\_example%21ajax\_example\_misc.inc/function/ajax\_example\_render\_link/7

### What they say :

* include the ajax.js
* add use-ajax class
* implement ajax callback under the link your link directs to

what should be done after the callback executes can be set by the ajax commands.
> 2 votes

---
Tags: 7, ajax
---


# Question
Title: One time login redirect to password change page
In D7, How can i redirect the user when he/she use One time login. My target is after clicking one time login button user has to redirect to change password. Can any one help on this.....

# Answer
> 4 votes
hook\_form\_alter can be used to add a custom redirect rule. Do it in your custom module.

```
function MODULE_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'user_pass_reset'){
        $form_state['redirect'] = array('path/to/redirect', array('param' => 'val'));
    }
}

```

---
Tags: users, redirection
---


# Question
Title: How do I ouput a node reference field using a node reference template in Drupal 7?
In drupal 6 you can create templates to control how node reference fields are output on a content type basis using the suggestion below:

```
node-nodereference-exampletype.tpl.php

```

and then output a node reference field that references 'exampletype' nodes in a node template like so:

```
$node->examplenodereference[0]['view'];

```

The file naming conventions and output syntax have changed in drupal 7.

Working off the information at this link http://drupal.org/node/998848 I have tried template suggestions like these with no luck:

```
node--nodereference--exampletype.tpl.php
node-nodereference--exampletype.tpl.php
node--nodereference-exampletype.tpl.php
node-node-reference-exampletype.tpt.php
and so on...

```

I have tried adjusting the display mode for the field from teaser to full content etc.

I have tried outputting the field with:

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

```

and

```
print $field_screening_movie_title;

```

and variations on the above.

What is the correct way to name a node reference template file in drupal 7? Do I need to use the render function to output a node reference field using the template?

Thanks

# Answer
> 1 votes
This module has one `display formatter` named `Rendered node`, in its setting you can select `view mode` which `referenced node` will render in that `view mode`.

so you can define new `view mode` and configure `referenced node` in that `view mode`

have a look at this post: http://mearra.com/blogs/juha-niemi/drupal-7-custom-node-view-modes

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


# Question
Title: Create content within the site instead of the Drupal modal popup?
I have a content-type "client-request" and I would the form to be displayed within the site (inside the banner and sidebar) when the user clicks new request instead of opening up in the Drupal modal popup.

Is this do-able?

# Answer
> 1 votes
It is, but you'll need a bit of jQuery:

```
(function($) {
  $(function() {
    $('a[href="/node/add/client-request"]').addClass('overlay-exclude');
  });
})(jQuery);

```

That will add the `overlay-exclude` class to any link that goes to the node add form for your content type; all this is does is force the overlay to close when the link is clicked, and forward you on to the right page. It'll also stop any links on non-overlay pages from invoking the overlay for that path.

---
Tags: forms, nodes, javascript
---


# Question
Title: What is the best way to allow user Edit one Form?
I want to make a dynamic website using Drupal 7 that allow user to edit any part of the site

this site has more than 10 pages each page has a different content and structure

should I make a content type to each page and add one node to each cck and give permission to site admin to edit this node

Or there is another way (I don't want to make a lot of cck because it make a lot of tables in database) also I need to edit only

I want the best way to make it

Thanks

# Answer
> 1 votes
If your question is primarily about how to allow the user to edit a form (as the title suggests), then I think the way to go is

1. Create a new role at /admin/people/permissions/roles and call is something like 'editor'.
2. Then go into the permissions page at /admin/people/permissions and give the new role 'Edit any content' permissions under the 'Node' section for each of the content types you have.

If you're simply wondering whether all those content types are OK, I'd say that having 10 content types for a Drupal site is not that crazy or unusual. Of course, if you're just trying to distinguish the pages from each other in some way, sometimes tagging/taxonomy is better than putting them in different content types, but that depends on what you're trying to achieve. If they legitimately have different fields/structure, than you're OK to have 10 content types.

Does that answer your questions or were you getting at something else?

---
Tags: 7, entities, performance
---


# Question
Title: How to get related nodes for node reference?
I have added related nodes using Node Reference module provided by the references module.
Now I want to retrieve all the related nodes. So I am looking for a function which takes a node id as input and returns all the related nodes.

Is there any function provided by Drupal API or reference module which helps me getting nodes related to a node?

I tried searching in the module functions but I found nothing.

# Answer
I don't know of an API function specifically for that but it's fairly simple to implement one using existing API methods:

```
function get_related_nodes($master_nid, $field_name) {
  // Load the 'master' node
  $master_node = node_load($master_nid);

  // Get the node reference items attached to this node
  $items = field_get_items('node', $master_node, $field_name);

  // Loop through and grab the nids
  $nids = array();
  foreach ($items as $item) {
    $nids[] = $item['nid'];
  }

  // Return the fully loaded reference nodes
  return node_load_multiple($nids);
}

```
> 2 votes

---
Tags: 7, nodes
---


title: Registration and Webforms

text:
# Question
Title: Registration and Webforms
I'm using Drupal 7 - is there any way to view and output the users who've registered with site in a similar way to how Webforms displays submissions and allows you to download and import into Excel?

I can export the users table from the database as a CSV file but I was hoping to find something that would be integrated into the Drupal admin ui (similar to the way Webforms is).

Thank you for any guidance you can provide.

# Answer
> 2 votes
There are two modules that you could use, the 'Database Administration' and 'Views Excel Export' These are still in alpha and dev for drupal 7 but might worth a try.

---
Tags: webforms, users
---


# Question
Title: How to make node delete confirmation inline?
I need to know how to override the normal delete node confirmation (preferably for a specific content type). My site has one content type that users are able to delete and right now it forward them to an unstyled /delete/ page to do so.

I'd like the same functionality but with an inline delete confirmation on that content type, ideally without additional modules.

Edit: Just realized I would have to manage permissions to account for deleting the content. May need to do it directly bypassing regular methods

# Answer
you can put this in your `node--node-type.tpl.php` file:

```
$item = menu_get_item("node/$nid/delete");
if ($item['access']) {
    include_once(drupal_get_path('module', 'node') . '/node.pages.inc');
    $page_title = drupal_get_title();
    $delete_form = drupal_get_form('node_delete_confirm', $node);
    print render($delete_form);
    drupal_set_title($page_title, PASS_THROUGH);
}

```

also you can remove `Cancel` link from $delete\_form
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: set variable in user object Recommended practice
I use a field in user account to store some user variables. These variables are not accessible by the user. I am worrying about the efficient of using the user\_load in every page in order to access the variables. Maybe it is better to use the variable\_set() ? What is the recommended procedure of setting/accessing variables in drupal?

# Answer
> 3 votes
If efficiency is the goal, and your variables aren't too complex, you could take advantage of the `data` property of the user entity. It's stored as a serialised string in the `{users}` table and is available by default as part of the global `$user` object. As it's loaded from the database for any type of user load (even the bare minimum one) you can reduce the overhead to basically nothing.

The best example of how to use it comes from the docs for `hook_user_presave()`:

```
function hook_user_presave(&$edit, $account, $category) {
  // Make sure that our form value 'mymodule_foo' is stored as
  // 'mymodule_bar' in the 'data' (serialized) column.
  if (isset($edit['mymodule_foo'])) {
    $edit['data']['mymodule_bar'] = $edit['mymodule_foo'];
  }
}

```

Then to retrieve the value at another point in code it's as simple as:

```
global $user;
$mymodule_bar = $user->data['mymodule_bar'];

```

Fields are great but as you know they do add overhead, so for small amounts of data I can't see any reason not to use the `data` property in this way.

I think using the variables table would get unmanageable quite quickly; you'd either end up with a different variable for each user, or having to store a single variable containing all users' data...neither of which are that desirable.

---
Tags: 7, hooks, users, performance
---


# Question
Title: Taxonomy - populate child dropdown based on parent dropdown?
I am wondering if there is a way to populate a taxonomy dropdown menu with the child terms of a selection made in another taxonomy dropdown menu. I would like to have two taxonomy dropdown menus, one for genre (parent) and one for sub-genre (child). When the a selection is made in the genre menu, I'd like the child sub-genre terms for that genre appear in the menu. Is there a way to implement this?

# Answer
> 0 votes
In Drupal 6, a good way to do this is to use a single taxonomy vocabulary and make the children terms selectable via Hierarchical Select. This will give you a single menu of the parents and then when users select one of the parent terms the menu of related children will automatically appear.

However, Hierarchical Select hasn't yet been fully ported to Drupal 7 (most notably, Views support does not work at all) and the timetable to do so is unknown.

For Drupal 7, you could try using the Conditional Fields module (or just use the States API directly if you're a developer) to set up logic to show/hide child menus based on the value of the parent menu. However, doing so has two big drawbacks:

1. Users will see all fields if they have Javascript disabled.
2. Depending on the number of items you have, this can get very complicated.

---
Tags: taxonomy-terms
---


# Question
Title: How to display, search, and edit form submissions from a table with WebForm?
I am very new to Drupal and I've been recently assigned a task to make a form for a single admin to register people and their info. It's basically a registration/contact form, except these people aren't users; the admin is just recording their info in a database. The admin needs to be able to search for a person's name through a table for a previous person's registration, and be able to click an edit link for that person as well.

I have been messing around with the WebForm module, and it is great for making the form itself, not to mention it already has a 'Results page' with a table of past submissions. However I do not know of a way to add a search functionality to the 'Results page'.

I also heard that you can put a search bar in Views module, so I messed around with getting the WebForm submission data into a table in Views, thanks to the Data and WebForm SQL Views modules. However I do not know how to put the corresponding edit link next to each of the rows in the table.

Is there a better approach to solving this problem? It seems I have to either handle adding searching functionality for a field, or making it possible to point to the WebForm edit functionality from each row of the Views table.

At this point, I am also wondering if its better to just hand code everything in php.

# Answer
No, it would not be better to hand-code everything in PHP. However, if you need heavy customization of the display of data the Webform module is probably the wrong approach. Webform is good at getting data in but the options for getting data out are somewhat limited.

Instead, I would make a custom content type and use Views to handle the display. To do so, navigate to /admin/structure/types/add and call it something like "People." Once you perform the basic configuration and click save, you will be taken to the *Content types* administration page; click *manage fields* for the content type you just created.

Here, you should be able to add the same kinds of fields that you added in Webform. This interface is not quite as clean as Webform's but it will allow you full flexibility with Views.

Once you have configured the fields as you like, go to the permissions page (/admin/people/permissions/roles) and make sure only the admin role has access to create and edit content of that content type.

Then, configure your view(s). Basically, you'll want a view of node content of the content type you just created. Add the fields you want to display under *Fields*. To get search filters, add *Filters* and check *Expose this filter to users*. When you set up the view(s), make sure to set the permissions using the Views edit interface so that only the admin role can access the views.

This is a very rough overview but hopefully it can get you started in a productive direction.
> 0 votes

---
Tags: 7, views, webforms, search, forms
---


# Question
Title: setting content in multiple regions with panels
I am trying to make a website, and I am needing some advices to solve a problem that I have, I will begin saying that I am using drupal 7, with panels and some other stuff, this is an example of the front page that I have thus far:

```
/**********************************************************************************
*                                                                                *
*                                                                                *
*                                                                                *
*                              header                                             *
*                                                                                *
*                                                                                *
*                                                                                *
***********************************************************************************
*             *                                                       *           *
*             *                                                       *           *
*             *                                                       *           *
*             *                      section                          *           *
*             *                                                       *           *
*             *                                                       *           *
*             *                                                       *           *
*             *                                                       *           *
*             * *******************************************************           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *            section         *          section         *           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *                            *                          *           *
***********************************************************************************
*                                                                                *
*                                                                                *
*                                                                                *
*                              footer                                             *
*                                                                                *
*                                                                                *
*                                                                                *
**********************************************************************************/

```

in my front page I have a section that I will use to show a message, but I am trying to make everything reusable, besides, I'd like to make everything with a neat structure, I'd like to make something like this:

```
/**********************************************************************************
*                                                                                *
*                                                                                *
*                                                                                *
*                              header                                             *
*                                                                                *
*                                                                                *
*                                                                                *
***********************************************************************************
*                                                                                *
*                                                                                *
*                                                                                *
*                                    highlighted                                  *
*                                                                                *
*                                                                                *
*                                                                                *
*                                                                                *
***********************************************************************************
*             *                            *                          *           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *            section         *          section         *           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *                            *                          *           *
*             *                            *                          *           *
***********************************************************************************
*                                                                                *
*                                                                                *
*                                                                                *
*                              footer                                             *
*                                                                                *
*                                                                                *
*                                                                                *
**********************************************************************************/

```

I'd like to turn that section into a region called higlighted, that region can be used in other pages, I tried to add a block into that region and then set some content dinamically to highlighted and content region, but it doesn't work like that, I don't know any other way to set content to the highlighted and the content region.

so, is there a possible way to do this??

# Answer
For static content, you can choose *New custom content* from the Panels *Add content* screen. Once you do so, you can check *Make this content reusable* at the bottom of the form that appears.

For dynamic content, the most general and commonly used way is the Views module. Using contextual filters, you can create a block that is dynamically changed based on the page url, taxonomy terms present on the page, or in other various ways. Moreover, although they are a little trickier to set up, you can use Views to make content panes, which are a special type of "block" specifically for Panels (Panels and Views were both developed originally by Earl Miles).

I can't explain how to do all of this here, but Node One has an excellent series of screencasts on Learning Views and Learning Page Manager/Panels.
> 0 votes

---
Tags: blocks, panels, nodes
---


# Question
Title: displaying field from node on page in url in block
I want to put a link in a block which will pull its url from a url field in the node being displayed on the page on which the block is. Meaning, the block will contain a different url for each different node-info page. How can I reference this node in the block?

# Answer
I figured out how to do it. Make a template file for that specific node ie: node-job.tpl.php and set the value of that url field (which is available to you while inside of that template file) as a global variable ie: variable\_set. Now you can access the url inside of your block using variable\_get.
> 0 votes

---
Tags: blocks, users
---


# Question
Title: How to geocode a form field on submission?
I'm writing a module with form alter that should geocode a text field value to the lat\lan format upon triggering the submit function. Should I use the Geocoder module for this? Are there any sample queries to learn how to perform geocoding with that module? Thanks.

# Answer
Personally, rather than `form_alter` upon submission, I would wire up an AJAX function to fire on the address/location textfield's onchange event, which would use the Google Maps Javascript API's Geocoder function. This would then populate a hidden text field (or two) with the lat/lng pair for form submission.

If you want to use the Geocoder module, it should probably go in the validate function so you can double check that you actually have a valid address.

Ideally, you would do both. Doing it client side is faster, and doing it server side supports users w/o Javascript.
> 1 votes

---
Tags: 7, location
---


# Question
Title: Create a new node by program and fill the specific field automatically
the goal of my program is to create a content of the specific content type

The specific content type (called A content type),have three fields:title,body,select option

when the user press a button, and the program will lead the user to the edit content page.

But the select option field will select the option i want and the AUTHENTICATED user can't

change this field.

How can i do?

the method i think is create a new node and fill the select field by programming. After

that, lead the user to the edit page of the node i just created.

but i still can't disable the select field

Does anybody have the suggestion? thx a lot !

i am not good at english. i hope you understand what i ask ?

# Answer
> 1 votes
The field permission module lets you define detailed permission on field level. If you have different types of users you may be want to define a new role for your users.

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


# Question
Title: Making one term in a vocabulary priority and print it separately
I have several terms in a vocabulary and my content type can be tagged with more than one of them.

When I print the term names tagged with the currently viewed node it seems that the term names are printed always in the same order (in the order of term id?)

However I somehow need to make one priority term per node and then print its term name first or separately from the rest.

Is there anyway to do this?

# Answer
> 0 votes
You could add a content taxonomy field and use that to select the highlight term. http://drupal.org/project/content\_taxonomy Then over ride or write your own theme function to loop through the terms array and remove the highlighted one before its output to the page

# Answer
> 0 votes
Easiest non coding way make a separate vocab and disable tags and multiple select for the new vocab then theme as required.

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


# Question
Title: Login form and registration form not properly displayed
I am using D7, with the help of Modal form module i am trying to display the login and registration form in a overlay effect. When the user visits /user/register or /user/login i get the overlay but not the form. I have attached a snapshot for further reference.

Where am i wrong in displaying this form?

Thanks.

# Answer
> 0 votes
Modal forms (with ctools)

> ### Supported forms
>
> * Log in (modal\_forms/nojs/user/login)
> * Request new password (modal\_forms/nojs/user/password)
> * Create new account (modal\_forms/nojs/user/register)
> * Contact (modal\_forms/nojs/user/contact)

It is also possible to build links manually.

```
    <a class="ctools-use-modal" href="modal_forms/nojs/user/login">Modal Login</a>
    <a class="ctools-use-modal ctools-modal-modal-popup-small"
href="modal_forms/nojs/user/login">Modal Login</a>

```

---
Tags: javascript
---


title: How can I redirect using hook_init()?

text:
# Question
Title: How can I redirect using hook_init()?
When the requested page is /user/login, users should be redirected to /mylogin.

I know this is possible with `hook_init()` or `hook_boot()`. Can someone explain how this can be achieved, exactly?

# Answer
> 6 votes
```
/**
 * Implements hook_init().
 */
function mymodule_init() {
  global $base_url;
  if (user_is_anonymous() && arg(0) == 'user') {
    drupal_goto($base_url . 'mylogin');
  }
}

```

---
Tags: 7, authentication-authorization
---


# Question
Title: How to pass variable to a view after submitting?
Why does the below code not work? I am trying to pass the $\_POST value to example\_page() when I submit the form:

```
function example_menu () {
  $items['example'] = array(
    'title' => 'Example',
    'page callback' => 'drupal_get_form',
    'page_arguments' => array('example_form'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function example_page($arg) {
  return "hello, $arg!";
}

function example_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'text',
    '#default_value' => t('Enter your name')
  );
  return $form;
}

function example_form_submit($form,&$form_state) {
  //BELOW DOES NOT WORK, and forget about passing raw HTML to output
  return example_page($form_state['values']['name']);
}

```

# Answer
> 2 votes
I'm only assuming but I would imagine that the form is redirecting somewhere after your submit handler, that's why the result of `example_page` is not being displayed. Also I'm not sure if you're copying the code or written it on StackExchange but you're missing a `return` from your `hook_menu`

This is how you'd normally pass variables to pages:

```
function example_menu () {
  $items['example'] = array(
    'title' => 'Example',
    'page callback' => 'drupal_get_form',
    'page_arguments' => array('example_form'),
    'type' => MENU_CALLBACK
  );

  $items['example/page/%'] = array( // % means variable
    'title' => 'Example arg',
    'page callback' => 'example_page',
    'page_arguments' array(2), // 0 is example, 1 is page, 2 is the % variable
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function example_page($arg) {
  return '$arg is: ' . $arg;
}

function example_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'text',
    '#default_value' => t('Enter your name')
  );
  return $form;
}

function example_form_submit($form,&$form_state) {
  // No return from submit handler, but set redirect
  $form_state['redirect'] = 'example/page/' . $form_state['values']['name'];
}

```

# Answer
> 2 votes
You're trying to return a string from a submit handler to have that string display: Drupal doesn't use submit handlers in that way. By default the form's action will point to the current URL, so after submission your form is displayed again. So effectively anything like displaying *Hello, arg* can be done from within `example_form` (or you can use the post, redirect, get method Baysaa mentioned).

# Answer
> 0 votes
Oh, you have a mistake in your naming, hook\_form can not be a valid form ID

change it to something else like example\_form\_test

---
Tags: 7, forms
---


# Question
Title: Search query for node content join taxonomy term
I am creating a form that searches the FAQ with the search term typed and the taxonommy term selected, i.e., the form will contain a search field and a select list of taxonomy terms associated with the FAQ. So I needed a sql query to achieve this. I need some modifications on this

```
db_query("SELECT question, nid
  FROM {faq_questions}
  WHERE question LIKE :term
  ORDER BY question asc", array(':term' => '%%' . $term . '%%'));
```
so that taxonomy term associated with question is also searched. The above code just searches FAQ with keyword only, not combined with taxonomy term selected

# Answer
Finally I managed to get results by using this code

```

db_query("SELECT faq_questions.question, faq_questions.nid,taxonomy_index.tid

FROM faq_questions
JOIN taxonomy_index ON faq_questions.nid = taxonomy_index.nid
JOIN taxonomy_term_data ON taxonomy_index.tid =taxonomy_term_data.tid
WHERE question LIKE '%$keys%' AND taxonomy_term_data.tid='$tid'");

```
> 0 votes

---
Tags: database
---


# Question
Title: How to create a user1, user2 and 3 others like this post?
I'm creating a website and there is a problem that I have encountered. I need to create list of posts. And each posts have a like button and shows who's liked the post exactly as in Facebook. The likes are handled by the flag module. The list of posts is in a view. What I need to do is figuring out each nid every post has in the view and pull the latest likes and the number of likes each post have.

# Answer
> 1 votes
If this is already in a view -- you can do the flag/like counts by adding a relationship to the view (I'm assuming you're on Drupal 7). Add the 'Flags: Node flag counter' relationship and select the flag you want the counts for.

Then you can add, for each piece of content in your block or page, the 'Flags: flag counter' field. That'll appear only once you've added the relationship. Make sure to select for it to use the relationship.

Let me know if this doesn't make sense and I can elaborate a little more. :-)

---
Tags: views, flags
---


title: Slash at the end of the breadcrumbs

text:
# Question
Title: Slash at the end of the breadcrumbs
How can I remove the slash at the end of my breadcrumbs?

*Markup:*

```
<div class="breadcrumb">
  <a href="/">Главная</a>
    /
  <a href="/admin">Управление</a>
    /
  <a href="/admin/build">Конструкция сайта</a>
</div>

```

*Screenshot:*

# Answer
I guess the slash is not in the end. It is the way you styled your breadcrumb thats why you are seeing it in the end. You can aid it using CSS, just tweak it a bit so you can hide it.
> 1 votes

# Answer
Try putting the following into your template.php file:

```
function MYTHEMENAME_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '<div class="breadcrumb">' . implode('  ', $breadcrumb) . '</div>';
  }
}

```
> 1 votes

---
Tags: breadcrumbs
---


title: Single page site - drupal 7

text:
# Question
Title: Single page site - drupal 7
I am trying to add multiple pages to my home page (about, contact), I assumed I do this in page--front.tpl. How to I call or pull in page nodes into my template?

# Answer
Seems like something perfecly suited to Panels.

> **An Overview of Panels**
>
> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Just create a panel page with the content you want displayed in a list, and then make this panel page your front page.

There are loads of tutorials/help on the project documentation page if you've never used it before.
> 3 votes

# Answer
There is a module that you can use: Single Page Website.

> This module provide the ability to display the content of all menu items of the menu that you indicate in settings on the Single Page Website module. On the page 'single\_page' the links in the menu will be replaced to the links to the correspondent anchors. You can set URL 'single\_page' as front page of your site, and your visitors will see the Single Page Website. But it will be the site managed by Drupal 7.
>
> This appoach is good for the small personal websites and promotional pages.
> 2 votes

# Answer
If you are running a single-page site, then all you want is a page.tpl.php file in your template directory for your theme.

What I recommend is you create your Contact and About pages utilizing the Basic Page content type, and before you save each make sure that under "Menu settings" towards the bottom, you check off "Provide a menu link" and "\<Main Menu\>" selected as the parent item. This will place the About and Contact page in the main menu at the top level. Also, under "Publishing options" verify that each is published.

Once you have created the pages and configured them so they show up in the main menu, then go into your Blocks configuration and place the Main menu block in the header region (or whatever region you wish, depends on what you want for a layout). That will expose those menu links on every page, assuming the header region is rendered in page.tpl.php.

Definitely ask for clarification if you're confused, I'll be here all day.
> 0 votes

---
Tags: 7, theming
---


title: Implementing jQuery-UI tabs

text:
# Question
Title: Implementing jQuery-UI tabs
I have all my js files in a folder under my custom theme:

```
htdocs/themes/<mytheme>/js

```

I load all these js files in 'mytheme.info' in this way:

```
scripts[] = js/<script1.js>
scripts[] = js/<script2.js>

```

All the javascript files are correctly loaded and are shown in the source code when I access the website.

In order to implement the tabs method I added jQuery and jQuery-UI libraries:

```
jquery-1.7.2.min.js
jquery-ui-1.8.21.custom.min.js

```

I have also added my 'custom.js' file with the code for implementing the tab method from jQuery-UI:

```
$(function() {
    $( "#tabs" ).tabs();
});

```

These three .js files also load properly and appear in the source code of the webpage.

In one of my modules I added the sample code in order to create the tabs:

```
<div class="demo">

<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Nunc tincidunt</a></li>
        <li><a href="#tabs-2">Proin dolor</a></li>
        <li><a href="#tabs-3">Aenean lacinia</a></li>
    </ul>
    <div id="tabs-1">
        <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
    </div>
    <div id="tabs-2">
        <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
    </div>
    <div id="tabs-3">
        <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
        <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
    </div>
</div>

</div><!-- End demo -->

<div class="demo-description" style="display: none; ">
<p>Click tabs to swap between content that is broken into logical sections.</p>
</div><!-- End demo-description -->

```

Wich appears in the webpage but without format, meaning, without implementing the .tabs method from jQuery.

Also the console doesn't output any error messages.

This is the link to the jQueryUI Tabs demo:

JQuery Tabs Demo

Any idea what am I missing here?

# Answer
It's very, very unlikely that you'll get jQuery 1.7 to work with Drupal 6. I haven't even heard of anyone getting it properly* set up in Drupal 7 as yet.

The question is...why do you need to? Drupal 6 comes with jQuery built-in, and you can get that up to v1.3.2 with the jQuery Update module. Since 1.3.2 is the minimum required version for jQuery UI 1.8.21 you should be good to go with that.

I'd advise installing the jQuery UI module; it makes it very easy to include the required libraries in your page requests.

* I've heard of people getting close, but there's always *something* that doesn't work properly.
> 2 votes

# Answer
Apart from what Clive focused.

You are missing `$(document).ready()` in your `custom.js` file.

```
(function($) {
  $(document).ready(function(){
    $( "#tabs" ).tabs();
  });
})(jQuery);

```

The other way can be adding js code in page footer by calling drupal\_add\_js in your custom module.

```
drupal_add_js('$("#tabs").tabs();', 'inline', 'footer');

```
> 0 votes

# Answer
I think your problem was the conflict beetween the native Drupal 6 jQuery and the 1.7.3 added in theme. You can, via preprocess, delete the native Drupal 6 jQuery and substitute it with jQuery 1.7.3

Try this code:

```
function <your-theme-name>_preprocess_page(&$vars) {
  // get all defined scripts as an array
  $scripts = drupal_add_js();

  // get jQuery core parameters
  $jQuery = $scripts['core']['misc/jquery.js'];

  // remove jQuery
  unset($scripts['core']['misc/jquery.js']);

  // prepend jQuery to core scripts array
  $scriptsCore = array_reverse($scripts['core'], true);
  $scriptsCore[path_to_theme().'/js/jquery-1.7.2.min.js'] = $jQuery;
  $scriptsCore = array_reverse($scriptsCore, true);

  // replace core scripts
  $scripts['core'] = $scriptsCore;
}

```

You have to delete jquery-1.7.2.min.js in your `your-theme-name.info`
> 0 votes

---
Tags: 6, routes, javascript
---


# Question
Title: What does the 'property_type' key do in hook_field_info()?
If you look at the hook\_field\_info() from Physical Fields the returned array has two keys that aren't mentioned in the documentation: `property_type` and `property_callbacks`. Can anyone explain what these are for? (Bonus question, are there any other missing keys in the documentation?!)

# Answer
They're not part of Drupal core, but are extra keys provided/used by the Entity Module. The comments in entity.api.php clear it up quite nicely:

> For providing entity property info for fields each field type may specify a property type to map to in its field info using the key 'property\_type'. With that info in place useful defaults are generated, which is already suiting for a lot of field types.
>
> However it's possible to specify further callbacks, that may alter the generated property info. To do so use the key 'property\_callbacks' and set it to an array of function names. Apart from that any property info provided for a field instance using the key 'property info' is added in too.

I'm afraid I don't know of any other undocumented keys, but a comment in the same file just above the previous ones notes:

> This is a placeholder for describing further keys for hook\_field\_info(), which are introduced by the entity API.

I would just keep your eye on that file when future versions of the Entity module come out to see if any new ones have been added; `property_type` and `property_callbacks` are the only ones mentioned at the time of writing.
> 9 votes

---
Tags: 7, entities
---


# Question
Title: Where are the "local files" for the Localization Update module stored?
I'm using the Localization Update module in Drupal 7. As the "update source", I can choose "Local files and remote server". I'd like to add some .po files that I created locally; where do I place them so that l10n\_update can pick them up?

I don't see any options on the module's configuration page (/admin/config/regional/language/update).

# Answer
> 1 votes
On the bottom of the module's configuration page you have to set a path for the local files.

> **Store downloaded files** A path relative to the Drupal installation directory where translation files will be stored, e.g. sites/all/translations. Saved translation files can be reused by other installations. If left empty the downloaded translation will not be saved.

---
Tags: i18n-l10n
---


# Question
Title: How to Add a quertystring to a link using jquery
I have a set of links on my page and some of them start with /mypath, like this `<a href="/mypath/other/stuff">`

I need to add a querystring to the links that start this way, so the result is something like `<a href="/mypath/other/stuff?parent=1234">` with the '1234' being the node id of the node we're currently viewing.

I've sucessfully passed the nid into my js file using drupal settings. The only part of this I can't get to work is putting the original link in where you see the second `attr('href')`.

My code is as follows:

```
    $('a[href^="/mypath/"]').attr('href', attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid);

```

Instead of that second attr('href') I've tried a number of things and can't figure out what it should be.

# Answer
> 1 votes
You've got nothing to hook onto for that second `attr()` as you're not storing the result of the jQuery call in a variable.

I'd advise using a loop instead:

```
$('a[href^="/mypath/"]').each(function(index, element) {
  var newAttr = $(element).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(element).attr('href', newAttr);
});

```

That will catch any link on the page that matches the path selector.

---
Tags: javascript
---


title: Disable user field on profile edit page

text:
# Question
Title: Disable user field on profile edit page
I've got a logintoboggan (http://drupal.org/project/logintoboggan/) module and my login is an email adress, so I dont want to have a "Name: " field on my profile edit page.

But when i just call in my theme preprocess page:

```
$vars['form']['account']['name']['#required'] = FALSE;

```

or unset() the field I've got an error:

> Username field is required.

How can I disable validation of this field? Thanks!

# Answer
> 0 votes
The username field is a required field in the `{users}` table so it has to be there one way or another.

A way round it might be to remove the "Change own username" permission for authenticated users at http://mysite.com/admin/user/permissions. I can't remember if the field will still display on the user edit form but either way it won't be editable.

---
Tags: 6, forms
---


# Question
Title: How to add data from one Drupal site to other?
Help me solve this scenario,

**Assumptions:**

1. Two users *user1* and *user2* are using their own copy of Drupal site - *site1* and *site2* on their respective machines.
2. They use same set of contributed modules (possibly with different configuration of the modules).
3. Both users add about 300 pages each to the sites.

Now, it is decided that the organization will use the site of *user2* and migrate it to the production server. The organization also wants the pages created by *user1* to be added to the site created by *user2*. How can this be done without changing the configuration of the site?

I did use the Backup and Migrate module to migrate the site *site2* of *user2* to the production server. Now, I am having difficulty in adding the content of *site1* created by *user1* to the production site; because if I use Backup and Migrate module again it will overwrite the existing pages from the site. It will also change the settings of the modules stored in the database. It is because, the nodes (pages) on *site2* and *site1* will have `nid`s starting from 1 and auto-incrementing in the `nodes` table. So, doing a backup and migrate procedure will replace `nid=1` from *site2* with `nid=1` from *site1*.

Is there a way so that I could append `nid` from the old database to new?

What other options do I have?

# Answer
> 2 votes
You need to migrate the content of site 1 keeping the config of site 2. My recommendation is to use migrate module coz I prefer it. But you'll have to write code to use migrate module.

There are other modules that may help you like node export, deploy. You can also write custom script but I have had most success with migrate module. You might need to justify the use of migrate in comparison to the content to be migrated, because you'll need to write migration classes but for lets say 300 nodes I'd still use migrate.

I wrote an answer sometime ago which talked about migration of content, users, categories etc. See if it helps you to choose as well - Updating content after major upgrade from 5 to 6 (changes to production site need to be reflected in dev environment)

# Answer
> 2 votes
I would recommend using the deployment module. It was develop by Al Jazeera for a similar but more complex workflow. It is extremely beneficial for sharing content amongst multiple sites and setting up automated syncs. However, in your case you will be able to quickly set up a deployment plan and run it once to get the content from one site to the other with out impacting settings and other data stored in the database. Deployment requires both services and uuid. It's not to difficult to setup and is extremely useful for deploying content amongst multiple sites or setting up a staging environment. You can find the documentation here.

# Answer
> 1 votes
You need to take care of node revision table as well. You need to write a procedure that does some thing like this in MY SQL

```
INSERT INTO node_revisions (nid,uid,title,timestamp,body,teaser,log) nid = 0
v = GET VID from last inserted row
INSERT INTO node (vid,type,title,uid,created,changed,status) vid = v
x = GET NID from last inserted row
UPDATE node_revisions SET nid = x WHERE vid = v

```

By doing this you will end up with new set of nid and vid with same content. I wanted to do the same some time back tried Deploy module but ended up writing my own scripts.

# Answer
> 1 votes
Also a shout-out for Feeds, which basically aggregates one site into another.

UUID-based solutions are much better, however, given that they'll allow you flexibility later on as well.

---
Tags: 7, migrations
---


# Question
Title: Filter criteria are not working with featured content blocks
I am trying to create a featured content block for my front page. To start I have set up a "featured" vocabulary with the two terms 'featured', and 'not featured'. I have then added that field to all my content types that I use.

Now when constructing the view to get all content that has the 'featured' term works if in the filter criteria it has only one content type. For example if I put the filter criteria to only check against the book term, then it brings back all book pages with the featured term. However, if I set up the filter criteria to check for book page feature, or article page feature, no content is found.

Is there a limitation on mixing content filtering in this way?

# Answer
First of all, in this case you don't need to add your filters to a new filter group, because views will use AND by default.

I don't see a filter for your taxonomy term. You should add one (see in the attached images).

For the content types you need just one filter, you can select which content types to filter on inside the filter.
> 0 votes

---
Tags: views
---


# Question
Title: Services 3.x json cache for anonymous user
Does the services module always invoke php to return data in json format? Is there anyway to cache the json output to be served for anonymous users (i.e. retrieve json data without invoking php)? First request will hit php and all subsequent hits should hit the cache.

My endpoint looks like this `api/anon` and it does not have any session authentication.

My request looks like this `http://localhost/api/anon/node/[nid]`

Thanks

# Answer
> 3 votes
Even in my experience, the boost module doesn't seem to cache responses from the Services module end points the last time I tried. But here's a discussion on this topic in the module's issue tracker. There's a patch for this requirement http://drupal.org/node/1219484

# Answer
> 1 votes
I feel like something such as Varnish would be more suited to this than trying to do it all in Drupal. The stock varnish configuration does a pretty good job at caching content that the backend says is safe to cache.

# Answer
> 0 votes
For json response use rest server.

For static cache use boost module, for caching responses as static pages.

---
Tags: 7, caching, services
---


# Question
Title: Is it generally safe to add same Drupal javascript multiple times?
I am trying to load content via AJAX calls which may include Javascript and its settings. This works more or less, but I cannot make sure whether a certain javascript code has been inserted and executed before. Now I need to find out, whether in case of problems resulting from a modules javascript code being executed multiple times, I would need to fix the modules javascript or whether I would have to take other precautions.

My question: Given Drupal's coding standards for Javascript added by modules, should it be unproblematic to execute it multiple times? I am aware of some modules where the javascript part is badly coded and problems will result, I just want to know whether this is allowed by some Drupal javascript standards (if any exist)

# Answer
> 2 votes
When you rely on Drupal's ajax framework, then it will take care of automatically adding only those js files on ajax requests that have not been added before. To accomplish that, it submits all currently existing js files to the server on each ajax request.

# Answer
> 4 votes
Usually, you add javascript with Drupal's behaviors as explain in the doc. If you have AJAX callbaks, javascript behaviors will be reloaded and this can cause some trouble.

For exemple, on my website I added moving clouds in the header with a javascript behavior, the speed beeing added by increments, each time I loaded an AJAX form it was sped up unintentionally. I could either add a jQuery Once behavior or use the common $(document).ready function.

So in conclusion, it depends on the way you call the code inside your javascript file. Your javascript code called inside a $(document).ready function should be loadded once, even with AJAX callbacks. On the contrary, a Drupal javascript behavior will be executed each time your DOM is updated, exept with jQuery Once enabled:

```
Drupal.behaviors.mybehavior = {
  attach: function (context, settings) {
    $('input.mybehavior', context).once('mybehavior', function () {
      // Apply the MyBehaviour effect to the elements only once.
    });
  }
};

```

Now if you are concerned with others javascript coding standards, see the official Javascript coding standards.

---
Tags: 6, javascript
---


title: How to secure Drupal website

text:
# Question
Title: How to secure Drupal website
I have Drupal CMS and I need to protect it from sensitive data leak, which are the customer names, addresses, the payments and order information.

I am new to Drupal, so my question is, is it possible to run each module in separate security context, so if one module gets exploited, the other data is not compromised? Is Drupal OOP based? Has drupal administration separated from the frontend? Would be these two achievable at all? I saw the LDAP module, which helps, but it doesnt help with the customer data...

# Answer
> 3 votes
You should read the official security thread, if you want to go further I advice you to take a look at the cracking Drupal book. In chapter 1, which is available for free download, you will get an idea of the places to look at.

According to this book, most common vulnerabilities found in Drupal sites are :

```
    Vulnerability   | occurences as a percentage of the total

     XSS            |      44
     Access bypass  |      14
     CSRF           |      10
     SQL injection  |      10
     Code execution |      8
     ...

```

So you shouldn't be concerned by Drupal architecture but with the way you implement your website, like any other. For instance, requiring administrator approval for users registration, making sure forms are safe and applying Drupal's updates should be a good start.

Also, if you choose to use the LDAP module for Drupal 7, keep an eye on its security related issues.

---
Tags: users, security, authentication-authorization
---


# Question
Title: Addind a meta noindex tag within template.php
I would like to add a meta tag noindex from within the template.php file of my theme.

The purpose is to remove two nodes 404 error page from google's index, I would like to do it like so :

```
// in mytheme/template.php
function my_theme_preprocess_node(&$variables, $hook) {
   $node = $variables['node'] ;
   // '123' would be nid of the 404 presentation page
   if($node->nid == '123'){
   /* META NO INDEX CODE GOES HERE */

```

Is this possible to do in my theme, without using any module at all ?

# Answer
You could use the following code.

```
function mytheme_preprocess_node(&$variables, $hook) {
  $node = $variables['node'] ;
  if ($node->nid == '123') {
    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
    drupal_add_html_head($element, 'mytheme_noindex');
  }
}

```

In Drupal 6, you just use `drupal_set_html_head('<meta name="robots" content="noindex" />')`, instead of `drupal_add_html_head()`.

I would rather use the code in a module, as a theme should not know details such as the existence of a node with a specific ID. Plus, if the site has more than one theme enabled, or it is possible that a different theme is enabled in future, the code should be copied in each enabled themes, while a module will always be executed, independently from the theme being used.
> 3 votes

---
Tags: hooks, theming, meta-tags
---


# Question
Title: Dynamic processing of string field based on user IP
I am a relative newbie looking for guidance on how to best tackle a requirement within the Drupal 7 realm. I have an entity defined with a field containing the URL for an external resource and would like to be able to manipulate the URL string programmatically before rendering the field as a hypertext link within a view. I thought about storing the alternate URLs in the database but the format is subject to change so the dynamic approach is more attractive since it would only involve a single edit. I need to first check the $\_SERVER\['REMOTE\_ADDR'\] to determine whether or not to execute this code because if the user is requesting the resource from a location off site then a proxy link must be generated for licensing purposes. What approach would make the most sense for this use case?

# Answer
> 0 votes
Store the data in the cleanest way possible and then use something like Custom Formatters or a custom module to modify the presentation of the stored data.

As for using $\_SERVER\['REMOTE\_ADDR'\] I feel that I need more data on how and where this will be used. Have you considered using the permissions or roles built into Drupal?

You would likely need to place this in a preprocess function to conditionally call it for a specific IP address.

For example.

```
/**
 * Implements hook_preprocess_node().
 */
function hook_preprocess_node(&$variables) {
    //Obviously a real IP is required above for correct syntax.
    if ($_SERVER['REMOTE_ADDR'] == xxx.xxx.xxx.xxx) {
        //Next you can edit the output of any field you want if your remote address matches.
        $variables['field_myfield'][LANGUAGE_NONE][0]['value'] = 'Something Modified Here';
    }
}

```

---
Tags: entities
---


# Question
Title: Node not being saved when using Rules redirect
I need help with basic setup of Rules. I have read tuts but could not figure this one out.

I have content type A. A is saved to system as unpublished. It saves personal information and those cant be changed anymore so users after using it get Access Denied message as they dont have permission to view it.

What i want to do with rules after node is being saved, 1. Redirects to some other internal url (any), 2. Get system message "Node creae successful".

Problem is that node after being saved with Rules module does not get saved at all. Nothing in Content, nothing in database. Without Rules everything works as intended.

Rules setup: 1. Events: "After saving new content"

1. Conditions: "Content is of type" - param: Content node, Content types: A
2. Actions: Page redirect - url: blog Show a message on the site: Parameter: Message: devtest

What happens is that redirect works correctly, message does not appear (no big deal, could create node with some text on it instead of system message). But node A does not get saved anywhere.

# Answer
You may be redirecting before the pending node\_save is called.

Try explicitly adding the action "Save Entity" under the Entities heading just before your redirect rule is evaluated. Make sure the redirect is the last action called.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How to use a hyphen instead of an underscore when using the content type as a Views argument? (Hackable URLs)
I have a classifieds site where I would like to list items at a URL structure like this:

classifieds/for-rent/apartments/title-of-my-ad.

That structure is broken down like this (views-page)/(content-type-argument)/(taxonomy-term-arg)/(node-title)

What I want to happen is this: If someone removes then all nodes will be listed that are apartments, which were created with the 'for rent' content type; If someone remove apartments (the tax arg) then all 'for rent' items, regardless of taxonomy, are listed.

See what I am getting at?

My problem is that the content type argument has to be written with an underscore instead of a hyphen before it will work. I want to use a hyphen. It's not as ugly, plus Google specifically recommends hyphens in the url instead of an underscore, and I want to keep google happy.

so, given the above example,

classifieds/for\_rent/etc/etc \<= works fine.

classifieds/for-rent/etc/etc \<= does not work.

How do I use the hypenated form as the argument? Is there a way to do this in views? Is there a way to write something in the .htaccess file so that when an argument is received with a hyphen the url is passed with an underscore behind the scenes?

Thanks!

# Answer
> 1 votes
If you have only six types, the quickest solution may be to create 6 page displays for your view, eg, one might be:

```
classifieds/for-rent/%/%

```

and then override the filter on this display and add node type for\_rent. Then create another page view, say:

```
classifieds/for-sale/%/%

```

and filter that page display on node of type for\_sale, another:

```
classifieds/personals/%/%

```

etc for personals.

ADDITION:

You could create a menu item and do this yourself, eg:

```
function YOURMODULE_menu() {

  $items=array();

  // any other menu items here

  $items['classifieds/%/%/%'] = array(
    'title' => 'YOUR TITLE',
    'page callback' => 'YOURMODULE_classifieds',
    'page arguments' => array(1,2,3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function YOURMODULE_classifieds($type, $tax, $title) {

  $type=str_replace('-', '_', $type);

  return views_embed_view(NAME_OF_YOUR_VIEW, NAME_OF_DISPLAY, $type, $tax, $title);

}

```

Now, this was just typed in off the top of my head so there may be subtle issues here, but the basic point is to create a menu item that responds to:

```
classifieds/SOMETHINGWITHADASHINIT/bar/baz

```

that gets the dash turned into an underscore for Drupal's internal name of the type. So, you could "just" create a block display in your view and remove all of View's paths and call it manually like the above. That, or ask that Views have a "transform underscores into dashes" checkbox like the "transform spaces to dashes" it has for taxonomy terms (which it might already have in D7 :)

---
Tags: 7, views, uri
---


# Question
Title: How can I hide certain values of CCK on node view page?
When a cck field can have multiple values I would like to hide certain values to print on node template.

For example, If `field_example` has the value `"red" "blue" "yellow" "black" "white"` I need to hide `"black" and "white"` and print only the rest on template file.

# Answer
You can use the Field Permission module. It allows to give different access rights to different roles per field.
> 0 votes

---
Tags: 6, entities, theming
---


title: how to display the suffix of the field?

text:
# Question
Title: how to display the suffix of the field?
Display the suffix for the field 'price', i use:

```
<?php
print $node->field_price['und'];
?>

```

but only it render the value without the suffix ($)

# Answer
You should ideally be using the render functions to output the stuff in content and node arrays in Drupal 7, the reason you are not seeing the suffix is that you are simply pulling out a value and not rendering.

So the following should work for you:

```
<?php echo field_view_field('node', $node, 'field_price'); ?>

```

Take a look at Drupal's reference on field\_view\_field and this article too
> 3 votes

---
Tags: 7, entities
---


title: Best way to change display for a field?

text:
# Question
Title: Best way to change display for a field?
I have a node display that shows about 20 different fields. One of the fields is a list of years (multiple values). Instead of printing the list of years I would like to just show the first and last year, for example "1999-2005".

Views has a great formatter for those situations but I don't want to use views for the node display.

# Answer
You might want to test the following simple formatter I put together for one of my projects - named mvspan (multivalue span). Soon after I wrote it, the specs of my client changed and I did not need it anymore, therefore it may need some more tests, therefore please accept it in its "as-is" shape.

It works for simple text or integer types, not date or datestamps, unfortunately. Feel free to shape it for your own needs.

It has two modes: displaying first/last values or min/max values. Plus, it allows you to set the delimiter to glue up the values.

mvspan.info:

```
name = Multi-value Span
description = "Formats multi-value fields to show first/last or min/max value spans."
core = 7.x
files[] = mvspan.module

```

mvspan.module:

```
<?php
 /**
 * Implements hook_field_formatter_info().
 */
function mvspan_field_formatter_info() {
  return array(
    // the key must be unique, so it's best to prefix with your module's name.
    'mvspan_formatter' => array(
      'label' => t('Multi-value Span'),
      'field types' => array('text', 'number_integer'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'settings' => array(
        'delimiter' => '...',
        'mode' => 'minmax',
      )
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mvspan_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  $delimiter = check_plain($settings['delimiter']); // The delimiter string in the settings form

  switch($settings['mode']){
    case 'minmax':
      $minv = NULL;
      $maxv = NULL;

      foreach($items as $delta => $item) {
        if(is_null($minv) || $item['value'] < $minv){
          $minv = $item['value'];
        }
        if(is_null($maxv) || $item['value'] > $maxv){
          $maxv = $item['value'];
        }
      }

      if($minv === $maxv) {
        $element[0]['#markup'] = $minv;
      } else {
        $element[0]['#markup'] = implode($delimiter, array($minv, $maxv));
      }

      break;

    case 'firstlast':
      reset($items);
      $firstv = $items[key($items)]['value'];
      end($items);
      $lastv = $items[key($items)]['value'];

      $element[0]['#markup'] = implode($delimiter, array($firstv, $lastv));
      break;
  }
  return $element;
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function mvspan_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();

  // settings
  $element['delimiter'] = array(
    '#type' => 'textfield',
    '#title' => t('Delimiter'),
    '#description' => t('Delimiter string to be inserted between min and max values.'),
    '#default_value' => $settings['delimiter'],
  );
  $element['mode'] = array(
    '#type' => 'select',
    '#title' => t('Value handling'),
    '#description' => t('How multiple values will be managed: min/max or first/last'),
    '#default_value' => $settings['mode'],
    '#options' => array(
      'minmax' => t('Minimum/maximum'),
      'firstlast'  => t('First/last'),
    )
  );
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function mvspan_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  switch($settings['mode']){
    case 'minmax':
      $summary[] = t('<strong>Min/max</strong> values will be displayed');
      break;

    case 'firstlast':
      $summary[] = t('<strong>First/last</strong> values will be displayed');
      break;
  }
  $summary[] = t('using delimiter: "<strong>@delim</strong>"', array('@delim' => $settings['delimiter']));
  return implode('<br />', $summary);
}

```
> 4 votes

# Answer
I came across the theme\_preprocess\_field() function and got it working. But I feel it's not a slick solution:

```
function bartik_preprocess_field(&$variables) {
    if($variables['element']['#field_name'] == 'field_mc_years') {
        if(count($variables['items']) > 1) {
            $to_year = end($variables['items']);
            $mc_years = $to_year['#markup'] . ' - '.$variables['items'][0]['#markup'];

            //destroy the array and just set the string to position 0
            unset($variables['items']);
            $variables['items']['0']['#markup'] = $mc_years;
        }
    }
}

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Retrieve create node form. Why cant save send values?
I want to add a custom page for creating "blog post". Ive got a node blog. So I write something like this:

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

    $items['user/%/edit/blog/add'] = array(
            'title' => 'Add blog post',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('module_add_blog',1),
            'access arguments' => array('createBlog'),
            'type' => MENU_CALLBACK,

    );
return $items;
}

```

And then in `module_add_blog` callback:

```
function module_add_blog(&$form_state, $arg) {
    $form = array();

    $id = intval($arg);
    if ($id == 0){
        drupal_set_message('ID must be an integer.' , '$error');
        return;
    }

    $user = user_load($id);
    module_load_include('inc', 'node', 'node.pages');
    $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog');

    $form = drupal_retrieve_form('blog_node_form', $form_state, $node);
    drupal_prepare_form('blog_node_form', $form, $form_state);
    return $form;
}

```

Form is rendered in path `user/1/edit/blog/add` but when I send data it is NOT SAVED.

Any ideas how fix it? Thanks

# Answer
> 0 votes
I think you're confusing Drupal by having a form within a form so-to-speak. I think it would be a lot easier to define a proxy function for the node form so you don't need to worry about doing so:

```
function module_menu() {
  $items['user/%/edit/blog/add'] = array(
    'title' => 'Add blog post',
    'page callback' => 'module_blog_form_proxy',
    'page arguments' => array(1),
    'access arguments' => array('createBlog'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function module_blog_form_proxy($uid) {
  // Validitiy checks etc...

  $user = user_load($uid);
  $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog');

  module_load_include('inc', 'node', 'node.pages');
  return drupal_get_form('blog_node_form', $node);
}

```

---
Tags: forms
---


# Question
Title: How do I get Path Auto to display one value in the URL structure when node:field has multiple values?
Using path auto to create a url structure, I would like the following:

my-content-type/\[node:field\_restaurant\_category\]

Note that node:field\_restaurant\_category can have multiple values, and in my url structure this is unfortunately the case. I have a url now that is my-content-type/t1-t2-t3-t4-tetc

How can I limited the node:field\_restaurant\_category to be just one and only one term? I honestly don't care which term the module chooses so long as the limitation is in place.

I read earlier that something like node:field\_restaurant\_category:values:1 should work, or something, but I cannot get any logical configuration of that to work correctly.

# Answer
For multiple cardinality fields you can use a pattern like `[node:field-name:1]` (note the use of hyphens instead of underscores).

This is an example of the tokens available for a field called `field_profile_categories` with multiple values:

I think in your case the pattern should be:

```
[node:field-restaurant-category:1]

```

Although the comments in the token table suggest that deltas start at `0`, so you might need to use `[node:field-restaurant-category:0]` if you want the first item to be used.
> 6 votes

---
Tags: 7, tokens, path-aliases
---


# Question
Title: Adding JS and CSS Dynamically to Override Theme
In Drupal 7 I'm trying to add JavaScript and CSS to dynamically modify the content in a theme. I've spent a good amount of time going over the Drupal documentation, several Drupal books, and the questions/answers on here. I'm trying to pull it all together, but I'm not sure how close I am and was hoping to get some feedback/help. What I have done so far:

(1) Created a CSS file with the code below called knitr.css and put it in the css folder

```
pre .operator,

pre .number {
 color: rgb(0, 0, 205);
}

pre .string {
 color: rgb(3, 106, 7);
}

```

(2) Created a JS file with the code below called jquery.knitr.js and put it in the js folder (note, to save space I have removed the js code)

```
var hljs=new function()
hljs.initHighlightingOnLoad();

 })(jQuery);

```

(3) Added the following code into the `preprocess_node` function of the *template.php* file. **Important: *responsive* and *page* need to be changed to your theme name and the machine name for your content, respectively**.

```
if ($variables['view_mode'] == 'full') {
$node =& $variables['node'];
if ($node->type == 'page') {
$path = drupal_get_path('theme', 'responsive');
drupal_add_css($path . '/css/knitr.css');
drupal_add_js($path . '/js/jquery.knitr.js', array('type' => 'file',
'scope' =>  'header'));
 }
}

```

(4) Placed the follwong in the basic content page with as full HTML text format

```
</head>

<body>
<pre><code class="r">1 + 2
</code></pre>

<pre><code>## [1] 3
</code></pre>

```

Expected output:

I expect the output on the page to look something like the following at this point. The JavaScript and the CSS should be changing the font color of 1+2 to blue (wasn't sure how to change color for example below). I'm getting no errors from what I've done above, but it is not implementing as expected.

```
1 + 2
## [1] 3

```

# Answer
> 1 votes
1. If the style sheet is used on all your pages, there's no need to load it dynamically with `drupal_add_js()`. Just put your style sheet into the .info file of your theme. The Writing theme .info files guide has detailed descriptions and links to more docs about this.
2. Your JS script looks fundamentaly wrong to me. Remove the `script` tag alltogether.
3. To add the JS script just add `scripts[] = foo.js` to your theme .info file. Look at the above mentionded guide, or here to get more detials.
4. What do you mean with *basic content page*.

---
Tags: javascript, theming
---


# Question
Title: How can i customize the output of "repeat rule" for human readability (german)?
I'm using the Calendar Module, which comes with a date-repeat feature. Showing the "repeat rule" in a view results in e.g.

> Wiederholungen jede Woche jeden Mittwoch !repeats\_every\_interval, 10 mal .

which is rather unacceptable. Is there a way to rewrite the output of this? Which replacement patterns do i have to use to reproduce the repeat rule?

# Answer
> 0 votes
I resolved this by just deleting the phrase by hand from the localized translation set.

I hope this won't trigger any other unwanted stuff.

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


# Question
Title: Exposed filter of a view embedded in a panel overriding a node form triggers node submission. How to prevent this?
I have a panel overriding the node/add form of a custom content-type in one pane and a view listing some nodes including 2 exposed filters to reduce the results of that list in another pane.

Both, the form and the view show up as i want, but if i use the exposed filters the node gets submitted instead of filtering the view.

How can i prevent this? Is there some way to do this step by step?

Drupal 7, latest dev-versions of Views and Panels.

Thanks in advance!

# Answer
> 0 votes
The little module i found and installed is doing a great job so far. I will now close this by answering my own question.

The problem was solved with this module.

> The Form Block module for Drupal (http://drupal.org/project/formblock) allows displaying user registration forms, node forms and some other forms in blocks. Unfortunately it was not available for Drupal 7 at the time of writing, which prompted me to write this module.
>
> It provides one block for each node type, displaying the node type's creation form. It respects user permissions, meaning that it will not display the creation form if you are not allowed to create the node.
>
> The module was created to allow using nodes as contact forms in Drupal 7. I have no plans on spending very much time on this module – have a look at Form Block if you want a long-term solution.

UPDATE: The Form Block Module now has a stable release for D7 and works well for the issue.

# Answer
> 0 votes
I have the same problem, what i have dug up so far is that the "form" html tag goes missing when the view exposed filter form is rendered within a node form. I am still trying to fix the issue as i haven't figured out why. I will update you if i get any further on this.

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


# Question
Title: Check if there's a content type published
How can I check (via PHP code) if a content type is published?

I have a content type called 'House' and a content type called 'People'. On the 'People' content type, there's a field called 'House'. If the user didn't publish a 'House' content type yet, I want to hide this field.

I thought I could do it by using a hook\_form\_alter, isn't it possible? If it is, I just don't know how to check if a content type was published or not. Something like: if (isset($node-\>type == 'House')) ... Of course it doesn't work.

Do you have any suggestions?

# Answer
Something like this?

```
hook_form_alter() {
  /* check that you're looking at the right form here.. */
    global $user;
    $type_to_check = 'House';

    $query = db_query("SELECT nid FROM node n JOIN users u ON n.uid = u.uid WHERE n.status = 1 AND u.uid = %d AND n.type = '%s'", $user->uid, $type_to_check);

    if(empty(db_result($query))) {
      /* kill the thing you don't want here */
    }
}

```
> 1 votes

# Answer
You can do this using a template to your content type. In the respective new template of your content type, you can add the condition to do this:

```
if ($node->status == 1){
unset($node->your_field_name);//here, for example, the field name is 'your_field_name'
}

```

**note:** to create a new template to your content type, look inside your theme directory, and create a copy of file node template **node.tpl.php**, then rename this copy according your Content Type, for example, if machine name of your content type is my\_content\_type, then:

```
node-my_content_type.tpl.php

```

and then add the code indicated above.
> 0 votes

# Answer
You have to query the nodes table for the uid of the current people node and type house. If you don't find a house unset the field in your hook\_form\_alter function.
> 0 votes

---
Tags: nodes, 6
---


title: drupal ahah not working

text:
# Question
Title: drupal ahah not working
I'm trying to make a ahah form. the problem is the ahah is ignored. when i check the classes on the submit button, it doesn't have the 'ahah-processed' class. The really interesting thing is that ahah is working perfectly on my site, and even on a nearly identical form I created. this is how i'm creating the ahah submit button:

```
$form['ri_email_submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#weight' => 1,
        '#submit' => array('ri_email_form_submit'),//none JS version
        '#ahah' => array(
          'event' => 'click',
          'path' => 'ri_email/ajax',
          'wrapper' => 'email-friend-wrap',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array(
            'type' => 'bar',
            'message' => t('Loading...')
          )
        )
        );

```

I checked the menu path, it's correct.

UPDATE: this is the menu callback:

```
function ri_email_ajax() {
    return drupal_json(array('status' => TRUE, 'data' => '<p><strong>Your email has been sent.</strong><p>'));   }

```

by the way, i discovered that it didn't work when i invoked drupal\_get\_form() from page.tpl.php, but it does work from node.tpl.php

there is something missing with the javascript that is supposed to handle the ahah

# Answer
> 1 votes
Can you post the callback function generating the page at 'ri\_email/ajax'?

It should look something like this:

```
<?php
  function awesome_ahah_callback() {
    $thing_to_process = $_POST['thingfromform']
    /* do stuff, including generating some kind of $processed_data variable */

    drupal_json(array(
      'status' => TRUE,
      'data' => $processed_data,
    ));
    exit();
  }
?>

```

If you aren't generating the thing you want to send back through AHAH with drupal\_json and then calling exit() then I don't think it will work.

---
Tags: 6, ajax
---


# Question
Title: enable jquery ui effects in theme .info file
Now I should add something like `<?php drupal_add_library('system', 'effects.bounce'); ?>` to my `page.tpl.php` to enable jquery ui effects to use in `views_slideshow_cycle` module.

is there anyway to do this inside theme .info file?

# Answer
> 1 votes
No, it's not possible to add a Drupal library through a module or theme's .info file. You can add single CSS/JS files, but not a defined library.

That means it's physically possible to download separate copies of system libraries and include them statically in your theme, **but you should not do this**. It's not the 'Drupal' way, and it makes things very difficult to maintain.

You're right in thinking the logic shouldn't be in your page.tpl.php file, it should rather be inside your theme's `hook_preprocess_page` function in the template.php file.

That way the library will be added in time to be included in the page, you maintain a nice level of separation between logic and display, and your theme will be protected in the case that core updates need to be applied to the libraries you're using.

# Answer
> -1 votes
Sure, download jquery ui from http://jqueryui.com/ and put the javascript file you need in your theme then add a line

```
scripts[] = relative/path/to/file.js

```

Just make sure that jquery UI is binding to the jQuery variable and not $ and you should be good to go.

---
Tags: theming, javascript
---