# Question
Title: Show a menu block only on nodes that belongs to this menu
I am trying to accomplish something similar to the book navigation module.

Say I create a block containing a menu. I want this block to become visible for nodes that *belong* to this menu.

So if **NodeA** belongs to the menu "**My SubMenu 1**", which is included in a block called "**My Submenu 1 Block**", I want this block to appear everytime NodeA comes up.

This could be accomplished with some pathauto tricks, or assigning a certain taxonomy term to all nodes of "My Submenu 1". But I realise this is redundunt, there is no need to force the user to create content with specific terms--the information is all there in menu--\>node connection.

# Answer
Take a peek at http://drupal.org/project/menu\_block. I think it might do what you want, or, if not, at least maybe its code might give you an idea on how to do so yourself.
> 6 votes

# Answer
Context module does exactly this. If you chose a "menu" condition, it will allow you to show blocks, menus, etc only for content that is listed in the menu.
> 0 votes

---
Tags: routes, blocks
---


# Question
Title: How to import an addressfield with Feeds?
Using Drupal 7.10 with Feeds 7.x-2.0-alpha4. I'm trying to create a feeds importer to import node data stored in a csv file. On the screen where you setup the mappings, my addressfield (that is part of my content type) doesn't appear in the drop down list of targets (whereas other fields of my content type do).

How can I get this to work?

I see some issues for this but being a Drupal newbie I can't really understand how to get this to work:

Mapping Address Fields using Feeds and Feeds JSONPath Parser

Mapper for Feeds importers

Do I need to switch to using the Dev release of feeds?

# Answer
Following the links you posted, it looks like it's all wrapped up. Yes, try the current dev releases for Feeds.
> 1 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: Call multiple hook inserts from different modules?
Is it possible for two modules that interact with one another to both call `hook_insert()`?

* I have a node type that calls `ModuleA_insert()` when the user hits the 'save' button.
* Module B is a custom comment-like module that gets injected into a form. In module B, I have a `ModuleB_insert()`, but it never runs.
* I am trying to keep module A from having to deal with the inserts/updates from module B.

I can get module B to insert by using `hook_nodeapi()`, but it would be easier if I could get `hook_insert()` to work, meaning module A and module B's data and actions are separated from each other - not to mention the overhead cost of having `hook_nodeapi()` run and check every time.

# Answer
> 1 votes
Rule of thumb: Don't call hook\_anything() in other modules. :-)

If you call `node_save($yourNode)` then the node API will invoke `hook_insert()` in the module that implements that node type, if the node is being inserted. Otherwise `hook_update()` gets called for updates.

If you need to act on an insert for any type of node, and it sounds like you do, then you want to implement `hook_nodeapi()`.

Examples has a node project and a nodeAPI project, so you can figure out which you need.

---
Tags: 6, hooks, nodes
---


# Question
Title: Convert timezone value from seconds to W3C hour format
Doing an API integration that requires timezones to be handed off in W3C format, while Drupal opts to store timezones in seconds.

Wondering what the clean way to do this is, rather than stripping the +/- sign, dividing by 3600 and adding it back on. There has to be a date transformation right?

FYI... W3C looks like this: `-08:00` and Drupal looks like this: `-28800`

Trying to avoid this code...

```
// $val = '-28800';
$sec = substr($val, 1);
$hours = intval(intval($sec) / 3600);
$minutes = intval(($sec / 60) % 60);
$w3cTZ = substr($val, 0, 1) .
  str_pad($hours, 2, "0", STR_PAD_LEFT) .":".
  str_pad($minutes, 2, "0", STR_PAD_LEFT);

```

# Answer
Ended up this this function...

```
// Convert timezone from second in Drupal to WC3 standard
function timezoneConvert($val, $toSeconds = false) {
  if(!$toSeconds) {
    // Starts like: "-28800" and becomes: "-08:00"
    $sec = substr($val, 1);
    $hours = intval(intval($sec) / 3600);
    $minutes = intval(($sec / 60) % 60);
    $w3cTZ = substr($val, 0, 1) .
      str_pad($hours, 2, "0", STR_PAD_LEFT) .":".
      str_pad($minutes, 2, "0", STR_PAD_LEFT);
    return $w3cTZ;
  }
  else {
    $seconds = 0;
    $units = explode(':',$val,2);
    $seconds += $units[0] * 3600; // Hours
    $seconds += $units[1] * 60; // Minutes
    return $seconds;
  }
}

```
> 1 votes

---
Tags: datetime
---


# Question
Title: Create dependent dropdown in views exposed filter
I've created a view of users. It includes two exposed filters as drop downs to filter the list. One is for the city and the other for the squadron. The squadron drop down is related to the cities as cities is a taxonomy vocabulary that gets added to squadrons. I would like to find out if it is possible, that when someone selects a city, to automatically filter the squadron drop down filter by that term.

I did this in a form for creating squadrons using ajax (node/add - with help here: see Dynamic select list in the form (dependent dropdown)) but don't know how to do it (or if it is possible to do) in a view exposed filter.

Many thanks in advance

(edit: I'm using D7 and Views 3)

# Answer
> -1 votes
I haven't check but

```
{
  $form['computer_stats']['os'] = array(
    '#title' => t('Operating system'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('', t('OSX'), t('Linux'), t('Windows'))),
    '#ajax' => array(
      'callback' => 'input_os_verify_ajax_callback',
      'wrapper' => 'input_os_verify_wrapper',
     ),
  );

  // Setting an empty element with a wrapper to be populated.
  $form['computer_stats']['os_verify'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="input_os_verify_wrapper">',
    '#suffix' => '</div>',
  );

  // When submitted, check for value of OS, and populate os_verify.
  if (isset($form_state['values']['os'])) { // Fixed this line, was throwing an error in the original video code.
    $form['computer_stats']['os_verify']['#type'] = 'checkbox';
    $form['computer_stats']['os_verify']['#title'] = t('Are you sure you are using @os?', array('@os' => $form_state['values']['os']));
  }

  ...
}

function input_os_verify_ajax_callback($form, $form_state) {
  return $form['computer_stats']['os_verify'];
}

```

from How to Build Beautiful Forms in Drupal 7 (Video Presentation) might help

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


title: Which database schema should I use?

text:
# Question
Title: Which database schema should I use?
I want to create a custom voting module to learn how to write a module. The vote table will contain four fields (id, title, vote\_up, vote\_down).
Should I create a new table? If I create a new database table, how do I keep the relationship with the node being voted?

# Answer
If you want to create a voting module you should look into Voting API, it's an API module that offers common functions and database storage for voting modules to use.

However, since this is a learning excercise, you might want to do it all yourself, in this case:

* Use hook\_schema() to define your database schema (the example on the documentation page is pretty self-explanatory!)
* In Drupal 6 you need to manually specify which schema to install so implement hook\_install() and hook\_uninstall():

```
function mymodule_install() {
  drupal_install_schema('mymodule');
}

function mymodule_uninstall() {
  drupal_uninstall_schema('mymodule');
}

```

An example of a hook\_schema might look like this:

```
/**
 * Implementation of hook_schema()
 */
  function mymodule_schema() {
    $schema['mymodule_votes'] = array(
      'description' => 'Your schema',
      'fields' => array(
        'vid' => array(
          'description' => 'vote id',
          'type'        => 'serial',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'nid' => array(
          'description' => 'node id',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'vote_up' => array(
          'description' => 'number of votes up',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
        'vote_down' => array(
          'description' => 'number of votes down',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
      ),
      'primary key'     => array('vid'),
      'indexes'         => array('node id' => array('nid'))
    );
    return $schema;
  }

```
> 4 votes

# Answer
Examples has a NodeAPI example that implements a five-star vote on nodes.

For a D7 version, you'd want to deal with entities instead, but it's a working example of how you might set up a schema for voting, based on your needs.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to pass multiple objects to hook_view()?
I want my `hook_view($node)` to display not only the `$node`, but other fancy stuff too - like a table on the bottom using a while-statement. How can I do this?

I am only able to pass one object to `hook_view()` so I am limited to one object for output? For example:

```
function Mymodule_load($node) {
  $sql = "SELECT colors FROM ctable,node WHERE ctable.nid=node.nid";
  //returns lots of color (e.g. blue, red, green, pink)
  $result = db_query($sql);
  //here's where I am stuck!
  while($row = db_fetch_object($result)) {
    return $row;  //oh noes! $row keeps getting overwritten
                  //and all my colors aren't being passed to hook_view
  }
}

function Mymodule_view($node,$teaser=false,$page=false) {
  node_prepare($node,$teaser);
  $node->content['colors'] = array(
    // only can display ONE color.
    '#value' => $node->colors
  )
  return $node;
}

```

The above code returns only ONE color whereas I want ALL my colors to be passed to `hook_view()`.

THE SOLUTION:

```
while($row = db_fetch_object($result)) {
  $colors[] = $row->colors;
}
$node->colors = $colors;
return $node;

```

# Answer
> 0 votes
`hook_load()` gives you the node that was just loaded. The reason it gives you the node is so that you can modify it. So you'd do something like $node-\>myModule\['colors'\] = array ( some colors here... ); Read up on the API documentation.

See also the API docs for `hook_view()`.

If you move on to Drupal 7, you can do all this stuff as fields. :-)

---
Tags: views, 6, hooks
---


# Question
Title: How to remove <ul><li> tags when printing out Menu
Is there any way to remove HTML list tags when this function is called to access Main Menu?

This code is used in page.tpl.php in for a theme:

```
print theme(
  'links__system_main_menu',
  array(
    'links' => $main_menu,
    'attributes' => array('class' => array('topNavItem')),
  )
);

```

# Answer
Sure, it's pretty easy. But first I think you need to know what's going on here.

Drupal's `theme()` call above is going to look for a `theme_links__system_main_menu()` function/hook and failing that, will look for a `theme_links()` function/hook.

`theme_links()` is in drupal core in `includes/theme.inc` if you want to take a look at it, as that's "who" is putting the ULs and LIs in there. **DONT** just edit that file/function/hook, but create your own in your theme. So, to take them out, or to put *whatever* you want in, you just write your own theme function to do it, and then `theme()` above will call it for you.

Drupal's theme layer is described well here: http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7 and here: http://drupal.org/theme-guide/6-7 and should put you on the path to doing all that.
> 1 votes

---
Tags: routes, theming
---


# Question
Title: Quickly build a Drupal website from another Drupal website
I have an existing website in Drupal, say abc.com, and it's in english. Now I want to quickly build this website for different domains. The layout remains same, but the language and images may change. How can I do this and how quickly can it be done? Should anything be done on the first site so that building the second site becomes easy like profiling or something?

# Answer
> 3 votes
There are several tools available to make this easier. Some benefit greatly from being applied, while some can be added in hindsight without issues.

1. Drush make, allows you keep a file with the definition of which modules, their versions, any patches etc, you need to build your site. This then makes it easy to quickly pull in all the modules again when you need to set up a new site. It also happens to be *very* useful whenever you need a workflow that includes patched modules.
2. Features on the other hand, allows you to take the configuration you make with your modules, such as Views, Panel Pages, Contexts and more, and export it to a module. To some extent, this module requires you to have thought about features from the beginning. Some things, blocks and their settings for example, cannot readily be exported this way, meaning that those will either need to be manually configured after the new site is setup, or be replaced by something. I use Panels content panes in place of blocks, largely for this reason.
3. An Install profile finally allows you to tie number one and two together. In the install profile, you first define dependencies on a few core modules, then on all your features, and finally on any other modules you need, that aren't pulled in by features. Then when you run the install, all of your modules will be enabled automatically. This part can easily be done in hindsight, but then you always end up with some amount of custom work that depends entirely on your site, and can't quite be captured in another way, and needs custom code to run during install. This step has proven to require quite a bit of work when colleagues of mine have attempted this after the site is already built.

This approach can readily be, and should IMO be, applied already when building the site initially, but can also be used afterwards to help cloning a website. Realistically, the second will require more work than the first. It is left as an exercise to the reader to discover other cool benefits of this approach, such as how one can automatically generate demo content and more.

# Answer
> 2 votes
1. Copy your files.
2. Copy the DB, backup & migrate module is very useful here.
3. Adjust settings.php to your new site
4. Install and configure the new language
5. Change the images to your needs.

Done.

# Answer
> 1 votes
Use the Features module:

> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

---
Tags: 7
---


# Question
Title: How to extract an nid from and EntityFieldQuery
I'm trying to figure out if a node already exist, I'm using the following code

```
$query = new EntityFieldQuery;
$result = $query
                      ->entityCondition('entity_type', 'node')
                      ->propertyCondition('type', 'item')
                      ->propertyCondition('title', $full_name)
                      ->execute();

       if (!empty($result['node'])) {
         // do something
       }

```

The problem is this, when a result is returned, the structure of the result is this

```
    Array
    (
        [node] => Array
            (
                [96] => stdClass Object
                    (
                        [nid] => 96
                        [vid] => 96
                        [type] => item
                    )

            )

)

```

I'm trying to get the nid, but I can't figure out how to access it $

```
result['node'][0]

```

does not work. How do I get the nid in this situation

# Answer
> 2 votes
Jimajamma is correct: The question you ask is a PHP one. You want `array_keys($result['node'])`, since the EntityFieldQuery always returns entities as an array of types, with each type having an array of entities keyed by their unique ID.

However... This query won't tell you if the node already exists or not. It will only tell you that there's a node with that title. That might be adequate for your project, however.

# Answer
> 6 votes
```
$nid = current($result['node'])->nid;

```

# Answer
> 0 votes
This appears to be a php question, as basically it looks like you are wanting the first item in your array regardless of its key. In this case that appears to be your nid, or 96. Regardless, you can accomplish this with either of the `array_slice(0,1)` or `array_values()` functions.

---
Tags: nodes, entities, database
---


# Question
Title: Creating custom panel page gives page not found error
I have been striving hard to make this work.I have created a custom panel page with the page url as `taxonomy/term/%term/content-type/how-to.` So i have this via pathauto url `Vocab : Category` `Parent term: food` `Child term : pizza`

After setting up the panel page when i go to `www.example.com/category/food/pizza/content-type/how-to` it gives me `404 error(page not found).`

And when i manually set up a custom panel page for each url(for e.g `www.example.com/category/food/pizza/content-type/how-to`) it is working fine.

Can you guys point out whats wrong with`taxonomy/term/%term/content-type/how-to` url ?

# Answer
The most common and likely reason is that you have not assigned a context to your %term argument. This causes Page manager to reject the term argument, failing to find the path, and finally returning a 404. There's a similar issue here.

I could tell more specifically if you provided an export of the Panel.
> 2 votes

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


title: Module design question

text:
# Question
Title: Module design question
I need to create a module that when visited with some get parameters in the url to be able to create user with specific roles in the database.

So if someone visits mydomain.com/my\_custom\_module/create/john/smith/role\_id/filename\_that\_includes\_hidden\_token\_for\_validation

Will create the user John Smith with a role specified by the id passed and in order not to allow anyone to create users I have a temp txt file with a random generated name where I keep a token

Is that possible? Is there a better way?

Thanks in advance

**EDIT**

Why I want a module like this:

I have a site written in cakePHP and the need for a forum came up. The client heard that drupal's advanced forum is the best solution (I've tried to persuade him to use phpbb with no luck...) but he wants the forum to be private and to give access and roles to existing members from the cakePHP's site admin. So I'll provide him an "give forum access to member" button which will redirect to the url described above after I've created a temp file with a hidden token somewhere in the server for security issues. I don't know if it is the best way to do this.

# Answer
That is no problem. user\_save an hook\_menu will be you're friends.

The file with the random is a good id for security. You could also have a look into the IP Login module.
> 2 votes

---
Tags: 7
---


title: User profile custom style (per user)

text:
# Question
Title: User profile custom style (per user)
Is there a way to theme a user's profile but make it per user instead of globally on all users?

# Answer
> 3 votes
You can use the Drupal theme suggestions to specify templates based on any of the users fields.

I've implemented a theme for each of the different roles on my site for instance:

```
function [theme]_preprocess_user_profile(&$vars) {

foreach($vars['elements']['#account']->roles as $role):

    $vars['theme_hook_suggestions'][] = 'user_profile__'. str_replace(' ','-', $role);

endforeach;

}

```

To do the same with a users name for instance you could do:

```
$vars['theme_hook_suggestions'][] = 'user_profile__'. str_replace(' ','-', $vars['elements']['#account']->name);

```

Then make sure you've got the corresponding theme files inside your theme folder. All underscores are converted by Drupal to dashes so a suggestion of user\_profile\__dave would become user-profile--dave.tpl.php for instance.

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


# Question
Title: How to include a caption (a cck field) in lightbox?
I'm working on a theme i bought and since i'm just learning php i'm having a hard time including a field as a description text in the lightbox once the thumbnail is clicked.

Here's the code (that's in the tpl.php file) that outputs the thumbnails (from a view)

```
<?php
if (isset($fields['field_image']->content) and strpos($fields['field_image']->content, '<img')) {
 print str_replace('<a ', '<a rel="prettyPhoto[gallery]" ', $fields['field_image']->content); ...
?>

```

Here's the html version of the lightbox script :

```
<a href="images/fullscreen/1.jpg" rel="prettyPhoto[gallery]" title="caption."><img ...

```

How can in include the caption tag ?

Thanks !!

# Answer
```
<a title="caption"><img alt="description"></a>

```

Both the caption and the description will be displayed on the image preview.
> 1 votes

---
Tags: 7, theming
---


title: Hide submenu of Revisioning-module

text:
# Question
Title: Hide submenu of Revisioning-module
I would like to hide the items marked in the image. But as it turns out, they aren't stored an Array as we are used to in Drupal (at least as far as I can see).
How can I unset or hide them. Hiding by using CSS isn't an option.

# Answer
I am not sure if you use drupal 6 or 7

You can configure this:

* go to: http:/your.drupal/admin/user/permissions
* CTR + F do search on page and search for this both permissions:
* unpublish current revision
* delete archived revisions

But if also admins should not see this any more, you have to modify code: (here for Drupal 6)

* edit sites/all/modules/revisioning/revisioning\_theme.inc
* search for: unpublish current revision
* 4 rows below you will see: `$links[] = $link;`
* change it to: `// $links[] = $link;`
* now search for: delete archived revisions and do the same
* save and done
> 1 votes

# Answer
For drupal 7 it is the same:

you can configurate it here also for all user http:/your.drupal/admin/people/permissions

> Delete content revisions
>
> Revert content revisions
>
> Publish content revisions (of anyone's content)
>
> Unpublish current revision (of anyone's content)

in code it is in: sites/all/modules/moduleS/revisioning/revisioning\_theme.inc \_revisioning\_generate\_node\_links\_according\_to\_permissions() there you will find serveral lines like:

`$themed_links[] = l(t('Publish'), "node/$nid/revisions/$node->vid/publish");`

to deactivate: place // in front of them, but i would suggest to use the config options if possible.

If you have to sue the code version, use git versioning with a pristine branch, you you will further be able to update the software, withput loosing your changes
> 1 votes

---
Tags: routes
---


title: Filter a view by the URL

text:
# Question
Title: Filter a view by the URL
I’ve a page, called Jobpage, where I’m listing all my members within a specific content type. Then I’ve at the right sidebar a list of geographical locations which each member has entered when signing up. I want my users to filter the Jobpage but instead of getting all the members for that content type, I want only to list the members which have that specific location.

Right now I’ve tried to create the links and filter by that like so:
Normal Jobpage with all members is: www.mydomain.com/jobpage
Filtered Jobpage is: www.mydomain.com/jobpage/Dublin

I’m using Views for my Jobpage and is there any way to “filter” by creating a link URL structure as described and how do I set this up??

Any suggestion or help is very much appreciated.

Sincere
\- Mestika

# Answer
You can use an argument on your view to apply the filter from the URL. If you set the "action to take if argument is not present" to display all values then your standard job page will continue to function as before.

In Drupal 7 arguments are called "contextual filters" and are hidden amongst the "advanced" view options.
> 2 votes

# Answer
There is a module called Node Reference URL widget and it will allow views to take argument from URL and filter content according to that.
> 0 votes

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


# Question
Title: How to send mails to users with bulk operations in drupal7
I want to select some users from a view with the field VBO , and to send to this users an email which cotaining a subject and a body. How can I proceed?

---

Thanks for the response. I'm a new user of drupal and my authenticated user have to send a mail for selected user with VBO, and have to enter the contents of mail. (subject + body). After confirmation the system send to selected users the mail.

# Answer
> 2 votes
You can use Rules module with VBO to extend the operations of VBO. In Rules module, you can select the action to send mails to users with whatever text you want.

---
Tags: 7, emails, views
---


title: Redirect on returning to site

text:
# Question
Title: Redirect on returning to site
In my site when a user logs in he is redirected to the profile page(profile2 module). But when returns to the site(and is already logged in), he is taken to the user account page. How do I override this redirect and see to that he is take to profile page?

UPDATE: The user must be redirected from the site frontpage which contains the user login form

# Answer
You can use Rules module, force user to redirect to whatever page after login. It's very easy to get it done via the Rules UI, try it out. http://drupal.org/project/rules
> 2 votes

---
Tags: 7, redirection
---


title: Let users rank pages

text:
# Question
Title: Let users rank pages
I'd like to let users rank pages (thumbs up/down) and display “most popular” pages in ranked order. What's the best way to do this in Drupal?

# Answer
I recommend the rate module, it seems more stable than the vote up/down.
> 4 votes

# Answer
Socially ranking content is a feature Drupal can provide very well. You will want to use a combination of modules consisting of something like:

* Views (used to build the lists of content and order them by votes / popularity),
* Voting API (a frame work for scoring / aggregation and will be used to record votes)
* Vote up/down (Vote up/down widget for user input on voting). you can even look at something like Fivestar.

Once you have chosen and setup your voting widget on your content you will need to setup some views to display them in lists order by votes. Typically you will create a page view for any landing pages such as a Home Page and a block for displaying in sidebars on content pages. I also use Quicktabs for the Blocks so you can have a nice tabbed interface which lists content by Most recent / Highest Rated / Most viewed etc.

On setting up the actual views you will need to add in fields for what you would like to show in each list. For example on a highest rated you might want the node title and the score for the node as voted for by users. Then you will add in a sort by option for the score so the list is presented in the correct order
> 11 votes

# Answer
One easy way is to use the Flag + Views combo.

You can create custom "flag" for certain content type. For example, you can do something like Google +1 for a content type, which will have two state: +1 and un'+1.

Then you can use Views to add 'flag' to Relationship, make a page/block view of most +1'ed content.
> 2 votes

---
Tags: 7, rating
---


# Question
Title: Is there a module to show a quick message to a user or role?
Is there a module to send a user or users having a role a message like the one that is currently on top of this site (*The Drupal Answers 2012 community moderator election is underway — nominations now being accepted.*")?

I don't need a message box like the one that Private message module provides, but a quick message.

# Answer
> 2 votes
See the User Alert Module. This module provides a simple way to show a short-term urgent message on the website. Think of CNN Breaking News, when they show a short message the top of the site (or the 'Welcome!' style messages at StackExchange websites). This module works for both anonymous and authenticated users by using a cookie, and recording actions in the database. This solves the need to show messages independent of the users authenticated status. With User Alerts, you can: Alert users about breaking news, or a special same-day sale for ecommerce. You can also set expiration timers for alerts (1 hour, 3 hours, Never, etc) (Drupal 6 Only, D7 requires Scheduler).

# Answer
> 1 votes
Not necessarily a module, but VIEWS could be used to do something very similar. Create a content type, say "motd," and to get fancy, put in a date field. Then create a view with a block display, filtering on node type motd and the date field equal to today, and displaying the body of the node, then put that block where you want your message of the day to go...

---
Tags: 7
---


title: including forms in hook_view

text:
# Question
Title: including forms in hook_view
Is it possible to include forms and have it be submitted when viewing a node type? A good example is the default 'Add Comment' module. When you view a node, there is a link you need to click on to leave a comment. This link essentially takes you to the comment form. Is there any way to do like Youtube.com where you can have the comment form textarea box in the node view? It just seems silly to have to make your users click a link to 'add comment'.

For example, the below does nothing in my custom module when viewing a node:

```
function Mymod_view($node,$teaser=false,$page=false) {
  $node->content['name'] = array(
    '#type' = 'textfield',
  );
  // hitting submit does nothing. NOTHING!
  $node->content['submit'] = array(
    '#type' => 'submit',
    '#value' => 'SUBMIT',
  );
  return $node;
}

```

# Answer
> 1 votes
You can create forms everywhere you want.

Your code adds form elements without a surrounding element. That makes it useless.

Define your form in a separate function and call `drupal_get_form('your function name')` to make it working. See the form generation doc for a full description.

---
Tags: 6, hooks, forms
---


# Question
Title: use drupal_add_js for file outside drupal dir
I would like to add a js file thats outside my drupal installation dir, but keep it relative to that dir.

```
mysite
  |-- drupal
  |-- dirWithJsFile
      |-- thisfile.js

```

i have already tried things like

```
/../dirWithJsFile/thisfile.js
../dirWithJsFile/thisfile.js

```

but add\_js seems not be able to go outside the drupal dir or is there an option i must set?

# Answer
> 0 votes
The javascript file you want to add is not inside your drupal installation so you need to add it the same way you would do it with an external file:

```
drupal_add_js('http://yourdomain.com/dirWithJsFile/thisfile.js', 'external');

```

See drupal\_add\_js for more informations.

# Answer
> 0 votes
In D6, no dice, but in D7, you could fudge it with setting $options to external and then using the full sitename and path to the file.

---
Tags: javascript
---


# Question
Title: Webform module - Contact form will not send webform emails to users with the same domain, but will send to all other email accounts I set
I have a Drupal 6 site. Using the Webform module.

I have it set to send all submissions to the webform to my email address (me@gmail.com) and the clients email (tim@domain.com) - for some reason webform is not sending the email to tim@domain.com only to my email address.

I tried different variations of emails, using other email addresses associated with the clients domain i.e. sales@domain.com but none of them work. But when I use other gmail and yahoo emails, the results come through just fine.

Any ideas?

# Answer
> 1 votes
You using a shared hosting? Could be that the recipients mail server is thinking your mails are junk if the originating mail is not coming from the resolved hostname. This problem is common with shared hosting since they use virtual hosts.

---
Tags: 6, webforms, emails
---


# Question
Title: Can I use views_bulk_operations with the D7 core toolbar module?
I'm building a site right now where I'd prefer to use views\_bulk\_operations to administer the standard content overview (admin/content) and user overview pages (admin/people). My trouble is that I also want to use the toolbar module (or something like it) to give my site admins the ability to easily browse to the pages generated by views\_bulk\_operations (admin/content2 and admin/people2). It doesn't seem possible right now.

Any ideas? Or, perhaps, any alternatives to the core toolbar module? Thanks!

# Answer
I figured out how I want to do it: http://drupal.org/project/quickbar

The Quickbar module allows me to provide an administration bar at the top of the page, much like the default toolbar, but I get to define what menu is placed in that bar. It will allow me to keep the content admins away from the default content admin pages by simply not providing a link to it.
> 1 votes

# Answer
The Drupal core toolbar gives you only the top-level menu items anyway, so you could use Admin Menu to give you a dropdown style toolbar (I personally like Admin Menu + Admin Menu Toolbar style; disable core Toolbar module).

Create your VBO pages with a path emulating the core administration paths (e.g. admin/content/vbo1) and create menu items for those views in the Administration menu. That should do it.
> 0 votes

---
Tags: nodes, views
---


# Question
Title: drupal 7: showing main menu links to anonymous users
I have successfully enabled the toboggan present login form on access denied (403), however am not sure how i can set my links to be visible to anonymous users. I used views to create the pages and limited access to users with view published content privileges. Problem is if i do not allow anonymous users to view published content in the permissions section the links will not show.

I have tried content access and ACL but they allow anonymous users to view the content. And i can't use the path /?q=user in the text field, titled, Page Not Found 403(access deneid). Any suggestions?

Summary -: I want to show main menu links to pages (e.g. articles) to anonymous users but i want them to be redirected to the log in page when they click the links.

# Answer
First you need to install the Chaos tool suite (ctools) module, and enable the Page Manager module, and go to *admin/structure/pages*

Then we need to wrap whatever we are linking to in a **Page**, handled by the **Page Manager**. Exactly how we do that will differ a little bit depending on what we are linking to. The page manager contains many options, and I cannot describe all of them in detail here. You may want to watch this video introduction if you have never seen page manager or panels before. Videos 1 to 3 together are less than 30 minutes, and are likely necessary to make sense of the instructions below.

For **nodes**: Enable the node template.

For **Views**: Click "Add custom page", add the View in that page instead, and save.

For **Module defined pages**: Use Page manager existing pages to hand them over to the page manager.

For **Something else entirely**: Comment on the answer and tell me what it is, and I'll add instructions.

Now, in the Page manager interface for the page you enabled/created above do the following

1. Create a variant of type "HTTP response code".
2. Set the response code to 301.
3. Set the path to /user
4. Go to "Selection rules" in the left menu
5. Add "User:role" == "anonymous user"
6. Save
> 2 votes

---
Tags: views, users
---


# Question
Title: Uploading files to two separate locations
I'm uploading a clients website early next week and they've just informed me that they use load balancing software to distribute over two servers.

Normally this wouldn't be an issue because content is stored in the database and as long as both files areas can access it then it should be fine.

However, the issue comes in when uploading files. I've been informed that files should be uploaded to both servers.

I wouldn't even know where to begin to make this modification. Can anybody shed some light on it for me?

Is there a global method that's invoked when files are uploaded?

Note: This needs to work with the file field on several content types and even when files are added through modules/cck

# Answer
> 2 votes
I very much suggest a solution which actually shares the files/ directory. My primary recommendation here is some dedicated hardware. To avoid marketing for anyone in particular, I just recommen you read, on Wikipedia, SAN and FAN.

If hardware is out of the question, then we have good experience with NFS for direct sharing. Samba on the other hand has proven to be to slow.

There is also a "native" Drupal solution called Storage API which can do a lot of neat things with your files, but I don't think your particular needs can be solved out of the box, but would require some extra coding.

I would only use some type of syncing as a last resort, but here's a really basic bash-script you could cron run. The major part of this script is a safeguard so it will refuse to start if it's already running.

```
#!/bin/bash
LOCK_FILE=~/.lockfile

if [ -f "${LOCK_FILE}" ]; then
  PID=$(head -n1 "${LOCK_FILE}")

  TEST_RUNNING=$(ps -p ${PID} | grep ${PID})

  if [ -z "${TEST_RUNNING}" ]; then
    echo $$ > "${LOCK_FILE}"
  else
    exit 0
  fi
else
  echo $$ > "${LOCK_FILE}"
fi

rsync -az local_files/ username@host:/remote/path/to/files
rm -f "${LOCK_FILE}"

exit 0

```

# Answer
> 0 votes
I would imagine that if the 2 storage servers are accessible from the web server through a share or mount, then you can make some system calls in your custom module to copy the file to the 2 locations.

Or do something really clunky with the sysadmins and do a schedule task or cron job to mirror a directory.

---
Tags: files
---


# Question
Title: How to create View with Full Content and Teaser
Can I create a View of nodes which has 'Full Content' for one node and 'Teaser' for the others ?

My page consists of a node containing full content followed by summary nodes which link to their pages.

I have a workaround but it not ideal:

I selected 'Teaser' `Show:Content | Teaser` in the View for all my nodes and increased 'Summary or Trimmed length' to 60000. That way, nodes with summary will show up and nodes without summary will display 60000 chars from body.

# Answer
First, list only the full node in a Views display, then add a second display of type "Attachment". This attachment view will then list all the teasers, and can be configured so that it always "attaches" to the bottom of the primary one.

This way you can get both Views, but they always render together.
> 2 votes

---
Tags: 7, views, nodes
---


# Question
Title: What is the difference between implementing hook_url_inbound_alter() and hook_url_outbound_alter(), and using a path alias?
In Drupal 7, a module could implement hook\_url\_inbound\_alter() and hook\_url\_outbound\_alter() to rewrite URLs used in Drupal. The same effect could be obtained with path aliases. The only difference is that for path aliases that are someway dynamic, you would need a module that adds a path alias every time there is the need. That is what the Pathauto module does.

Is there any difference between the two approaches (implementing those hooks, and using path aliases)? Is there any reason to prefer one approach to the other one?
Is there any performance difference between the two approaches?

The only difference I can see is that with those hooks there could not be the need of accessing the database (depending on how the hooks are implemented). Is that the only difference, or are there more differences?

# Answer
> 5 votes
Using `hook_url_outbound_alter()` has some potential performance issues because it is executed by every single URL on a page via the url() function. This means a module could implement `hook_url_outbound_alter()` with some complex and slow code that is called 100's of times per page.

Also hook\_url\_outbound\_alter() allows a link's `$options`, including its query string, to be altered, which is impossible to do to path aliases and a very useful feature. For example, I have altered internal RSS URLs to point to their respective Feedburner and iTunes URLs.

Conceptually, the Path module should be calling the `hook_url_*_alter()` hooks but it is probably slightly faster to have the `drupal_get_path_alias()` calls directly in `url()`.

My personal conclusion is when possible use the built-in path system, but for most special circumstances you will have to use the `hook_url_*_alter()` hooks.

---
Tags: 7, uri
---


# Question
Title: How can I programatically enable a block by default for a theme?
I have set up my site to allow users to set a different theme for each node, which works fine. Some of my themes make use of blocks, so I created a custom blocks module added them programatically, which works fine. The problem comes when I need to enable them. When a user creates a new node, all of the themes are available but none of the blocks are enabled. I have to go in and enable each block manually for each theme on each node. Is there any way to basically programatically say "when this theme is enabled, enable this block in this region" so I don't have to manually enable each block?

Please note that I am using Drupal 6 and upgrading is not gonna happen any time within the next couple of months.

# Answer
> 2 votes
There isn't a way to perform programatic actions during the enabling of a theme. You can, however, have your custom blocks module add an entry to the database for the placement of the block into a theme's region, before that theme is enabled.

To do that, you would implement a database insert query, perhaps in your module's install function, that creates an entry in the blocks table for the block(s) in certain regions in any theme. You can create these entries whether the theme(s) are enabled or not.

The result will be that the block appears to be enabled when the theme is installed.

Here is a d.o forum post on the subject, with some helpful examples

---
Tags: 6, nodes, blocks, theming
---


title: Cookies for a webform using page breaks

text:
# Question
Title: Cookies for a webform using page breaks
I'm using the Webform module in a Drupal 6 installation. This webform is appearing in an iFrame, and can be found on every page. The website that contains the iframe is static, the Drupal installation with the Webform module is the only thing being loaded in the iframe. This webform is a quiz with 20 questions. The rest of the site is kind of like a handbook, and I want my users to be able to use the static handbook website as a guide while taking the quiz. Each quiz question is on its own page; I am using webform's pagebreaks to split each question up.

Is there a way to set a cookie that takes the user back to the question they left off at, should they choose to leave the form and return?

# Answer
> 0 votes
You can find some well written answers on using cookies in Drupal here.

---
Tags: webforms, cookies
---


# Question
Title: Any way to stop Drupal css from dynamically resizing pages?
We recently upgraded from Drupal 5.x to 6.22 and one thing noticed right away was that when the browser was taken off full-page the displayed page content would reformat into a very undesirable order. Previously the page would not resize and users could focus on only a small portion of the screen when in a windowed mode. This was true for mobile displays as well. Is there any 'simple' way to prevent this from happening? I realize this might be a css issue of which I am no expert. But because this entire site is generated and delivered via Drupal I thought I would ask others.

# Answer
> 1 votes
You need to add some css to various places in your theme, then. Give a 'width' attribute to the divs that contain the pieces of your page.

You may also be interested in 'min-width' and 'max-width' attributes.

Check out the drupal theming guide, or better yet, the README in your active theme's folder, to learn where and how to add the css. You don't have to be an expert- with just a little bit of time, this should be pretty easy.

---
Tags: 6, theming
---


# Question
Title: Is it possible to add CSS to theme without a subtheme?
I am using a contributed theme and I would like to add a bit of CSS.

The theme uses a lot of stuff that isn't inherited by sub-themes (settings, colors, etc), and I don't want to create a sub-theme just for the small amount of CSS I need.

What would you suggest in this case?

# Answer
> 4 votes
Of course you could just change the theme's CSS but the cleanest/most elegant thing to do here is create a simple custom module that implements hook\_init() and uses drupal\_add\_css() to add your custom stylesheet:

```
function mymodule_init() {
  $options = array(
    'group' => CSS_THEME,
    'every_page' => TRUE,
    'weight' => 9999
  );
  drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css', $options);
}

```

Create mymodule.css in your custom module's folder and put all your css tweaks there.

# Answer
> 6 votes
My understanding is to never use hook\_init if possible. It's a hook that's call in the early stages of the bootstrap process and can produce some funky results. The API docs clearly state:

> To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.

I'd suggest adding a stylesheets\[all\]\[\] entry in the .info file -\> Adding style sheets

# Answer
> 1 votes
If you want to theme a Form API form consider using #attached instead of hook\_init()

see http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html#attached

# Answer
> 0 votes
The easiest thing to do is create an additional stylesheet with your changes and add it to the bottom of the load order in the theme's .info file. All your changes live in a separate file from the base theme, keeping it clean, and the stylesheet is loaded by the theme, where you would expect to see it. This seems far simpler and clearer than writing a module to add a stylesheet. If you put the stylesheet load in a module, enable the module, then change the theme to a different theme, that module is still loading that extra stylesheet on top your new (different) theme.

My .02, keep it in the theme.

# Answer
> 0 votes
What I would do, if it were only for minor css changes, is add a 'custom.css' file to the theme folder and the .info file and put my changes in there.

To avoid the theme updating (breaking my custom css), I'd also delete the version information and drupal.org-generated content (if it has any) from the theme's .info file.

---
Tags: 7, theming
---


# Question
Title: Can FileTransfer be used to target remote FTP servers?
I need to send files to a remote server within an ajax callback. Snooping around Drupal's includes, I came across the FileTransfer class, but I haven't fully understood the concept of its access limit to $jail (defaults to Drupal's root). Is it possible to use this class to access remote FTP directories as well? If so, how?

# Answer
What used for the `$jail` parameter is the directory for which the operations are limited; if you try deleting a file outside that directory, the operation is not allowed.

If you want FTP access to a directory on a remote site, you should use the FileTransferFTP class, and create an instance with FileTransferFTP::factory().
> 1 votes

---
Tags: 7
---


title: Views and theme functions for nodes

text:
# Question
Title: Views and theme functions for nodes
Is there a way for a view to pull out x number of nodes of the same content type but use a different theme function for each one depending based on the value of one of its fields?

I need each node to be themed according to a field which will have the name of a theme function.

# Answer
> 1 votes
Display Suite Extras, shipped with Display Suite, lets you choose a different build mode for every row in the View. You might look its code to see how it's done and then hook into it to switch based on the value of a node field. Shouldn't be hard.

# Answer
> 0 votes
I gotta ask, why use Views?

This can easily be acheived in a block or menu callback using a simple db\_select() and then you can iterate over the results yourself and apply your theme functions as you see fit.

Alternatively, if you are too lazy to write the query yourself, create the view and use views\_get\_view\_result() to get the values and iterate over them yourself.

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


# Question
Title: Drupal combine nodes and comments in view
I have a view with nodes of the type 'Note' (custom CT). I have A view with comments that are associated with those nodes. How can I combine these views into one view so that I can filter them individually on the date ?

# Answer
Add 'Comment' as a node type to display in the view but keep your 'Note' content type filter. You should get both the nodes and the comments associated with any of those nodes, which you can then add an exposed filter to for date.
> 1 votes

# Answer
There is no combine views together you will need to add more content fields in the view showing the Note type nodes. It sounds like you just want to add more comment fields in your view such as the comment body, title and author.
> 0 votes

# Answer
http://sethsandler.com/code/drupal-6-creating-activity-stream-views-custom-sql-query-merging-multiple-views-part-1/ describes a (code-heavy) way of accomplishing this.
> 0 votes

---
Tags: views, nodes, comments
---


title: Module version format

text:
# Question
Title: Module version format
I would like to know what is the correct version format for custom modules in Drupal 7. I see some contributed modules come with 7.x-1.2-rc1. I don't know what is rc1. When I name my custom module with version 7.x, my module didn't work in module installation and it wasn't enabled. When I name the version 7.x-1.2, it works fine.

Is there any documentation for Drupal module version format?

# Answer
> 4 votes
Release naming conventions reports exactly the format used for the release names, and how they are formatted.

In short, the format is *\[Drupal version\].x-\[major version\]-\[minor version\]-\[flags\]*.

* Drupal version is the Drupal version with which the module is compatible
* flags are extra identifiers that starts with one of the following string:

+ unstable
    + alpha
    + beta
    + rc \[a.k.a. release candidate\]

For a development snapshot, the format is *\[Drupal version\].x-\[major version\]-x-dev*.

"Major version" and "minor version" refer to the module version, where "minor version" is a progressive number.

As for the module not working if the release number doesn't follow the schema, I think the problem is another one; as far as I know, Drupal doesn't check the format, and the release name is only used from the update manager, when it is looking for the module updates, and the module is hosted on Drupal.org.

You should not be worried about the format used for the release version identifier, if not when you are developing a module that is host on Drupal.org. If you are developing a custom module that is not hosted there, you don't need to report the module version. In fact, in my test site I have a test module that doesn't report its version, and Drupal is still able to use it; the only difference is when another custom module depends from that, and it is reporting with which version of the first module is compatible. Then, Drupal will not show the module version in the module page, if the .info file doesn't report that.

# Answer
> 0 votes
The use of a *version* is discouraged, the value that is required is *core*, and you can only set it to *7.x*. See the community documentation: Writing .info files (Drupal 7.x) for more information.

For your info, "rc1" means "release candidate #1". Modules can have different version: Alpha, Beta and Release candidate.

---
Tags: .info
---


# Question
Title: How to relate a complex field to another node
I'm building a hobby site that is going to be used to record results (golf). A round of golf will have any number of players, selectable from a known list of players.

I would like to be able to create a new round and add players to it, entering a score for each one. My first thought is to create content types for player and round, and a complex field that does something similar to node reference.

Before I went down that path I wanted to see if there was a smarter more Drupal way of doing this. One idea I had was to have a third content type, result, which would be a node reference to a player and an integer field, but this would require having to create the results before hand. Or perhaps the result has a relationship to a round and a player, so the workflow is create a round, then create as many results as required.

The basic question, is there a smarter way to do this?

# Answer
> 0 votes
My solution to this is as follows:

* I have basic content types of Player and Golf Course.
* When I want to enter new scores, I first create a Round (which is another content type with a node reference to a Golf Course and a date field).
* Once the round is created I create Results (another content type which has a relationship to a round and a player and an integer for the score).

This handles my data entry requirements even though the workflow is a bit of a kludge, but I can streamline that later I think. Now the next step will be using views to display my results but that will probably be another question :)

---
Tags: entities, nodes
---


title: Creating a custom aggregation for views

text:
# Question
Title: Creating a custom aggregation for views
I have implemented the data described here and now want to create a view that will work out the handicap for a particular player. I have so far created my view which list players and using a relationship to results for the player, and then aggregating these fields, can display things like the players best score and their average score.

Next I want to display the players "Handicap", which is a complex aggregation. Namely, it's the average of the best 8 of the last 20 results multiplied by 0.93. Can you write custom aggregation functions? Or should I create a new field on the result? I'm not sure of the easiest way to go about this.

Thanks!

EDIT: Thanks to @Jimajamma I was pointed in the right direction. You can do what he suggested purely from a module. I used the Fields UI to create a field that I can then manipulate to keep it simple. In the module I've used hook\_theme to register a tpl.php file. I struggled to get my preprocess function to be recognised because of the `base_hook` directive which seems to then cause views/core to ignore the `preprocess functions` directive. The following is the simplest module you can create:

```
function golf_ladder_views_api() {
  return array('api' => 3.0);
}

function golf_ladder_theme($existing) {
  return array(
    'views_view_field__field_handicap' => array (
      'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
      'template' => 'views-view-field--field-handicap',
      /* 'base hook' => 'views_view_field',
       * Don't do this if you want to use a preprocess that you control.
       * If you define base hook views seems to want to ignore the
       * 'preprocess functions' directive below
       */
      'path' => drupal_get_path('module', 'golf_ladder'),
      'preprocess functions' => array(
        'template_preprocess',
        'template_preprocess_views_view_field',
        'golf_ladder_preprocess_views_view_field__field_handicap',
      ),
    ),
  );
}

function golf_ladder_preprocess_views_view_field__field_handicap(&$variables) {
  $variables['output'] = '4'; // TODO: calculate proper handicap
}

```

After that create a template file `views-view-filed--field-handicap.tpl.php` which is simply:

```
print $output;

```

# Answer
Whether this is the best, I don't know, but it is pretty easy:

1. Create a new field called handicap. It doesn't need to have any value as you will be computing it.
2. Create a views template for that field. It would be something like `views-view-field--field-handicap-value.tpl.php.` If you want it specific to the view, you will need to include its name in there as well, but just look in the Views Styles/Themes to find it.
3. In that template, do your custom aggregation function, and then output that result instead of the default `$output.`

Now, if all is good in the world, you will have your handicap output in the view and you can aggregate on that value as well later on in the view, too.
> 1 votes

---
Tags: views
---


# Question
Title: Disable user registration for certain pattern of: IP address, name, mail
I run a Drupal 7.10 / CentOS 6.2 website (where users can register after confirming their mail by clicking on a link) and there is a person registering at my site every night and then changing his name to obscene words.

First I've added a line to /etc/sysconfig/iptables to block his area:

```
-A INPUT -s 2.132.0.0/16 -j DROP

```

but this has blocked other users from that area (Alma-Ata city).

The pattern of this user is:

1. His IP address: **strpos($\_SERVER\['REMOTE\_ADDR'\], '2.132.') === 0**
2. His mail (changing every time): **preg\_match('/vlad.+@mail.ru/i', $mail)**
3. His name (usually): **stripos($name, 'st') !== FALSE**

As you see - I have all the components there, I just need to know a good spot to put this code in. Anywhere to make his registration more difficult. An ideal case would be to sent admin a mail for registration verification, but just bailing out of the registration script (which one is it please?) would be okay too.

# Answer
Drupal 6 had the possibility of avoid specific usernames, email addresses, matching an SQL pattern match could be used from users, and avoid those users matching those conditions could log in. There was also a setting for avoiding users could be log in from specific IPs, which is the only part kept in Drupal 7.

The other part has been moved to a third-party module I maintain. Being the maintainer, I can tell you that I didn't recently commit code for User restrictions, which at the moment is not usable because the code needs to be fixed. I count to start committing the code I have developed in the previous months starting from tomorrow, if there is not something else that take me busy. I actually need it in my website, which is running Drupal 7. I count to make the module as much generic as possible, and allow other modules to integrate with it through hooks; for example, the code I developed allows other modules to add rules that would be used to temporary block users.

For avoiding users would use specific usernames, there is also Ban List.

> Banlist allows the administrator to disallow users from using a username from a list of usernames. The list consist of usernames such as: admin, administrator, root, demo, test, superuser, etc.
>
> Although core can handle this, the primary purpose of the module is for people in the community to contribute to the list and make it very easy for everyone else to take advantage.
> 2 votes

---
Tags: 7, users
---


title: add Drupal subform

text:
# Question
Title: add Drupal subform
I have a question in drupal I want to make a content type that have a title and body and a subform that contain a title and image and video and date and I can add more than one subform I have searched for this module but I didn't find any so I tried making a custom modules using field hooks API but I face problem My site does not work again I don't no if I have an error or not but there is no syntax error at all but after adding my field and saving data the site does not work

Does any one have a good tutorial for that Hope you can help me

Thanks

# Answer
> 0 votes
I advise you to use the Field Collection module. With Field Collection you can add fields like title, picture and video into a collection then you add the collection in the principal form.

---
Tags: 7
---


# Question
Title: Theme "seven" – how to allow regular users edit content with this theme?
please instruct me how to allow regular users (non-admins) to use Seven theme to edit content. Now users are forced to edit content using the default drupal theme which wasn't designed for this purpose (looks ugly). Is it matter of some permission? Admins are editing with Seven theme without problem.

I've found some topics about more complex cases with module recommendations like this: http://drupal.org/project/themekey . As my case is pretty simple, I decided to ask!

Cheers!

# Answer
> 3 votes
Checking the permissions "View the administration theme" fixed my problem.

# Answer
> 0 votes
You can try the Administration Theme module to control which pages are rendered with the admin theme (in your case: Seven).

---
Tags: theming
---


title: Encoding problem with node.tpl.php

text:
# Question
Title: Encoding problem with node.tpl.php
I am new in Drupal theming and I would like to control the "submitted by" part of a node. I want to remove the name of the author and stylize the created\_date of the node. The problem is that I also echo some greek characters that show up in weird symbols in my site. I tried changing the encoding to utf-8 but it won't work. I am not even sure what the original encoding of node.tpl.php is. How would I go inserting my own custom text inside node.tpl.php and printing it correctly?

```
<?php if ($display_submitted): ?>
  <footer class="submitted"><?php $posted="Δημοσιεύτηκε στις "; echo mb_convert_encoding($posted, "UTF-8", "Windows-1252") . date( "d F, Y",$node->created); ?></footer>
<?php endif; ?>

```

The code above returns:

> Äçìïóéåýôçêå óôéò 12 January, 2012

I also tried utf8\_encode function but that was a long shot since it converts ISO-8859-1 strings to UTF-8.

# Answer
If the file is correctly saved as UTF-8, it should correctly handle Unicode characters. So far, I have had a problem with the saved file just because the editor I was using added the BOM ("**B**yte **O**rder **M**ark") used to identify the encoding of the file, but the error was a different one.

Generally speaking, the Drupal way to have a translatable site is to use t() in your code, which requires the English string that will then be translated to the language set as default, basing on the translation provided to the Language module.

The code should be rather be similar to the following one:

```
<?php if ($display_submitted): ?>
  <footer class="submitted"><?php t('Submitted by !username on !datetime', array('!username' => $name, '!datetime' => $date)););</footer>
<?php endif; ?>

```

The alternative is implementing hook\_preprocess\_node(&$variables) (`template_preprocess_page()` in a theme), and initialize the variable `$variables['submitted']` to the string you want to appear ("Submitted by !username on !datetime" in the code I shown before).
> 2 votes

# Answer
You might want to try the submitted\_by module. Since all entered strings go through the Drupal system you shouldn't need to use any encoding functions in your template.
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: How to display only  certain values  otherwise display empty field in Views
I would like to display only certain values of CCK value in a views field. In another words, I don't want to display certain values of CCK in the views field. Is this possible?

For example I have a CCK field called "fruits" with multi selections of "orange", "apple", "banana". I have also a table view with a "fruits" field and then I would like to display only "orange" value but keep this field empty when the field have the value other than "orange"(when the value is "apple" or "banana" ).

# Answer
> 0 votes
You can make use of a computed field (fruits\_computed) which takes the input value of the fruit field (fruits) and filters values via php, sth. like this:

```
$allowed_values = array('orange');
if ( array_in($fruits_value, $allowed_value) ) {
$output = $fruits_value;
} else {
$output = '';
}
```

Then in views, you do not use the fruits field, but fruits\_computed.

---
Tags: entities, views
---


# Question
Title: Panels Node Add form and passing url parameters
I'm using panels to override a nodes display page. I also want to use it to overide the edit and add page. The cck type I'm trying to add has a node reference field, this needs to be passed in through the url.

So far, I've add the panel varaint, added a context (node add form), and added the form to the "content" of the panel, All I need to figure out is how to pass the referencing node ID to the form. Does any one know how to do this?

# Answer
> 1 votes
This is an old question but there is an easier way with the Node Reference URL Widget module, which should work with Panels as well.

# Answer
> 0 votes
You can create your own menu callback using `hook_menu` (you need to do this from your custom module). Then from your custom callback you you can call whatever callback function is assigned to the different panel pages you have. In your custom callback, you will need to specify the path to whatever function panels is using in it's callback. Here's how your custom callback could look like:

```
<?php
/**
 * The 1st %node argument represents the node you are editing.
 * The 2nd %node argument would represent the referencing node ID.
 */
$items['node/%node/%node/edit'] = array(
    'page callback' => 'mymodule_edit_node',
    'page arguments' => array(1,2),

    // Other arguments ...

    // This includes the node_edit.inc file, needed for calling the page_manager_node_edit() function.
    'file' => 'node_edit.inc',
    'file path' => drupal_get_path('module', 'page_manager'). '/plugins/tasks',   );

/**
 * The callback above automatically converts $node_edit and $node_ref to node objects.
 */
function mymodule_edit_node($node_edit, $node_ref) {
  // Do something with $node_ref, like building a Form or storing it
  // statically in a function for later use.
  &drupal_static(__FUNCTION__, $node_ref);

  // page_manager_node_edit() is what Panels uses for rendering it's custom edit node page.
  return page_manager_node_edit($node_edit);
}

```

It's a little hard to figure out how your form is looking in that panel page, based on your description above, so I cannot give a concrete example of how to insert the node reference directly into the form. However most likely it would involve using one the hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() functions. Using these you can retrieve the referenced node using the drupal\_static() function or directly using arg():

```
<?php
// Retrieve from static cache:
$foo = &drupal_static(__FUNCTION__);

// Retrieve from URL:
$foo = arg(2)

```

---
Tags: forms, panels, nodes
---


title: Workflow does not work correctly

text:
# Question
Title: Workflow does not work correctly
I create a workflow for the content type "Article":

```
creation -> draft
draft -> expert review
expert review -> head review
head review -> publish

```

When authors create an article node, and send it for "expert review," they can still view and edit the node but "expert review" cannot view the node.

Is there any bug or trick for Workflow?

# Answer
Edit your Workflow again (after you created the states) and scroll down to the bottom to 'Access control' section. In there you can set permissions for each state.

You can also look at the Workflow Fields module if you want to set access to individual CCK fields.
> 0 votes

---
Tags: 7, workflows
---


title: hook_menu() wildcard problem

text:
# Question
Title: hook_menu() wildcard problem
I can't get the wildcard from a hook\_menu to pass it to a callback function

Here is what I have:

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

    $items['spin/login/%'] = array(
        'title' => 'SPIN',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
        'page callback' => 'spin_check_access'
    );

    return $items;
}

function spin_check_access($type = '') {
    echo $type; // type is never the %
}

```

Is it correct? I need the $type to be replaced with the wildcard's value.

# Answer
You have two options:

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

  $items['spin/login'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page callback' => 'spin_check_access',
  );

  $items['spin/login/%'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page callback' => 'spin_check_access',
    'page arguments' => array(2),
  );

  return $items;
}

```

Hook menu will not send any wildcard params to the callback function, but it will send params not defined in the url. So in the first example if you go to `spin/login` type will be `''` and `spin/login/foo` type will be `foo`. For the second example `spin/login` will return 404 and for `spin/login/foo` type will be `foo`.
> 2 votes

# Answer
You are missing page arguments, telling Drupal which values to pass on. Try:

```
$items['spin/login/%'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page arguments' => array(2),
    'page callback' => 'spin_check_access'
);

```
> 1 votes

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


# Question
Title: how do i add last name new field in default user registration page
how do i add last name new field in default user registration form my code is

```
$form['account']['lname'] = array('#type' => 'textfield',
  '#title' => t('LastName'),
  '#default_value' => $edit['LastName'],
  '#maxlength' => LASTNAME_MAX_LENGTH,
  '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
  '#required' => TRUE,
);

```

but i don't know how to show last name field in default user registration form?

# Answer
> 1 votes
I would use the content profile module, you can add new fields to a users profile just like how you use cck to add new fields to a node. There is a configuration option where you can then set which fields you want displayed on the registration form.

# Answer
> 0 votes
You can alter the form by implementing hook\_form\_alter.

Alternatively you can have a look at the content profile and cck module to get additional user fields without coding.

---
Tags: theming
---


# Question
Title: How should I fix an incorrect query in hook_update_N()?
I made a new release of a module, and soon afterwards an issue was filed that the hook\_update\_N() used SQL that didn't work on PostgreSQL. In this situation I can see two solutions:

(Let's say the release with the problem is 1.1 and that N=6100.)

1. Modify update\_6100 to have a fixed query and release as 1.2. If a user with Postgres updated to 1.1, got the error, and then updated to 1.2 they still wouldn't have run the query as it wasn't put in a new hook\_update\_N(). However they should've seen the error when doing the update, and the issue's in the issue queue, and can include instructions on how to fix the problem. It feels *ugly* to modify an existing (released) update function though.
2. Add update\_6101 that has the fixed query. In the case of this particular query however, it would be destructive to run it after the user's started using some of the new functionality. So if a user with MySQL updated to 1.1, used the module a lot, and then updated to 1.2 there would be a good chance they'd lose data. I could check what DB's being used in update\_6101 so that it would only be run for users with Postgres, but that feels ugly too. Also if someone with Postgres ran update\_6100, saw the errors and then fixed and ran the query manually, they also could lose data when updating to 1.2.

Note that there's no way to detect if the query has run successfully, or has never been run.

I'd like to know what people think is the best way to deal with this situation?

# Answer
> 3 votes
Something similar happened with Panels, update 7301, a new field was added, and while the column creation happened, Drupal wouldn't accept the update as valid.

If you check the code in panels.install, you will see that the action taken by merlinofchaos, was to modify the 7301 to first check "Does this column already exists? Then smile and pretend we just created it, otherwise create it now."

If merlin does it that way, I would do it that way. Relevant issue here, maybe that will help further.

Since each of your scenarios above have potential for data loss, which is serious, and people *dont actually take backups*, and in your case, there is *no*, way to tell, then perhaps you will need to **force** the user to tell you. Refuse the update unless the variable module\_name\_has\_1\_1\_content is set to either TRUE or FALSE. Then either you can add a form in the admin UI with an explanation and yes/no button that just sets the variable. Or just one "I have read the issue and understand the consequences, let me update" button.

Perhaps you can provide instructions for "How to export and import all content". That way the user can export, update, truncate the table, and import.

---
Tags: hooks, updating
---


# Question
Title: How do I create a multisite with  shared users and nodes?
I want to create a multisite with Drupal 7: Every site works separately but users, and nodes must be shared among the sites.

How do I achieve it?

# Answer
You can change the settings for the access to the database that are contained in the settings.php file used by your Drupal site to something similar to the following one (replace the values between brackets with the correct values for your site):

```
$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);

```
> 17 votes

# Answer
Sharing users and content between different domains is what the Domain Access module is for. Essentially, it allows you to run multiple Drupal sites out of the same database, and share content.

When you install, enable, and configure the module, a new tabs shows up on the node edit page which allows you to target a node for particular domains. It also plays nicely with views, panels, and other modules that use ctools selections rules.

This solution is different than true multisite, which is a common set of core and contrib files, but different databases for different sites.
> 10 votes

# Answer
This is a bit complicated, but you can create a multi-site environment with shared users and multiple databases. I think it gets very complicated if you want to have separate databases with shared users AND nodes. Have a look at this document for more information about the different setups with pros and cons.
> 2 votes

---
Tags: 7, users, multi-sites
---


# Question
Title: User activity not showing in the personal log but is in the public log using Heartbeat module
I have installed the Heartbeat module (6.x-4.11) with Heartbeat activity and Heartbeat rules enabled. If a user adds a comment to the site the activity is being logged in the database and showing on the public heartbeat page. However, looking at the user's personal heartbeat it shows as "no activity yet."

The uid and uid\_target values in the database table are both "0" which I am guessing is not right (surely these should be the user's id).

Is there a configuration setting that controls whether the activity appears against the user?

I'm attempting to use this module as a way of allowing users to see how active other users are on the site; so it is important that the activity appears against the personal heartbeat.

# Answer
Finally sussed it. I needed to go into the Triggered Rules page and change the "do" behaviour for the "Heartbeat: When a user adds a comment" rule.

Setting "User Id" to "\[comment\_author:uid\]" links the activity log to the author, and "Node context Id" to "\[node:nid\]" links to the node being commented on. After changing these the activity showed up in both personal and public Heartbeat activity streams.

Hope this helps somebody else who may be struggling with this.
> 1 votes

---
Tags: 6, users, heartbeat
---


# Question
Title: Import multiple node reference from CSV using feeds
I am trying to import multiple node references for one node using feeds. How should my CSV look like for that??

Will this work :

```
"title","description","status","code","details",("contact1","contact2", ..., "contactN" );

```

given that I have another content type named **contact** with titles *contact1*, *contact2,* ..., to *contactN*

# Answer
> 2 votes
I would recommend you the Node Import module for Drupal 6. It's very powerful and works great with references.

---
Tags: 6, feeds, importing-exporting
---


# Question
Title: Controlling the display format of a rss feed
I am using drupal 6. I have created an RSS feed to display the nodes of a certain type (set in the filter). This type of content has many different fields, but I only want to display some of them. Is this possible? At the moment I am very new to Drupal, and I am only working in the front end view.

To fix this issue, do I need to go deeper and mess with the PHP code somewhere?

# Answer
Use the module Views RSS
> 1 votes

---
Tags: 6, feeds
---


title: Is memcache only for logged in users?

text:
# Question
Title: Is memcache only for logged in users?
I am trying to understand what the role of Memcache is. A few of my friends who have been working with Drupal for more than a year tell me that Memcache would only work for logged in users, and I would have to look to Varnish or Boost for caching the content shown to anonymous users.

While I understand that varnish acts as a reverse proxy, and caches a copy of the page, I wanted to know if anonymous users make a request, and if varnish does not have a cached copy of it, would the webserver route the request to Memcache, or would the request directly go to the database?

Architecture example: Varnish/Boost, web server, Memcache, database.

# Answer
> 8 votes
In short, yes memcached will benefit both anonymous and authenticated visitors (even if you also use Varnish).

Memcached and Varnish operate at different layers. Varnish caches entire HTTP requests (and sometimes edge-side includes, but this is less common in the Drupal ecosystem). Memcached stores frequently used data within the application, and it is a replacement for the `cache_*` family of database tables.

Memcached will speed up anonymous requests when the Varnish cache misses or is bypassed.

# Answer
> 1 votes
What memcache adds to the mix is in it's name. "Memory caching". That is, instead of writing certain cachebins to database and disc, it keeps a *volatile* cache in RAM. This makes both reading and writing much faster, but you also loose the cache in cache of, say a server reboot.

This certainly *can* help either, or both, or anonymous and authenticated users, but whether or not it does comes down to what you cache, which users use what data, and what cache bins you move to memcache.

---
Tags: performance, caching, proxies
---


# Question
Title: What steps are necessary to build secure database queries from user input?
Example Drupal 6 query:

```
$q = db_query("SELECT id FROM {table} WHERE no = %d AND name LIKE '%%%s%%'",
               $_GET['something'], $_GET['something_else']);

```

Example Drupal 7 query:

```
$q = new EntityFieldQuery();
$q->entityCondition('entity_type', 'some_entity')
  ->propertyCondition('id', $_GET['something'])
  ->fieldCondition('field_name', 'value', '%'.$_GET['something_else'].'%', 'like');

```

The $\_GET values could be anything the user can technically send. Should additional steps be taken like using PHP-s `is_numeric` function for numbers and `db_escape_string()` for strings to make sure the input wont cause any harm or are the queries already secure? Does the same count for other Database API functions?

# Answer
It depends what you mean by "secure." If your goal is just to block sql injection then yes, that's it :) For Drupal 6, be sure you are using the right placeholder based on db\_query docs:

> Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose in '') and %%.

And be sure that you enclose the %s placeholder in ''. Failure to match these properly can lead to sql injection.

Drupal 7 takes care of that for you. Even if you use the Drupal 7 db\_query you use placeholders like :name and it will figure out the data type and take care of proper filtering/substitution/quoting for you.

The other security related topic for queries is the node access system. In Drupal 6 you should use db\_rewrite\_sql. In Drupal 7 be sure to use $query-\>addTag('node\_access'); if you are querying for nodes.

This system of preventing SQL Injection as part of the API is, in my opinion, one of the great features of Drupal. Similar functions that perform both functional and security features are the t() and l() function which will prevent XSS when they are used properly.
> 6 votes

---
Tags: database, security
---


# Question
Title: Can I use Corolla theme as a fixed width layout?
I have a fresh install of D7 and have downloaded Corolla theme.

I go into appearance and set the page width from 100% to 944px, which works fine, but, whenever I resize the browser window, the first sidebar breaks and drops to the left of the page. I would like it to just display a horizontal scrollbar.

Is there anyway to modify this theme to do this?

# Answer
Though I have not used that theme myself, it indicates on the project page that it's 'Responsive' so the sidebar is doing what its supposed to do when the browser is resized to a narrower width -- it's using a Media Query. I tried the demo and this was my experience as well. Though that might have seemed odd in the old days, now it's actually what you want for the site to work with multiple devices and screen widths. You will note that if you resize even narrower, the other sidebar goes underneath as well and this is as expected.

From the project page:

> "The new 7.x-2.x version is a subtheme of Adaptivetheme which includes a powerful new responsive layout engine with full support for mobile devices."

You may want to take a look at this for a primer on Responsive Design: http://www.alistapart.com/articles/responsive-web-design/
> 2 votes

---
Tags: 7, theming
---


title: Basic code to make a module themable

text:
# Question
Title: Basic code to make a module themable
I almost titled the question "Hello world of theming a module", as that quite well describes what I'm looking for. I feel maybe it's to much "slang" though. There's probably a lot of people out there in this situation. I know a lot about programming, but very little about (Drupal) theming.

So, for a trivial "Hello world" module like:

```
function _modules_page_callback($data) {
  return '<span class="module-functionality">' . $data . '</span>';
}

```

What does the equally trivial version look like, that moves the HTML into the theme-layer?

# Answer
> 3 votes
You first let Drupal's theme system know about your "theme" functions. You just create a function called `mymodule_theme` and that should return an array with your theme functions defined. See hook\_theme for more details.

Example:

```
function mymodule_theme() {
  return array(
    'funstuff_output' => array(
      'variables' => array('node' => NULL),
    ),
  );
}

```

Now the 'funstuff\_output' function does not exist... so create it!

```
function theme_funstuff_output($variables) {
  $node = $variables['node'];
  $output = '<h1>' . $node->title . ' is fun stuff</h1>';
  return $output;
}

```

Now you can call taht theme function anywhere like so: `print theme('funstuff_output', array('node' => $node));`

In Drupal 6, I think variables is called arguments and there are some other differences. But that's the basics.

# Answer
> 1 votes
For Drupal 6, I will attempt to answer this myself, since I've continued my research since I asked the question. Our module below is called something original, "foo".

foo.module:

```
function foo_theme() {
  return array(
    'foo_useful_output' => array(
      'arguments' => array('data' => NULL),
      'file' => drupal_get_path('module', 'foo') . '/foo.theme.inc',
    ),
  );
}

function _modules_page_callback($data) {
  return theme('foo_useful_output', $data);
}

```

foo.theme.inc

```
function theme_foo_useful_output($data) {
  return '<span class="module-functionality">' . $data . '</span>';
}

```

---
Tags: theming
---


# Question
Title: Displaying the node title in different region
My designer just killed me, I realised he put node titles in a different region of the page layout, just beneath a menu and before left/right sidebars. No going back now.

How can I display titles of things (nodes, views etc) in a different region and hide it from the content region?

# Answer
> 1 votes
If you don't want to touch the template file and prefer to use the UI, you can also use the Blockify or Omega Tools module. Either one of these will put the page title into a block for you to place in any region of your choosing.

# Answer
> 1 votes
Not sure which version of Drupal you're using, but the method is basically the same. In D6 just place where ever you need it in the page.tpl.php template and remove it from the node.tpl.php template (or use conditionals to output it there when needed).

---
Tags: theming
---


# Question
Title: Multisite - Put one alias in maintenance mode
We have one installation (let's call it example.com) with two domains (development.xpto.com and example.com) serving as alias (defined in sites.php) to the main site folder.

We wanted to put one of those aliases (the example.com) in maintenance mode and leave the development domain working np.

What's the best course of action to attain this functionality?

# Answer
> 0 votes
If they are aliases defined in sites.php, then you will have to unset the domain you want to turn off. Once you have unset it, create a folder sites/example.com/ and put a copy ofe sites/default/settings.php (or the settings.php you're using).

In it, write:

```
$conf['site_offline] = 0;

```

# Answer
> 1 votes
If your multi sites have separate databases than you can simply put whichever (sub)domain you desire into maintenance mode without effecting the other domains.

If you are using the *Domain Access Module*, you should navigate to that domain's maintenance page and put it in the mode you desire at `subdomain.example.com/admin/settings/site-maintenance` \- see my screen capture

---
Tags: multi-sites, maintenance-mode
---


# Question
Title: How do I overwrite node title for specific content type?
I'm trying to add a chapter tag (§) in front of a title for content type 'ABC' in a Drupal 7 site.

I tried the following:

```
function mytheme_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
  //watchdog("mytheme_preprocess_node", 'items %items', array('%items' => print_r($variables['node'], true)));
  $node = $variables['node'];
  if ($node->type=='abc') {
    $node->title = 'this is a test' . $node->title;
    $variables['node'] = $node;
    watchdog("mytheme", 'items %items', array('%items' => print_r($variables['node'], true)));
  }
}

```

I did see the message output in the log, however updated title is not showing up on the site.

# Answer
Every implementation of `hook_preprocess_node()` made from a module (or a theme) is executed after template\_preprocess\_node(), which contains the following code:

```
  $variables['node_url']  = url($uri['path'], $uri['options']);
  $variables['title']     = check_plain($node->title);
  $variables['page']      = $variables['view_mode'] == 'full' && node_is_page($node);

```

`template_preprocess_node()` is the preprocess function executed from the Node module, which is the module that defines `theme_node()`.

The template file is then using `$title` for the page title.

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

```

If you want to change the value for title, you should change the value of `$title`, in your preprocess function.

The execution order of preprocess functions is explained in the documentation for theme(). In that documentation "HOOK" is a placeholder for the type of the preprocess function, e.g. "node," "html," and "page." Between the rendering engine used for the theme, a module, and the currently set theme, the preprocess function implemented from the theme is the last one to be called. This helps if there is another module that alters the title, and you want to use the one set from the theme.

What I reported is also valid for Drupal 6.
> 7 votes

---
Tags: theming
---


# Question
Title: Override Domain-Restricted Content in a View
I have a site running Domain Access, which is restricting content to the domain it was created on. Using Domain Views, I've created two types of views:

1. views displaying content for the current domain.
2. views displaying content for all domains.

However, #2 displays as #1 for anyone without the "Administer Content" permission. How can I set this up so anonymous users on one.mysite.com can see linked content on two.mysite.com ?

In addition, when they click links to other domains, I want them to be transfered to the other domain to view the content.

How can this be done?

# Answer
> 3 votes
I posted this on the Domain Access issue queue as a support request and got this helpful answer:

You can only accomplish #2 under three conditions:

1. The content is marked "Send to all affiliates"; or
2. The view is a page marked as a Special Page Request (which disables Domain Access rules); or
3. The view is set to ignore node access control -- this is an advanced Views configuration.

Option 3 can create security issues if you are using other node access modules.

To make the content link to the appropriate domain, use Domain Source, which lets you specify a canonical URL for each node. If you don't use Domain Source, the canonical URL is calculated for you.

---
Tags: 7, views, domain-access
---


title: Build something like open atrium

text:
# Question
Title: Build something like open atrium
I just installed open atrium and was amazed how it works and how its made. It is made to work with just some clicks while installation. I want to build something like this. I just want to pre configure just blogs, gallery and forums and with some groups. Installation profile knowledge i need. what else should i know properly so as to build such a thing.

# Answer
You're going to want to understand the relationship between Organic Groups, Spaces, Context, Features and possibility the Persistent URL and Strongarm modules. Aside from Organic Groups, they were all created by the same developer who started Open Atrium.

Here is one very basic run-through about how Open Atrium works.

Here is a description of how each of those modules factor into the OA structure.

**Be warned**: I don't think I've seen a more complex site built with Drupal. Most of those modules are not only complex, but also genius.
> 12 votes

# Answer
I think if you are wanting to get this involved in drupal installation profiles and how the sites work, it would be a good idea to research using Drush. Its a command line tool for working and administering Drupal.
> 2 votes

---
Tags: 7, distributions
---


# Question
Title: Plain Unstrucutred HTML Content Types, How to Pull image from them in Views
This is a plain unstructured node with no CCK structure or anything like that (the site includes thousands of posts so it is impossible to retroactively go back and re-insert the images in using CCK).

How can I pull the first image in the node out and use that image within a view as a thumbnail image? (It's a related posts view)

I'm not 100% sure how to create a view theme, the drupal documentation on it is really confusing and I can't find a good tutorial on how to create a custom view theme either. So since I think that is the best solution if you know how to do that, could you point me to a tutorial or something that actually teaches you how to create your own themed view (one that makes sense).

Thanks for any tips or advice.

# Answer
you will need to only create one view theme. That will be a theme for the BODY field of your node. It's actually super simple.

* create a PHP file in your theme folder called views-view-field--YOURVIEWNAME--body.tpl.php
* your file has one variable you need to worry about, $output and that's the HTML. Write your PHP code to isolate the very first image tag and then this site has a nice example of how to do that

I think the code in this file would end up looking like this

```
  $first_img = '';
  $numMatches = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $output, $matches);
  if($numMatches){
    $first_img = $matches [1] [0];
  }else{ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  echo '<img src="' . $first_img . '" alt="thumbnail" class="thumb"/>';

```
* add some CSS to make the thumbnail, or alternatively you can use theme with imagecache I think.
* refresh your template cache

You're done!
> 2 votes

---
Tags: views, nodes, media
---


# Question
Title: Using a template_preprocess_node in an adaptive subtheme
I'm using the adaptive theme with the pixture\_reloaded subtheme, and I'm trying to place a preprocess to change the format of `$date`. This is what I thought should do the trick but haven't had any luck with getting the output I want.

In ./sites/all/themes/adaptivetheme/adaptivetheme\_subtheme/template.php, I've entered the following:

```
function adaptivetheme_subtheme_preprocess_node (&$vars)
{
   $vars['date'] = format_date($node->changed);
}

```

In ./sites/all/themes/adaptivetheme/adaptivetheme/templates/page.tpl.php, I've added:

```
print $date;

```

under the location where the main content is rendered.

The date prints where I want it to, however, the date format is still showing up as the date which the content was created, and not the updated date. I've edited the content multiple times as well.

Is my preprocess hook supposed to be placed into a different area to make this work?

Any help is much appreciated.

# Answer
Since you are using a node preprocess function, the variable you created will be available to the node.tpl.php file, not the page.tpl.php file. You need to either move your print statement to node.tpl.php or implement template\_preprocess\_page() in template.php.
> 2 votes

---
Tags: theming
---


title: DIsplaying images on nodes?

text:
# Question
Title: DIsplaying images on nodes?
In one of the sites I have created, I am using a specific made up 404 page instead of the default one that comes with the server. This 404 page contains an image, and then a block containing text next to it. I then made the url alias for this page "404." Now when I go into the configurations, and set 404 as the 404 error page, it automatically saves it as "node/4." The problem then arises when you go to a page that doesn't exist. If the page is something like www.yrambam.org/nonexistentpage then there is no problem. The page works. But if the page is something like www.yrambam.org/something/nonexistentpage then the page displays without the image, and the formatting of the page becomes all messed up. I am wondering why this happens, and if there is a way to fix it.

# Answer
This is definitely an error where the HTML of the 404 page is referencing the image via a relative path rather than an absolute path.

Screenshot of the page + source

Change the HTML of the page to use the image source path '/sites/default/files/pictures/404-error.png'
> 1 votes

---
Tags: nodes, media
---


# Question
Title: drupal_set_title not setting $title variable
I'm trying to use `drupal_set_title()` in my node.tpl.php but the text I'm setting the title to is only showing up in the `$head_title` (`html.tpl.php`) variable and not the $title variable. The $title variable is still set to the node's title.

This is in Drupal 7. I've used `drupal_set_title()` multiple times like this in Drupal 6 and it has worked perfectly.

Is this broken in D7?

This is how it is being used in `node--news.tpl.php`:

```
$actual_title = $title; // save for later use
drupal_set_title('News');

```

# Answer
By the time you've hit node.tpl.php it's too late to set the title as `$head_title` has already been set in template\_process\_html() and the `$head_title` variable has already been output.

You'll need to use template\_preprocess\_node() or similar to set your title as desired.
> 10 votes

# Answer
Apparently trying to set the title in node.tpl.php is too late in the execution order. Same goes for `template_preprocess_node()`. Instead, it can be set in `template_preprocess_page`:

```
function mytheme_preprocess_page(&$vars){
    if (isset($vars['node']) && $vars['node']->type == 'news'){
        drupal_set_title('News');
    }
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How would I by default have a dropdown block expanded instead of collapsed?
I want to be able by default have a dropdown block expanded instead of the current default which is to show just the link and if the user clicks on it then it would expand. Below is some code related to collapsing and expanding dropdown blocks which is contained within a .js file within the default theme (`sites/all/themes/fusion/mapsindeed/js`). How would I, by default, have a dropdown block expanded instead of collapsed?

```
//ability to expand and collapse dropdown blocks
Drupal.behaviors.mapsindeedDropdownBlock = function (context) {
$('.mapsindeed-dropdown-block .content').hide();
  $('.mapsindeed-dropdown-block h2.block-title').bind('click', function(){
  $(this).siblings('.content').slideToggle('slow', function() {
     });
   $(this).parents('.mapsindeed-dropdown-block').toggleClass('expanded');
});
}

```

# Answer
Remove `$('.mapsindeed-dropdown-block .content').hide();` from the above, and replace it with the following code:

```
$('.mapsindeed-dropdown-block .content').addClass('expanded');

```
> 0 votes

# Answer
I have fixed the issue by doing the following:

* Remove `$('.mapsindeed-dropdown-block .content').hide();`
* Replace it with `$('.mapsindeed-dropdown-block .content').show();`
> 0 votes

---
Tags: theming, javascript
---