# Question
Title: How can I auto tweet any node of a specific type to Twitter?
I know the Twitter module lets you setup automatic tweets of new content to your twitter account, but I am wondering how/if its possible to schedule automatic tweets of old content as well.

# Answer
> 1 votes
I ended up doing this with Rules, Rules Bonus Pack, Views, Flag & Twitter Modules.

Set up a Rule that is:

1. Triggered during Cron runs.
2. Has no conditions
3. Loads a list of Node IDs from Views (Rules Bonus Pack)
4. Posts to twitter based on the first NID in the view.

For my view, I made a flag called Tweet This attached to my node type, and the view displays nodes that have this flag. You could use a different method to grab the list of nodes you want to tweet, such as filtering by date posted (get older content based on a given date) or number of views (popularity).

Good luck!

# Answer
> 0 votes
You can achieve using hook\_cron() function.

```
function mymodule_cron() {

    // Find all the node which are not tweeted yet.

   // Check the twitter module and look for the code which performs tweet of newly created node. I would have posted code but not able to access right now

   // Use this code and tweet this nodes

   // This will tweet old nodes which are not tweeted yet

}

```

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


# Question
Title: Can't log in to Drupal instance after duplicating database
I wrote a quick script to pull down a live drupal database on to a machine on a local network, and that works fine.

I also made a copy of the actual Drupal instance on my *own* machine.

I edited settings.php to use the db on the network, and everything appears to be working correctly when I run the site from localhost, except I can't log in.

At first I thought I should just change the password directly using MySQL, but that didn't work. Then I tried running update.php, which also didn't work.

I'm stuck, why won't it accept the username/password? I have double checked that I'm using the correct login credentials on the live site, and it works fine.

**Edit:** The site was duplicated from a Linux server onto a Windows 7 machine, if that makes any difference.

# Answer
> 3 votes
First check whether `$cookie_domain` is set to localhost or not?

If it is set as the URL of the live site then it might not work. I faced this issue previously.

Other cause might be clean urls. You can check whether clean URL is enabled in your localhost or not.

You can check whether `mod_rewrite` is on or not here. If clean url is causing problem then you can disable from your database. If you want to disable clean url goto your database find variables table, find clean\_url variable and set it to 0.

---
Tags: users, migrations
---


title: Login attempt failed

text:
# Question
Title: Login attempt failed
My Drupal 6 site's login function stopped working all of a sudden, with no error other than "login attempt failed".

* No database table crash
* Cookie domain is not set
* Drupal runs in "single-site" mode, not "multi-site"

The copy of the site runs well on my local machine. Do you have any advice?

# Answer
> 0 votes
Now I found the cause: The "pass" field in "users" table by some accident was set as 32 chars long, which is far less than required by phpass module (128 chars long). I re-installed phpass to make the table change as required and fixed the problem.

---
Tags: 6, authentication-authorization
---


# Question
Title: How to configure the views slideshow from the CMS?
Currently I am configuring the views slideshow from the views edit. where I can set the interval time, slide show type and effect, control of the slideshow pause/stop/start etc.

My need is that I want to configure all these things from the CMS not from editing the view.

Is it possible? Is there any module which will do this? Or any other alternative for this?

Thanks in advance.

# Answer
> 1 votes
You can check a very helpful module in Drupal JCarousel. It has views integration and the settings which you want as well.

> This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.

---
Tags: 7, views
---


# Question
Title: Show custom content in Main Page Summary
I have a site using Ubercart that shows product summaries on the main page (I believe these are called teasers). Each product has a voting widget provided by Vote Up/Down on its actual node/page. I've copied page.tpl.php to page-front.tpl.php because I want to add a small block or box that shows the number of upvotes on the main page (but not actually allow voting here) and finally sort these teasers by popularity (number of votes).

I can see that `print $content` is outputting this page's content but I am not sure where this is being generated so I can either hook into it or modify directly. I've coded themes and plugins in Wordpress but I don't know Drupal well enough yet.

Thanks in advance.

# Answer
> 1 votes
You can find node.tpl.php inside your sites/all/themes/yourtheme folder. `$content` is generated in that file.

---
Tags: theming, ubercart
---


# Question
Title: Print primary and secondary tabs separately
I am creating subtheme of bartik theme.

According to page.tpl.php file of Bartik theme it shows that tabs can be printed by following code.

```
<?php if ($tabs): ?>
  <div class="tabs">
    <?php print render($tabs); ?>
  </div>
<?php endif; ?>

```

The above code prints primary and secondary tabs at a single place.

Now i want to print primary and secondary tabs seperately in template file.

Is there any variable which gives me the primary and secondary tabs seperately ?

# Answer
> 4 votes
Finally I ended up like this:

```
<?php
  $primary = menu_primary_local_tasks();
?>
<ul class="tabs primary primary-with-secondary clear-block"><?php print render($primary); ?></ul>

```

The above code will return the primary links:

To print the secondary links

```
 if ($secondary = menu_secondary_local_tasks()) {
    $output .= "<ul class=\"tabs secondary clear-block\">\n". $secondary ."</ul>\n";
  }

```

Above code will return the secondary links for the theme.

# Answer
> 1 votes
You might wanna set some variables for your page template...

**/themes/YOURTHEME/template.php**

```
function YOURTHEME_process_page(&$vars) {
  // Set local tasks variables
  $vars['primary_local_tasks'] = menu_primary_local_tasks();
  $vars['secondary_local_tasks'] = menu_secondary_local_tasks();
}

```

**/themes/YOURTHEME/templates/page.tpl.php**

```
<?php if ($primary_local_tasks || $secondary_local_tasks): ?>
<div id="tasks">
<?php if ($primary_local_tasks): ?>
<ul class="tabs primary"><?php print render($primary_local_tasks); ?></ul>
<?php endif; ?>
<?php if ($secondary_local_tasks): ?>
<ul class="tabs secondary"><?php print render($secondary_local_tasks); ?></ul>
<?php endif; ?>
</div>
<?php endif; ?>

```

---
Tags: theming, routes
---


# Question
Title: render form in page--node--add--contenttype.tpl.php
In Drupal 6, there was a method to theme the edit form for nodes of a custom type:

```
 /**
* Implements hook_theme().
*/
function hook_theme($existing, $type, $theme, $path) {
    return array(
   'node-type_node_form' => array(
   'variables' => array(
   'form' => NULL,
     ),
   'template' => 'node_type-node-form',
   ),
 );
}

```

Drupal 7 handles this method with the following template files: page--node--add--contenttype.tpl.php, or, page--node--edit--contenttype.tpl.php.

I didn't find any documentation about how I should render form items in these templates. `$form` is null.

Which variable should I use to render the edit form for my content type?

# Answer
Can you try this code in `page--node--add--yourcontenttype.tpl.php`

```
module_load_include('inc', 'node', 'node.pages');

$form = node_add('your node type');

print drupal_render($form);

```

Refer Change aspect of node add form (not only via css)
> 4 votes

---
Tags: theming
---


# Question
Title: Render all items of the main menu on one page
i am building a overview page of my website. My Main Menu has the following structure:

MenuItem1

* submenuitem1
* submenuitem2
* submenuitemn

MenuItem2

* submenuitem1
* submenuitem2
* submenuitemn

MenuItem3

* submenuitem1
* submenuitem2
* submenuitemn

MenuItem4

* submenuitem1
* submenuitem2
* submenuitemn

I want to render each Menuitem with his submenuitems in a different div and add an image to it. I know i can work with the menu block module. But because we have the domain access module running and lots of domains, it has to be a coded solution. Each domain has his own main menu and should build dynamically the overview.

I managed to output the whole main menu expandend with this code:

```
$main_menu_tree = menu_tree_all_data('main-menu');
$main_menu_expanded = menu_tree_output($main_menu_tree);
print render($main_menu_expanded);

```

How can i accomplish my mission ?

Thx

# Answer
> 0 votes
You can try with dhtml menu.

1. download dhtml module http://drupal.org/project/dhtml\_menu
2. Configure menu setting
admin/config/user-interface/dhtml\_menu

---
Tags: routes
---


# Question
Title: Experience with Drupal 7 Install Profile
"How to Write a Drupal 7 Installation Profile": http://drupal.org/node/1022020

Any experience with this (good or bad)?

The link above references the ability to create an installation profile. Question is, how much can it do?

The real objective is to be able to put everything into code (and version control) that defines the website; permissions, OG field group settings, you name it. And then use that as a routine production path from dev, to stage, to production.

I've heard theory that this technique could be used to not only establish a site, also as a vehicle for migrating from the dev environment, to staging, to production.

Clearly, there is a benefit to be gained by an organization like Pressflow to be able to build a preconfigured base distribution. But, how viable is this technique for routine website updates and maintenance?

# Answer
> 4 votes
I have 1 site in production (re)built every academic quarter off of an installation profile. I have various sites in development I am building using installation profiles.

It's a PITA to try and include content into an install profile in my opinion. It seems to be a great way to code up the functionality of a website. But I still rely on a BASH build script and Drush to run additional import stuff -- and tools just as Migrate, Taxonomy\_csvimport and backup migrate to move "content" around places.

I do like "building" the site codebase using an install profile and would recommend the Profiler module to help you along. You can do *alot* with install profiles.

# Answer
> 3 votes
I began to consider this alternative some time ago; I have started to make a drush command to generate an installation profile from an existing site. My general thought was that backing up unmodified versions of Drupal core and contrib modules was inefficient and clumsy to analyze; much better to commit only a makefile plus an installation profile that contains the custom components.

There is an open question as to whether configuration should be represented in the installation profile, or in features. Drupal 8 has a better solution, but in the meantime, many people use features to deploy configuration options. It was therefore my assumption that I should make features that capture my configuration, and save the features in my installation profile. I have discovered, though, that `drush feature-revert` does not always handle dependencies inside a feature very well. I did not get to the bottom of it, but as a workaround, running `drush fra` multiple times (until nothing further changed) seemed to be a potential workaround. It would also be possible to create multiple features, and install each one in turn, effectively manually managing dependencies. Of course, features cannot capture *all* configuration information in code, but the alternative of manually hand-crafting all configuration in code in an installation profile seems too labor-intensive for smaller projects.

I have not gotten to the point of using this mechanism for any live sites, but some people have.

# Answer
> 3 votes
Don't try to use the installation script in a profile to maintain your configuration unless you're shooting to make a distribution profile. Using Features, or the results of the CMI in D8 is a good way to maintain your configuration.

Keeping everything grouped in a profile so you can use a stub drush make file and a single git repository isn't just "theoretical", it's an excellent way to keep things organised and deploy.

You can use Aegir to manage backups, deployments and migrations between different versions of your profile.

---
Tags: distributions
---


title: Context Module set default block

text:
# Question
Title: Context Module set default block
I am looking to have a subfooter that I can toggle with all types of rich content based on the page that visitors are on. I would like to be able to say the homepage has this block, the blog section has this block, and so on. I have quite a few uncategorized pages that I would like to be caught in a 'default' block of some form. The issue is, if I have a default, it will show two if a condition is met with another context. I would prefer to avoid the use of php snippits in blocks if possible.

# Answer
> 0 votes
You can exclude other contexts. In the default (sitewide?) context, add a Condition: Context, and use the ~ character to exclude the specific contexts that should not be in effect.

E.g., `~rich_subfoot` (if rich\_subfoot is the name of the context providing the rich subfooter content)

---
Tags: blocks, 7
---


# Question
Title: Weird Drupal Error (The character encoding of the HTML document was not declared)
I have Drupal 7 with multiple taxonomies and recently for only one (the largest one) when I go to the following taxonomy page:

www.site.com/taxonomy/term/216746

all is fine.

Then when I click edit:

www.site.com/taxonomy/term/216746/edit

My screen goes blank and I see in the console that I get this error:

> The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.

This does not happen with any other taxonomy term and suggestions would be great. Also, I looked in the database and I notice any differences between the terms.

# Answer
I turned on errors in the settings.php with `ini_set('display_errors', 1);` and I found it was a memory issue.

I added `ini_set('memory_limit', '500M');` to the settings.php file, and all works.
> 1 votes

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


# Question
Title: how to stay on the same page on clicking a link
I need to know how to stay on the same page when a link is clicked. If `l()`, what can be passed as the second argument for the link to be for the page currently visualized?

I need to override `l()` for menu slot titles inside the megamenus module so that they don't redirect to a different page. Is there any token in Drupal 7 which stores the URL of the current page being displayed?

# Answer
> 1 votes
Try hash # char...

```
l(t('test'), '#');

```

# Answer
> 1 votes
You can try this also.

```
<?php
  l(t('Link text'), 'javascript:void(0);');
?>

```

---
Tags: routes, navigation
---


# Question
Title: How to customize the output of node content in Drupal 6?
I am looking to customise the templated output of the `$content` variable in `node.tpl.php` Can you tell me how I could achieve this? Is is possible with another template file?

The reason for this is to achieve AJAX pagination thus I need an ID on node\_body and also to pull out the paging nav from this same DIV.

Any help appreciated :)

# Answer
> 0 votes
These are the available them files where you can get `$content`

> node--\[type|nodeid\].tpl.php
>
> base template: node.tpl.php

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

> node--nodeid.tpl.php
>
> node--type.tpl.php

node.tpl.php

See `node.tpl.php` in the Drupal API documentation for more information.

Drupal 7 Template (Theme Hook) Suggestions

---
Tags: 6, theming, nodes, paging
---


# Question
Title: How do I auto enable modules within an install profile
I have created an sample installation profile (based on one that I grabbed from the Acqua Drupal install profiles. Thus far I understand the basic architecture. I add dependancies, but I cant figure out how to enable the modules. For instance, I want to require views, views\_ui, and features, and I want those modules to be automatically enabled when I install the profile. I'm assuming I add code somewhere in my .install file within the profile. Can someone give me an example of how I would require and enable views for instance?

# Answer
> 3 votes
You need to add them as `dependencies` in the .info file. To take a segment from standard.info:

```
dependencies[] = block
dependencies[] = color
dependencies[] = comment
dependencies[] = contextual
dependencies[] = dashboard

```

To add a little reference from How to Write a Drupal 7 Installation Profile:

> The contents of the profilename.info file are as follows:
>
> * The name, description, and core assignments are all required.
> * **The dependencies list includes all modules that will be enabled when this profile is installed (the ones above are the defaults from the Standard install profile).**
> * You can optionally include other declarations that can also appear in module .info files.

(Emphasis mine).

So enabling views would just be:

```
dependencies[] = views

```

And if you want the UI:

```
dependencies[] = views_ui

```

---
Tags: distributions
---


title: Selected date events in Calendar view

text:
# Question
Title: Selected date events in Calendar view
I have a calendar of content type as a block. Currently clicking the date link opens the single day calendar view (from the Calendar template). Is it possible to display a view/list of events for the selected date on the same page? like this:

Thanks in advance!

# Answer
One thing you can do is create a second block display view that's simply an html list of events (rather than a calendar display) and put that block on the same page as your current mini calendar.

The trick is that that event list can be set up to take a contextual filter that only displays it when you click on a day from your first calendar.

Here's how you can make it work

1. Customize your calendar-datebox.tpl.php file (except make sure you name it such that you're only customizing it for **your specific calendar block**, rather than globally) and place in your custom theme's templates folder. It should have something like this, rather than the typical one line it comes with:

```
// Notice how I'm placing the current day's selection into a URL variable called selected_day.  You may need to customize this a little to fit your needs.
<?php
  if ($selected) {
       $output = '<a href="/' . $_GET['q'] . '?selected_day=' . $date . '">' . $day . '</a>';
} else {
  $output = $day;
}
?>
<div class="<?php print $granularity ?> <?php print $class; ?>"> <?php print $output; ?> </div>

```
2. Once you've done that, the links that are printed for your days that have events, will just add a parameter to your existing URL that is called 'selected\_day', rather than replacing your calendar block.
3. Now just create a new block, which is an html list that prints out the event's name, time and description, like you have in your screenshot. Place that block on the same page as your current calendar either via a context or your block's admin screen.
4. Create a contextual filter for your new block listing, which should be the event's start date. Set the default value to be a php snippet, which just gets the url's 'selected\_day' variable

> return $\_GET\['selected\_day'\] ;

If both of your blocks are present on the page, the second one -- the listing -- shouldn't display anything until you click on an event date, at which point the url's variable will be created and the second block should appear. I just did a small test, and it works for me.

:-)
> 1 votes

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


# Question
Title: How can I highlight only the contents that have been never published yet in the Views?
The contents always need approval of administer to be published on this site.

For example, The contents are once unpublished by Rule module when non-adimin users update them. And then the administer publish those contents again.

I have a node View with table style. In this view the administer wants to find "The contents that have never been published yet" easily for example, by making them hi-lighted.

Is there any way to achieve this?

# Answer
> 0 votes
The published (actually status) field is just a toggle, 0 for unpublished, 1 for published. There is no history of if a node has been published and then unpublished, so, there is no way to use it to find "contents that have never been published yet." To do that, you would need to create another field in your content and set it upon the first publishing of the node. Provided, of course, that that is your question.

# Answer
> 0 votes
To display unpublished content using views you have to add "Node: Published" option as "No" under "Filters".

---
Tags: views, 6, nodes
---


# Question
Title: Change aspect of node add form (not only via css)
I need to recreate graphically the "node add form" (my client has passed me via PSD the final version of the ***node add's form design***). Is there a way to manipulate the node add form ***design*** that is not the usual change using CSS?

# Answer
> 1 votes
Ok I think that I have found the solution:

Theming Node Forms in Drupal 7 -- http://drupal.org/node/1092122

M.

---
Tags: 7, forms
---


# Question
Title: Split an array returned by menu_tree_output
I want to display an expanded menu and split it in two columns after a certain amount of items:

Right now I have the following in my `hook_block_view`:

```
$menuTree = menu_build_tree('my-menu');
$menuOutput = menu_tree_output($menuTree);
$block['content'] = array('#markup' => drupal_render($menuOutput));
return $block;

```

So I would have to put some extra logic between `menu_tree_output` and `drupal_render` splitting the array after 5 items and wrapping the result in something like `<div class="first_column">`...

But `dfb($menuOutput)` gives me this huge array which I can't just `array_chunk($menuOutput, 5)`.

Any idea how to handle this?

# Answer
Just in case someone needs this: I found a solution altering `menu_build_tree`s output:

```
$menuTree = menu_build_tree('my-menu');

// flatten out the hierarchic menu tree
foreach ($menuTree as $key=>$value) {
    // if the item has children
    if (count($value['below']) > 0 && $value['link']['hidden'] != 1) {
        $flatMenu[$key]['link'] = $value['link'];
        // add a custom class to the first level items
        $flatMenu[$key]['link']['localized_options']['attributes']['class'] = array(
          'first-level-item',
        );
        // override nested menu items
        $flatMenu[$key]['below'] = array();
        // and add those to the new array
        $flatMenu = array_merge($flatMenu, $value['below']);
    // if the item has no children
    } elseif ($value['link']['hidden'] != 1) {
        $flatMenu[$key] = $value;
        $flatMenu[$key]['link']['localized_options']['attributes']['class'] = array(
          'first-level-item',
        );
    }
}

$markup = '';
$chunk = 5;
// split the new array in chunks and wrap them each with a numbered class
foreach (array_chunk($flatMenu, $chunk, true) as $key=>$value) {
  dfb($value);
  $markup .= '<div class="flatmenu-column-' . $key . '">';
  $markup .= drupal_render(menu_tree_output($value));
  $markup .= '</div>'."\n";
}

$block['content'] = array('#markup' => $markup);
return $block;

```

It is a bit hacky but with some extra lines of `CSS` it works perfectly well!
> 2 votes

---
Tags: 7, routes
---


title: Moving Drupal in a sub-directory

text:
# Question
Title: Moving Drupal in a sub-directory
I want to install Drupal 7 in a new directory of my site, using the same database account used in my previous Drupal site. Will this cause any data loss?

# Answer
> 2 votes
If you are going to move the Drupal files from a directory to a sub-directory, you should not have problems of lost data, which means the database still contains the data for user accounts, and for the created nodes.

Keep in mind, though, that some database tables contain absolute paths/URLs. Moving Drupal files to a sub-directory means that some URLs change, such as the ones to access uploaded files. The cache for the visited pages contain the absolute URL of the page; changing the directory where Drupal is installed means changing the absolute URL of pages, and not allowing Drupal to get the page content from its cache.

I would not talk of lost data, but rather of database references that need to be updated.

---
Tags: 7, installation
---


# Question
Title: Lightest way to control a field's markup
So far I have used Display Suite to control the output of entities. This especially applied to node's fields which by default receive multiple wrappers (like `field-items`, `field-item`, zebras and such) which I don't need. Correct me if I'm wrong, but I would say that installing Display Suite only for that purpose is a big overhead. If you agree on that, what would then be the lightest way to get exactly the markup I want?

# Answer
> 2 votes
Yes I think Display Suite is quite an overhead just to control field markup. You could obviously overwrite the templates manually, but for a quicker solution there's the excellent Fences module

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
>
> Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!

The difference in markup is huge. From

```
<div class="field field-name-field-test field-type-text field-label-above">
  <div class="field-label">Foobar field: </div>

  <div class="field-items">
    <div class="field-item even">Leaner markup means better front-end performance.</div>
  </div>
</div>

```

to

```
<h3 class="field-label">Foobar field</h3>

<div class="field-foobar">Leaner markup means better front-end performance.</div>

```

# Answer
> 1 votes
Consider the Fences module. Here is a quote about it (from the module's project page):

> ... is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
>
> Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!
>
> This kind of tool is needed in order to create semantic HTML5 output from Drupal. Without such a tool, you have to create custom field templates in your theme for every field.
>
> Similar projects include Semantic fields, Field Wrappers and a tool inside the Display Suite extras.

You can also just create your own field formatters.

---
Tags: entities, theming
---


# Question
Title: display a node id within a specific content type
I'm looking for a way to display the node id somewhere on all displayed instances of a given content type. It doesn't need to happen in any particular way, but it would sure help my users to be able to see the node id, as we use it to track physical objects.

I would imagine that there are a couple of ways to do this, so if someone could outline the options that would also help.

I've tried something like

```
<?php
$node_id = arg(1);
echo($node_id);
?>

```

To no avail, as I can only put this in each individual node instead of all nodes for a given content type.

# Answer
If you're trying to do this for a certain content type, and have a custom theme you're using with your site, I'd suggest modifying the template file for that content type to print out the node id somewhere below or above the content.

However, if you're not very good with theming a really creative way to do it is by creating a view block and enabling it for that content type. Then the node id can be displayed on the side of the content. It can be nothing more than a line... doesn't have to be obtrusive.

To do the above:

1. Create a new view and call it something like 'Node id display' (uncheck the page version of the view and only create a block version). Restrict it to the content type you want here, and make sure it's displaying fields, rather than titles, summaries or whatever is the default
2. Under the view's 'Fields' section, remove all fields that appear by default and only dislay the 'Content: Nid' field. You can change the label to be something like "Node id" instead of 'Nid' if you prefer.
3. Under the 'Advanced' section of the view, add a contextual filter of 'Content: Nid', and in the configurations, select for it to 'Provide a default value' if a filter is not present. From the drop-down, select 'Content ID from URL'
4. Either through a context or from the block's admin page, enable the new block for your specific content type... place the block on a sidebar, above the content, below the content... anywhere you want.

:-)

Hope this helps!
> 2 votes

---
Tags: nodes
---


# Question
Title: Ubercart particular item has extra shipping fee domestic vs international
I am using Ubercart 2.9 with Drupal 6.

Is there a way to add an extra fee to a certain product that has one value for domestic and a different value for international?

# Answer
> 0 votes
Install the modules Ubercart Fee and UC Catalog Conditional Actions

On the fee admin page, admin/store/fees, add fees with the required additional amounts. Add two conditions to each fee: that the product is in the cart, and that shipping address is \[your country\] or \[your country\] and condition negated.

# Answer
> 0 votes
You can try UC Multiprice

> This module allows you to set a different product pricing for each enabled country in Ubercart. It also got support for roles, currencies and i18n

*Its only in dev version use at your own risk.*

---
Tags: 6, ubercart
---


# Question
Title: How does one change the machine name of a Feature?
I have created a feature with a typo in the machine name. I've tried just search/replacing instances of the misspelling with the proper spelling in all files within the feature's directory, but when I do that it disappears from the list of available features entirely. (Yes, I `drush cc all`'d.)

How can I change the machine-readable name of this feature?

Using Drupal 6, btw.

# Answer
> 8 votes
Use this procedure to rename a Feature module:

* `drush pm-disable old_feature_name`
* `drush pm-uninstall old_feature_name`
* rename the Feature module folder
* rename the `.info` file
* rename the `.module` file
* rename any hook prefixes
* `drush pm-enable new_feature_name`

---
Tags: 6, features
---


# Question
Title: Drupal 7 Error 324 (net::ERR_EMPTY_RESPONSE)
I am working on a new Drupal 7 site and I am randomly getting connection errors to my server.

I am getting "Error 324 (net::ERR\_EMPTY\_RESPONSE): The server closed the connection without sending any data." in Chrome and Connection reset Errors in firefox. They are sporadic and tough to replicate. I call my service provider (MediaTemple) and they are unable to replicate the problem.

I am honestly at a loss and will look into any ideas given.

# Answer
> 1 votes
I found something else as well. It turns out that I was using a beta version of a module that was spitting out so many error messages that it was crashing apache.

Best advice I can give is to stick to trusted and tested modules.

---
Tags: 7
---


# Question
Title: Access front page node only by front page link
I have a problem with front page node redirection. I have created a node which I want to be a front page (let's say it's path is `node/6`). I have also set "**Default front page**" path with path of my node. The problem is that my node is accessible by two links now:

* `http://example.com/`
* `http://example.com/node/6`

How can I make my node to be accessible only by front page link?

# Answer
> 0 votes
Assuming you want http://example.com/node/6 to redirect to http://example.com/, I'd take a look at the global redirect module: http://drupal.org/project/globalredirect

---
Tags: 7, redirection, nodes
---


# Question
Title: Cron has been running for more than an hour and is most likely stuck
I am using poorman Cron Run and it is giving error like this: "Cron has been running for more than an hour and is most likely stuck." plz help if any solution for it??

# Answer
Issue was because of a second cron `elysia cron` was running with poormans cron. It was fixed. Sorry for not answer it here. I answered it in above comment.
> 1 votes

# Answer
It seems that cron is locked, hence the semaphore variable needs to be deleted before running cron again. In your `includes/common.inc` file, on line 2755 you need to delete the variable from `drupal_cron_run()`. You can use the following code:

```
function drupal_cron_run() {
  //The following line will delete the semaphore variable.
  variable_del('cron_semaphore');
  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
}

```

Then visit `http://yoursite/cron.php` and check the logs for errors.
**Note:** You should comment out the line `variable_del('cron_semaphore');`, after cron runs successfully.
I know it is not recommended to hack the core, but this was the only solution I found useful. If there is any work-around to this solution, please let me know.
> 1 votes

# Answer
If you permanently have such errors - it means that you have too much functions that are trying to run during cron.

I advice to install Elysia Cron module http://drupal.org/project/elysia\_cron It will allow you to tune which tasks will run during cron and how often. This will dramatically increase performance of cron jobs.
> 1 votes

---
Tags: cron
---


# Question
Title: TinyMCE input format is set to "Full HTML" but code is still being stripped
I am trying to enter some HTML into TinyMCE. I know that some input formats can strip code depending on your settings, but I have "Full HTML" selected, yet my code is still being stripped.

What else might be causing this to happen?

# Answer
Assuming that the stripped tags in question are mostly things like embedded CSS style tags you might need to enable the Full Page plugin to allow them in your content, apparently having style tags in regions apart from `HEAD` tag is not the best practice and that's the reason the functionality is not enabled out of the box from my understanding. Also assuming that you have the WYSIWYG module with TinyMCE library installed for your cause and not the TinyMCE module, here's a sample code of how I enabled the full page plugin in my case. (The code goes in your custom module, replacing your module name with MYMODULE in the function name).

```
/**
 * Implementation of hook_wysiwyg_plugin
 *
 */
function MYMODULE_wysiwyg_plugin($editor) {
  // if the editor is tinymce include the fullpage plugin so that embedded css is included
  $plugin_path = wysiwyg_get_path('tinymce');
  switch ($editor) {
    case 'tinymce':
      $plugins = array(
        'fullpage' => array(
          'path' => $plugin_path . '/jscripts/tiny_mce/plugins/fullpage',
          'buttons' => array('fullpage' => t('Full Page')),
          'url' => 'http://www.tinymce.com/wiki.php/Plugin:fullpage',
          'internal' => TRUE,
          'load' => TRUE
        )
      );
      return $plugins;
    default:
      break;
  }
}

```
> 1 votes

---
Tags: wysiwyg, input-formats
---


title: Retrieve Taxonomy Term by Field in D7

text:
# Question
Title: Retrieve Taxonomy Term by Field in D7
I have a vocabulary with a field "legacy\_id" which is a primary key another related system. I am building a routine to update the data in the drupal system based on changes in the related system. Other then hitting the DB directly, is there a way to retrieve the tid or the entire term from the field?

# Answer
> 2 votes
You can use EntityFieldQuery,

Here is the sample code,

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', 1) // change 2 to any vocabulary ID
  ->fieldCondition('field_test', 'value', 'test');
$terms = $query->execute();

```

First param to fieldCondition is the field name, second one will be the column name for example for text fields column name is **value** and for term reference field **tid**, then the final one is to specify the value. Hope this helps.

---
Tags: 7, taxonomy-terms, entities
---


# Question
Title: Multistep user registration using profile2
How can we create a multistep user registration form in drupal 7 using profile2 module.

# Answer
You can try Field group

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

Available group types

* Fieldsets
* Horizontal tabs
* Vertical tabs
* Accordions Divs
* **Multipage steps:** Note: This is only client side.

And i found a nice tut here
> 1 votes

---
Tags: users, forms
---


# Question
Title: CSS class for view display not being applied
I have a view set up with a block display. Its style is set to HTML list, which it does with no problem. But it doesn't seem to be applying the CSS class listed in the setup. What do I need to do to get this to apply?

Edited to add: Drupal 6, Views2

# Answer
> 2 votes
I said IF its D7 bc I could not find what version. I was reading it on my phone. But here's your Drupal 6 answer:

But here's the template suggestions for D6: http://drupal.org/node/1089642

You can download devel module to get template suggestions as well.

-OR-

Download this module to add css classes to specific blocks:

http://drupal.org/project/block\_class

# Answer
> 0 votes
Don't know if this will work but it's what I've done on occasion:

Remove the css class name in your view. That should cause Drupal views to automatically add the class ".view-sessions-by-track" which should be easy to track down.

# Answer
> 0 votes
You can do theme overrides in D6 too. Just look up the specific syntax for the API & replace it w/ that. There really isn't a big diff between D6 & D7. It's just naming conventions, a few processes, & hooks.

Wait til D8 comes out in 12 months. No more php template. It's going to Twig.

# Answer
> -2 votes
If its Drupal 7 you need to theme your blocks. You can override that by creating a block.tpl.php file & place it where your html.tpl.php file resides.

Next goto http://drupal.org/files/issues/Core\_templates\_and\_suggestions.pdf to see what template suggestions you might need. You can also search drupal.org for more, bc your block.tpl.php file might be named block--%--.tpl.php \< % denotes wildcard.

Next you will have to theme you block. You can control the HTML output with the $output variable, as well as classes and ID's. You have the option of generating classes and UD's statically or dynamically.

You could also do a theme preprocessing function (your\_site\_name HTML &vars function) in the template.php file.

Example for block.tpl.php

/\* more code here, below outputs whatever you code here \*/

$output .= '' . $links\['title'\] . ''";

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


# Question
Title: An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging information follows. Path: /system/ajax StatusText: Forbidden ResponseText:
I have received this error twice, first during panels everywhere, and now again working with Features module. It is produced When you create new feature:

Structure \> Features \> and click on 'Edit Components'

I have to select Content type: node and As soon as I check on any of the check boxes of content types available on my website, I get similar error:

> An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging information follows. Path: /system/ajax StatusText: Forbidden ResponseText:

I am logged in as an Administrator, so have all the rights.

Hoping to find any work around soon. I am encountering this error on two different areas of the website, and it prevents me from doing any work further.

# Answer
> -4 votes
It might be a file permission issue. Change them to 777.

---
Tags: ajax, panels, features
---


# Question
Title: Comma seperated text field into a HTML ol
I have created a custom content type and one of the fields will be a texfield with values separated by a comma e.g.

value 1, value 2, value 3

I want to then display this as an unordered list in the output.

Can anyone help with how this can be achieved?

Thanks

# Answer
You can make use of hook\_node\_view like this

```
function hook_node_view($node, $view_mode) {
  // explode the field contents with comma
  // replace the content with your exploded value.
  $node->content['yourfield'] = 'YOUR_EXPLODED_VALUE';
}

```

explode
> 1 votes

---
Tags: 7
---


title: View arguments in entity selection

text:
# Question
Title: View arguments in entity selection
I have a profile type which uses an autocomplete field which references to another profile. As an entity type i selected user and for filtering the results i use an entity selection with views where i choose what view to filter my content. So far so good , but i've seen that i can pass additional arguments to the view. My question is: How could i pass the input from autocomplete to the referenced view ? ( what should i type in the view arguments field to get the input from autocomplete ? )

# Answer
The solution was to create a module which it will alter the query executed by the view and by grabbing the input from url generated by the autocomplete.
> 0 votes

# Answer
What you're asking doesn't quite make sense if I understand it correctly. You see, the view you're choosing when setting up the field is used *before* your user has even entered anything in the auto-complete field. So you can't have that be an argument. The view is generated and used prior to any input.

The view is used simply to determine which set of users are available for the auto-complete field. It doesn't make sense to generate the view after the user has already entered in a value, because at that point they've already made a selection anyway.

So - I'm wondering, since you're asking about basing that view on user input, if what you're looking for is simply something like the 'auto-complete' functionality which exists with entity and user/node references. If you select for your field to be Autocomplete, when the user starts typing in a username, a list of related suggestions will automatically appear at the bottom.

Here's an example of a user reference field with autocomplete turned on
> 2 votes

---
Tags: views, entities, users
---


# Question
Title: How to join a path to a file in code, "windows safe"
Given a hook (e.g. `hook_theme()`) and a path where something has to be looked up (e.g. templates), what is the cleanest way to deal with this?

I have the following directory structure:

* sites/all/modules/mymodule
    + mymodule.module
    + templates
        1. mymodule.tpl.php

When I define that path in code, I use the following code.

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    "mymodule"  => array(
    "variables" => array(),
    "path"      => $path . "/templates",
    "template"  => "mymodule"
  );
}

```

I want this code to work on Windows too, without having to do checks for OS inside that function.

# Answer
Just use / as path separator: It will work on Windows, and any other OS.

PHP defines the `DIRECTORY_SEPARATOR` constant, but that constant is not used from Drupal core code, and Drupal works on Windows too.
A note on the parameters accepted from basename() says:

> On Windows, both slash (/) and backslash (\\) are used as directory separator character. In other environments, it is the forward slash (/).
> 3 votes

---
Tags: uri
---


# Question
Title: Updating modules with drush without breaking SVN?
Right, this has been breaking me for two days. I can't get an answer anywhere!

I have drush 4.4 on my server. I am using SVN via Unfuddle.com. I have a site, I want to update a lot of modules. I want to update just the code, then check it's working (DB updates are not a concern at this point) then commit the relevant code.

It used to be that drush dl would simply download the module code over the top of the old module, without removing it. That is no longer the case. Now, AFAICT, drush removes the module directory and replaces it with the newer version. That's all well and good, because it solves the problem of old files that are no longer in the updated module being left behind.

However, using the drush dl or upc commands, I am stuck, because running these commands does indeed get the newer version, but it destroys the SVN data folder in the process, leaving me with "! module/file.php" problems everywhere for files that aren't there any more.

I have been advised that "drush upc/dl modulename --version-control=svn" should work, but it doesn't. The SVN data is still destroyed.

This leaves me with the potential nightmare of having to: svn del module, svn commit -m"Removed module", drush dl module, (test the module), svn add module, svn commit -m"Added module" - for every single module, which is a total horror.

I do not want to set up drush to auto-commit my changes, I just want to download them and commit them all manually at the end when I'm happy with the changes. This *can't* be that hard, but I simply cannot get it to work.

I have also been advised that moving to git (yes, I'm aware unfuddle supports git!) is also a solution, but it's not an immediate one, and is not satisfactory at this point in time.

Can anyone please shed some light on this?!

# Answer
> 6 votes
> because running these commands does indeed get the newer version, but it destroys the SVN data folder in the process, leaving me with "! module/file.php"

I'm running Drush 4.4 and this does not appear to be the case for me. Running `drush upc` or `drush up` keeps your `.svn` directories intact. You can `svn status` to review the changes to the modules. New files are indicated by `?` and removed files are indicated by `!`.

Test your site's functionality. Once you are satisfied that the modules are still working correctly, you can then svn add/remove with a snippet such as the following:

**add:**

```
svn status | grep '^\?' | cut -c8- | while read f; do svn add "$f"; done

```

**remove:**

```
svn status | grep '^\!' | cut -c8- | while read f; do svn rm "$f"; done

```

# Answer
> 4 votes
You should add `--svnsync` to your command.

Example :

```
 drush pm-update module_to_update --version-control=svn --svnsync

```

---
Tags: 7, drush, version-control
---


# Question
Title: Check not NULL in entityfieldquery propertyCondition
I want to only return results in entityfieldquery that have a propertyCondition of 'field\_entry\_path' that is not empty.

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'example')
        ->propertyCondition('field_entry_path', '', 'NOT IN');
  $result = $query->execute();

```

Thanks.

# Answer
According to the docs it is possible. See Excluding empty(Null) fields when using EntityFieldQuery query condition @Clive
> 0 votes

# Answer
Unfortunately, it is impossible at the moment. See the workaround described on http://drupal.org/node/1226622.
> 2 votes

---
Tags: entities, database
---


# Question
Title: MySQL server has gone away - production site
> **Possible Duplicate:**
> Solving “MySQL server has gone away”, mysql error 2006

My website is moved from localhost to virtual hosting and after 1 week I receive an error 2006 2006 MySQL server has gone away. Now I can create/edit content but not content types and cannot clear the cache, I see white screen in this case. My hoster said that the max\_allowed\_packed size is only 1M and I cannot change it.

Is there a way to fix this error?

---

I deleted content types I don't use now and the problem has gone away... And now I can also clear the cache and edit other content types. What it was I cannot understand, it's beyond me

# Answer
Culprit may be `max_allowed_packet` which is too little. Drupal Requirements page suggests 16M, but it depends on your site. If you are not able to get sufficient memory allocated, better change host.

> When using Drupal 5.x or later, particularly with contributed modules, it may be necessary to set the system variable max\_allowed\_packet to at least 16M. Some inexpensive hosting plans set this value too low (the MySQL default is only 1M). In that case, you may need to choose a better hosting plan. A value of 1M may be sufficient for 5.x.
> 3 votes

---
Tags: 7, database
---


# Question
Title: Use of hyphen instead of slash in hook_menu
For SEO purpose, I need to use hyphens instead of slashes in a URL defined in `hook_menu`, here's an example :

```
$items['mypath-%'] = array(
  'page callback' => 'mypath_render',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'access arguments' => array('access_content'),
);

```

Apparently Drupal doesn't support it natively. Is there a way to make it work ?

Cheers

# Answer
Although I would never do this just for the sake of SEO personally, I believe the workaround is to use both hook\_url\_inbound\_alter() and hook\_url\_outbound\_alter(). By using these hooks you can change any URL displayed by the site to replace slashes with the hyphen, and then back again when Drupal processes the page after the user has clicked the URL. That way you can still use slashes in your hook\_menu(), but it would show as hyphens in your site.

I'm not sure there is any other way.

**Oh dear, I just realised the question was for Drupal 6, my apologies.**

I think for Drupal 6, using custom\_url\_rewrite\_inbound() and custom\_url\_rewrite\_outbound() could be used instead.
> 1 votes

---
Tags: 6, routes
---


title: How should I create a custom form?

text:
# Question
Title: How should I create a custom form?
I create a module like this:

```
<?php
function mymodule_menu(){
    $items['mymodule/edit']=array(
        'title'=>t('Edit item'),
        'type'=>MENU_CALLBACK,
        'page callback'=>'mymodule_edit_view',
    );
    return $items;
}

function mymodule_edit_view(){
    //...
    $html.='<form '.$form_attr.'>';
    //...
    $html.='</form>';
    //...
    return $html;
}

function mymodule_form_alter(&$form, $form_state, $form_id){
    //...
}

```

I create a form in mymodule\_edit\_view, but when I access mymodelu/edit, the drupal did not call mymodule\_form\_alter. I do not want to create the form with drupal\_get\_form(), So how should I create the form?

# Answer
> 1 votes
This shouldn't work as @Alex said, because you are not using Drupal's Form API. You should implement `hook_form($node, &$form_state)`, to create a form.

Sample code which creates a form with a single text field:

```
function MODULE_form() {
  $form = array();
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Field description goes here...'),
    '#required' => TRUE,
  );
  return $form;
}

```

---
Tags: 7, forms
---


# Question
Title: maxlength depending on nodetype (contenttype)
i use one field in different content-types. for example in article, this field should be limited to 130 characters, but in gallery, the same field should be limited to 50 characters. The field is also used to generate the breadcrumb menu, so i can not simply add another field. so is it possible, to set different maxlength-values depending on the nodetype?

# Answer
You could use `hook_node_presave` to set the maximum length of a fields value before the node is saved or inserted in the database.

For example, to force a field `field_dummy` for a node of type `article` to a maximum of 50 characters you could do like this:

```
function HOOK_node_presave($node){
  if($node->type == 'article'):
    // force the field to max 50 characters
    $node->field_dummy[$node->language][0]['value'] =
       substr($node->field_dummy[$node->language][0]['value'], 0, 50);
  endif;
}

```
> 0 votes

---
Tags: 7, nodes
---


title: Google doesn't see the friendly URLs

text:
# Question
Title: Google doesn't see the friendly URLs
Google doesn't see my SEO friendly URLs, while the other search engines can.

The browsers (IE, Chrome, FF), the RSS, the TweetFeed everything can see the SEO friendly URLs; in the XML sitemap, the system also see them. Google Webmaster, and Google Analytics also see the friendly URLs, but if I search on my site via Google ("site:mywebsitedomain"), it can see only the node system URLs (e.g. mysite.com/node/6574).

Before the system update, it was working well. My host supports friendly URLs; I have installed the PathAuto, and the Global Redirect modules; clean URLs are enable.

Why doesn't Google see the SEO friendly URLs I set for the site?

# Answer
Google will only index one version of the same page. It sounds like you have multiple URL's showing the same page. This is called *dublicated content*. Google will just choose one of the URL's, in your case, the wrong one.

When you enter mysite.com/node/6574 are you redirected to the friendly url? If not, then the GlobalRedirect module is not active or there is no aliases for the URL.

So make sure it's active and in `admin/config/system/globalredirect` check *Deslash* and *Non-clean to Clean* to further minimize dublicated content.

Also make sure that all internal and external links are pointing to your clean url's.

If the above is done, you just need to wait. Be patience - it can take weeks/months.

And forget about the sitemap. The important part is your internal links.
> 1 votes

---
Tags: path-aliases, uri, xml-sitemap
---


title: I need an AJAX cart like these below:

text:
# Question
Title: I need an AJAX cart like these below:
Is there a project or something that already integrated a cart similar to:

http://interface.eyecon.ro/demos/cart.html

or an integration of jcart:

http://conceptlogic.com/jcart/

I tried ubercart but despite the fact is an overkill it doesn't work like these.

# Answer
> 0 votes
Well, you didn't write the required version. I found a module Ecwid shopping cart. This module has drag and drop features for items and ajax support everywhere.

For more information, have a look at Ecwid Demo.

---
Tags: 7
---


# Question
Title: How can I eliminate duplicate Drupal nodes in a View when one CT references the other?
*Drupal 7 with relevant Modules: Views & Entity Reference*

I have a view that simply shows the "Teaser" display type of two different Content Type records, we'll say they are Article and Page. This is built into a Views Page.

My Article CT has some simple fields that are shown.

My Page CT has a few fields, but also an Entity Reference field (unlimited entries). The Entity Reference field points to other Article nodes.

My View then, as expected, shows each record's Teaser display and of course when a Page record references another Article record, that Article's teaser is shown as part of the Page teaser.

This is great. The problem is, I do not want to show duplicate Article teasers. That means, if a Page references an Article, I don't want to show that same Article teaser as an individual listing.

Think of it like this, I have these Articles:

1. Article 1
2. Article 2
3. Article 3

And I have these Pages:

1. Page 4
2. Page 5
3. Page 6

Page 4 points -\> at Article 1 and Article 2

Page 6 points -\> at Article 2

***TL;DR***

**Right now the view would show something like:**

* Article 1
* Article 2
* Page 4
    + Article 1
    + Article 2
* Page 5
* Page 6
    + Article 2
* Article 3

**What I want is this:**

* Page 4
    + Article 1
    + Article 2
* Page 5
* Page 6
    + Article 2
* Article 3

Here's a Diagram: https://i.stack.imgur.com/2joEr.jpg

# Answer
> 1 votes
My guess would be to use fields instead of teasers, first. Then, use filter to *undisplay* Articles that *are* nodereferenced by pages - you then would **only have pages and unreferenced articles showing up**.

You might be able to do that with the relationship *entityreference - reverse*, or with views PhP if it doesn't work.

# Answer
> 0 votes
* Go and edit your view
* In Advanced » OTHER section by enabling Use aggregation: Yes
* In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

# Answer
> 0 votes
I ended up knocking this out by making use of the Corresponding Entity Reference module (CER). This creates a 2-way relationship that is sync'd between the parent\<-\>child. Using that, I could simply filter all children which have a parent from the View.

---
Tags: views, entities
---


# Question
Title: From where does variable_get() get the first parameter?
```
function variable_get($name, $default = NULL) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

```

From where does `variable_get()` get the first parameter?

# Answer
> 2 votes
I think you're referring to the `$conf` variable?

It's set in `sites/default/settings.php` (or `sites/SITENAME/settings.php` if you have a multi-site installation), and that file is included in Drupal's page build.

# Answer
> 2 votes
The first parameter passed to `variable_get()` is the variable name. Every module decides the name of the persistent variables it uses.

Apart from avoiding conflicts with other variables defined from other modules, developers can use the variable name they like better. Preferably, they should use characters from *a* to *z*, the underscore, and numbers. Using other characters in the variable name could cause compatibility issues with other database engines, as different coding used for tables could not maintain the difference between lower-case characters, and upper-case characters.
The suggestion to use only lower-case characters is also reported in the Drupal.org coding standards:

> Persistent variables (variables/settings defined using Drupal's `variable_get()`/`variable_set()` functions) should be named using all lowercase letters, and words should be separated with an underscore. They should use the grouping/module name as a prefix, to avoid name collisions between modules.

For each call to `variable_get()`, there is an equivalent call to `variable_set()`, which can be implicit (i.e. made from Drupal) in the case variable is used in a form similar to the following one.

```
function book_admin_settings() {
  $types = node_type_get_names();
  $form['book_allowed_types'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Content types allowed in book outlines'),
    '#default_value' => variable_get('book_allowed_types', array('book')),
    '#options' => $types,
    '#description' => t('Users with the %outline-perm permission can add all content types.', array('%outline-perm' => t('Administer book outlines'))),
    '#required' => TRUE,
  );
  $form['book_child_type'] = array(
    '#type' => 'radios',
    '#title' => t('Content type for child pages'),
    '#default_value' => variable_get('book_child_type', 'book'),
    '#options' => $types,
    '#required' => TRUE,
  );
  $form['array_filter'] = array(
    '#type' => 'value',
    '#value' => TRUE,
  );
  $form['#validate'][] = 'book_admin_settings_validate';

  return system_settings_form($form);
}

```

The "book\_child\_type" variable is not explicitly set by the Book module, but from system\_settings\_form\_submit(), the form submission handler added by system\_settings\_form().

```
  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

```

# Answer
> 0 votes
Drupal maintains a table called `variable`, it's used as a key-value store, and is the permanent storage for all "variables".

Each variable\_set encodes data and inserts/updates in the table.

During `boostrap`, Drupal loads the entire variable table into memory, in the form of the `$conf` variable. Since most variable tables are fairly small, loading everything into RAM is seen as prefered to making a `SELECT` query in the table for every variable get.

As Clive pointed out, one can override individual values in the `settings.php` file, either because one needs data available *really* early during bootstrap, such as for cache-related settings, or because a site needs a temporary workaround for a certain variable value.

---
Tags: configuration
---


# Question
Title: Show menu items with limit access to anonymous users
I have a website that uses Private module in order set the access to the content, and of course some of my pages have menu items. Now if I set a page to be private, only users with proper permission could see that, which is great and what I wanted.

But I am having a bit of issue with the menu items, they disappear if the content assigned to them are not public (ie the page assigned to them is Private), this is OK but I would like to be able to still show those items in the navigation, so if user clicks on them, it will take them to the login page asking them to enter their details in order to see that particular page.

So basically I would like to change the behavior of the menu items the way that they will always be visible to anonymous and registered members of the website but when you click on them, you will be either able to see the page (if you are logged in) or be redirected to the login page (if anonymous)

I found this solution which is not the best one for me since I have many pages like that so I am looking for a better approach. I have even tried Menu item visibility module but that didn't help either!

How do I achieve this please?

Luca

# Answer
Your problem is quite common.

Here is discussion how to implement such trick in Drupal 6 and 7 and 8: http://drupal.org/node/300607

> Drupal 6 (and 7) removed the ability to display menu items the user doesn't have access to. However, in some cases it is desirable to show a menu item even though the user doesn't have access to the menu item. For example, if you use an authentication mechanism that tries to acquire authentication when a 403 would be displayed, you still want to display the menu item so that users get a chance to provide credentials to log in.

Solution for Drupal 7 can be found here: http://drupal.org/node/300607#comment-4450062

If you prefer ready module - you can download it here https://github.com/systemseed/always\_visible
> 4 votes

# Answer
I had a similar situation where pages had to appear in the menu system, but the content should only appear to logged in users. The final solution was very simple, and continues to work.

Instead on controlling content access, the node template checks if the user is logged in. If so, it displays the content. If not, text appears with links to log in or register.

They are not automatically redirected, so if that is critical then this is not the solution.

The code in a nutshell:

```
<?php
global $user;
if ( $user->uid ) :
print render($content);
// or in some situations, display a view;
else :
print 'Please <a href="/user/login">log in</a> or <a href="/user/register">register</a> etc etc.'
endif;
?>

```
> 1 votes

---
Tags: 7, routes, users
---


title: How to use <front> tag in views?

text:
# Question
Title: How to use <front> tag in views?
I have a site on Drupal 7, where I'm using Views with Multilingual settings. I have 2 languages, Russian and English.

On the front page, I have created a "Latest News" block with Views. Each news item has a link to the full article like the following ones:

* example.com/en/news/1
* example.com/ru/news/1

This block is also shown on some other pages, such "Services - \> Service 1" shown at example.com/en/services/service-1.

The problem is that on my block I use global text to format the output of the latest news; the link is built using the following:

```
<h2><a href="./news/[nid]">[title]</a></h2>

```

It works fine on the front page, but when I'm on the Services page, the news link is similar to example.com/en/services/news/1,which is incorrect; Drupal gives me an error about a not existing page.

Is there a way to reference the front page with any tag I can use in the "Global Text" settings?

# Answer
> 1 votes
You can use php filter, or install Token Filter module and then enable tokens in filter which you use (admin/config/content/formats). Token for front page is \[site:url\] so you should write your link like follow:

```
<h2><a href="[site:url]news/[nid]">[title]</a></h2>

```

---
Tags: views
---


# Question
Title: Wildcard Loader function called multiple times (_load)
I have a loader function which is called excessively whenever the user accesses the page. Naturally, I only need it to run once per page request, instead, it is called multiple times. Earlier the \_load() ran only twice with MENU\_CALLBACK, then I tested it with the default MENU\_NORMAL\_ITEM and it increased to four. Although I've changed it back, and cleared my cache, it still runs four times now, and I only want it to run once.

My question is, why is my loader function being called multiple times? Any insight would be greatly appreciated.

```
$items['daycare/%isValid/home'] = array(
    'title' => 'Daycare Admin Home',
    'page callback' => 'daycares_home_page',
    'load arguments' => array(0),//Passes 1st part of url 'daycare' as 2nd arg
    'page arguments' => array(0),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

function isValid_load($pageID, $pageType){
    /*Do stuff to validate wildcard part of URL. Will throw 404/403 if invalid*/
    return $pageId;
}

```

# Answer
> 5 votes
There's an issue for this. It looks like you have to implement caching in your loader.

I was curious and tried it out on `admin/structure/types/manage/%node_type`. I grepped for `node_type_load` and nothing seemed to be calling it directly, so I put a `ddebug_backtrace()` in the load function. I got 13 traces when visiting that path! 10 of these came from menu\_local\_tasks() which loops through the local tasks and calls `_menu_translate()` which calls `_menu_load_objects()` for each router item. The other two extra calls came via `menu_set_active_trail()` which also called `_menu_translate()`. So I guess it depends on your menu structure how many times a loader might be called. As far as I can tell the object's loaded only to check whether or not it can be (access is denied if it can't). I guess this just reinforces Damien's comment about implementing static caching in your loader.

# Answer
> 0 votes
You can manually implement static yourself:

```
function isValid_load($pageID, $pageType){
    static $page;
    if (!isset($page)) {
      // Do expensive stuff here. If you set $page to FALSE it will cause a
      // 404 error when someone tries to call the page.
    }
    return $page;
}

```

This way your expensive stuff will only run once per pageload.

---
Tags: 7, nodes, routes
---


# Question
Title: hook_form_alter() and hook_nodeapi() to alter fields and insert additional data on insert
I have the code below, and I want to update the fields on my node using `hook_nodeapi()`. How do I set the fields on insert?

```
/*
 * Implements hook_form_alter().
 */

function feature_contact_form_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'contact_form_node_form') {
    $form['field_user_agent']['#type'] = 'hidden';
    $form['field_ip_address']['#type'] = 'hidden';
    $form['buttons']['submit']['#weight'] = 1;
  }
}

/*
 * Implements hook_nodeapi().
 */
function feature_contact_form_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($node->type == 'contact_form') {
    if ($op == 'insert') {
      function getRealIpAddr() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
          $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
          $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else {
          $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
      }

      $ipaddress = getRealIpAddr($ip);
      $node->field_user_agent = array($ipaddress);
      $node->field_ip_address = array($_SERVER['HTTP_USER_AGENT']);
    }
  }
}

```

# Answer
As mentioned in the comments any extra fields you add to to a node form won't automatically be persisted to the database, the node module only takes care of the fields that it knows about.

Traditionally there are 2 options:

1. Use CCK instead and add fields to the node that way. Then you don't need to take care of data storage/loading yourself.
2. Add your own table for data storage using `hook_schema()`, making sure you have a column for `nid` (node id). Then in `hook_nodeapi()` use the `insert` and `update` ops to run a `db_query()` to insert/update the data in that table for the current node.

Then you just need to load that data back from the DB on to the `$node` object in the `load` op of `hook_nodeapi()`. Your data will then be available at `$node->field_name` when you have a node object loaded with `node_load()`.
> 2 votes

---
Tags: 6, hooks
---


title: Do You Implement hook_help()?

text:
# Question
Title: Do You Implement hook_help()?
How should I implement hook\_help()? Should I output the content of the README.txt file, or inline text?

# Answer
I think this really depends on what you need.

For page specific help, returning translated text does appear to be the norm from the modules I have surveyed, and does follow the Help text standard (for core and contrib).

For the text on the admin/help page, I think that using the README.txt is best, since that should really be a "one-stop-shop" for help with the module, and you don't want to have to track your changes in two places. It is also a pain to format that much text with code. However, this does make translation hard.

I have not seen a "standard" way to handle the README.txt. If you look at the Module documentation guidelines, they give this example for Drupal 6:

```
function mymodule_help($path, $arg) {
  switch ($path) {
    case 'admin/help#mymodule':
      // Return a line-break version of the module README.txt
      return filter_filter('process', 1, NULL, file_get_contents( dirname(__FILE__) . "/README.txt") );
  }
}

```

and there is a comment for a Drupal 7 version:

```
function mymodule_help($path, $arg) {
  switch ($path) {
    case 'admin/help#mymodule':
      // Return a line-break version of the module README.txt
      return check_markup(file_get_contents( dirname(__FILE__) . "/README.txt") );
  }
}

```

Personally, the version I like what Features does:

```
function features_help($path, $arg) {
  switch ($path) {
    case 'admin/help#features':
      $output = file_get_contents(drupal_get_path('module', 'features') .'/README.txt');
      return module_exists('markdown') ? filter_xss_admin(module_invoke('markdown', 'filter', 'process', 0, -1, $output)) : '<pre>'. check_plain($output) .'</pre>';
    // ...
  }
}

```
> 9 votes

# Answer
I prefer inline text, because it's really hard to parse README.txt if you want to show different help for different paths.

```
function hook_help($path, $arg) {
  switch ($path) {
    case 'admin/help':
      return 'Hello Admin!';

    case 'admin/structure/block':
      return 'Hello Block!';
  }
}

```
> 0 votes

---
Tags: hooks
---


# Question
Title: Countdown Timer Field cannot find Countdown Timer Library - even though it's there
I'm facing trouble with the enabling of the "Countdown Timer Field" module from within "Administrator" -\> "Modules" -\> Fields. The error message I get is

> "The jQuery Countdown Timer Library could not be found. Please download it, install it in a libraries directory, and rename the directory to jquery-countdown. The library should be available at a path like sites/all/libraries/jquery-countdown/assets/countdown/jquery.countdown.js (Currently using jQuery Countdown Timer Library Not found)".

This doesn't really make sense to me, since I unzipped the JQuery in the correct location (I think.)

This is part of the "JQuery Coundown" module, version 7.x-1.0-alpha1. My end goal is to use Views on a field with a Countdown.

This is my directory structure:

```
root@brian-VirtualBox:/var/www/drupal/sites/all/libraries/jquery-countdown/assets/countdown# ls -laSh
total 16K
drwx------ 2 root root 4.0K Dec 30  2011 .
drwx------ 6 root root 4.0K Dec 30  2011 ..
-rwx------ 1 root root 3.0K Dec 29  2011 jquery.countdown.js
-rwx------ 1 root root 1.7K Dec 29  2011 jquery.countdown.css
root@brian-VirtualBox:/var/www/drupal/sites/all/libraries/jquery-countdown/assets/countdown#

```

Opening up index.html located in /var/www/drupal/sites/all/libraries/jquery-countdown/index.html works on my browser.

This looks like a permissions error.

```
root@brian-VirtualBox:/var/www/drupal/sites/all/libraries# chmod -R 777 jquery-countdown/

```

Then, the module will install correctly. However, I do **NOT** think 777 is a good permission to use on this, so I'm continuing to read about Drupal 7 Libraries, and what permissions should be used. It looks like the .zip I unziped did not preserve the correct file permissions for jquery-countdown.

More specifically, my question has now become, what should the permissions be for directories in sites/all/libraries for Libraries 7.x-20?

# Answer
> 0 votes
The permissions were wrong after unzipping. They should have been:

```
 drwxr-xr-x 4 www-data www-data

```

which can be accomplished by:

```
 chmod 755 -R jquery-countdown/

```

---
Tags: entities
---


title: How to add new values to a custom field

text:
# Question
Title: How to add new values to a custom field
I can't seem to find the answer to this anywhere.

Programmatically, I need to add new values to a custom field of a new node instance I just created via API. I am taking input via a form and want to add that data to the custom field in the new node. I know the columns of the custom field.

How can I do that, or where is a good reference?

(the custom field type is address, if that matters)

# Answer
> 1 votes
If you are using a custom form which is invoked by a menu callback, you could try this.

Assuming that you have a postal address field type (provided by the addressfield module) which as 5 sub-fields - country, address 1, address 2, city and postal code in your content type.

```
/**
 * This will be invokded by a menu callback
*/
function yourmodule_custom_form($form, &$form_state){

    /* your form elements definition here */

    $form['#validate'][] = 'yourmodule_custom_form_validate';
    $form['#submit'][] = 'yourmodule_custom_form_submit';

    return $form;
}
/**
 * Validation attached to the form
*/
function yourmodule_custom_form_validate($form, &$form_state){
    // do validation here
}
/**
 * Submit handler attached to the form
*/
function yourmodule_custom_form_submit($form, &$form_state){
    global $user;
    $values = $form_state['values'];

    # Create a node object, and add node properties.
    $node = new stdClass();
    $node->type = 'your_content_type';
    $node->uid = $user->uid;
    $node->created = strtotime("now");
    $node->changed = strtotime("now");
    $node->status = 1;
    $node->comment = 0;
    $node->promote = 0;
    $node->moderate = 0;
    $node->sticky = 0;
    $node->language = LANGUAGE_NONE;

    $field_address = $values['field_address'][LANGUAGE_NONE][0];

    $node->field_address_country = $field_address['country'];
    $node->field_address_thoroughfare = $field_address['thoroughfare'];
    $node->field_address_premise = $field_address['premise'];
    $node->field_address_locality = $field_address['locality'];
    $node->field_address_postal_code = $field_address['postal_code'];

    node_object_prepare($node);
    # Save the node.
    # The node will also get published, if $node->status was set to 1.
    node_save($node);
    $nid = $node->nid;
    # if you want to redirect to a page after submission, use this
    $form_state['redirect'] = 'path/to/redirect';
    drupal_redirect_form($form_state);
}

```

I did not test the code. It is just for example. You may need to amend it by yourself. You can inspect your address field name by printing out `$form`.

```
dpm($form); // if you have devel module enabled
echo '<pre>'; print_r($form); echo '</pre>'; // if you don't have devel moduel

```

Also note that when you create a new field, Drupal creates two new tables starting with **field\_data\_field** and **field\_revision\_field**. If you name the field "address", you will see two new tables **field\_data\_field\_address** and **field\_revision\_field\_address**, you could look up into those tables.

# Answer
> 0 votes
Sithu, thanks for your help. That worked. In the end, Drupal made it easier than I was thinking it would be. I'll post my code and do a walk-through when I get some time.

---
Tags: 7, entities
---


# Question
Title: What hook runs on all filtered input text of all filter types?
This is one of those, "Looked everywhere in the API for a hook, can't find it" questions. There must be a hook like I'm looking for, but none of my searches have found anything.

I'm looking for a simple hook in D7 that lets me edit text filtered content, after it's gone through a text input filter, before it's saved: regardless of which input filter, and regardless of entity type (i.e. not just nodes).

I can't find a suitable hook. The new-style `hook_filter()` alternative `hook_filter_info()` isn't suitable because I want this code to run on all input filters, so I don't want to define a new one.

`hook_node_save()` is too specific. I could maybe hook on `hook_entity_presave()` then load field info, then look through all fields looking for fields that are longtext fields, then act on those, but I'm hoping there's something more direct. That sounds like a lot of extra work for something simple. I'd prefer not to have every single entity save load all the field info and check every field (unless there's a very low-overheads way to do that).

What's the simplest, cleanest way to get code to run on all text that has gone through an input filter, regardless of the input filter?

# Answer
> 3 votes
Here's my best clunky workaround so far:

```
  <?php
  function mymodule_entity_presave($entity, $type) {
  $fields = field_info_fields();
  foreach($fields as $field) {
    if ($field['type'] == "text_long" || $field['type'] == "text_with_summary") {
      if( isset($entity->{$field['field_name']}) ){
        foreach ($entity->{$field['field_name']} as $langcode => $items) {
          foreach ($items as $delta => $item) {
            $value =&$entity->{$field['field_name']}[$langcode][$delta]['value'];
            $value = _mymodule_do_stuff( $value );

            if ($field['type'] == "text_with_summary") {
              $summary =&$entity->{$field['field_name']}[$langcode][$delta]['summary'];
              $summary = _mymodule_do_stuff( $summary );

            }
          }
        }
      }
    }
  }
}

```

Not ideal at all, but I think it beats the only non-core-hacking alternative I can see which is to use `hook_field_attach_presave();`. The code would be almost identical, and I believe it would be worse since we'd have to call and loop through field\_info\_fields() once for every field on every saved entity (instead of once for every saved entity).

# Answer
> 1 votes
Other than clunky workarounds like the one you've suggested, I can't see a way to do it without patching the core filter module. It's the `check_markup()` function which is ultimately responsible for running the filters against the text, round about line 757 of filter.module:

```
// Perform filtering.
foreach ($filters as $name => $filter) {
  if ($filter->status && isset($filter_info[$name]['process callback']) && function_exists($filter_info[$name]['process callback'])) {
    $function = $filter_info[$name]['process callback'];
    $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
  }
}

```

The only thing the function does after that is cache the text if necessary and return, so between that and no hooks being invoked inside the loop I think you're out of luck.

If you go down the route of patching the module (with extreme caution and a backup plan of course) it wouldn't take much, just few lines like

```
foreach (module_implements('filter_text_process') as $module_name) {
  $function = $module_name . '_filter_text_process';
  $text = $function($text, $name, $filter);
}

```

in the filter loop should do it. It's basically just adding a new hook that your module can implement like so:

```
function MYMODULE_filter_text_process($text, $filter_name, $filter) {
  return do_something_to($text);
}

```

Patching core is obviously never desirable, but sometimes unavoidable when the alternative is taking a performance hit like the one you've described and the original code wasn't designed for the purpose you need.

---
Tags: 7, hooks, input-formats
---


# Question
Title: Keep file download list of each authenticated users
I have a content type "Application" and each "Application" content has a downloadable file.

I'd like to keep the downloaded file list, actually node list, & count for each authenticated users.

Is there any ready-made module provided for this feature ? Or How can I achieve it by programming ?

# Answer
The Download Count module may be useful. The module page says

> The download\_count module tracks downloads of private files attached to nodes via the core upload or contributed filefield modules for d6 and private core file fields for d7.

But it has only development version for D7.
> 0 votes

---
Tags: users, files
---


title: Edit a node via code authentication

text:
# Question
Title: Edit a node via code authentication
I'm creating a website and I have to give the possibility for an anonymous user to update a node. The node is recognized through the use of a code, code that I am sending to the user when the node is saved for the first time. And when I save this node (for the first time), the node is modified to ensure that it is owned by user X and not by anonymous. Ok, is a little complicated, but these are the requests from my client.

So, I send to the user a mail with this line into: http://DOMINIO.EXT/node/123/edit/codeSHA1.

My problem is that Drupal obviously tells me that access is denied to perform the edit operation (node uid is X, but I'm uid 0) when I click onto that link (in my email client).

How can I resolve this "problem"? I don't want to install TAC or TACLITE, but I can write PHP code into one of my custom module.

# Answer
Here is a solution using custom coding.

1. Store all hash codes that are the access code to the DB (I think you do this already), a word of caution do not do md5(node id) or sha1(node id) as anyone will be able to figure it out.
2. Enable anonymous users to edit the content type they are submitting where the code is needed to edit the node. I know what this mean, keep reading.
3. Create a custom module where you are going to use the NODE API to intercept the node edit step.

**If Drupal 6:** http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook\_nodeapi/6

```
function YOUR-MODULE-NAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'prepare':

    // Add PHP Code here to validate the hash code
    // You can use an if/else condition to print an access denied message
    // if the code is not valid or expired

    break;
  }
}

```

**If Drupal 7:** http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_prepare/7

```
function YOUR-MODULE-NAME_node_prepare($node) {
    // Add PHP Code here to validate the hash code
    // You can use an if/else condition to print an access denied message
    // if the code is not valid or expired
}

```

And that is all.
> 2 votes

# Answer
You just need to change the access callback for node/%node/edit with the one you implement in your custom module.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['node/%node/edit'])) {
    $args = !empty($items['node/%node/edit']['access arguments']) ? $items['node/%node/edit']['access arguments'] : array();
    $old_callback = $items['node/%node/edit']['access callback'];
    $items['node/%node/edit']['access callback'] = 'mymodule_node_access';
    array_push($args, $old_callback);
    array_push($args, 4);
    $items['node/%node/edit']['access arguments'] = $args;
  }
}

function mymodyle_node_access() {
  $args = func_get_args();
  $sha1 = array_pop($args);
  $old_callback = array_pop($args);

  if (!empty($sha1)) {
    // The SHA1 value was passed in the URL.
  }
  else {
    // The user is accessing the edit form without SHA1; let the other callback decide
    // who can access the node edit form.
    return call_user_func_array($old_callback, $args);
  }
}

```

The code is written as it is to be able to call the previously set access callback without to make any assumption about which callback it is, and how many arguments it requires.
`mymodule_node_access()` must return `TRUE` when the user has access to the node edit form; in your case, the access callback needs to verify the SHA1 value is correct, and return `TRUE` just in that case.
> 0 votes

---
Tags: 7
---


# Question
Title: Inserting a form into a block in Drupal doesn't work
I am creating block module in Drupal 7.

In the body of block I want to put the form which will restripe the data of table in forms.

I have created block as shown below but it doesn't showing the form.

```
<?php
/**
 * @file
 *  This is module file which display the links on the welcome page.
 *  This module will create a block of the link which is to be displayed on the welcome page.
 */

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function welcomepage_links_block_info() {
  $blocks['user-filter-ajax'] = array(
        'info' => t('User Filter'),
        'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function welcomepage_links_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'user-filter-ajax':
        $block['subject'] = t('User Filter');
        $block['content'] = drupal_get_form('restripe_command_example_fieldset');
        break;
   }
  return $block;
}

function welcomepage_links_form() {
    $form = array();
    $form['restripe_command_example_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t("Demonstrates the Ajax 'restripe' command.")
);
    $form['restripe_command_example_fieldset']['restripe_num_rows'] = array(
            '#type' => 'select',
            '#default_value' => !empty($form_state['values']['restripe_num_rows']) ? $form_state['values']['restripe_num_rows'] : 1,
            '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
            '#ajax' => array(
                    'callback' => 'user_filter_ajax_restripe_num_rows',
                    'method' => 'replace',
                    'wrapper' => 'restripe_table',
            ),
    );
    $form['restripe_command_example_fieldset']['restripe_restripe'] = array(
            '#type' => 'submit',
            '#value' => t("Restripe the table"),
            '#ajax' => array(
                    'callback' => 'ajax_example_advanced_commands_restripe_callback',
            ),
            '#suffix' => "<div id='restripe_div'>
            <table id='restripe_table' style='border: 1px solid black' >
            <tr id='table-first'><td>first row</td></tr>
            </table>
            </div>
            <div id='restripe_status'>'Restripe' Command Status: Unknown</div>",
    );
    return $form;
}

```

# Answer
Got it.

There was error in my programming. This is how i fixed it.

```
<?php
/**
 * @file
 *  This is module file which display the links on the welcome page.
 *  This module will create a block of the link which is to be displayed on the welcome page.
 */

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function welcomepage_links_block_info() {
  $blocks['user-filter-ajax'] = array(
        'info' => t('User Filter'),
        'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function welcomepage_links_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'user-filter-ajax':
        $block['subject'] = t('User Filter');
        $block['content'] = drupal_get_form('welcomepage_links_form'); /**Problem was here**/
        break;
   }
  return $block;
}

function welcomepage_links_form() {
    $form = array();
    $form['restripe_command_example_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t("Demonstrates the Ajax 'restripe' command.")
);
    $form['restripe_command_example_fieldset']['restripe_num_rows'] = array(
            '#type' => 'select',
            '#default_value' => !empty($form_state['values']['restripe_num_rows']) ? $form_state['values']['restripe_num_rows'] : 1,
            '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
            '#ajax' => array(
                    'callback' => 'user_filter_ajax_restripe_num_rows',
                    'method' => 'replace',
                    'wrapper' => 'restripe_table',
            ),
    );
    $form['restripe_command_example_fieldset']['restripe_restripe'] = array(
            '#type' => 'submit',
            '#value' => t("Restripe the table"),
            '#ajax' => array(
                    'callback' => 'ajax_example_advanced_commands_restripe_callback',
            ),
            '#suffix' => "<div id='restripe_div'>
            <table id='restripe_table' style='border: 1px solid black' >
            <tr id='table-first'><td>first row</td></tr>
            </table>
            </div>
            <div id='restripe_status'>'Restripe' Command Status: Unknown</div>",
    );
    return $form;
}

```
> 0 votes

---
Tags: forms, blocks
---


title: Change Drupal URL

text:
# Question
Title: Change Drupal URL
I use cpanel and ftp (filezila)

I don't know much about drupal. I believe i am using v.6

I have an old website made in drupal: www.oldwebsite.com

I don't want to delete my oldwebsite but change to www.oldwebsite.com/drupal So I have then www.oldwebsite.com free to put whatever.

Easy?

How and where do i acess the files to change such a thing? thanks!

# Answer
> 4 votes
I believe in order to switch Drupal from using no sub directory to instead use on, you only need to:

1. Copy all of the files into the sub directory e.g. /drupal. This can be done with FTP (or SSH)
2. Edit the file .htaccess and uncomment the line 103(`RewriteBase /drupal`). Make sure the rewrite base is the same as the name you gave your subfolder above
3. Optional extra, ensure all your content is linked correctly as any hard coded links in content are will now no longer work, or better yet, use a module like pathologic to ensure links never break

---
Tags: uri, files
---


title: Restrict Specific Nodes to Roles

text:
# Question
Title: Restrict Specific Nodes to Roles
I been using Drupal for a while, but I am completely in the dark when it comes to Roles, permissions, etc.

What I want to do is have all my content types, but I want to restrict certain nodes for certain roles. Does anybody know any modules or if the core can do this? The reason why I am doing this is to share with a specific group of people on my site.

Thanks!

# Answer
> 1 votes
You can use the Content Access module to achieve this.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

---
Tags: nodes, users
---


title: Customized Search Results Page

text:
# Question
Title: Customized Search Results Page
I'm seeking some help to better understand how to go about creating a custom search results page. I've created search views and facetted search, but they really aren't what we are needing. We are consolidating 4 indexes into one streamlined Drupal account and are needing our search to display results grouped by content type (basic filtering)...we were able to do this in search api (views) but we are also needing to display certain content a specific way. For instance, images should have a thumbnail with no title. Other pieces of content should just list the title name. Here is an example of the search we're trying to replicate: http://www.retrometrookc.org/. (Search for, e.g., *belle isle*.)

In theory this seems really simple but I can't seem to wrap my head around it. If anyone has any suggestions or recommendation, I really would appreciate it!

# Answer
> 2 votes
It sounds like you are almost there but without writing custom templates for each content type I would look at display suite. That way, when you click manage display for each different content type you can choose "custom display settings" and then "search result". This will let you build a different layout for each different content type as a search result (and if you like eventually build your own template files easily based on display suites templates).

Then you go back to your view and choose "Show: Display Suite -\> Search Result" and each result will be shown as you have set up in the manage display screen for that type. You can still use all the filters and sorts as you like.

# Answer
> 1 votes
Try this

```
<?php
/**
 * Format the result page of a search query.
 *
 * Modules may implement hook_search_page() in order to override this default
 * function to display search results. In that case it is expected they provide
 * their own themeable functions.
 *
 * @param $results
 *   All search result as returned by hook_search().
 * @param $type
 *   The type of item found, such as "user" or "node".
 *
 * @ingroup themeable
 */
function theme_search_page($results, $type) {
  $output = '<dl class="search-results">';

  foreach ($results as $entry) {
    $output .= theme('search_item', $entry, $type);
  }
  $output .= '</dl>';
  $output .= theme('pager', NULL, 10, 0);

  return $output;
}
?>

```

Read more here

---
Tags: search
---


title: template.php breadcrumb function

text:
# Question
Title: template.php breadcrumb function
I'm trying to change the breadcrumb in Drupal to display in Danish through the template.php in my theme, but I cannot change it. I've flushed the cache.

This is what I've put in the template.php.

```
  function modeindeks_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];

    if (!empty($breadcrumb)) {
      // Provide a navigational heading to give context for breadcrumb links to
      // screen-reader users. Make the heading invisible with .element-invisible.
      $output = '<h2 class="polle">' . t('Du er her') . '</h2>';

      $output .= '<div class="breadcrumb">' . implode(' › ', $breadcrumb) . '</div>';
      return $output;
     }
    }

```

# Answer
> 1 votes
Breadcrumb is made up of an array. So to add any element in the breadcrumb you have to give the offset.

So if you want to set `t('Du er her')` in place of the front page link then you should try this:

```
$breadcrumb[0] = l(t('Du er her'), 'front');

```

To know the exact position of element which do you want to add, you can use `var_dump($breadcrumb)`.

I would rewrite the code as follows.

```
function modeindeks_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    // Instead of front, you can use the URL of your site's front page.
    $breadcrumb[0] = l(t('Du er her'), 'front');

    $output .= '<div class="breadcrumb">' . implode(' › ', $breadcrumb) . '</div>';

    return $output;
  }
}

```

If you want to add only **You are here** link then use the below code.

```
function modeindeks_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '<div class="breadcrumb">You are here: ' . implode(' › ', $breadcrumb) . '</div>';
  }
}

```

---
Tags: theming
---