title: Add a link to unflag all node

text:
# Question
Title: Add a link to unflag all node
By default, it just available to flag or unflag an item, **reference here**. I want to add a link to unflag all flagged node of current user, is there any way to do that?

At this moment, I get the code to clean all flagged node, but I don't know how to make this snippet as a link

```
db_query("DELETE FROM {flag_content} WHERE sid = %d", flag_get_sid());

```

# Answer
> 2 votes
Create a custom module that implements `hook_menu()`. Use that to create a path and a custom callback function that will run your query. Something like:

```
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['flags/remove/%user'] = array(
    'page callback' => 'MYMODULE_remove_flags',
    'page arguments' => array(2),
    'access callback' => 'MYMODULE_check_access',
    'access arguments' => array(2),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

// Adding custom functions, etc

```

To get started on creating a custom module, the Module developer's guide

# Answer
> 1 votes
I used this workaround to implement an "unflag spam" feature. Basically, I created a second (global) flag "no spam" that moderators can use in a few to now show nodes that have been flagged for spam.

Screenshots (right click and open in new window for full size):

flag\_spam counter settings:

flag\_nospam setting

The "flag link" fields will set the "nospam" flag to suppress those nodes from the view. I didn't see a choice for which flag the flag links applies to. I assume you'll have to add the "flag\_spam counter" relationship.

---
Tags: flags
---


# Question
Title: Views Exposed Filters - position each filter independently
I am working on a drupal 7 project and have a view (v3) over 6,000 product items with 4 exposed filters. This all works fine - I can put the "filter form" in a block - that is fine.

But I can't figure out how to separate out the individual filter drop downs for nicer positioning. Say I want two dropdowns on the top of the result area and 2 with the apply button stacked on the left...

Is my only option to play with absolute positioning in the css?

# Answer
> 8 votes
you can add more functionalities to Exposed Filters forms, or control his style/layout, touching template views-exposed-form.tpl.php. try this resource http://drupal.org/node/320992 or this http://ykyuen.wordpress.com/2011/07/25/drupal-theme-the-exposed-filter-in-views/ to see guides about how to implement it.

---
Tags: views
---


# Question
Title: How to format user profile content to be printed on a printer?
I'm building a recruiting website using the eRecruiter profile distribution which uses Profile2 and was wondering if there is defined solution to creating a formatted page specifically for printing in D7 so the resumes can easily be printed in a nice format.

# Answer
One of the easiest is to create your separate CSS for print. If you have a custom theme you can add the css file in the theme's info file. This way you can hide regions you don't need on paper to be printed.
> 3 votes

---
Tags: theming
---


# Question
Title: How to programmatically set a value to a node attribute
I have a node named let's say "group" to which I added a field called "foo".

How would I programmatically give a value to this "foo" attribute?

I would like to do this when a user is joining a group. This joining process does not involve a saving of the current node, it just add data to a custom table i made. So Hooks don't apply here.

I am guessing i would have to:

1-load the node 2- add data to my attribute 3- resave the node

I am still trying to figure out how to do that, so if anyone has experience to share that'd be much appreciated..

Thanks

# Answer
Actually very straight forward, here is how i have done it:

```
$group = node_load ( $nid );
$group-> foo = 'bar';
node_save ($group);

```

That's it.

Hope that' ll help anyone.
> 1 votes

# Answer
You have a lot of different hooks you can use to edit the node with. See Node API Hooks for more information on those.

I would personally use hook\_node\_presave() to add a value to "foo" this will then be added to the node before it's saved to the database.
> 0 votes

---
Tags: 7, nodes
---


title: Unit test for custom content type

text:
# Question
Title: Unit test for custom content type
I created my custom content type 'Proposal' in D7 and used field API to attach fields. In order to write unit test for it using "simpletest" (core module), do I need to setup my proposal content type in the unit test method from scratch or will the content schema be available to the unit tests?

# Answer
If the custom content type is set up from within a module you're testing, then no you won't have to implement hooks from within the testing environment or anything. However, if your custom content type is set up through the interface on your site then yes you *will* need to do the same in your test. It is very important to realize that tests run in Simpletest are from the perspective of an absolutely clean environment - no users, no permissions, no custom content types, etc - so all of that needs to be implemented in code.

It's not such a big task once you get used to writing tests though. You can probably set up your custom content type in the `DrupalWebTestCase::setUp()` method. A simple series of form posts (with `$this->drupalPost('path/to/form', $form_values, t('Save'));`) and your custom content type will be set up in no time.
> 2 votes

---
Tags: nodes, entities, testing
---


# Question
Title: How do I find out the content type within template.php?
I'm using THEME\_page\_alter to give my site a meta description, and is working fine. However I can't find the variable which defines the content type - I need to use it as an argument to give different pages different descriptions. I tried $node-\>type

Side question: where on earth can I find answers for such simple tasks like this without having to ask in DA? I did a lot of Googling and looking in the API, and looking at the Globals list... but it seems like the official Drupal documentation doesn't make things easy for you in some respects.

Thanks

# Answer
> 1 votes
hook\_page\_alter() is invoked for every output page for which drupal\_render\_page() is invoked; `$node` is not a parameter passed to the hook, nor is there such global variable.

As reported in the documentation, the structure of a page that is output from the Node content contains some specific elements; in particular, it contains the array `$page['content']['system_main']['nodes']`, which has an element for each shown node. For every node, the array contains:

* "body": the body of the node
* "links": the links attached to the node
* "#node": the node object

The code to handle that array should be something similar to the following one:

```
if (!empty($page['content']['system_main']['nodes']) && is_array($page['content']['system_main']['nodes'])) {
  foreach ($page['content']['system_main']['nodes'] as $nid => $content) {
    if ($content['#node']->type == 'The content type you are interested to') {
      // Append to $page['content']['system_main']['nodes'][$nid]['body'] the meta information you want to add.
    }
  }
}

```

Using a test module I wrote, and the Devel module, I noticed that the structure of `$page['content']['system_main']['nodes']` is the following one:

The structure for the "body" index is the following one:

To append a string to the body, you should append it to `$page['content']['system_main']['nodes'][$nid]['body'][0]['#markup']`.

# Answer
> 1 votes
Im new to Drupal. Finding variables and displaying them the way i wanted was very important to me. So i used a code that works in any php script. But i recommend you to always to stick with the Drupal API.

Here is the magic code.

```
<pre><?php var_dump(get_defined_vars()); ?></pre>

```

This will output all the available variables for the current page. However the page will be very long so don do this on your live production site. Test it on a local site or put your site in maintenance mode.

Also check the http://www.hoomanb.com/cs/QuickRef/drupal-7-theming-cheat-sheet.pdf

---
Tags: 7, nodes
---


# Question
Title: menu items saved with menu_link_save() don't have the delete button, and I can't edit the menu path
When I add menu items manually, they work fine. When I try this I get no delete link in the admin, and I can't edit the menu items.

```
$link = array();
$link['link_title'] = "text";
$link['link_path'] = 'node';
$link['menu_name'] = $menu;
$link['expanded'] = 1;
$link['module'] = "dl_migration";
$link['weight'] = $i;
menu_link_save( $link );
menu_cache_clear_all();

```

# Answer
> 1 votes
Specifying the module name is what caused the lack of ability to delete. I'm not sure why, though. Sort of lame I think.

# Answer
> 2 votes
The reason the "delete" link is not shown is that the link is only shown when the menu item is created by (or associated to) the Menu module. \_menu\_overview\_tree\_form() contains the following code:

```
  // Only items created by the menu module can be deleted.
  if ($item['module'] == 'menu' || $item['updated'] == 1) {
    $operations['delete'] = l(t('delete'), 'admin/build/menu/item/' . $item['mlid'] . '/delete');
  }

```

menu\_link\_save() uses some defaults for the array `$item` passed as argument; this means that if the module associated with the menu link is not explicitly set, it receives the default value ("menu").

```
  // Load defaults.
  $item += array(
    'menu_name' => 'navigation',
    'weight' => 0,
    'link_title' => '',
    'hidden' => 0,
    'has_children' => 0,
    'expanded' => 0,
    'options' => array(),
    'module' => 'menu',
    'customized' => 0,
    'updated' => 0,
  );

```

---
Tags: routes
---


title: Module to show code and its output

text:
# Question
Title: Module to show code and its output
What I want to do is setup a "PHP filter" to run the code I'm told to run, and display the results as a normal page.

I also want to be able to have a way to show the code; many websites do it, and I was wondering how I could do so within drupal. Maybe I could tabs in a content type (one for processed code, other for actual code), or an overlay with the PHP Text, or something to show the text in the "PHP Text Field" easily.

**Further Description:**
Say I have the following code as the body content of my page.

```
<?php echo "Hello World!" ?>

```

Who watch the page would see the code output ("Hello World!"); they would not see the PHP code that generated that output. I want something to display the code.

The output of the Geshi Filter module is the following:

# Answer
> 2 votes
I think that in your case, you can insert easyly your own PHP snippets in a common content type to be executed and displayed.

For run your own code from a node you can enable the PHP filter module (it is already in Drupal core, so you does not need download, just enable). this module allows embedded PHP code/snippets to be evaluated. And then, for syntax highlighting of your code, there are several alternatives of modules like:

http://drupal.org/project/geshifilter GeSHi Filter module, for D6 and D7. In this page you will find links to modules alternatives. I have tested this module in drupal 6. Follow the readme.txt instructions. According my test you can show your code (inside respective tags to show code) and run PHP code (copy/paste your code after your code to show, outside the tags to show code). this is an example:

```
<code type="php">
<?php
echo "hello world";
?>
</code>

<?php
echo "hello world";
?>

```

and this is the output:

http://drupal.org/project/wysiwyg\_syntaxhl (for tinyMCE rich text editor) for D6. This alternative seems not listed in Geshi Filter page.

I hope this information be useful.

# Answer
> 1 votes
Propably the best is Syntax Highlighter

---
Tags: 7
---


title: How to get nid of a managed file?

text:
# Question
Title: How to get nid of a managed file?
in hook\_file\_download there is just a parameter named *uri*. How can I get nid of the node that contains the file in uri?

For exmpale I have a file field in my content type.I create a node and add some files to file field. Now when this file is going to be downloaded, in hook\_file\_download I want to get nid of the file.How?

# Answer
If this is an file attached through a file or image field, you can instead implement hook\_file\_download\_access(), which gives you the $field, $entity\_type and $entity to which the file belongs.
> 1 votes

---
Tags: 7, files
---


# Question
Title: How to read file submitted through file field in block configure form
I have created a block through custom module and added file field in block configuration form using below code.

```
function mymodule_block_configure($delta){
if($delta=='mymodule'){
    $form = array();
    $form['mymodule_file']=array(
        '#type'=>'file',
        '#title'=>'Upload text file',
        '#name'=>'files[sample]',

    );
    return $form;
      }
 }

```

When I try to check this field in hook\_block\_save, the form element is empty even when the form is submitted after browsing the file.

```
 function mumodule_block_save($delta,$edit=array()){
    if($delta=='mymodule_block'){
    dpm($edit);
    }
     }

```

`$edit['mymodule_file']` is empty after the form is submitted.

Am I missing anything?

# Answer
You want to use the #type 'managed\_file' instead of just file: http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html/7#managed\_file.

That will then automatically save the file and create a row in {file\_managed}, You just need to set it as permament, as explained in the link above and then save the fid, for example with variable\_set().

You can also set the #default\_value for the fid, and it will display the field again.
> 1 votes

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


title: How to nest elements in a render array

text:
# Question
Title: How to nest elements in a render array
So, I'm trying to generate some markup using render arrays. I need to create some nested divs. I thought that I could do this by nesting the arrays, as such:

```
function make_array() {
  $items = port_view_get_block();
  $array['container']['#prefix'] = '<div id = "container">';
  $array['container']['#suffix'] = '</div>';
  $array['container']['#markup'] = 'This is inside the container div';
  $array['container']['slider']['#prefix'] = '<div id = "slider">';
  $array['container']['slider']['#suffix'] = '</div>';
  $array['container']['slider']['#markup'] = 'This is inside the slider div';
  return $array;
}

```

This doesn't seem to work. The inner array isn't rendered.

What is the proper way to get a nested structure using render arrays?

# Answer
If an element is given `#markup`, the render process stops searching for nested elements. To accomplish what you need, just create a second child element with no `#prefix` or `#suffix`.

```
function make_array() {
  $items = port_view_get_block();
  $array = array(
    'container' => array(
      '#prefix' => '<div id="container">',
      '#suffix' => '</div>',
      'markup' => array(
        '#markup' => 'This is inside the container div',
      ),
      'slider' => array(
        '#prefix' => '<div id="slider">',
        '#suffix' => '</div>',
        '#markup' => 'This is inside the slider div',
      ),
    ),
  );
  return $array;
}

```
> 11 votes

---
Tags: 7, theming
---


title: Drupal messages won't disappear

text:
# Question
Title: Drupal messages won't disappear
I don't understand why, but **my Drupal messages won't disappear**, they just get "added" to each other. Someone has posted a similar problem on drupal.org: "warning/error messages won't disappear", but no solution has been posted yet. There's another one which is almost the same: Drupal messages won't go away.

Here's an example of the problem:

I do have the Administration menu installed, but the problem didn't occur earlier, so I don't think this is the source of the problem.
**I've already cleared cache, ran update.php, ran cron**, so I'm out of ideas.

I recently installed Ubercart module, but I don't know if it has anything to do with my problem.
But there's another one which I also don't understand: if I try to open a page which doesn't exist, I don't just get a "Page not found" error, but many MySQL errors too, which looks like this: (1) (2). It's really unhealthy too... Maybe there's a connection between these problems.

Any ideas?

Thanks!

# Answer
> 3 votes
Messages are kept in the user's session, which by default is stored in a database table called 'sessions'. If your database server dies partway through the page request, the messages may not get cleared from the session.

You can see the MySQL server failing when updating the sessions table in this image due to a max\_allowed\_packet error.

1M is a very small max\_allowed\_packet for a Drupal installation. You may need to ask your host to increase this limit. Alternatively, you could turn off dblog and use syslog instead, which sends your Drupal logs to a system daemon - but this may require your host to set up a syslog location for you.

There may be a module that implements hook\_watchdog() that can save logs to a standard file. I can't find one, but if one exists, that could be a good option in your situation too.

---
Tags: 6
---


# Question
Title: drupal 7 frontpage image scroller: getting image URL in overwritten view template?
I am creating a frontpage image scroller. I have created a new content type with a title, blurb and image field, and created a view block and set it up on the frontpage. All good so far; this works.

I obviously want to use some javascript and custom HTML to create the image scroller so I have overwritten the views 'row style output' template (views-view-fields--content-type-for-scroller--block.tpl.php). This template is getting picked up correctly and I can customize my 3 fields.

The problem is that the output from the image field:

```
$fields['myimage_field']->content

```

includes markup for the image, similar to:

```
<div class="..."><a href="..."><img src="..." />

```

whereby I only want it to output the Image src so that I can use the image as a background to another element.

I'm not too familiar with Drupal 7 but I image somewhere 'further up' I need to overwrite what sort of output I want for that particular field using some preprocessor but I'm not sure how to do this? Or is there a better way in general to be doing this?

# Answer
> 1 votes
here two alternatives to get the image address: (to both examples the machine name of the image field is \*image\_test\_field\*).

1) this example is using the $row offer by view template (in this case the name of the field was obtained using `dsm($row)` or `print_r($row)`):

```
  $uriImagefromView = $row->field_field_image_test_field[0]['rendered']['#item']['uri'];
  $urlImagefromView = file_create_url($uriImagefromView);
  // $urlImagefromView variable now has the path to the image

```

2) this example is loading the data from entity\_load (in this case the name of the field was obtained using `dsm($entity)` or `print_r($entity)`):

```
  $nid = $row->nid;
  $entity = entity_load('node', array($nid));
  $uriImagefromNode = $entity[$nid]->field_image_test_field['und'][0]['uri'];
  $urlImagefromNode = file_create_url($uriImagefromNode);
  // $urlImagefromNode variable now has the path to the image

```

I hope this information be useful.

---
Tags: views, theming, media
---


# Question
Title: How to make Drush rsync @dev @staging exclude some directories?
I am using the following drush commands to synchronize development and test environments.

```
drush rsync @dev @staging
drush sql-sync @dev @staging

```

How to setup drush to exclude certain directories (such as *sites/all/modules/devel* ) from this synchronization process ? I don't want devel module and some other modules to be included in staging environment and would like drush to automatically take care about this requirement.

# Answer
> 3 votes
It's not so simple like just don't send the directory.

Actually, you're synchronizing SQL and directories. If you want avoid some directories (specially modules) you should also avoid their tables and configuration sync.

The best way its, from my point of view, to sync them and after to dis and pm-uninstall them in the staging process.

---
Tags: drush, staging, debugging
---


# Question
Title: cron error Fatal error: Call to undefined function filter_xss()
I am running a remote command on my server to execute cron.php and I get this error : Fatal error: Fatal error: Call to undefined function filter\_xss() in /home/k1004/html/www\_dem o/oan/srcs/includes/common.inc on line 655 Does anyone have an idea about where it comes from??

# Answer
I finally found a patch that solved the problem. It seems that it was a problem in the core update I have made.
> 0 votes

# Answer
Can you make sure the filter module is enable.

I think this problem is because you have a function call to filter\_xss() before the filter module load.

Is your Drupal is stand install or this problem exist after install other module?
> 1 votes

---
Tags: 6, cron
---


# Question
Title: node_load() Performance and alternatives
I created a custom module which lists the last X nodes from a certain content type, with the following query:

```
SELECT n.title, r.teaser, r.timestamp
FROM node n
INNER JOIN node_revisions r ON r.vid = n.vid
INNER JOIN term_node tn ON tn.nid = n.nid
INNER JOIN term_data t ON t.tid = tn.tid
WHERE t.name= 'breaking_news'
AND n.status = 1
ORDER BY n.nid DESC LIMIT 25

```

Then I do a `node_load($nid)` to check if there is a image and an audio file inside, for example

```
$mynode = node_load($queryresutl->nid);
if ($mynode->field_efe_audio[0]['filepath']) {
  $audio = 'yep, has audio';
}

```

But I've read that `node_load()` could be a performance killer, so I wonder if this is true and if there's is an alternative to check fields in my module?

# Answer
First i would make sure that using node\_load() does slower your script. If you are sure it really does you can either:

* 1- Create an `index_audio` table with a nid and `use_audio` columns. You could update this table on node `creation/update/delete`. Then you can just query this table to make sure a specific node does have audio attached to it. I would use that solution only if i you have to intensively make such a check
* 2- Directly query your field table with your `nid` as `etid`, in your instance : `field_data_field_efe_audio` table see if it returns `FALSE` or some actual data
> 5 votes

---
Tags: nodes, 6
---


title: Ajax call module function

text:
# Question
Title: Ajax call module function
I need to make asynchronous page requests on *every* page load using AJAX, the idea being that a function in my module is called even when pages are cached.

The only documentation I've been able to find (Drupal 7) is for form handling using AJAX and handling links.

**How do I call a module function from a custom AJAX request? Would I just implement hook\_menu() and write a custom ajax request or is there a better way of doing this in Drupal 7?**

# Answer
> 0 votes
I guess the answer depends on what that ajax call does, and if it is for a 'one site use' or for a contribution module.

If it s for a contribution module hook\_menu might be the only way to go.

Though if it s just for a 'one site use' i would just add a *JS snippet* in your `page.tpl.php` or even `html.tpl.php` that launches the Ajax query. This would work on every page even when if cached.

**EDIT** Actually you could also use the page preprocess function and add a js file to all your pages.

---
Tags: 7, ajax
---


# Question
Title: Not display page with meta - front.tpl.php
When I use metatags and page--front.tpl.php, the meta will not be displayed. But when I remove the top page--front.tpl.php, meta displayed correctly.

Page =\>

```
        <?php include_once 'templates/header.tpl.php'; ?>

        <div class="clearer"></div>
        <div id="gbl-content">
            <div id="content-maison">
                <?php print render($page['content']);?>
            </div>
                            <div id="sidebar-right-custom">
                    <div>
                        <?php
                            if(isset($node)) :
                                if($node->nid == 57 || $node->title == 'Le label BBC') :
                                    foreach ($node->field_imagead['fr'] as $key => $imgMaison) :
                                        echo '<img src="'.$base_path.path_to_theme().'/images/bbc.png" class="bbc" title="Éligible BBC" style="margin: -7px 0 0 249px" />';
                                        echo '<img src="'.file_create_url($imgMaison['uri']).'" id="thumbnail_'.$key.'" class="imgBBC" />';
                                    endforeach;
                        ?>
                            <div class="textCadreBBC">
                                Maison Atlantique Demeures<br/>
                                bénéficiant du label BBC
                            </div>
                        <?php
                                endif;
                            endif;
                        ?>
                    </div>
                    <?php
                        if(isset($node)) :
                            $nid = $node->nid;
                            $daily = get_dailymotion($nid);
                        foreach ($daily['query'] as $key => $value) :
                    ?>
                    <div id="dailymotion-bcc">
                        <span class="dailyTitle"><?php echo $value['title'] ?></span>
                        <iframe frameborder="0" width="260" height="194" src="<?php echo $value['video'] ?>?width=260"></iframe>
                        <div class="daily_allvideos">
                            <a style="font-size: 13px; color: #666666;" title="Voir toutes les vidéos" href="#" target="_blank">Voir toutes les vidéos</a>
                        </div>
                    </div>
                    <?php
                        endforeach;
                        endif;
                    ?>
                    <?php include 'templates/sidebar-info.php';?>
                </div>

                    <div class="clearer"></div>
        <div id="footer">
            <?php include 'templates/footer.tpl.php';?>
        </div>
        </div>
    </div>

```

Front =\>

```
        <?php include_once 'header.tpl.php'; ?>

        <div class="clearer"></div>
        <div id="gbl-content">
            <?php  include_once path_to_theme().'/carrousel.tpl.php'  ?>
            <div id="content">
                <div id="content-text">
                    <h2><span class="title_bleu">Bienvenue chez</span> <span class="title_orange">Atlantique Demeures</span></h2>
                    <p class="text"><span class="textOrange">ATLANTIQUE DEMEURES</span>, constructeur de maisons individuelles en Loire Atlantique (44) vous accompagne tout au long de la construction de votre projet : maison plain pied, à étage, maison en Z, BBC, terrain…</p>
                    <div class="separatorText"></div>
                    <p class="text paddingLeft10">
                        Bénéficiez des garanties <span class="textOrange">ATLANTIQUE DEMEURES</span>: garantie décennale-biennale, garantie de <br/>dommage-ouvrage, garantie de remboursement
                        de l’acompte, garantie à prix et délais convenus.
                    </p>
                    <div class="clearer"></div>
                    <div id="blocTerrain">
                        <div class="bc-haut"><a href="/terrains">Terrains à bâtir</a></div>
                        <div class="bc-bas">
                            <a href="/terrains"><img alt="" src="<?php echo $base_path.path_to_theme().'/images/maison.jpg' ?>"></a>
                            <p><a href="/terrains">Trouvez votre terrain dans le secteur de votre choix pour la construction de votre maison.</a></p>
                        </div>
                    </div>
                    <div id="blocMaison">
                        <div class="bc-haut"><a href="/maisons">Maisons</a></div>
                        <div class="bc-bas">
                            <a href="/maisons"><img alt="" src="<?php echo $base_path.path_to_theme().'/images/maison.jpg' ?>"></a>
                            <p><a href="/maisons">Choisissez une maison correspondant à vos besoins parmi nos différentes gammes.</a></p>
                        </div>
                    </div>
                    <div id="blocExclu">
                        <div class="bc-haut"><a href="/exclus">Nos exclusivités</a></div>
                        <div class="bc-bas">
                            <a href="/exclus"><img alt="" src="<?php echo $base_path.path_to_theme().'/images/maison.jpg' ?>"></a>
                            <p><a href="/exclus">Découvrez tous nos packs maison + terrain pour la construction de votre projet.</a></p>
                        </div>
                    </div>
                    <div id="blocBBC">
                        <div class="bc-haut"><a href="/maisons-bbc">Maisons BBC</a></div>
                        <div class="bc-bas">
                            <a href="/maisons-bbc"><img alt="" src="<?php echo $base_path.path_to_theme().'/images/maison.jpg' ?>"></a>
                            <p><a href="/maisons-bbc">Réalisez des économies d'énergie en construisant une maison BBC</a></p>
                        </div>
                    </div>
                </div>
                <?php
                     $query = db_select('dailymotion', 'd');
                     $query->fields('d');
                     $query->join('dailymotion_node', 'dn' , 'd.did = dn.did');
                     $query->condition('dn.nid', 0);
                     $result2 = $query->execute()->fetchObject();
                ?>
                <div id="sidebar-right">
                    <span class="dailyDecouverte">Découvrez virtuellement visite en vidéo de la</span>
                    <span class="dailyTitle"><?php echo $result2->title ?></span>
                    <iframe frameborder="0" width="260" height="194" src="<?php echo $result2->video ?>?width=260"></iframe>
                    <div class="daily_allvideos">
                        <a style="font-size: 13px; color: #666666;" title="Voir toutes les vidéos" href="#" target="_blank">Voir toutes les vidéos</a>
                    </div>
                </div>
                <div class="clearer"></div>
            </div>

        <div id="footer">
            <?php include 'footer.tpl.php';?>
        </div>
        </div>
    </div>

```

# Answer
> 1 votes
It sounds like page.tpl.php prints a certain variable, but page--front.tpl.php does not. However it's hard to tell because I can't see your code. If this isn't enough help for you, please update your question and post the code from your page and page--front tpl files.

\[update\]

I believe @akalata is right about html.tpl.php, but that said: You're clearly hacking your way around the Drupal theme system, instead of using is the way it's meant to be used. Your template files above are a mix of styling (html, images, inline css), functionality (db queries, menu-items) and content (caroussel, video). If that works for you, I will not stop you. However it hard for me to help you with it and IMHO, you shouldn't be surprised that some modules break.

---
Tags: 7, meta-tags
---


# Question
Title: How to set Drush sql-sync not to clone users between @dev and @staging?
As I wrote in my previous question, I am using the following drush commands to synchronize development and staging environments.

```
drush rsync @dev @staging
drush sql-sync @dev @staging

```

How to set up **drush sql-sync not to clone users between @dev and @staging** environments? I would like to have separate users (and passwords) on @dev and on @staging sites.

# Answer
> 3 votes
The `drush sql-sync` has an option `--skip-tables-key` that allows you `drushrc.php` to skip tables during the synchronization.

In your drushrc.php you add this line.

```
$options['skip-tables']['staging'] = array('users', 'users_roles', 'roles', 'permission');

```

Your drush command line should look like the following.

```
drush sql-sync --skip-tables-key=staging @dev @staging

```

You've to be careful, as you've to skip all tables that had informations related to your users, including the tables used from third modules.

---
Tags: users, drush, staging
---


# Question
Title: How to let public access to the sitemap page?
I am using the Site map module that creates a page called sitemap. However, I cannot access it if I am not logged in, as the access is denied for that page for the anonymous users.

How can I let public access to the sitemap page?

# Answer
> 5 votes
As far as I can tell, this is permission based, so you need to give anonymous users the `access site map` permission.

From the module:

```
/**
 * Implements hook_permission().
 */
function site_map_permission() {
  return array(
    'access site map' => array(
      'title' => t('View published site map'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function site_map_menu() {
  $items['admin/config/search/sitemap'] = array(
    'title' => 'Site map',
    'description' => 'Control what should be displayed on the site map.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('site_map_admin_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'site_map.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['sitemap'] = array(
    'title' => 'Site map',
    'description' => 'Display a site map with RSS feeds.',
    'page callback' => 'site_map_page',
    'access arguments' => array('access site map'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}

```

# Answer
> 1 votes
Go to "Module \>\> Sitemap \>\> Permission" (on OPERATIONS tab). Look for the Site map module, and select the suitable checkboxes.

---
Tags: 7, users
---


# Question
Title: SQL select data from more than one table
I've constructed a nice query in drupal 7:

```
SELECT og.label AS title, og.gid AS gid
FROM og
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
WHERE ( (field_data_field_group_category.field_group_category_value IN  ('1')) )
ORDER BY title ASC

```

This works but actually I want to remove the WHERE clause and instead put field\_data\_field\_group\_cat.field\_group\_category\_value in my result. But when I try:

```
SELECT og.label AS title
  , og.gid AS gid
  field_data_field_group_category.field_group_category_value AS cat
FROM  og, field_data_field_group_category
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
ORDER BY title ASC

```

This won't work.. How do I get a value of another table in the result object?

Greetings!

# Answer
You second query is incorrect because you have the table `field_data_field_group_category` two times, so it would generates duplicates and there's a missing coma in your SELECT clause. If you want your column in the result without filtering it, just put it in the SELECT clause and that's it.

```
SELECT og.label AS title
  , og.gid AS gid
  , field_data_field_group_category.field_group_category_value AS cat
FROM og
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
ORDER BY title ASC

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: How to obtain Drupal session cookie via an XMLRPC request?
I would like to implement single sign-on to Drupal and other site (not PHP) via xmlrpc.

Is there a way to make an xmlrpc call with user name & password and in return obtain information on success of authentication and the session cookie - so that we could set the cookie and log in to both sites at once?

# Answer
> 2 votes
The Services module does this. See its user.login service. Core Drupal does not offer this service via XML-RPC.

---
Tags: 7, users, authentication-authorization, cookies
---


# Question
Title: Adding Fivestar rating each item in a view containing most recent stories?
I'm using the Fivestar module (drupal.org/project/fivestar) and was just wondering if it is possible to add it to a view of my most recent stories. Basically, I want it to appear below each item in the view so users can both view it and use it.

# Answer
Adding the Fivestar widget to your views is pretty simple:

1. Add the relationship *Node: Vote Results*
2. Add the field *Vote Results: Value*
3. Choose how you wish to display the widget by changing **Appearance:** to either *Fivestar Stars (clickable, with text)* or *Fivestar Stars (clickable, no text)*
4. Click "Update" and save your view
> 3 votes

---
Tags: views, 6, rating
---


# Question
Title: Sorting rows and return the value as a simple array using EntityFieldQuery
I have a drupal custom entity\_type. I am trying to do to things, find the row that is the oldest and return with a simple array. I currently have the following:

```
function oldestTicket(){
   $query = new EntityFieldQuery;
   $ticketTime = $query
  ->entityCondition('entity_type', 'as_ticket')
  ->propertyCondition('status','new')
  ->fieldOrderBy('updated', 'value', 'ASC')
  ->pager(1)
  ->execute();
  $entities = entity_load('as_ticket', array_keys($ticketTime['as_ticket']));
  return $entities;
}

```

This results with an error saying that updated is not a valid column field (it is in the db) and the return array is a complex multidimensional array. I would prefer something a little simple. In fact I would prefer that the returning result was just a string with updated timestamp value.

# Answer
> 1 votes
fieldOrderBy is for ordering by a Field API field. You want propertyOrderBy('updated' 'ASC').

And the return structure can't be changed, it's always the same (a stub entity in technical terms). You use the id from that return structure to load your entity and get the data you want. I see you've already figured that one out, judging by your code.

---
Tags: entities
---


title: Create a hook function

text:
# Question
Title: Create a hook function
I want to create a hook function so that other modules implement it, any pointers to how it is done?

# Answer
You don't create a hook, in the same way Drupal core doesn't create `hook_nodeapi()`, or `hook_hook_info()`. You write code that uses (invokes) the implementation of a hook done in other modules. The modules that want to interact/integrate with yours will implement that hook, and your module will use `module_invoke()`, `module_invoke_all()`, or `drupal_alter()` to invoke those hooks.

The correct phrase is not *creating a hook*, but *defining a hook*, which is essentially documenting that your module invokes a specific hook.
> 3 votes

# Answer
> Essentially there are 2 things needed to create your own hook(s).
>
> * Create your own function that calls `module_invoke_all('WHAT_YOU_WANT_YOUR_HOOK_TO_BE_CALLED');`
> * Create your new module and a function called `YOURMODULE_WHAT_YOU_WANT_YOUR_HOOK_TO_BE_CALLED()`
>
> That is ALL it actually takes to implement your own hooks in a Drupal module. The great thing here is the flexibility that it provides for you to do anything, AND allow other developers to easily extend your work. The major consideration I can see here is naming your hook. You should obviously try to choose something unique to your module, that a core or another contributed module wont be using.
> 7 votes

---
Tags: hooks
---


# Question
Title: How to change access callback for content create?
I want to allow each user to create a specific node type only once.I know that I must use hook\_menu\_alter and change *access callback* to my own callback function.But using this way Drupal's main access callback is overriden and it will skip permissions defined in permissions page.

Is there a way to call my own access callback after main access callback is called?

# Answer
> 1 votes
I would implement code similar to the following one:

```
function mymodule_menu_alter(&$items) {
  $content_type = 'the machine name for the content type for which you want to alter the access callback';
  $type_url_str = str_replace('_', '-', $content_type);

  if (isset($items['node/add/' . $type_url_str])) {
    array_unshift($items['node/add/' . $type_url_str]['access arguments'], $items['node/add/' . $type_url_str]['access callback']);
    $items['node/add/' . $type_url_str]['access callback'] = 'mymodule_node_access';
  }
}

function mymodule_node_access() {
  $args = func_get_args();
  $callback = array_shift($args);
  $result = call_user_func_array($callback, $args);

  // ...
}

```

The new access callback invokes the old access callback passing the arguments it is expecting; it can verify the result returned by the old access callback, and decide the next step to follow.

# Answer
> 1 votes
Absolutely. Just replace original access callback with your own function, and then in your function do both your checks AND call the original callback function.

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


# Question
Title: Rendering a Block Region in My Custom Theme
I am having my custom theme. In the theme.info i have a region latest defined

```
regions[latest] = Latest

```

How do i print that region in my theme? Is the below code correct?

```
<?php print render($latest);?>

```

I tried dragging the Recent Posts block to this, but nothing appears. What am i doing wrong?

# Answer
> 1 votes
clear your theme cache to see your custom regions working: http://drupal.org/node/337176

Also see this link to review if something more is missing in your process: How-to create custom regions in a theme?

---
Tags: blocks, theming
---


# Question
Title: How to dynamically populate the condition method argument in a Dynamic Query
I am writing a query that will retrieve nodes that match a set of criteria. Though the number of cirteria is unknown. I was hopping i could pass to the `condition()` method an array of criteria with a key as the 'column name' and that value as the 'value to match' for that colum. For instance :

```
$criteria = array ('nid' => 1, 'etid' => '1')

$query = db_select('table', 't');

$query
  ->condition( $criteria)
  ->fields('t', some_field);

```

I have almost 10 criteria and no way to know which will be selected so writing a query for each wont be possible.

Is there a way to achieve that ?

**EDIT:**

i thought about using that :

```
if (empty($criteria1)){
    $criteria = array (":criteria1"= '*');
}else {
 $criteria = array (":criteria1"=$criteria1);
}
$query = db_query('SELECT nid FROM { parce_index } WHERE criteria1 = :criteria1 AND criteria2= criteria2...',$criteria));

```

Would that make sense ?

# Answer
If anyone ever need that i got an answer there.

http://drupal.org/node/12843

This is useful as well :

https://stackoverflow.com/questions/7476611/how-to-write-a-query-with-a-dynamic-where-clause
> 0 votes

---
Tags: 7, database
---


title: Weighting Javascript in .info files

text:
# Question
Title: Weighting Javascript in .info files
Drupal 7 adds a new 'weight' option to drupal\_add\_js so that you can control the order in which Javascript files are added to the page. Is there any way to do this when adding Javascript in .info files?

# Answer
> 2 votes
But to answer the actual question, the order that the files are included in the .info file should be the order that they appear on the page.

# Answer
> 6 votes
Despite its instructions to not use it for adding JS to every page, `hook_init()` will allow you to add JS in an more sophisticated way with `drupal_add_js()`.

That said, it is rare that a JS file must be loaded on *EVERY* page, so there is likely more optimization you can do. Also see the FAPI property `#attached` for adding JS to a form.

---
Tags: 7, .info, javascript
---


# Question
Title: Where to define permissions for user roles in FCKEDitor file uploads?
There is this page where you upload files with FCKeditor My admin user can do that , but I want the same for the Editor role (I already defined a profile for it) It´s a matter of permissions and I´ve enabled all on the FCKEditor but I´m sure it´s something else...that I have to enable...

# Answer
Are you using the IMCE module for file uploads/directory? It could be a setting there that you need to enable.
> 0 votes

---
Tags: users, wysiwyg, files
---


# Question
Title: How to create a RSS feed of certain content type ( without affecting the front end layout )?
I would like to create a RSS feed of certain content type ( without affecting the front end layout ), but I am not quite sure how can I add this feature to Drupal. Any clues for me to start with?

p.s. I'm using Drupal 7.

# Answer
> 2 votes
Views will allow you to do it. But when you make changes to the view you must select "over ride for this view" or it will change all views associated with the RSS feed.

---
Tags: 7, nodes, feeds
---


title: editor interface with views

text:
# Question
Title: editor interface with views
I had a site where the developer set up an screen that you went to directly upon logging in. it was a custom view, within a template that displayed all the content. The view was a block and displayed only to editors. I set this all up but the blocks are not displaying. Am I missing a step here

this is all i have in my page.tpl.php file

```
  <div id="content" class="clearfix">
    <?php print $content; ?>
  </div>

```

# Answer
In your page.tpl.php there's nothing regarding regions ? You're certainly missing some code like:

```
<?php if ($page['sidebar_first']): ?>
  <div id="sidebar-first" class="sidebar">
    <?php print render($page['sidebar_first']); ?>
  </div>
<?php endif; ?>

```

See page.tpl.php documentation.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: Override "Display select options" to see them in reversed alphabetical order
Can anyone advise me how to override the Hierarchical Select module to display select options in reverse alphabetical order?

# Answer
> 1 votes
there seems to be a patch to change the sort order: http://drupal.org/node/466828#comment-4904174

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


# Question
Title: What are some design patterns found in prominent contributed modules?
Besides Presentation-abstraction-control and other patterns that are used in Drupal core, are there any other design patterns prominently used in the more popular contributed modules such as Views, CCK, and Features?

# Answer
One place to start is with core itself and the patterns exposed to contrib. - a great write-up by Larry Garfield (Crell) can be found in a Drupal Watchdog article.

> ### Observers, visitors, and peeping toms
>
> Drupal is actually built on the twin patterns of Observer and Visitor, although it doesn't call them by name. Instead, it calls them hooks. `hook_node_load()`, `hook_user_login()`, and so forth are, in essence, observers on nodes and users. `hook_form_alter()`, `hook_node_view()`, and so forth are, in essence, visitors. Because Drupal does not differentiate between the two, some hooks could arguably be considered both patterns but the principle is the same.
>
> ### Factories and commands
>
> There are several variations on the Factory pattern, but they all boil down to the same idea: One object, a client, asks another object, a factory, for an appropriate implementation of a piece of logic, but doesn't care which it is. That's up to the factory to decide. Consider the `db_insert()` function, the important bits of which are show below:
>
> ```
>    function db_insert($table, array $options = array()) {
>        // ...
>        return Database::getConnection($options['target'])->insert($table, $options);
>      }
>
> ```
>
> The `Database::getConnection()` method is a factory that returns a connection object appropriate for this site.
>
> ### Doctor Drupal's Dependency Injection
>
> In Drupal 6, the menu system was gutted and rewritten to be a multi-step process. We would now implement the same page callback like this:
>
> ```
>    function example_menu() {
>        $items['node/%node/example'] = array(
>          'page callback' => 'example_page',
>          'page arguments' => array(1),
>          // ...
>        );
>        return $items;
>      }
>
>      function example_page($node) {
>        // Do useful stuff here.
>      }
>
> ```
>
> In this new setup the menu router gets more complex. In return, however, the page callback gets the node on which it depends passed to it, that is, injected into it. That gives us a number of benefits.
>
> ### Go for Broke(r)
>
> One common approach is some variation on the idea of a Broker or Mediator. In this design, an object doesn't request information from another object directly. Instead it asks an intermediary object, which may have been injected into it, to make such a request on its behalf. While it still means the first object has to actively request information, it is only tightly coupled to the mediator object and not to the myriad of other objects it may need to request information from. That means if those other systems change we need only update the mediator, not every system that touches it.
> 11 votes

---
Tags: 7
---


title: Ajax reload of block on an event

text:
# Question
Title: Ajax reload of block on an event
I have created a block through custom module. The content of the block should be random every time it loads the block. Call back function for this was written. The block also has a link say "Next" and when clicked on should reload the block with next random content.

How to get the block to reload without reloading the whole page when the link Next is clicked on?

Below is the module code I am using and js file.

```
/*
 * Implement hook_menu
 */

function my_module_menu(){
    $items['tips/reload']=array(
        'title' => 'Block Reload',
        'page callback'=>'reload_tip',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

/*
 * Implement hook_block_info().
 */
 function my_module_block_info(){
    $blocks['my_module']=array(
        'info' => t('My Tips'),
        'status' => TRUE,
        'region' => 'content',
        'weight' => 0,
        'visibility' => 0,
    );
    return $blocks;
 }

 /*
  * Implement hook_block_view().
  */
 function my_module_block_view($delta=''){
    switch($delta){
        case 'my_module':
            $block['subject'] = t('Teamie Tips');
            $block['content'] = my_module_block_content($delta);
            return $block;
        }

 }

 /*
  * tips block content function
  */
 function my_module_block_content($delta){
    $output = "<div id='divTip'>".getrandomtip()."</div>";
    $output .="<a id='NextTipLink' href='tips/reload'>Next</a>";
    return array('#markup'=>$output);
 }

  function reload_tip(){
    $tip = getrandomtip();

    return drupal_json_output(array('nexttip'=>$tip));
    exit;
 }

 function my_module_theme(){
    return array(
        'my_module_javascript'=>array('arguments'=>array(),),
    );
 }

 function my_module_init(){
    theme('my_module_javascript');
 }

 function theme_my_module_javascript(){
    $jsfile = drupal_get_path('module','my_module').'/my_module.js';
    drupal_add_js($jsfile);
 }

```

and my js file is as below

```
 (function ($) {Drupal.behaviors.my_module = function (context){
    $('a#NextTipLink').click(function(){
        var nextTip = function(data){
            $("#divTip").html(data.nexttip);
        }
        $.ajax({
            type:'POST',
            url:this.href,
            success:nextTip,
            data: 'js=1',
        });
        return false;
    });

}})(jQuery);

```

When I click on next link, pop up is coming with file having json object. But I need to reload the blok content. Am I doing something wrong?

# Answer
To answer my own question below is the correct js file that is working.

```
(attach:function ($) {Drupal.behaviors.my_module = {function (context){
    $('a#NextTipLink').click(function(){
        var nextTip = function(data){
            $("#divTip").html(data.nexttip);
        }
        $.ajax({
            type:'POST',
            url:this.href,
            success:nextTip,
            data: 'js=1',
            dataType:'json',
        });
        return false;
    });

}};})(jQuery);

```
> 6 votes

---
Tags: 7, blocks, ajax
---


# Question
Title: How to redirect all 404s to the same path on a different server
I want to redirect all 404 errors on my site to the same path on a different server.

For example:

http://drupal.example.com/url/not/in/drupal should be redirected to http://othersite.example.com/url/not/in/drupal

The sites are not on the same server and the other site is not running Drupal.

I know I can use the redirect module to redirect specific URLs but I don't have a complete list of the URLs on the other site so building the list is not practical.

Suggestions for modules or pointers to the appropriate hooks if I want to write my own module would be appreciated.

# Answer
> 1 votes
Here is small trick:

Enable module PHP Filter, add PHP filter to administrator

Create a node can use php filter, add code: (We are using header here, not use **drupal\_goto** because handle 404 workfollow of Drupal will redirect to the node first.

```
<?php
  $url = drupal_get_destination();
  header('Location: http://other.example.com/' . $url['destination']);
  drupal_exit();
?>

```

Config Drupal using 404 page is the node you was create.

---
Tags: redirection
---


# Question
Title: Create a RSS using Views of a content type
How to configure Views to display a RSS feed of certain content types, which contains several articles?

I would like the RSS to have **1 news feed for 1 content type**. How to config it?

I can only set the feed to display all article titles in 1 news feed, which does not make sense.

The sample XML is like this:

```
<news>
    <article>
        <title>Some Title Here</title>
        <content><![CDATA[Some Contents here]]></content>
        <pubDate>2011-09-20 10:01</pubDate>
    </article>
    <article>
        <title>Another Title Here</title>
        <content><![CDATA[Other Contents here]]></content>
        <pubDate>2011-09-20 11:01</pubDate>
    </article>
</news>

```

where the 2 articles above is in certain content type.

# Answer
> 2 votes
Following comment exchange under the question - just add a new view showing "content" of type \<your\_type\>, tick "Create a page" and "Include an RSS feed" underneath. This will give you a feed with list of all nodes of a specific type. Then just play with all other settings to get what you need, and that's it.

# Answer
> 0 votes
Currently there is only to create a custom RSS templates from views. Unfortunately not allot of data is passed on, but I believe content types do pass on, though you would want to order the RSS view by content type first.

---
Tags: 7, views, feeds
---


# Question
Title: Assigning CSS classes to exposed widgets in a view?
I have several exposed widgets in a view, they allow users to sort stories by date or by tag. However, I am trying to style the block and because each widget is only given a 'views-exposed-widget' class by default, I can't figure out a way to style each widget differently. Is there a simple way to give each widget a different css class or id? I need to set different widths to different divs, etc.

# Answer
Drupal – Theme the Exposed Filter in Views. Basically make a custom views-exposed-form.tpl.php file at your theme level that is specific to each of the widgets you have setup. You can then adjust the markup in each of the template files to include a unique ID to allow styling specific to each widget.
> 4 votes

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


# Question
Title: Provide variable to page.tpl.php to mark page as Access Denied or 404?
Ideally I'd like to provide new classes to the body tag such a access-404 or access-denied, but unfortunately I'm not really aware of how to capture these.

I don't mind to identify these pages from the Page Title itself from template\_preprocess\_page, however it seems that $vars\['title'\] does not exist in D7? How can I access the page title from within a template\_preprocess function?

SOLUTION: Thanks to DeeZone:

In my template.php:

```
function template_preprocess_html(&$vars){
  $status = drupal_get_http_header("status");
  switch($status){
  case "403 Forbidden":
  case "404 Not Found";
    $vars['classes_array'][] = 'drupal-page-error';
    dsm($vars);
    break;
  }
}

```

# Answer
If I uderstand your question perhaps try: Drupal 7 Custom 404 Page Template \- use this method to setup a custom page template (tpl) file for your 404 page. This will give you a specific page template that you can hard code classes you're wanting - "access-404" or "access-denied" in the body tag.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How can I direct the user to a different page on a multisite installation based on which subdomain they go to?
I have a site, let's call it www.example.com, and I'm going to create subdomains for it with the same Drupal installation on every subdomain. I can do that. However, when someone goes to a subdomain, I would like them to see a different page depending on which subdomain that they go to. Say for example they go to user1.example.com, can I make that somehow redirect them to an arbitrary page within the Drupal installation? I hope that's clear.

# Answer
This is one of the things that you can do with the Domain Access module. Essentially, it allows you to have different behaviors for a site with subdomains, but running from the same database. This is different from multisite, which uses a different database for each site.
> 0 votes

---
Tags: redirection, multi-sites
---


# Question
Title: Controlling blocks displayed in domain access for each sub-domain
I'm a noob in Drupal and have been exploring the Domain Access module ( http://drupal.org/project/domain ) in my local environment and till now has been doing pretty well. But when it comes to configuring block content i'm a bit baffled. Problem goes like this: domain is localhost.com Sub domains are:

* one.localhost.com
* two.localhost.com
* three.localhost.com

When i enable a block in one of the sub-domains two.localhost, say enabling Search in Right Sidebar and saving the changes they are applied not only to two.localhost but to all the others too.

Note that I'm working in drupal 6.22 with Garland theme in all the sub domains. Is there anything I'm missing from the functionalities provided by the module like Domain Theme? or does it have to be coded by me to make blocks also in domain specific manner...any suggestions/helps would be much appreciated.

Thanks and cheers!

# Answer
You've a module that gonna help you. Domain Blocks. And here you've many other that add some features to Domain Access module.
> 2 votes

---
Tags: domain-access, blocks
---


# Question
Title: How to get body field within THEME_page_alter
> **Possible Duplicate:**
> How do I access node body from template.php?

I've actually asked this previously, but I received an unsatisfactory answer, and thus my question was forgotten, as it was marked 'answered'.

My aim is to have a meta description on my front page, and a meta description for each of my blog entries, I'm using THEME\_page\_alter to achieve this. Both the metatag and metatags\_quick modules don't seem to work properly despite several hours of changing settings.

Here is the code located in my template.php:

```
function vertaxe_page_alter($page) {
    $description = 'My default desc';
    if (!empty($page['content']['system_main']['nodes']) && is_array($page['content']['system_main']['nodes'])) {
        foreach ($page['content']['system_main']['nodes'] as $nid => &$content) {
            if ($content['#node']->type == 'blog') {
                $description = '';
            }

        }
    }

    $meta_description = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'description',
            'content' =>  $description
        )
    );

    drupal_add_html_head( $meta_description, 'meta_description' );

}

```

How do I get the node's body field for use in my description?

# Answer
> 2 votes
According the hook\_page\_alter() documentation you should be able find the body like that.

```
$description = $page['content']['system_main']['nodes'][$nid]['body'];

```

But if you still have the problem you can display all data from your page with the help of Devel module or simply with a `print_r($page);` and look where is the content that you're looking for.

---
Tags: entities, nodes
---


# Question
Title: What security should I double-check before opening my site to being multi-user?
I've been using my D7 installation as a single-user blog, and operated assuming that would always be the case. In the process, I may have been sloppy with permissions in various places, such as viewing, authoring, input formats, etc.---I'm no longer sure.

Now, however, I am going to open my site to subscribers (for a mailchimp mailing list), and possibly allow another content author.

Before I undertake these, what should I go over to make sure I'm safe, and ensure my site stays secure and is well permissioned? Can someone help me construct a security checklist for all items I need to verify to move from single-user to multi-user?

# Answer
Joao's suggestions are all good.

One other easy thing to do is install the security review module which can test a lot of things for you.

Read over the page at admin/people/permissions (d7) or admin/user/permissions (d6) and make sure the "authenticated" user doesn't have any surprising permissions.
> 3 votes

# Answer
Mittenchops, here is a suggestion

1. Create a role for the new users
2. Guarantee that this role doesn\`t have permission to use PHP Filter
3. Check all the "administer " permissions to see if the new role is not having access to certain areas that it should not have
4. Create a new user for you with this new role and test the site.
5. During the process of creating the new user check if you are able to choose the role (you shouldn't be)
6. You should also try to access pages like http://yousite.com/admin which a common user should'n have permission

I think you would be safe with this.
> 4 votes

---
Tags: security, users
---


# Question
Title: Drupal 6 - Using node_view and display comments
i'm using node\_view to print nodes in a custom page. But the problem is that i need also the comments and the form comment to be shown under the node view.

How can i achieve this?

# Answer
> 2 votes
You probably need to use the node\_show() function instead; it outputs the node as well as its accompany comment thread and comment form. node\_show() relies on node\_view() to print the node itself, but also calls comment module's code to build the rest.

One good rule of thumb for tracking down these scenarios is to visit the api.drupal.org site, look up the function that you're using to output a portion of the information you need, and look at the functions that *also* call it in Drupal core.

---
Tags: nodes
---


# Question
Title: Created a module that has a form: How do I display on a page?
I just created a module called member\_survey that just contains a simple information gathering form.

What I'd like to do is create a page with the url www.example.com/member-survey that contains the survey that i just created.

I can't for the life of me figure out how to do this. Can anyone point me in the right direction?

# Answer
You should use `hook_menu()`.

```
function member_survey_menu() {
  $items['member-survey'] = array(
    'title' => 'Your title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('your_form_function'),
    'access arguments' => array('access content'),
  );
  return $items;
}

```

Replace `your_form_function` with the function that generates the form.

Replace `array('access content')` with your desired permissions.

You can also use the webform module instead of writing a module.
> 4 votes

---
Tags: 7, forms
---


title: Hook for removing a role from a user

text:
# Question
Title: Hook for removing a role from a user
Specifically, when an admin goes to the 'People' admin screen, selects some users, then goes to 'Remove a role from the selected users', I want to capture this and apply some other actions.

To give a little bit of insight into what I'm doing: I have another set of tables in the same database belonging to a CRM, and when the user is removed from xyz group, it should toggle the account status in the CRM as well. The action of toggling the status is no problem, I just need to know the best way of going about capturing the role removal. Is there a quick way of doing this, or am I going to need to create a new cancellation method via `hook_user_cancel_methods_alter()`?

# Answer
You can use Rules module for it. There is an event "After updating an existing user account", add conditions "User has roles" (both for account-unchanged and account parameters to check roles before and after an update), and as a action you can use "Run custom PHP code" to do whatever you want.
> 2 votes

---
Tags: hooks, users
---


# Question
Title: Add a div at end of the form so that i can display data over there
This is my code..

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

  $items['mymodules/page'] = array(
    'title' => t('my module settings'),
    'description' => t('change values here'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_page'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
   );
  return $items;
}

function mymodule_page()
{
$form = array();

$brandarray = array('nokia','siemes');
 $form['mymodule_brand'] = array(
    '#type' => 'select',
    '#title' => t('Brand'),
    '#default_value' => variable_get('mymodule_brand', 'nokia'),
    '#options' => $brandarray,
    '#description' => t('Change this.'),
  );
 $form['div_tag'] = array('#type' => 'markup', '#value' => '<div id="div-id-1">content comes here</div>');
 return system_settings_form($form);

}

```

I just want to do like this. After the form is displayed i just want to add a div so that i can use it for my dynamic data which comes after select is changed. How do i do it?

# Answer
> 8 votes
Try this:

```
$form['my_markup'] = array(
  '#markup' => '<p>Lorem ipsum</p>'
);

```

Check the documentation at http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html#markup

---
Tags: 7, forms
---


title: Theming taxonomy nodes?

text:
# Question
Title: Theming taxonomy nodes?
Is it possible to theme a node based on taxonomy the same way you can theme a node based on its content type (something equivalent to node-news.tpl.php for example) or do I need to organize my content by content type to achieve this?

# Answer
You can add new "template suggestions" using a preprocess function. Here's an article with more details.

Here's another example, but for different templates based on the vocabulary, rather than the term.
> 1 votes

---
Tags: 6, theming, nodes, taxonomy-terms
---


# Question
Title: Return both a form and content in a menu callback
I have the following code.

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

  $items['mymodules/page'] = array(
    'title' => t('my module settings'),
    'description' => t('change values here'),
    'page callback' => 'mymodule_page',
    //'page arguments' => array('mymodule_page'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
   );

  return $items;
}

function mymodule_page() {
  return drupal_get_form('test_form');
}

function test_form() {
  $form = array();
  $brandarray = array('nokia','siemes');

  $form['mymodule_brand'] = array(
    '#type' => 'select',
    '#title' => t('Brand'),
    '#default_value' => variable_get('mymodule_brand', 'nokia'),
    '#options' => $brandarray,
    '#description' => t('Change this.'),
  );

  $form['my_markup'] = array(
  '#markup' => '<p>Lorem ipsum</p>',
  );

  return system_settings_form($form);
}

```

This works perfectly. What I wanted to so is returning a form and page content together, i.e after the page content, in a menu callback function; I tried using the following code:

```
function mymodule_page() {
  $variable =  drupal_get_form('test_form');
  $variable .= '<div class="newclass">here</div>';

  return $variable;
}

```

But it prints something like the following:

```
    Array
    here

```

How do I return both the form and content together in a menu callback?

# Answer
> 5 votes
In Drupal 7 drupal\_get\_form() returns a render array instead of a string, so you should return a render array as well:

```
return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_form' => drupal_get_form(...),
);

```

---
Tags: 7, routes
---


# Question
Title: adding javascript to tpl file from template.php
```
<?php
drupal_add_js(drupal_get_path('theme', 'mytheme') .'/my_js_file.js', 'theme');
?>

```

I want to add a javascript file just to the tpl file titled

```
views-view--gurus--page-1.tpl.php

```

I have this code to enter it to a specific them but what about just a certain tpl file.

I am guessing something like this

```
drupal_add_js(drupal_get_path('theme', 'mytheme') .'/my_js_file.js', 'view');

```

# Answer
This is what I'm using. I don't know if this will have any gotchas in future where the template file I want is in the array but not actually used. So far it's working flawlessly.

```
function yourthemename_preprocess_page(&$vars) {
    $templates = $vars['template_files'];
    if (in_array('page-node-add-discipline', $templates)) {
        drupal_add_js(path_to_theme() . '/js/create_discipline.js');
        $vars['scripts'] = drupal_get_js();
    }
}

```

Put that in your template.php
> 1 votes

---
Tags: theming
---


title: Customising the contact form

text:
# Question
Title: Customising the contact form
I'm using the contact form inside a block on my frontpage, however the labels are pretty ugly, and I'd like to customise the form a bit.

Is there some template file I can grab and put in my theme? I'm using Drupal 7.

I've done some looking but no luck.

# Answer
> 0 votes
I decided to go with a non-Drupal alternative to create my contact form: jQuery Contact Form

I modified the CSS heavily however :)

---
Tags: emails
---


# Question
Title: How do I access node body from template.php?
Here is my code so far:

```
if (!empty($page['content']['system_main']['nodes']) && is_array($page['content']['system_main']['nodes'])) {
    foreach ($page['content']['system_main']['nodes'] as $nid => &$content) {

        // Blog
        if ($content['#node']->type == 'blog') {
            $description = ???;
        }

    }
}

```

I can't figure out how to access the node's unformatted body field, I can't believe it's so difficult to achieve such a simple task..

# Answer
This thread has the answer - `$page['content']['system_main']['nodes'][$nid]['body'][0]['#markup']`
> 0 votes

# Answer
It all depends where exactly you want to access it from.

For example in template\_preprocess\_node() you have full node object in `$variables['node']`, including `body` field (`$variables['node']->body`).
> 1 votes

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


title: Hierarchical Select Question

text:
# Question
Title: Hierarchical Select Question
I don't know if its possible at all but I need something like what is seen in this demo for one of the menus with Hierarchical Select module. This works fine when I use it for a vocabulary with hierarchical terms but don't know how to use it for generic Drupal menus.

# Answer
> 1 votes
You have a separate submodule for using Hierarchical Select with menus, the same as for taxonomy terms.

So, for taxonomy terms you have **Hierarchical Select Content Taxonomy** submodule (hs\_taxonomy), and for menus you have **Hierarchical Select Menu** (hs\_menu) submodule, which you should use in your case.

Click on 'Show config' links on the demo page you have mentioned to see the details.

# Answer
> 0 votes
I was able to create drop down menu but still couldn't figure out how to add only/just Primary menu/links to the drop down I did something like this but it displays all the menus in the system

```
$form['select_some_term'] = array(
    '#type' => 'hierarchical_select',
    '#title' => t('Please Select'),
    '#size' => 1,
    '#config' => array(
      'module' => 'hs_menu',
      'params' => array(
        'exclude' => '',
      ),
      'save_lineage'    => 0,
      'enforce_deepest' => 0,
      'entity_count'    => 0,
      'resizable'       => 1,
      'level_labels' => array(
        'status' => 0,
      ),
      'dropbox' => array(
        'status'   => 0,
      ),
      'editability' => array(
        'status'           => 0,
        'item_types'       => array(),
      ),
      'animation_delay'    => 400,
      'exclusive_lineages' => array(),
      'render_flat_select' => 0,
    ),
  );

  return $form;

```

I've spent hours but couldn't figure this out. Please help!

---
Tags: routes
---


# Question
Title: How to render CCK image field within page.tpl.php
I have my image field's array `$node->field_blog_image`, but how do I render it as it does in the `$page['content']`?

The URI confuses me as its simply `public://my_image.jpg`

# Answer
> 2 votes
`file_create_url` to get the path of your image:

```
// $nid is the id of your node
$entity = entity_load('node', array($nid));
$uriImagefromNode = $entity[$nid]->field_image_test_field['und'][0]['uri'];
$urlImagefromNode = file_create_url($uriImagefromNode);
// $urlImagefromNode variable now has the path to the image

```

I hope this information be useful.

---
Tags: entities, media
---


# Question
Title: Difference between field_data and field_revision tables?
I have a lot of custom functions; I just want to make sure I'm doing this right.
If I want the most recent version—the live version—of a node, I go to the `field_data_field_xyz` table, right?

My understanding is the `field_revision_field_xyz` keeps all older versions, correct?

# Answer
That is correct: Working with Field SQL Storage.

> **Database tables:**
>
> * {field\_data\_\[field\_name\]} Standard data storage for a field.
> * {field\_revision\_\[field\_name\]} Standard revision storage for a field.
> 13 votes

---
Tags: 7, database
---


# Question
Title: How do I flag and categorize Drupal Commerce related products?
Given that there isn't a related products contrib module yet.

What is the canonical means (with priority of maintainability, developer experience) to flag related products and thus have them displayed in views ?

Would it include setting up content types with many different taxonomy vocabulary fields? Another product reference field?

# Answer
The core taxonomy module offers a flexible system for sorting content. You can easily build views based on content type and taxonomy.
> 1 votes

---
Tags: views, commerce
---


title: Hide and show logo based on user role

text:
# Question
Title: Hide and show logo based on user role
Drupal 7

Is it possible to write an if statement in the page.tpl.php file that first gets the user role and then compares it to a string and it either shows the logo or doesn't. Something like...

```
//some how get user role

global $user;
$user_fields = user_load($user->uid);

$current_role = $user_fields->role[];

if ($current_role == "public_user"){
>?
<?php
 print $front_page;
?>" title="

<?php
 print t('Home');
?>
" rel="nofollow">

?>
}else{
//don't show.
}

```

# Answer
I'd suggest checking against a permission, rather than an entire role.

In your custom module, add:

```
function mymodule_permission() {
    return array(
        'view site logo' => array(
            'title' => t('View Site Logo'),
            'description' => t('Allows a user to view the site logo'),
        ),
    );
}

```

And in your theme's template.php page preprocessor, add:

```
if(!user_access("view site logo")) {
    $variables['logo'] = "";
}

```

This way, $logo will not be processed in page.tpl.php for a user without the permission.
> 4 votes

# Answer
Get the ROLE ID from the listing of roles in the admin section of site at http://YOURSITE.COM/node#overlay=admin/people/permissions/roles

```
global $user;

if (array_key_exists('ROLE ID', $user->roles)) {
  print $front_page;
}
elseif (array_key_exists('SOME OTHER ROLE ID', $user->roles)) {
  print t('Home');
}
else {
  //don't show.
}

```
> 1 votes

---
Tags: 7, theming, media
---


# Question
Title: Form API, drupal_add_js() and setting a JS variable
Consider

```
drupal_add_js(array(
  'radio86_media' => array('barfoo' => 'booboo')), 'setting'
);

```

and

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'radio86_media') . '/select_media.js',
);

```

These two 'lines' work well separately, but I think they could (and should) be combined so that the variable setting is set on the second line, combining the logic.

I've been fumbling around it and just can't get it to work. With this current way, I can console.log the `barfoo` variable via JS by using `Drupal.settings.radio86_media.barfoo` so it does work, but I really would like to have it combined.

Any suggestions greatly appreciated!

# Answer
> 5 votes
I never tried, but I guess you can do it like that :

```
$form['#attached']['js'] = array(
  array(
    'data' => drupal_get_path('module', 'radio86_media') . '/select_media.js',
    'type' => 'file'
  ),
  array(
    'data' => array('radio86_media' => array('barfoo' => 'booboo')),
    'type' => 'setting'
  )
);

```

According the documentation you should be able to add settings and files.

---
Tags: forms, javascript
---


title: 403 error - unable to login into admin

text:
# Question
Title: 403 error - unable to login into admin
Recently I created two pages for http 403 and 404 and assigned them so that on error those two will be shown. But today when I tried to login to my admin in my site: http://www.indiacustomercare.com/admin it is giving error "Error 403 - Permission Denied".

The message:"Unfortunately the page you are looking for is not accessible by you." is from the page I had assigned for http 403.

Looks like I did some silly mistake, my other two D6 sites have no problem logging in.

How do I login into admin again?

# Answer
> 1 votes
this may seem a silly suggestion, but have you tried going to /user rather then /admin the former being the login page, the latter being the admin pages once logged in?

---
Tags: 6
---


# Question
Title: Custom webform component for displaying a list of nodes
I would like to have a content-type with *Add to cart* button that would allow a user to add current node to the cart. Then there would be a webform that would list all the items (nodes) that the user added to the cart.

Can anyone give me directions on how to achieve this? I think it has something to do with creating custom webform component.

# Answer
To answer my own question. My solution was to add a 'Add to Cart' button on the node which stores that node to the session. I created a new webform component based on textarea that is readonly and lists all nodes that the user added.
> 1 votes

---
Tags: webforms
---


# Question
Title: Do 'edit node' redirect via custom PHP code?
I have a rule for returning users to finish creating a cck form. I need to 'Do' custom PHP code to redirect the user to editing/finishing their cck form (node limiter limits user to only one PPE content item). The following does not work:

```
function ppe_edit_user_login(&$edit, $account) {
  global $user;
  $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid', array(':uid' => $user->uid))->fetchField();
  drupal_goto('node/' . $nid . '/edit');
}

```

What am I missing?

# Answer
Here is the right code, or at least code that works:

```
$nid = db_result(db_query('SELECT nid FROM {node} WHERE uid = %d', [account:uid]));
$_REQUEST['destination'] ='node/' . $nid . '/edit';

```
> 2 votes

# Answer
```
function ppe_edit_user_login(&$edit, $account) {
  global $user;

  $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid', array(':uid' => $user->uid))
    ->fetchField();

  drupal_goto("node/$nid/edit");
  exit;
}

```
> 1 votes

---
Tags: rules
---


# Question
Title: Controlling block page display options programatically
On block configuration page we can control the display of the block on three factors: 1. All pages except those listed 2. Only the listed pages 3. Pages on which this PHP code returns TRUE (experts only)

how can it be done programatically in my module file?

# Answer
i solved it by giving configuration in hook\_block\_info function

```
function hook_block_info(){
    $blocks = array();
    $blocks['appendices_page_options'] = array(
        'info' => t('Appendices Page Options'),
        'status' => TRUE,
        'theme' => 'MY_THEME',
        'region' => 'MY_REGION',
        'weight' => 0,
        'visibility' => 1,
        'pages' => "aboutus/*",
        'custom' => FALSE
    );

    return $blocks;
}

```
> 2 votes

# Answer
Take a look at block\_add\_block\_form\_submit in modules/block/block.admin.inc. This is the regular block creation form; it appears to just insert the records directly rather than calling another function. Note that each record in the block table is linked to a single theme (you can just use the active one but it's safer to insert records for all themes). The block\_custom table holds the content.

Note the 'visibility' value being set at line 569. This is where you would set the display settings you're inquiring about.
> 1 votes

---
Tags: blocks
---


# Question
Title: How can I modify the login form using hook_form_alter()?
I'm trying to alter the login form with the following code:

```
function git_form_alter(&$form, $form_state, $form_id) {
  $forms = array(
    'user_login_block' => 'user-login-form',
    'user_login' => 'user-login'
  );
  if (array_key_exists($form_id, $forms)) {
       //my altering code
    }
}

```

I got this from the openidselector module that introduces some JavaScript widgets and more or less is what I'm trying to do.
When I go to mysite/user/login it doesn't call the block where I have to alter the form. It simply doesn't call `hook_form_alter()`.

A different thing is with the register form, or any other form, that are calling the hook.

Can anyone tell me what can I do? How is it possible that openidselector uses the same method, but in that module the code works, while it doesn't work in my code?

# Answer
> When I go to mysite/user/login it doesn't call the block where I have to alter the form. It simply doesn't call hook\_form\_alter().

example.com/user/login doesn't show the user login block; it shows the login form. Your code should work, even if I would rather make the code simpler (if you are not using "user-login-form" in any way).

```
function git_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // …
  }
}

```

As for the reason why the code doesn't work, I can think of the following reasons:

* The hook name doesn't match the short name used for the module; for example, the short name of the module is "git\_form" and you are using `git_form_alter()` for the implementation of `hook_form_alter()` when it should be `git_form_form_alter()`.
* You are editing a module that is enabled. In this case, when you add a new hook to the code, you also need to flush the cache used by Drupal as Drupal caches the list of hooks implemented by third-party modules.
* The module is not enabled.
> 6 votes

# Answer
Your code is fine, and it works ok. At least this part that you've shown.

I assume that you've put it in 'git' module, and the module is enabled? Do you have any code (there or in any other place) that could break the flow and stop your hook from executing?
> 0 votes

---
Tags: forms, hooks
---


# Question
Title: Any better popup modal framework in drupal
I use the Chaos tool suite module for modal popup in Drupal 7; I am unable to open popup from within a popup using ctools. Can it be done using ctools, or is there any better popup modal module in Drupal 7 which can do this? (I am using forms in popups and not only pages.)

# Answer
> 2 votes
Could the Colorbox module be useful for you?

> Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.3 through 1.6. This module allows for integration of Colorbox into Drupal.

---
Tags: 7, javascript, chaos-tool-suite, forms
---


title: Load page through ajax

text:
# Question
Title: Load page through ajax
what are the options (all possible ways) to open a page through ajax in D7?, also can ctools module be useful in this?

if yes then can anyone provide an example hint using ctools.

# Answer
> 3 votes
Ctools give you a modal frame api as well as many different ajax helpers. This is probably your best bet for implementing AJAX in your site.

As for listing all possible ways there are loads, ranging from custom implementations to contrib modules, your best bet would be to search drupalmodules.com for potential candidates.

---
Tags: ajax, javascript, 7
---


# Question
Title: IE Stylesheets being ignored - only on production server though
Production server - http://speysideleisure.com

Dev server - http://superallan.com/dev/speyside/

On IE the Dev site is referencing the css properly but the Production site isn't. The Prod is hosted on different servers with a different host - all the files are the same though. The only thing is that I noticed the problems once I'd uploaded it to the Prod server so then I made the changes. I've cleared the Cache a million times but that's the extent of my knowledge in how to solve it. The Dev site changed pretty much instantly.

Is it a setting somewhere on the Prod server?

Cheers for any help - it's appreciated.

# Answer
> 2 votes
IE chokes if you have more than 31 stylesheets, which most Drupal sites do if you create a zen subtheme. Turn on CSS aggregation in your performance settings to fix that.

There are potential (temporary or easily fixable) problems associated with migrating a Drupal site from http://example.com/dev/ to http://example2.com/ that you can avoid completely if you develop on a subdomain, ie. moving http://dev.example.com to http://example.com

check your database and theme files for paths starting with "dev/" and give your .htaccess files the once-over.

---
Tags: theming
---


title: send fields in a email

text:
# Question
Title: send fields in a email
I'm fairly new to D7 and I don't know where to start. I have a "Event" CT(ContentType) with many fields in it. Dates, prices, text, html description.

I need to put some fields in a plaintext email and send it to a specific adress. Thats the data export for a ticket system. Some of these fields need to be reformatted. Date =\> Timestamp, MD5 Hash etc. Textblob with HTML Tags =\> plaintext, etc.

Also it needs to be saved. So the User can see if its already submitted.

I'm a bit overwhelmed where to start. I think a module and drupal\_mail() is the right way to start. How would you do it (General direction)?

Thx in advance T

# Answer
> 1 votes
The Email Example in the Examples Project should be just the thing for you.

# Answer
> 0 votes
if you want the email to be a triggered event (like upon saving a node) you could create a Rule - http://drupal.org/project/rules

it is a bit unclear whether you want the email saved, or the node..

---
Tags: 7, entities, emails
---


# Question
Title: For a personal-use module, what would be good practice for database tables?
I've a set of tables that install with my module, but I worry about mixing them in with Drupal's tables. I shouldn't simply create a separate database for my own tables, should I?

Is there a 'good' approach to this?

# Answer
> 0 votes
I would create them in the main Drupal database, especially in case you need to `JOIN` them with other tables.

Personally, I preface custom tables with the module name.

That said, creative use of CCK / fields (depending on Drupal version) often cuts down on the need for custom fields, and integrates nicely with other features (eg, Views).

# Answer
> 0 votes
Creating tables to go along with a custom module is acceptable and perhaps event "best practice" in the Drupal world. Using a separate database would require an additional connection via PHP which I suspect would be a waste of server memory but an option if you insist on doing so. Often there's no one "right" answer in Drupal. There are of course "best practices" which I encourage you to follow but there's a lot of room for personal style.

---
Tags: database
---


# Question
Title: I want to get a Mobile version of my drupal site working
I am trying to setup what I would call a multisite configuration on my local development server, which currently looks like this. I'm using Xampp in a windows environment so my root is Xampp\htdocs. Any site I'm working on is created under a folder here; for example, for \devsite this gives me the following Drupal structure: \sites\all\themes\devsite.

In my browser, I can go to *http://localhost/devsite*, and it launches my Drupal site. If I go to *http://localhost*, I get redirected to the Xampps install site.

My hosts file is altered to include these two entries.

* 127.0.0.1 devsite.com
* 127.0.0.1 m.devsite.com

Browsing to http://devsite.com/devsite, or http://m.devsite.com/devsite now launches my site.

I copy the content of the \devsite\sites\all directory to the \devsite\sites\m.devsite.com directory (I make some CSS changes so it would be obvious), and setup a \devsite\sites\sites.php file with these entries.

```
$sites = array(
  'devsite.com' => 'all',
  'm.devsite.com' => 'm.devsite.com',
);

```

If I browse to either hostname, both load the site configuration which is in All. I can't seem to get it to load anything within m.devsite.com? I've tried copying the settings.php file into each stucture which produces an error message. I've tried renaming All to devsite in folder and sites.php but then I get a blank page when browsing.

Do you have any idea on how can I achieve what I am trying to do?

# Answer
You're just trying to create a new theme on the subdomain right?

I got this working recently on a CentOS server; all I had to do was added a folder in the sites directory called "m.mydomain.com" with a copy of the settings.php file from "sites/default" with the following line appended:

```
$conf['theme_default'] = 'fusion_mobile';

```

Come to think of it, I should probably include the other settings.php file to keep things organized, but that was all I needed for the basic functionality you're describing (beyond the DNS setup). I didn't have to create a sites.php file, or copy the entire file structures across.
> 0 votes

# Answer
I use Omega for that. It's based on CSS media queries.
> -1 votes

---
Tags: multi-sites, theming, subsites
---


# Question
Title: How to set different languages for different domains, and display the language switcher accordingly?
I have a website with different domains and I'd like to have some domains to have different languages.

I have a main site which is example.com, it's the main "group" site, it has multiple languages, in this case french, english, russian and spanish.

Then i have several other "sub" sites assigned to other domains and each have one or many assigned languages. For example: es.example.com is in spanish ru.example.com is in russian

The problem is for a sub site that have more than one language. for example: ca.example.com would be in french and english.

How do you configure drupal to be able to achieve this, and how do you make the language switcher display only the languages available on the domain ?

I have domain access and i18n installed obviously.

Thanks in advance for your help.

# Answer
A complete summary of the multilingual system for Drupal 7 can be found here: Drupal 7's new multilingual systems compilation. Specific to your question of "...some domains to have different languages", setting / detecting the language by domain can be setup in http://YOURSITE.com/#overlay=admin/config/regional/language/configure -\> Detection and selection tab after the Locale module has been enabled. Details on the Detection and selection tab.

Notice that new to Druapl 7 this is now a weighted list that is processed to determine what method to use for the display language. The higher in the list the more likely that the method will be used.

In the case of you situation I suspect you'll have to write your own language selector to add to this list. I have to confess that the situation you describe sounds like it could better be solved in configuration that in code. Perhaps consider add the language into the domain in addition to the country - for example ca.example.com could be French: fr.ca.example.com and English: en.ca.example.com.
> 3 votes

# Answer
Have a look at Domain Internationalization. I have never used it but according to the description, it seems to be what you need.

For Drupal 7 there is good module named domain locale.
> 0 votes

---
Tags: 7, i18n-l10n, domain-access
---


# Question
Title: Mobile browser to be assigned different background
I'm trying to get my site to operate differently depending on if the browser is a phone or a computer etc... I understand that this is most likely done using the sites.php file but I've been unable to get this working, and have an open question on SO about it.

Broad Question

This question is a little more specific and is to tied me over while I battle the broader issue out. I would like to remove the current background image when a mobile browser turns up. I thought something like the following would do it (same CSS file)

```
body {
 background-color:blue;
}

@mobile {
 body {
 background-color:green;
 }
}

```

but this doesn't appear to make any difference when using my HTC desire using Dolphin.

# Answer
I use Omega for that.

It's based on CSS media queries.
> 1 votes

# Answer
two things:

1. Why not keep things neat by creating a new stylesheet and putting the css media rule in the .info file?
2. If you're thinking of @media queries, that syntax isn't right.. maybe you're thinking of `@media handheld { /* rules */ }`

have a look here - http://www.w3.org/TR/CSS2/media.html

regardless, I know the question referenced the HTC desire but I thought I'd warn you that iPhones ignore `@media handheld` and use `@media screen` instead, so you need to do something like this:

```
@media only screen and (max-device-width: 480px) { /* rules */ }

```

Courtesy of Smashing Magazine - http://coding.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/
> 1 votes

---
Tags: theming
---


# Question
Title: Setting a Warning message in the Page.tpl.php file
I'm trying to set a warning message based on a PHP if statement in my page.tpl.php file. I can get a message out using `$messages` but I cannot using `drupal_set_message()`. Should I be using the latter before page.tpl.php?

The problem is the `$messages` variable comes out as plain text, I'd like to use Drupal's message system if possible:

```
drupal_set_message(t('Don\'t panic!'), 'warning');
$messages = t('Don\'t panic!');

```

# Answer
> 8 votes
If you want to use Drupal's message system, and you want to do this at the theme-level, as opposed to writing a module, you would enter the code

```
drupal_set_message(t('Don\'t panic!'), 'warning');

```

into your theme's template.php file as a preprocess function. For instance, if you wanted to display this message on all content of the type 'page'

```
function YOURTHEME_preprocess_node(&$variables) {
 if ($variables['node']->type = 'page') {
  drupal_set_message(t('Don\'t panic!'), 'warning');
 }
}

```

It should then automatically show up in the $messages area whenever someone visits a 'page' content type.

Note: You might also need to flush your theme cache after making these changes.

---
Tags: theming
---


title: Search in specific content type

text:
# Question
Title: Search in specific content type
I want to make a custom search box but I only want to allow users to search in a specific content type. How can I do this?

# Answer
These modules may help: Custom Search, Search Configuration
> 1 votes

# Answer
If you use D7 check search configuration page.
> 0 votes

---
Tags: 6, search
---


# Question
Title: Any Modules to help with price caculator?
Ive made a booking form using Drupal 6, where bookings are a content type and you create a node of that type to make a booking.

I now need to add a price calculator. When creating a booking node, one of the CCK fields you fill in is distance. I then need the price to be calculated from the rates below, and that value to be given to another CCK field.

Rates: 0-5 km $20/ mile 5-10 km $15/ mile 10-20 km $10/ mile 20-30 km $5/ mile

So if the distance was 11km, the price would be 11 x 15 = 165. Also, the rates table needs to be editable by the site admin.

Can any modules do or at least help with this? I could probably manage to do the calculations and change the price field value with jQuery. If the table was shown on the page then jQuery could grab the values from it, and the table could be editable by the admin so the rates could be changed. Im far from a jQuery expert though and I love Drupal's ability to do powerful stuff without writing code. Thanks

# Answer
> 0 votes
I think what you're looking for is the Computed Field module to populate the field with the calculated value. For the rates table, you may have to write a custom module, create another content type, etc to manage it.

From the Computed Field project page:

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

# Answer
> 0 votes
if you need an admin interface for this your best bet is to write a small module for it in PHP, not jQuery. Unless you want your "rates table" to be handled by nodes as well..

---
Tags: 7
---