title: Ajax form that changes a button value

text:
# Question
Title: Ajax form that changes a button value
When a user pushes a button element marked with ajax, I would like the callback to modify the button value (text shown on button), and have it updated both in the browser and the form state. Updating in the browser is easy by return an ajax\_command\_replace call. But I'm not having any luck with getting the form updated to remember the updated button value the next time the button gets pushed.

It seems the way the ajax form is built, that the initial value of the button gets hardcoded where the callback function in the javascript page gets defined, which probably explains why the button element returned to the ajax callback does not match with the value it shows in the browser (after I changed it with the ajax\_command\_replace).

But I can live with that, as long as I can get the form (or form\_state) to actually remember the new value of the button element from a previous invocation of the callback.

I've also tried modifying the form/form\_state values in the form validate hook, but without success.

So, despite already knowing this does not work, the following code tries to illustrate what I'm trying to do:

```
function testajax_callback($form, &$form_state) {
  $form['mybtn']['#value'] = 'New value';
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace('#mybtnwrapper' => drupal_render($form['mybtn']))
  );
}

```

Any help on how to do this the Drupal 7 way would be appreciated.

**update 1:**

Got a hint on the Drupal Forums. The following code is probably more according to Drupal 7 design and style:

```

function betapp_testajax_callback($form, &$form_state) {
  $form['mybtn']['#value'] = 'New value';
  return $form['mybtn'];
}

function betapp_testajax_form($form, &$form_state) {
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#prefix' => '',
    '#suffix' => '',
    '#default_value' => 'Default value',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  return $form;
}

```

The code manages to change to appearance of the button (button value), but when pressing the button with the updated value, the old one is still the one sent, so effectively, no values in the form has changed, only the button appearance.

It may have something to do with hardcoded values in the callback definitions in the html page (which is only loaded once). I find entries such as these:

```

{"callback":"betapp_testajax_callback","wrapper":"testajaxwrapper","method":"replaceWith","effect":"fade","event":"mousedown","keypress":true,"url":"\/d7\/system\/ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Default value"}}

```

If \_triggering\_element\_value is used regardless of the actual value of the element, that explains why the new value is not picked up. Maybe the \_triggering\_element\_value should be looked up at runtime when the callback gets activated?

Any ideas on workarounds/fixes?

# Answer
The short solution to my original question can be coded like this:

```

function betapp_testajax_callback($form, &$form_state) {
  return $form['mybtn'];
}

function betapp_testajax_form($form, &$form_state) {
  dd('');
  dd('betapp_testajax_form');
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#default_value' => 'Ignored default value',
    '#prefix' => '',
    '#suffix' => '',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $prevval = '(blank)';
  if (isset($form_state['values']['mybtn'])) {
    $prevval = $form_state['values']['mybtn'];
    dd('prevval : ' . $prevval);
  }

  $form['mybtn']['#value'] = 'Newval ' . rand(0, 100);

  dd('newval  : ' . $form['mybtn']['#value']);
  return $form;
}

```

which lead to output like:

```

betapp_testajax_form
newval  : Newval 48

betapp_testajax_form
prevval : Newval 48
newval  : Newval 62

betapp_testajax_form
prevval : Newval 62
newval  : Newval 0

betapp_testajax_form
prevval : Newval 0
newval  : Newval 59

```

My usage requires a little bit more; whenever a button is changed, there are other elements that should be updated as well. But I think I managed to pull it together (looks correct for now anway), and in the spirit of sharing, here's what I managed to glue together:

```

function betapp_testajax_callback2($form, &$form_state) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace('#mybtn', drupal_render($form['mybtn'])),
      ajax_command_replace('#inp', drupal_render($form['inp']))
    )
  );
}

function betapp_testajax_form2($form, &$form_state) {
  dd('');
  dd('betapp_testajax_form');
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#default_value' => 'Ignored default value',
    '#prefix' => '',
    '#suffix' => '',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $prevval = '(blank)';
  if (isset($form_state['values']['mybtn'])) {
    $prevval = $form_state['values']['mybtn'];
    dd('prevval : ' . $prevval);
  }

  $form['mybtn']['#value'] = 'Newval ' . rand(0, 100);

  $form['inp'] = array(
    '#type' => 'textfield',
    '#value' => $prevval,
    '#id' => 'inp'
  );
  dd('newval  : ' . $form['mybtn']['#value']);
  return $form;
}

```

This code updates the original button, and sets the input field to the previous value of the button. My case requires modifying other buttons, but hopefully that will work. If not, I'll bug you on this thread again.

Thank you.
> 0 votes

# Answer
One more thing. If you have forms with many buttons and you use ajax like I have shown above, make sure you set the button names to unique values as well (I set mine to the same as the id property), or Drupal will have trouble recognizing which button was actually click when you modify the button values. By default, Drupal names all buttons "op" which seems to cause some trouble if you try to modify the values of multiple buttons when one of them is pressed.
> 0 votes

# Answer
And just to complete the information further, here is a bit more:

**Special care with buttons Posted by kjeldahl on May 18, 2011 at 6:02pm**

If you have forms with many buttons and you use ajax like I have shown above, make sure you set the button names to unique values as well (I set mine to the same as the id property), or Drupal will have trouble recognizing which button was actually click when you modify the button values. By default, Drupal names all buttons "op"..

**Another gotcha related to $form\_state\['triggering\_element'\] Posted by kjeldahl on May 18, 2011 at 8:47pm**

In my application (a simple game), I have a series of buttons that triggers an ajax callback to my Drupal module. The button's id and name is different from the value, since the value of the button is used to show some human readable information to the user. Similar to the code I've shown here, if I create a series of buttons where pushing it toggles the value (e.g. by toggling the prefix of the button value with a star or similar), it works fine as long as I keep pushing one button. However, as soon as I press another button, Drupal loses track of what was pushed, and triggers some other default action that sets the triggering\_element to the first button defined by default. I've only looked briefly at form.inc and related code, and it seems the behaviour of selecting the first button is "by design".

What is possibly not by design however is the fact that Drupal is not able to track the triggering\_element in the use case I described below. Dumping the state of $form\_value however, led me to attempt to use something I believe is a "private" state value instead, namely $form\_state\['input'\]\['\_triggering\_element\_name'\] which, differently from $form\_state\['triggering\_element'\], always seems to be populated with the correct value in my ajax application.

I believe this is a bug, but haven't got the time to track down the exact details right now. Inside form.inc there is code that seems to behave differently depending on whether the button id equals it's name and/or value, but I have no idea what the design goal for this behaviour really is. But without using \_triggering\_element\_name it seems Drupal doesn't work well for my ajax'y button elements.
> 0 votes

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


# Question
Title: Primary Links Not Showing Up On Certain Themes
In Drupal 7, I have a page in the Primary links menu. I set the page content type to use the primary links. In Garland I can see the item at the top of the page, but in a bunch of other themes I can't, like AT Adaptive, Fusion, and Sky. What gives? How do I get the primary links to show up in those themes?

# Answer
There are two ways to show primary links: through the theme settings or through a block placement. Check your theme's settings to see if it has a setting for display of primary links. If it does not, your only configuration option is to place the primary links block into a region through block administration.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Getting specific property from node_load
I have an article that I've set to a variable like this:

```
$this_node = node_load($nid);

```

I've done a print\_r on $this\_node and this is what I get - it's pretty long, sorry:

```
stdClass Object
(
    [nid] => 67572
    [type] => imagevault
    [language] =>
    [uid] => 3
    [status] => 1
    [created] => 1303347600
    [changed] => 1305662899
    [comment] => 0
    [promote] => 0
    [moderate] => 0
    [sticky] => 1
    [tnid] => 0
    [translate] => 0
    [vid] => 67572
    [revision_uid] => 1
    [title] => Anne Jones
    [body] =>
    [teaser] =>
    [log] =>
    [revision_timestamp] => 1305662899
    [format] => 2
    [name] => pbreen
    [picture] =>
    [data] => a:0:{}
    [field_pub_date] => Array
        (
            [0] => Array
                (
                    [value] =>
                    [timezone] => America/Chicago
                    [timezone_db] => America/Chicago
                    [date_type] => date
                )

        )

    [field_att_file] => Array
        (
            [0] => Array
                (
                    [fid] => 59327
                    [uid] => 3
                    [filename] => KCJones.jpg
                    [filepath] => sites/default/files/images/KCJones.jpg
                    [filemime] => image/jpeg
                    [filesize] => 54806
                    [status] => 1
                    [timestamp] => 1304023490
                    [list] => 1
                    [data] => Array
                        (
                            [description] =>
                        )

                )

        )

    [path] => imagevault/67572

    [0] =>
    [taxonomy] => Array
        (
            [264] => stdClass Object
                (
                    [tid] => 264
                    [vid] => 15
                    [name] => Kimberly-Clark
                    [description] =>
                    [weight] => 0
                )

            [137] => stdClass Object
                (
                    [tid] => 137
                    [vid] => 10
                    [name] => People
                    [description] =>
                    [weight] => 0
                )

        )

)

```

I know I can get certain values from the node like this:

```
$imagefile = array();
$imagefile['name'] = $this_node->field_att_file[0]['filename'];

```

Here's what I need to do, though (and I'm very new to Drupal so forgive me if this is really simple.) The article can, as shown, have multiple taxonomy terms. I need to treat a chunk of display code differently if the article has 137 as one of the taxonomy terms. How would I go about this?

Something like this, or is there a better way? (Don't even know if this way works yet; it probably won't since each tax term is an object, not an array.)

```
$this_tax = $this_node->taxonomy;
if (array_key_exists('137', $this_tax)) {
   // Do stuff
}

```

# Answer
> 2 votes
Something like that should actually work.

The only issue might be that you are looking for the string '127' but want the integer 127, so remove the '. But I'm not 100% sure right now how PHP handles that.

Also note that you can use isset() instead of array\_key\_exists() here, so just

```
if (isset($this_node->taxonomy[137])) {
}

```

should work too. The difference between isset and array\_key\_exists() is that isset() returns FALSE if they key exists but the value of it is NULL, while array\_key\_exists() returns TRUE in that case.

---
Tags: nodes
---


title: Feeding arguments into Views

text:
# Question
Title: Feeding arguments into Views
I'm not sure how to frame this question, so I'm sorry if the answer already exists.

Basically, I want to know how to modify the way arguments are fed into views. For example, say I'm presenting a income statement and balancesheet, it seems like its formatting the links as www.example.com/balancesheet/ibm and www.example.com/incomestatement/ibm

Is there a way to make it www.example.com/ibm/balancesheet or www.example.com/ibm/incomestatement, so I can create views and have them grouped this way?

My problem is instead of grouping content by views, I want to try to group views by content so if someone searches for IBM they basically get all the views that apply. I'm open to any suggestions anyone has.

# Answer
> 3 votes
Each item between the slash after the domain name of the website is called an argument. Take, for example, example.com/one/two/three/four/five -- in this case one is the first argument, two is the second argument, ect.. Drupal has a function that separates these arguments named arg() which takes an argument as a number. arg(1) when called while loading this example URL will always return 'one' while arg(5) will always return 'five'. This way context can be passed into all the modules in a consistent way. I just want to make sure you see arguments for what they are.

Here is why. You are creating a two separate pages for items that should be on the same page. Instead of creating pages you might consider blocks in views and place the many blocks on the same page. This way you can, for example, use taxonomy terms to tag content as IBM, Intel or Apple. Create a balance sheet and tag it IBM. Create another tag it Apple. Create an income statement and tag it IBM. Create another and tag it Apple.

Then create a basic page with a brief description of the IBM corporation and a logo using the path alias module to change the name of the URL to example.com/ibm. Then add the two views as blocks to the page. Each view will be called when the user goes to example.com/ibm and arg(1) will be ibm. Then you can use the arguments (in View 3 contextual filters) to use this argument to define the Taxonomy term to filter the information in the database with. In this case IBM. Now you might have 12 reports for IBM for each category going back 4 years. Views will pull them all and you can use a field of title that links to the node to have a link going to each one. Then you can also use the date filter to make sure that the most recent one is on top. Once the View block is created, Views will just load the other view using once again arg(1) to define the taxonomy term to find all the other reports information in the database.

Now there are more advanced ways to trigger which Views get called with modules like Context or Panels which are super high powered tools that focus on just this simple purpose. You might be interested in the videos on Panels at Node One or the Mustard Seed Media video on the Context module.

(edit) To create a similar tabbed look like companies on the WSJ you can use either Quick Tabs for an ajax tabbed effect or creating a Views page and assigning it a Menu Tab for the menu item so that several tabs are found on the same page.

---
Tags: 7, views
---


# Question
Title: Determining What Text Editor to Use By Default Based on Site Location in Drupal 7?
Okay, so this is something I've been wrestling with for a while. We have several different types of users on our site. For example: Bloggers, Writers (for actual articles), editors, and ordinary users that don't have access to writing blogs or articles.

When a user that falls under the Blogger/Writer/Editor role goes to post on our forum section, he/she is presented with the option of choosing what text editor to use.

What I'd like to do is set things up so that a plain text editor is used by default for the forum, and that a WYSIWYG editor is used for articles and blogs. I don't want to present the user with a choice as to which one to use. It should be a straightforward process.

So what do I need to do in order to define the default text editors?

# Answer
> 2 votes
I use the WYSIWYG module to define different profiles for each text input format and the Better Formats module to define which roles get what input formats on which content types.

---
Tags: 7, wysiwyg, nodes, input-formats, users
---


title: Which SQL query should I use?

text:
# Question
Title: Which SQL query should I use?
I want to get the number of rows where the "value" field is equal to 1, and output its number and all the `content_id` where `value_type` is `option` in table `votingapi_vote`. the following is my code, but it doesn't work.

```
$result = db_query("SELECT content_id,count(value=1) FROM {votingapi_vote} WHERE value_type = '%s'" , "option");

while ($obj = db_fetch_object ($result)) {
  return $obj->content_id.'<br>'.'$obj->count';
}

```

it showed an error. when i delete the filed value in the query. it only output one result of `$obj->content_id`/ why? i want to output all the results of $obj-\>content\_id

**ps: now, if i want to get this result.**

1,get the `content_id` and descending it according to the value(the count of each `content_id` 's value=1 substract the count of each `content_id` 's value=0 ,each content\_id has many value=0 or value=1)

how to write the query.

# Answer
First, that condition syntax is just wrong, you need to add that as a WHERE condition. Second, if you want the count per content id, you need to group by that.

And third, you need to collect the output in a variable instead of returning it directly.

Something like this:

```
$result = db_query("SELECT content_id, COUNT(*) AS count FROM {votingapi_vote} WHERE value_type = '%s'"  AND value = 1 GROUP BY content_id, "option");

$output = '';
while ($obj = db_fetch_object ($result)) {
  $output .= $obj->content_id.'<br>' . $obj->count;
}
return $output;

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: Multiple copies of Views filter form (exposed filters)
I know in views you have the option to expose the filters form as a block, but doing so removes the exposed form from the view page. Is there any way to expose the filters form as a block and *keep* the exposed form in the view as well?

For example, is there a way to see
at the top of my view, but on every other page have an exposed form block like
in the side bar?

This would be helpful as when a user is on a view page, he/she will be primarily concentrating on the main content and would look for a search there (instead of in a block on the side of the page). However, users should be able to search the view from any page on the site (enter block).

Currently I have a custom module creating a block to act as the exposed form block while in Views I have *Expose form in block* set to "No". Is there an easier way to handle this?

# Answer
> 3 votes
This hack works very well but there's no need for a hack if you have seperate displays from your view. My search results were displayed as a "Page" display and you also have the "Default" display.

On the page you would click "Exposed form in a block" then click "Override" on the right hand side. Set this to "No" (so the form now displays on the search page). In the "Default" display, have "Exposed form in a block" set to "Yes" - so by default it produces a block, but you also get the form to appear on the search page as well.

Thanks guys, Garry.

---
Tags: 6, blocks, views
---


# Question
Title: How do do "Facebook style" image tagging?
I couldn't find a module that would allow "Facebook style" image tagging (select an area of an image and tag it with a username, for example).

Any good starting points to build such a feature?

# Answer
It's called "image annotation" if you want to search for it. There are a handful of modules, but not sure how great they work or how often they are maintained. This one seemed the best:

http://drupal.org/project/image\_annotate
> 4 votes

---
Tags: 7, media
---


# Question
Title: Does anyone know how to use the Ubercart UC VAT module?
I have to implement different VAT for different products (regardless of the category). Some products can have 19%, some 4%, some 6%, and some they don't have a VAT rate at all.

So far I couldn't even specify a global 19% vat.

I don't understand how this is handled. I've searched for documentation but it's almost nonexistent.

# Answer
> 1 votes
VAT module adds 'VAT settings' tab to your Store administration \> Configuration \> Tax Rates and Settings (/admin/store/settings/taxes), where you can specify global VAT value.

---
Tags: ubercart
---


# Question
Title: How do I correctly add jQuery UI widgets?
Im using Drupal 7, which ships with jQuery UI. I need to have Accordion only on the homepage. jQuery will not just let me download Accordion and then use `drupal_add_js()`.

Do you have any suggestion?

# Answer
jQuery UI Accordion is included in core, use `drupal_add_library('system', 'ui.accordion');` to add it.
> 8 votes

---
Tags: 7, javascript
---


title: Problems with a global variable

text:
# Question
Title: Problems with a global variable
I have the following code:

```
$a='1';

function check() {
  global $a;

  if ($a == '1') {
    return "1";
  }
  else {
    return "2";
  }

  var_dump(check());
}

```

When I run this code stand alone, its output is `string(1) "1"`; when I use the code inside page-front.tpl.php the output is `string(1) "2`.

Why?

# Answer
When Drupal includes the template file, your declaration of `$a = '1'` is not in the global scope. You need to declare it as such:

```
global $a;
$a = '1';

```

Since you're diving into the realm of global variables though, I'd recommend using a more distinctive name, or figuring out how to avoid globals altogether.
> 3 votes

---
Tags: theming
---


# Question
Title: How do I change a MySQL query into a Drupal query?
```
mysql_query("SELECT nid,title, type,created, v_api.ContentSum
  FROM `node` n
  LEFT JOIN ( SELECT content_id,
                     SUM(CASE WHEN value=1 THEN 1
                         WHEN value=0 THEN -1
                         ELSE 0
                     END) AS ContentSum
                FROM votingapi_vote
               WHERE value_type = 'option'
               GROUP BY content_id) v_api
    ON n.nid = v_api.content_id
where type='provider'
ORDER BY v_api.ContentSum DESC, created DESC LIMIT 0 , 22");

```

How do I change this query into a Drupal query?

# Answer
> 1 votes
Check out the drupal Database abstraction layer. Without thinking about what you want to achieve with your query I would write it like that:

```
db_query_range("SELECT nid, title, type, created, v_api.ContentSum
                FROM {node} n
                LEFT JOIN (SELECT content_id,
                                  SUM(CASE
                                       WHEN value=1 THEN 1
                                       WHEN value=0 THEN -1
                                       ELSE 0
                                      END) AS ContentSum
                           FROM {votingapi_vote}
                           WHERE value_type = 'option'
                           GROUP BY content_id) v_api
                ON n.nid = v_api.content_id
                WHERE type='provider'
                ORDER BY v_api.ContentSum DESC, created DESC", 0, 22)

```

Maybe one of the values (type,value\_type,...) could be set via arguments, too.

EDIT:

here again with arguments:

```
db_query_range("SELECT nid, title, type, created, v_api.ContentSum
                FROM {node} n
                LEFT JOIN (SELECT content_id,
                                  SUM(CASE
                                       WHEN value=1 THEN 1
                                       WHEN value=0 THEN -1
                                       ELSE 0
                                      END) AS ContentSum
                           FROM {votingapi_vote}
                           WHERE value_type = %s
                           GROUP BY content_id) v_api
                ON n.nid = v_api.content_id
                WHERE type= %s
                ORDER BY v_api.ContentSum DESC, created DESC", 'option', 'provider', 0, 22)

```

---
Tags: database
---


# Question
Title: During installation, the 'set up database' phase was skipped. Is that normal?
This isn't the first time I install Drupal 7 locally, but it is the first time that during installation the 'verify requirments' and 'set up database' phases were skipped.

I did have databases set up with the same name as the sites (testsite.localhost and testsite2.localhost). Is that why those steps were skipped?

I did look though the databases in phpmyadmin and it looks as though both installations were populated properly.

# Answer
> 2 votes
Did you perhaps already have a settings.php file in place with the database information already in it? If Drupal can find that, it will use that information instead of prompting you and creating a new settings.php file itself.

---
Tags: database, installation
---


# Question
Title: performance: rule set or triggered rules?
I need to create some rules like "when create photo, when create video, when create story" but all use the same Event "after content is saved"...

so, what's the best way? a rule that trigger a rule set with various rules or varios indepedent triggered rules?

i.e:

**RULE SET**

```
rule (when create content) >
    event (after content is saved) >
        set (set: when create content) >
            rule (when create photo) >
                if:
                do:
                    rule (when create video) >
                        if:
                        do:
                    rule (when create story) >
                        if:
                        do:
                    rule (when create page) >
                        if:
                        do:
                    rule (when create product) >
                        if:
                        do:

```

total:

```
1 set
6 rules
1 event

```

**TRIGGERED RULES**

```
Rule (when create photo) >
    Event (after content is saved) >
        if:
        do:

Rule (when create video) >
    Event (after content is saved) >
        if:
        do:

Rule (when create story) >
    Event (after content is saved) >
        if:
        do:

Rule (when create page) >
    Event (after content is saved) >
        if:
        do:

Rule (when create product) >
    Event (after content is saved) >
        if:
        do:

```

total:

```
5 rules
5 events

```

thanks.

# Answer
I believe the performance different is marginal, so I would chose the most maintainable.

Anyways in regards to performance my bet would be on the last option. Events function pretty much like a SQL where clause, so having more events doesn't hurt performance in itself. The number of rules that has to be fetched from the database, and initialized does effect performance, along with the number of queries that need to be executed.

So Rules will (most like) in the first case be running two queries. One to get the rule set based in the event and one to get the 5 rules in the set. It will need to instantiate 6 rules classes.

In the second case, rules will run a sigle query and only need to instantiate 5 rules classes.

So with fewer queries and rules classes that need to be instantiated the last version should be the most performance optimized. I doubt that you actually will be able to measure this though.
> 1 votes

# Answer
You could also (depending on the complexity of your action) put this inside an extra module like this:

```
function YOURMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    if($op == 'insert') {
        $action_types = array('photo','video','story','page','product');
        if(in_array($node->type,$action_types)) {
            // put your action here
        }
    }
}

```
> 0 votes

---
Tags: 7, performance, rules
---


title: Odd user login error

text:
# Question
Title: Odd user login error
For some reason on my site, if a user logs in using the user login block it will send them to the /user/ page to login where they have to type in their details again and it will log them in. It will redirect them here whether the initial details are correct or not.

This is also happening with the slipjaq module (slide down login panel) so I think it might have something to do with clean URLs. Do you have any idea?

# Answer
Try disabling Clean URLs and see if it works. If it does, it might be a problem with the module you are using.

Do this behavior also happen if you disable slipjq module? If no, I recommend that you build this functionality yourself using jQuery. It would be easy. If yes:

Have you created any alternative URL's pointing or coming from /user ? If yes, try removing it.
> 2 votes

---
Tags: users
---


# Question
Title: My implementation of template_preprocess_block() isn't working
My block has `id=block-block-10`, now i want to add a more link after the title. This is my code in my theme's template.php.

```
function mytheme_preprocess_block(&$variables) {
  if($variables['block_id'] == 10){
    $variables['block']->subject='<h2>test></h2><span>more</span>';
  }
}

```

There is no more text on the block's title. What's wrong with my code?

# Answer
> 3 votes
The `$variables['block_id']` variable is based on the number of blocks in a region (see `template_preprocess_block()`. If you want this for a specific block, despite what region it is in, you should be checking `$variables['block']->delta == 10` instead.

---
Tags: blocks, theming
---


title: Add CCK form with overlay or colorbox

text:
# Question
Title: Add CCK form with overlay or colorbox
I have a CCK form. When users submit the form, and add new content, I would like the form to be viewed in an overlay that allows the form to use all of the browser window's area in a similar manner as colorbox or lightbox.

The reason for this is to provide more screen space for the large form. I have most blocks hidden for this content type, but there is still other page elements and menus ect taking up room.

Also, I am using the multistep module. This means the content is created before submitted. After the first step, the path is no longer /add/\[…\]. Multistep also provides a block for the form index and progress bar. If I only display the node in colorbox (which is installed and used for other features) then I miss out on the multistep block.

# Answer
> If I only display the node in colorbox (which is installed and used for other features) then I miss out on the multistep block.

A "quick-and-dirty" solution that I can think of, is to embed the multistep block in the node using the Insert Block module. Notice, that if you are using D7, you can check this, which is a community submitted port of the module.

If this is not what you need, please add a couple of screenshots of the form and the multistep block so that we can understand exactly what you are trying to do here.
> 1 votes

---
Tags: modal-dialogs, forms
---


title: mysql binary log makes disk full

text:
# Question
Title: mysql binary log makes disk full
Suddenly, I got my website down (drupal 6.19) and could not start mysql (too many tables got crashed). by checking *df -h*, I found that the MySQL partition is full due to very large binary log files (I keep binary logs for one day only, **expire\_logs\_days = 1**); by checking mysqlbinlog for one of the bin logs I found out that most of the entries are for cache tables (cache\_form, boost\_cache, boost\_cache\_relationships, cache\_content, etc) and for sessions table; some of the data is repeated many times.
by the way, i have **watch ls -lh** and the bin-log files got larger exponentially (every one or two minutes i got new binlog file with 100M file size!!)

Do you have any idea of what causes this? How can I fix this problem?

# Answer
> 6 votes
I guess one obvious improvement would be to use a different cache backend.

If you have a single server and enough memory, you could use an APC backend (D6: http://drupal.org/project/cacherouter, D7: http://drupal.org/project/apc) to have various of the often used caches directly in shared memory. That is probably the fastest cache solution you can get.

Another alternative is Memcached, which is especially interesting if you have multiples servers that should share a cache.

Note that you can't move the cache\_form because that contains information about currently displayed forms and is not really a cache since it contains unique information, not just aggregated things like the others, which can always be cleared. Also, some other caches, especially cache\_update, you might want to keep in the database, because that shouldn't be cleared like the rest as it contains information about update information of your used modules, something that doesn't change *that* often and can be very slow to re-fetch if you have many of them.

You can also move the sessions information out of the database, for example can you place it in MongoDB, and there are probably others too.

# Answer
> 3 votes
Have you checked the date of your bin logs ? **expire\_logs\_days** setting is not "auto-magic". It only takes effect when restarting mysql or when executing the command `flush_logs` or when **max\_binlog\_size** is reached.

Then mysql should rotate the current log file (creating a new one) and deleting the files older than 1 day (in your case)

Try to set up this last setting in your **my.cnf** and see if it works combined with **expire\_log\_days**.

---
Tags: caching, database
---


# Question
Title: Using Contextual filter in Filtering attached view
Suppose I have these two node types, with the following fields:

### Port

Name
Description

### Voyage

Name
Port1
Port2
Port3

I used References to link the port fields in Voyage to the node ID of the Port nodes.

Now, in the page of any port node, I need to attach a display of voyages names that has calls to that port. How can I achieve that in Views with EVA?

Or to put it logically: "SELECT Name FROM Voyage WHERE (port1 = (urlid) or port2 = (urlid) or port3 = (urlid));" urlid is the ID of the port we are getting through the argument (contextual filter).

I have used contextual filter, but there seems to be no way to use OR in contextual filters...

# Answer
The contextual filters belong to the first filter group so if you click the little arrow besides the Filter "add" then choose "and / or" then you can switch the operator of the first group to OR.
> 6 votes

---
Tags: nodes
---


# Question
Title: Using a PHP class defined in the module file inside the implementation of hook_install()
If the implementation of hook\_install() of my module needs to use a class defined in the module file, should the code first load the module file with drupal\_load()?

I would think that when the hook is invoked, the Drupal registry has not been yet updated to contain any reference to the PHP classes defined in the modules used by my module, and which are referred in the .info file. I looked at Drupal code, but I could not find any proof for what I think Drupal does.

Should I use `drupal_load()` or the file will be loaded automatically when I try to create an instance of the PHP class defined in the module file? Is it different with `hook_update_N()`?

# Answer
There is no need to do that: It's already loaded. That is done from `module_enable()` which uses the following code.

```
if ($existing->status == 0) {
  // Load the module's code.
  drupal_load('module', $module);
  module_load_install($module);
  // …
}

```

That code is executed before the code that invokes the `hook_install()` implementation done by the module.

```
// Now install the module if necessary.
if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
  drupal_install_schema($module);

  // Set the schema version to the number of the last update provided
  // by the module.
  $versions = drupal_get_schema_versions($module);
  $version = $versions ? max($versions) : SCHEMA_INSTALLED;

  // If the module has no current updates, but has some that were
  // previously removed, set the version to the value of
  // hook_update_last_removed().
  if ($last_removed = module_invoke($module, 'update_last_removed')) {
    $version = max($version, $last_removed);
  }
  drupal_set_installed_schema_version($module, $version);

  // Allow the module to perform install tasks.
  module_invoke($module, 'install');

  // Record the fact that it was installed.
  $modules_installed[] = $module;
  watchdog('system', '%module module installed.', array(
    '%module' => $module,
  ), WATCHDOG_INFO);
}

```
> 4 votes

# Answer
Or you can just:

```
require_once dirname(__FILE__) . '/mymodule.module';

```

Anywhere inside of your .install file (top is better).

This is not the "Drupal way" but it will work seamlessly whatever happens.

The proper method would be:

```
drupal_load('module', 'mymodule');

```

Inside all hook\_install() and hook\_update\_N() implementations that needs the class. But I'm not sure it will work at install time.
> 0 votes

---
Tags: hooks
---


title: Imagecache preset table

text:
# Question
Title: Imagecache preset table
I got my database crashed and fixed it, but some tables missed some of its data. one of these tables are the table that contains the preset values for imagecache (imagecache v 1.6.2.1, Drupal 6.19).

```
mysql> select * from imagecache_preset;

+----------+-----------------------------------------+
| presetid | presetname                              |
+----------+-----------------------------------------+
|        1 | article_headline_main                   |
|        2 | article_headline_thumb                  |
|        3 | article_headline_node                   |
|        4 | article_behind_the_news_old             |
|        5 | article_main_news_old                   |

```

By editing any of the above presets, i found that it is UNSET and I have to respecify action, height and width.
I have a dump of my database, but I need to know the table that contains the preset values so I can get them back from the backup. Which database table is it?

# Answer
> 0 votes
Check out the `imagechache_action` table, that should have the information you are looking for.

---
Tags: media
---


# Question
Title: Please help with this query! Need to get taxonomy terms of related nodes
I've inherited this code that runs on our home page. It's used to do a custom display of specific pieces of related info. Here's how things are set up:

We have an article. It has a series of node reference fields that allow us to link related images (actually nodes themselves, which contain a headshot and some text; it's not an actual attached image.) Each of those headshots has a thumbnail created via ImageCache so that we can display a small version in search results and on list-type pages.

We have a new requirement that if the related image node for a specific article has a certain taxonomy term (tid) associated with it, it should display differently than other images.

The existing query (which I did not write) looks like this:

```
SELECT DISTINCT n.title, nr.teaser, n.nid, DATE_FORMAT(FROM_UNIXTIME(n.created), '%M %e, %Y') AS date, f.filepath AS image, cfri.field_related_images_nid as image_id

FROM node n JOIN node_revisions nr ON n.nid = nr.nid
LEFT JOIN content_field_related_images cfri ON (n.nid = cfri.nid AND cfri.delta = 0)
LEFT JOIN content_field_att_file cfaf ON cfri.field_related_images_nid = cfaf.nid
LEFT JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn2 ON n.nid = tn2.nid

WHERE n.status = 1 AND n.type = 'article'   AND nr.body LIKE '%kimberly-clark%' AND tn2.tid = 143 ORDER BY n.created DESC LIMIT 3

```

This returns a recordset that looks like this:

```
TITLE         |  TEASER           |  NID |  DATE            |  IMAGE                            | IMAGE_ID
==========================================================================================================
Exec Profile  |  Could you please | 67491 | April 29, 2011  | sites/default/files/kcjones.jpg   | 67572
Unilver Ads   |  Unilever topped  | 67421 | April 20, 2011  | sites/default/files/unilever.jpg  | 66889

```

This is all well and good. But what I need to do is (in the same query, somehow) also return the tid that goes with the image\_id from the term\_node table. On its own for a single image node that query is simple:

```
SELECT tid FROM term_node WHERE nid = 67572

```

But how do I modify the existing query to bring in the tid based on the image\_id found in the main part of the query? I'm guessing I need some kind of subquery, but this is stretching the limits of my sql chops...

# Answer
You already have the {term\_node} table joined in your query so I'm pretty sure you should just be able to change your first line to include `tn2.tid`. Try this:

```
SELECT DISTINCT n.title, nr.teaser, n.nid, tn2.tid, DATE_FORMAT(FROM_UNIXTIME(n.created), '%M %e, %Y') AS date, f.filepath AS image, cfri.field_related_images_nid as image_id
FROM node n JOIN node_revisions nr ON n.nid = nr.nid
LEFT JOIN content_field_related_images cfri ON (n.nid = cfri.nid AND cfri.delta = 0)
LEFT JOIN content_field_att_file cfaf ON cfri.field_related_images_nid = cfaf.nid
LEFT JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn2 ON n.nid = tn2.nid

WHERE n.status = 1 AND n.type = 'article'   AND nr.body LIKE '%kimberly-clark%' AND     tn2.tid = 143 ORDER BY n.created DESC LIMIT 3

```
> 1 votes

---
Tags: database
---


title: overlap dropdown menu and slideshow

text:
# Question
Title: overlap dropdown menu and slideshow
I use Zeropoint theme and the drop-down menu in this theme.
When I hover the mouse over a menu, and the menu is expanded, my submenu is placed under the slideshow and is not show completely.

Do you have any suggestion on how to solve it?

# Answer
> 2 votes
I have this problem using things like Views Slideshow and NiceMenus. You can perhaps fix it by changing the CSS of the menu to include the following: `z-index: 99`. If you post a link to the site I can give you a more detailed answer.

---
Tags: routes, theming, navigation
---


title: How to measure user growth over time?

text:
# Question
Title: How to measure user growth over time?
I have a client that is looking to measure how their drupal user accounts grow over time.

I currently have the http://drupal.org/project/chart module with the System Charts sub module enabled and this does provide a nice pie graph of the users as the system *currently* stands.

Has anyone found a solution for this? Integration with the charting API would be nice too ;)

# Answer
> 2 votes
You can use `select count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%m-%Y') as month from users group by MONTH(FROM_UNIXTIME(created));`. This uses the created field of the `users` table.

Edit:

In your code this should look something like

```
$result = db_query("SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%m-%Y') AS month
                    FROM {users}
                    GROUP BY MONTH(FROM_UNIXTIME(created))");

```

This will return all new usercreations grouped by month. You could use other Date/Time Functions like DAY. But be carfull with the groups. The example above only works correct if you track the data of one year (because it does not group by year). Here is a more complex example:

```
$result = db_query("SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%d-%m-%Y') AS month
                    FROM {users}
                    GROUP BY YEAR(FROM_UNIXTIME(created)),
                             MONTH(FROM_UNIXTIME(created)),
                             DAY(FROM_UNIXTIME(created))");

```

I'm not entirely sure if there is a better solution to this. I can't help with the Integration into the charting API as I never used it.

# Answer
> 0 votes
You will have to write the number of users regularly (for example once a day) into a database and then create a chart based on that.

Drupal does not keep that information.

# Answer
> 0 votes
I disagree with Berdir; Drupal *does* track this information, though in a way that will take a bit of massaging. Check out the `{users}` table in the database; for each user account, the `created` column stores the UNIX timestamp of when the account was created. After exporting that data into a spreadsheet, functions could be written to count the number of accounts were created on or before any given day/week/whatever, and from there you have your graph. It'll be a bit of work, but all within the realm of possibility.

# Answer
> 0 votes
Charts API has views integration so you could use a view in conjunction with an argument to display different months. As Garrett Albright and nonsenz have said, you can use the Drupal users created dates and display them by the month they signed up.

---
Tags: nodes
---


title: Passing Arguments to block in 7.x Views

text:
# Question
Title: Passing Arguments to block in 7.x Views
I've got a block view set up to get the latest 3 blog posts by term. I'm providing the default argument with the following:

```
$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
if($path[0] == 'laws' || $path[0] == 'issues' || $path[0] == 'culprits' || $path[0] == 'themes' :
return $path[1];
endif;

```

Using dpm on $path\[1\] gives me the term alias and I assumed that the Argument validator for Taxonomy Terms, which is set to "Term Name converted to Term ID", would get me the ID, but maybe not?

Works fine in views preview with arguments entered, but on an actual page it returns nothing. Never had a problem with this before in 6.x. Is there something new I'm completely missing? I've read through docs and tried a few different ways to return the default arg, but no luck.

Any help would be appreciated.

Thanks

Edited to fix code

# Answer
> 2 votes
Added `return '';` to the argument code if the if statement was false. Somehow that did the trick.

---
Tags: 7, views, blocks
---


title: Help with function in template.php

text:
# Question
Title: Help with function in template.php
Drupal 7.

Can anyone spot what could be wrong with this function? I'm just trying to pull a taxonomy term or its parent. The taxonomy is called "pubissue."

In template.php:

```
 function ain_core_getpubname() {

// Load the node from unaliased url
if ((arg(0) == 'node') && is_numeric(arg(1))) {
$node = node_load(arg(1));}

// first find out if it's level two or not
$query = "SELECT t1.tid, t1.parent FROM taxonomy_term_hierarchy t1 JOIN field_revision_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = ".$node->nid;

    $result = mysql_query($query);
    print_r(mysql_fetch_assoc($result));

        $mytid = $row["tid"];
        $myparent = $row["parent"];

    if ($myparent == 0) {

        // No parent, top level
        $query = "SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$mytid;

        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);
            $pubname = $row["name"];
    }

    else {

        $query = "SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$myparent;

        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);
            $pubname = $row["name"];

        }

print $pubname;

```

}

Then in my node.tpl.php file:

```
 <!-- Begin Publication -->
    <div class="<?php print $node->type; ?>-pubname"><?php ain_core_getpubname() ?></div>
<!-- End Publication -->

```

OK, so going with the suggestion below:

```
function ain_core_getpubname() {

// Load the node from unaliased url
if ((arg(0) == 'node') && is_numeric(arg(1))) {
$node = node_load(arg(1));}

// first find out if it's level two or not
$query = "SELECT t1.tid, t1.parent FROM taxonomy_term_hierarchy t1 JOIN field_revision_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = ".$node->nid;

    $result = db_query($query);
    $row = db_fetch_array($result);

        $mytid = $row->tid;
        $myparent = $row->parent;

    if ($myparent == 0) {

        // No parent, top level
        $pubname = db_query("SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$mytid)->fetchField();
    }

    else {

        $pubname = db_query("SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$myparent)->fetchField();

        }

print $pubname;

```

Still not working. Will continue to troubleshoot, I think I am on the right track. Thanks again.

# Answer
Your queries should look something like this:

```
$query = "SELECT t1.tid, t1.parent FROM {taxonomy_term_hierarchy} t1 JOIN {field_revision_field_pubissue} t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = :nid";
$result = db_query($query,array(':nid' => $node->nid));
// Result is returned as a iterable object that returns a stdClass object on each iteration (@see http://api.drupal.org/api/drupal/includes--database--database.inc/function/db_query/7#comment-7019)

```

After all I would suggest you check out the drupal taxonomy api. Using something like taxonomy\_get\_tree() could be much better.

EDIT:

Using the taxonomy api I would say what you want to do would be something like:

```
$parents = taxonomy_get_parents($tid);
if(!empty($parents)) {
    // use whatever you need from your $parents
}
else {
    $term = taxonomy_term_load($tid);
    // use whatever you need from the term (No parent, top level)
}

```

EDIT 2: fixed code example...
> 1 votes

---
Tags: nodes, theming
---


title: File field label

text:
# Question
Title: File field label
I have created a custom content type that has a file field. When I upload a file the node displays the complete file name, test\_file.pdf. I would rather display its file name as clickable link. I have tried manage display and set the format to URL to file and it displays "File: site\_name.com/sites/default/files/test.txt," which is only text.

Is there anything I am missing?

# Answer
You are on the right track! Go to "Manage Display" and set the format to "Generic File", it will give you a clickable filename with a link to the file!
> 3 votes

# Answer
I've created a module on drupal.org that provides a formatter that does just that: https://www.drupal.org/project/file\_formatters.
> 3 votes

---
Tags: 7, files
---


title: Adding more menu in the menu settings?

text:
# Question
Title: Adding more menu in the menu settings?
In Drupal 7, in admin/structure/menu/settings we have the main links and the secondary links.

Can we add third one here? Is there any way to get the list of all menus created in backend?

# Answer
> Can we add third one here?

Yes, we can. Use `hook_form_alter()`, alter form\_id `menu_configure`.

How do I know what form\_id? Let's see `menu_menu()` at `http://api.drupal.org/api/drupal/modules--menu--menu.module/function/menu_menu/7`

> Is there any way to get the list of all menus created in backend?

Again, We can. Select menus in table {menu\_links} where {menu\_links}.menu\_name = management.

```

    $result = db_select('menu_links', 'm')
    ->fields('m')
    ->condition('menu_name', 'management','=')
    ->execute()
    ->fetchAssoc();

```
> 2 votes

# Answer
On the "Menus" menu, you can select "Add new Menu" in the upper part of the window. Once added, you can go to "Blocks" to select where that new menu will be.

Also on "Menus" you can see all menus in your site (Main, Navigation and user-created)
> 0 votes

---
Tags: routes
---


# Question
Title: Render a full entire html page from custom module
I've searched/asked around without success.

I'm creating a custom Drupal 7 module, and I would like to render the code in an empty full template (not a page/node.tpl.php); by full template I mean a template containing the `<html>` tag.

Since now, I've used the following code but the template is rendered in page.tpl.php (`render($page['content'])`).

```
function mymodule_theme() {
  return array(
    'adm_xyz' => array (
      'render element' => 'render',
      'template' => 'adm_xyz', //  template *.tpl.php
    ),
  );
}

```

# Answer
Your callback in hook\_menu() will by default call drupal\_deliver\_html\_page() which in turn calls drupal\_render\_page() where the page.tpl.php comes from.

It is possible to implement your own "delivery callback" method, which will be called by drupal\_deliver\_page() this is how the ajax is delivered in D7
> 5 votes

---
Tags: 7, theming
---


# Question
Title: 301 redirecting broken links after moving Joomla! to subdomain and giving parent domain to Drupal7?
I've recently started doing way more Drupal development than Joomla!, and given I use my personal website as a testing platform that changes about once every few years, am trying to migrate it from Joomla! 1.5 to Drupal 7.

To this end, I've moved the entire Joomla! website to http://v3.aendrew.com and in doing so, broken all incoming links, which are now met with a Drupal install that's never heard about any of my prior content -- http://aendrew.com.

**Is there any way I can do the following via Drupal 7?**

1. Detect broken incoming request (Drupal 404s)
2. Check whether the path exists on the Joomla! subdomain.
3. Issue a 301 redirect pointing to the Joomla! page if so; issue a 404 if not.

Thank you!

# Answer
I would personally follow the steps described below:

1) Use this technique to detect the 404s and issue the redirect

2) Since you don't want to issue the redirect right away, but first check whether the URL exists in the Joomla! subdomain, you can use a function like this to determine whether the URL exists.

3) In order to determine what the URL of the incoming request was (so that you can use it to match it against the Joomla! subdomain), you can use this: $\_SERVER\['REDIRECT\_URL'\]
> 1 votes

---
Tags: redirection
---


# Question
Title: How do I implement hook_finder_goto_alter()?
I'm having a bit of trouble with troubleshooting a module I am working. I am trying to modify a module to redirect traffic but even though its enabled it doesn't seem to do anything. I've had problems in the past with using hooks and i'm not sure what I'm doing wrong.

I am basically using the finder module and here's the code to redirect:

```
function test_finder_goto_alter(&$result, $finder) {
  /* Redirect to a different page in the current directory that was requested */
    drupal_goto("testpage");
}

```

I see the module in modules and enabled it but it still doesn't redirect the way I want it to. Do you have any suggestion on what I'm doing wrong? I don't think its specific to this module I think I might be doing something wrong in general.

# Answer
> 1 votes
Implementations of `hook_*_alter()` are generally supposed the first parameter passed as reference, not to execute `drupal_goto()`, or any other functions that redirect the user.

Looking at the code of the Finder module, I notice that the following code is one that handles the hook you implemented.

```
$base_module = &$finder->base_handler['#module'];

if ((isset($finder->go) && $finder->go && count($result)) || ($goto == 'best' && count($result) === 1)) {
  drupal_alter('finder_goto', $result, $finder);
  $current_result = current($result);
  module_invoke($base_module, 'finder_goto', $finder, $current_result);
}

```

Finder calls that hook with drupal\_alter(), which is the function used to invoke such hooks, and it passes the altered argument to the implementation of hook\_finder\_goto() implemented in the `$base_module` module.

# Answer
> 1 votes
**Hooks 101**

hooks should be created in a module. The module which they are called from should be enabled.

So in the first instance you will need to create a .info and a .module file with the correct information in.

Then to implement a hook you must use the module name.

So the example code above would work if the php code is in a module called *test* which was enabled.

So `hook_menu()` in a module called `test.module` would be a function called `test_menu()`

Secondly hooks will only be called when invoked, some get invoked rarely when for example building the menu system, and others are invoked when specific actions happen. You will need to read up on the documentation for the hook in question to find out more.

The same goes for parameters and return values, each hook is different. So the documentation is important there.

So a general checklist for hooks.

* Is the hook in a module?
* Is the module enabled?
* Is the hook named the same as the module?
* Is the action which is calling the hook being called?
* Have I cleared the cache?
* Am I using the hook in the correct way?

# Answer
> 0 votes
You should clear Drupal cache after you implementing hook.

Go to the admin-\> Performance -\> Clear cache

---
Tags: hooks
---


title: What is page_fast_cache?

text:
# Question
Title: What is page_fast_cache?
The Cache Router module advertises that it "has an option to utilize the page\_fast\_cache part of Drupal in order to reduce the amount of resources needed for serving pages to anonymous users."

However, the only Google hits for "drupal page\_fast\_cache" point back to cacherouter.

What *is* page\_fast\_cache?

# Answer
> 4 votes
I believe the project page is referring to page\_cache\_fastpath(), which is called during Drupal bootstrap from the following code:

```
if (variable_get('page_cache_fastpath', FALSE) && page_cache_fastpath()) {
  exit;
}

```

The documentation page reports the following description for the function:

> By implementing `page_cache_fastpath()`, a special cache handler can skip most of the bootstrap process, including the database connection. This function is invoked during DRUPAL\_BOOTSTRAP\_EARLY\_PAGE\_CACHE.

The example code reported in that page helps to understand how the function needs to be implemented, and what should do.

```
function page_cache_fastpath() {
  $page = mycache_fetch($base_root . request_uri(), 'cache_page');
  if (!empty($page)) {
    drupal_page_header();
    print $page;
    return TRUE;
  }
}

```

If the module reports to utilize it, it means it actually defines the `page_cache_fastpath()` function, which is called by Drupal core code.
To notice that it's not a hook, but a function. This means that a module called "mycache" doesn't need to implement `mycache_page_cache_fastpath()`, but `page_cache_fastpath()`. In fact, the bootstrap code is explicitly calling `page_cache_fastpath()`, as it is evident in the code I reported at the beginning of this answer.

---
Tags: caching
---


title: Image module for photogaleries

text:
# Question
Title: Image module for photogaleries
I wanted to download Image module, but I notice that it's not for Drupal 7. Is there some alternative I can use in Drupal 7?

thank you

# Answer
The Future of Image in Drupal 7 reports the following text:

> Image module is being put into core, but not in its current incarnation. Drupal 7 has already made several major improvements that will make handling images (and files in general) much easier, eliminating a lot of the existing code from image.module.

> The Drupal 7 core plan is as follows:
>
> * Move ImageAPI into core to provide better support for toolkits such as ImageMagick (done).
> * Move ImageCache into core to provide thumbnailing abilities as part of image.module (in progress).
> * Move FileField into core as file.module.
> * Move ImageField into core as part of image.module.

This means that most of the functionality of those modules are already integrated in Drupal 7.
ImageAPI still contains code that has not been merged with Drupal 7 code; you should install it if you need the ImageMagick toolkit it implements, or the unsharpen mask action.

As gallery modules, you can try:
> 2 votes

# Answer
There are actually a lot of modules that have been ported to (or are initially written for) Drupal 7. A typical example is Gallery Formatter.

However, if I were you, I would read thoroughly through the following 2 links:

Link 1

Link 2

since there are a lot of different ways to create a photo gallery in Drupal 7. You have to pick the way that is the more convenient for you (e.g. you may want a module that does just this, or you may want to stick to the "lego-logic" of drupal and create the gallery from a cck field).
> 1 votes

---
Tags: 7, media
---


title: How do I remove this part?

text:
# Question
Title: How do I remove this part?
I have created a content type, but it doesn't use the following part. I want to remove it without using CSS. how can I doit?

# Answer
> 2 votes
You can implement hook\_form\_alter() for your content type and then do something like this inside your implementation:

```
// implement hook_form_alter() for cex_3dr content type:
function cex_3dr_form_alter( &$form, $form_state, $form_id ) {

  if ($form_id == 'cex_3dr_node_form')
  {
    // get rid of form elements that may confuse end-users
    unset( $form['menu'] );
    unset( $form['body_field']['format'] );
    unset( $form['revision_information'] );
    unset( $form['path'] );
    unset( $form['attachments'] );
    unset( $form['author'] );
    unset( $form['options'] );
    unset( $form['comment_settings'] );
    unset( $form['buttons']['preview'] );
  }
}

```

you can also print out the contents of the form to see what fields are there, and then you know which ones to get rid of via an 'unset()'.

BTW, this is Drupal6 logic. Haven't done D7 modules yet, so the technique may vary a bit, but the concept is 'very drupal' so I'd be surprised if it were no longer possible.

# Answer
> 1 votes
The Jammer module will allow you to hide admin options on whatever node form you choose.

Install the module and make sure you enable the submodule 'Content form jammer'. Navigate to ~/admin/config/user-interface/jammer to select which parts on which node types to hide.

---
Tags: theming
---


title: Custom variables in node content

text:
# Question
Title: Custom variables in node content
Is it possible to use custom variables in content?

For example we have the price of a product which is listed on a large number of nodes as £9.99... This price then changes to £11.99. Updating this price becomes a pain!

What we would like is to be able to have a variable such as \[product1price = £9.99\] which we can include in node body. Then should we need to change this price, we can edit the variable to instantly update it everywhere it appears in the system.

Does a Module already exist for functionality like this?

# Answer
You could implement custom tokens, and the coupled with the module http://drupal.org/project/token\_filter \- your content will be rendered as per usual.

In this way you could have a token:

\[price-tier-1\] = $9.99

and when the price changes you only have to change the token value (in one place, in code)
> 2 votes

---
Tags: 7
---


# Question
Title: How can I re-Install a site I pulled in from a git repo?
I cloned an entire site from git. I cannot install it.

1. Inside the foo.com/sites folder there are a couple folders. The settings.php file is in the folder dev.foo.com rather than the default folder.(I know this is how multisite is.)

I have added a line in my hosts file

```
    127.0.0.1       dev.foo.com

```

I have added a stanza to the http.conf file

```
    <VirtualHost *:80>
DocumentRoot /var/www/foo.com
ServerName dev.foo.com
    </VirtualHost>

```

Restart Apache - then I go to dev.foo.com - then I see the It Works! file created by apache rather than the drupal installer that I should see from dev.foo.com

How come?

2.. How can I use the database of the site I cloned? With Backup and Migrate?

EDIT: tried the site in a couple other browsers and I see this

> Site off-line
>
> The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.
>
> If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.

3...Looks like I need the database before trying to install? Yeah?

# Answer
I got it to work. Kind of. Aside from this

What did it was -

* I made a backup of the database with Backup and Migrate module from the Production site.
* I created a database and user with phpmyadmin that matched the settings.php file.(locally)
* I ran the dev.foo.com/install.php and it went though.
* After that I enabled the Backup and Migrate module.
* Then imported the database from the initial backup. (there was a problem with the php only allowing 2M for import so I hunted down php.ini and changed the value to something high enough.
* Site was there.

I understand this is a round-about way. I know there are better ways to import/export the database thought the command line.

But is there a way to get the site to work without making a database that matches the settings.php file? Or is that the best way?
> 1 votes

# Answer
1. If you see "it works", Apache hasn't recognised index.php - either you are being served files from the wrong directory, or Apache isn't configured to use index.php as the default file in a directory. You can test the latter readily: http://dev.foo.com/index.php will show the correct page while http://dev.foo.com/ will display "It works".
2. mysqldump, backup and restore, PHPMyAdmin ... whatever tools you have available.
3. Yes, you need a working DB locally to install Drupal. And you need the values in settings.php to work to load your existing DB.
> 1 votes

---
Tags: version-control, installation, multi-sites
---


title: X-Drupal-Cache http header

text:
# Question
Title: X-Drupal-Cache http header
Examining for http headers, I mentioned the header "X-Drupal-Cache HIT". I use varnish reverse proxy.

Is it necessary for this header to appear? Can I make it be ommited? If yes, how? Would that have negative implications?

# Answer
> 5 votes
To change drupal http-header information check out drupal\_set\_header() (D6) or drupal\_add\_http\_header() (D7).

Looking at the documentation for \_drupal\_bootstrap\_page\_cache, it seems the header shows 'HIT' if the page is displayed from cache, and 'MISS' in the case it is not.

Check out Set X-Drupal-Cache header during page\_cache\_fastpath and Implement better cache headers for reverse proxies for more information about the X-Drupal-Cache header. It seems to be a Drupal 7 or Pressflow only thing.

---
Tags: caching
---


# Question
Title: Allowing users to create calculated views
I am using Views 3 and I was able to do some math on the fields using the "Views Custom Field" module that was recommended to me.

It works perfectly and does exactly what I want it to do, but my problem is that I need to grant access to users to create views and calculations on them. Views custom field is not really a math only field, it's basically allowing them to execute PHP code directly on my site, which I suspect is dangerous.

Also, another requirement is that they are not directly modifying the actual data, but creating a view for themselves(or to share) that derived from this data. That means the view they create must somehow be connected to their ID and not modify the master data.

I don't know if it is the best approach, but I was thinking of using something like phpexcel and exposing the tables so they can link to certain data; it seems complicated for me and even more complicated for the users.

How would you approach this?

# Answer
> 1 votes
You are right, you shouldn't allow people to change php code on your site.

I would allow a lot of customization to the data that is returned via views filters.

You can return the data in a table format and allow this table to be exported to excel or csv (there are views modules for both of these). Then people can create whatever they want.

There are a few js libraries which can give you spreadsheet like functionality in the browser with an HTML table, that may be an option too.

---
Tags: views
---


title: Upgrading to a development snapshot

text:
# Question
Title: Upgrading to a development snapshot
I currently use Drupal 7.0.

I am thinking that upgrading to 7.x-dev would resolve some performance issues I have.
Do you think that upgrading a production site to the development snapshot would break any possible database upgrade path?

# Answer
> 1 votes
It is safe to use the 7.x-1.x-dev version now. The updates happen incrementally, based on a number that is updated for every new update function.

It was only before the 7.x-1.x-beta releases, where upgrading was not supported (And apart from some bugs during the beta IIRC) for the -dev version.

# Answer
> 0 votes
Generally speaking, using a development snapshot could create problems while updating from two releases of the same development snapshot; this is because there could not be an update path from the previous release to the latest release of a development snapshot.

Talking of Drupal, I remember that when I was testing Drupal 7 on my computer, and I used the development snapshot, I had to install the latest release from scratch all times. I don't remember if that happened before Drupal 7 had an official release, or it was still true when Drupal 7 had an official release.

Considering that Angie Byron (a.k.a. webchick, the maintainer of Drupal 7) reported a schedule for the release of the next Drupal 7 official releases, I would wait for the next official release, which (basing on that schedule) should happen today.

---
Tags: updating
---


# Question
Title: Ability to 'mark' nodes and build a book functionality
I am looking for ways to do the following:

* users (both anonymous and authenticated) 'mark' nodes in some fashion to say that they want paper copies sent to them
* users can set quantity of the paper versions they require
* users get review their 'marked' nodes and potentially add/remove items from it
* users enter in address to postal system

This problem could probably be solved in several ways, what is the cleanest?

# Answer
For 'marking' nodes, you'll definitely want the Flag module.
> 3 votes

# Answer
I am an advocate of the voting api for such things. It seems to fit cases where you wish to save user data against an asset (node user whatever), without making it public and with a lot of flexibility.

You can change the content-type of the vote to be something other than node, 'node-marks' for example.

The querying of votes is easy via the api or via views. It will also allow for anonymous users to mark nodes. So will tick most of your boxes.

I have used the voting api for private tagging of items (non node items) in a site I am working on and it has worked fine. It doesn't sound that dissimilar to what you are trying to achieve here.
> 1 votes

---
Tags: nodes
---


title: Taxonomy menu expanded with count

text:
# Question
Title: Taxonomy menu expanded with count
I have an accordion menu (taxonomy menu) as a block.

I want to have a very similar block but this time I want to have all taxonomy items expanded. I am thinking to something like this:

How can I accomplish that?

# Answer
I have scoured the web, banged my head on the keyboard a few times, and finally settled to the fact that there is currently no viable way of achieving this with taxonomy menu.

A simple solution that should work though I have not tried it is using views to achieve the desired effect. I quickly googled that up and came across someone with the same/similar requirement here; http://drupal.org/node/165417. Their questions seem to have been answered and I will therefore try my hand in that direction tomorrow.

Hope this helps.

Edit: Tried using views but had to upgrade to using the 6.x-3.0-alpha3 version. After that it worked perfectly. I used content taxonomy for the relationships with the settings to update core taxonomy vocabularies. Then, using views, I selected HTML list as the style and grouped by the cck taxonomy field.
> 2 votes

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


title: Create Forms in Drupal and process them

text:
# Question
Title: Create Forms in Drupal and process them
i am new to Drupal and i want to implement training / seminar program in my Drupal site. I want to know how to implement the following features:

1. The administrator will be creating a seminar / training session program from a form in admin panel, with details like name, date and description. How to add a form in admin panel and save its details in a new table in database ? Do i need to create a module here?
2. The training sessions and seminars created by admin can be viewed by the users in the front end with a scrollbar div block. How to show this information in front end ?
3. When they click on the name of a program in the block, it will lead to a separate screen, where the user can view the program details (name, date and description) and a button to register... how to create a new screen in drupal?
4. When the user clicks on register button, he will be enrolled in the program (saved in database with inactive status). Now the admin must be able to view the programs he created, in admin panel, and when he clicks on a program name, the registered users in that program will appear. Then he can click on a user's name and a small screen to 'Accept' him in the program and save his status to 1 in the database. How to implement this ?

Basically i want to know how to create forms in Drupal and how can i show them in the front end. Any help is appreciated.

# Answer
I'm assuming that you're using Drupal7. I will provide some pointers but you'll have to look up the details on your own.

1. Sounds like you might want to create a new Content Type.
2. Views can generate a list of a specific Content Type (in your case, list only seminars).
3. Views typically links each item in the list to the actual node with the full info
4. The Webform module will allow you to create sign up forms but there's likely more that you'll have to do to tie everything together.
> 1 votes

---
Tags: forms
---


title: If else for main menu

text:
# Question
Title: If else for main menu
im trying to do a if else statement for the main menu, i have something like this but i dont know where to begin.

```
<?php if ( !$is_front ) : ?>
function bartik_links__system_main_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l('<h2>'. check_plain($link['title']) .'</h2>', $link['href'], $link);
  }
  return $output;
}

<?php else: ?>

function bartik_links__system_main_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l(''. check_plain($link['title']) .'', $link['href'], $link);
  }
  return $output;
}
<?php endif ?>

```

as you can see i want the tags on the front page and if it isnt then i want the tags to disappear.

# Answer
With a few tweaks this is the correct way to do it.

```
function bartik_links__system_main_menu($variables) {
    $output = '';
    $opening_tag = '<h2>';
    $closing_tag = '</h2>';

    if (!drupal_is_front_page()) {
      $opening_tag = '';
      $closing_tag = '';
    }

    foreach ($variables['links'] as $link) {
    $output[] = l($link['title'], $link['href']);
    }
    return $opening_tag . implode($closing_tag . $opening_tag, $output) . $closing_tag;
}

```
> 0 votes

# Answer
Not sure where/when this function is called, but here's your code with some fixes:

```
function bartik_links__system_main_menu($variables) {
    $output = '';
    $prefix = drupal_is_front_page() ? '' : '<h2>';
    $suffix = drupal_is_front_page() ? '' : '</h2>';

    foreach ($variables['links'] as $link) {
        $output .= l($prefix.check_plain($link['title']).$suffix, $link['href'], $link);
    }
    return $output;
}

```
> 2 votes

# Answer
The list of the variables passed to that theme function is listed in the documentation for theme\_links(); `$variables["is_front"]` is not passed to `theme_links()` or `theme_links__system_main_menu()`.

There is a misunderstanding here: template.php is a file containing functions used by Drupal when using the theme containing that file; it should not contain any `<?php else: ?>`.

The code you should use is, roughly, the following one (it is not optimized):

```
function bartik_links__system_main_menu($variables) {
  $output = '';
  $opening_tag = '';
  $closing_tag = '';

  if (!drupal_is_front_page()) {
    $opening_tag = '<h2>';
    $closing_tag = '</h2>';
  }

  foreach ($variables['links'] as $link) {
    $output .= l($opening_tag . check_plain($link['title']) . $closing_tag, $link['href'], $link);
  }
  return $output;
}

```
> 2 votes

# Answer
You need to do the if check *inside* the theme function, where it is probably $variables\['is\_front'\] and if that doesn't work, use drupal\_is\_front\_page().

The $is\_front variable is only available inside a template file, not template.php.
> 1 votes

---
Tags: routes, navigation
---


title: Unsubscribe Newsletter

text:
# Question
Title: Unsubscribe Newsletter
I was implemented "simplenews\_register" module in my drupal project. so, Whenever user want to register in this site He has to enter his user name,email address,password and at the same time he want to subscribe any existing newsletter then he check the related newsletter check box. Then, automatically user will receive one mail regarding to subscribe link . So, he want to subscribe then he will click that link .

Here my requirement is if user has been subscribed any newsletter then automatically he has to receive "Unsubscribe" link . So, for this requirement what I have to do please guide me.

# Answer
> 3 votes
Unsubscribe links are automatically included when emails are sent via simplenews.

By the way, if you're using simplenews-2.x, you don't need the simplenews\_register module; that functionality is included.

---
Tags: users, notifications
---


# Question
Title: Views Slideshow vs list View+jquery cycle lite?
The rotating images on my work site's home page are created as a View in list format. I'm using the jQuery Cycle Lite plugin for the rotator effect. The cycle.lite.js file is set in the scripts array in my theme's .info file, and there's a bit of code in page.tpl.php to check whether this is the homepage, and if so, set up the rotator.

Now I'm working on a second rotator for another section, and I've been trying out the Views Slideshow module.

What are the pros & cons of each approach (theme vs module), especially from a server load or page weight point of view?

# Answer
I personally try to avoid using any Views jQuery modules for popular jQuery plugins and prefer just to add the jQuery plugin directly to my theme by adding the .js file to my theme.info file. I will then create another .js file that runs on load that instantiates the jQuery plugin.

I use Semantic Views module which allows you to tune the output of the view to your liking. I will use this module to output the markup in a compatible format for use with the jQuery plugin.

I find that if you use a Views plugin module for something like jQuery Cycle or jCarousel for example, you are limited by the options exposed by that plugin. I prefer not to rely on a 3rd party module which may not support the latest changes or all the features of that latest jQuery plugin.

I would expect there would be a very minimal overhead using if any at all using a Views plugin instead of using the jQuery plugin natively.
> 4 votes

# Answer
I can't speak to any specifics on performance of Views Slideshow, but it is a very widely used module, and performs well on many large sites.

In general I find it best to go with the most popular solution when working with Drupal if it fits your needs, this usually means others have put it through its paces and helped iron out any weaknesses.

There is also the added benefit that maintaining any necessary updates will be far easier with the less custom approach of Views Slideshow.
> 2 votes

# Answer
When I started to build Drupal sites I did what Camsoft is suggesting. I used views tpl files to generate only the html I needed and I used jQuery Tools to add effects. The end result was very clean code and less reliance on contrib modules. However, I ended up with many tpl files I had to maintain. Also, since I created custom solutions, I was the only one testing them. After building many sites, I have come to believe that using contrib modules is the way to go for the reason pointed out by Mark Ferree. Using Semantic Views gets me almost the code I want but the speed advantage is tremendous. So if you build Drupal sites for a living I would recommend to use contrib modules and to look at the underlying jQuery plugins so you understand the settings.
> 1 votes

---
Tags: 7, theming, views, javascript
---


title: JavaScript asynchronous loader

text:
# Question
Title: JavaScript asynchronous loader
Which module (not library) works best in Drupal 7 (they support corresponding libraries), labjs or headjs? Which is one better written, tested, and with less bugs?

# Answer
> 3 votes
Both LABjs and HeadJS are recent modules, actively developed by professional Drupal developers, both are offering versions for Drupal6 and 7 and both have less than 100 installations (see statistics).

Also both are aware of each other modules and collaborate together, see

Because they are so recent modules and you can't know how well they will be supported later in the future, I would base my decision on which JS library fits your needs. Probably I would trust more on LABjs, that is much more tested and used (twitter, vimeo, etc are using it), plus it's a library focused in JavaScript loading, nothing else.

HeadJs library in the other hand also is offering other features: detecting CSS3 features, detecting screen resolution, etc something that can be good or not, depending what you are looking for. And also HeadJS is better integrated in the Drupal ecosystem: integration with Boost, CDN, Advagg modules.

If you are interested in this topic, I would recommend you a must read blog post from the author of LabJS to get a inside view of the technology under these JavaScript loaders (LABjs, HeadJS, ControlJS from Steve Souders, etc )

---
Tags: javascript, ajax
---


# Question
Title: How does Drupal.org's packaging script works?
Is Drupal.org's packaging script publicly accessible? How does it works? What tools does it use to fetch a module and package it as a tarball? What are the best practices in building a nightly builds for Drupal modules?

# Answer
The projects on drupal.org are managed by the Project project, which also contains the scripts for this. Some drupal.org specific code (for example the zip. and tar.gz packaging implementations) are also in the Drupal.org customizations project.
> 2 votes

---
Tags: community-official-site
---


# Question
Title: How do I restrain domain names of e-mails in the Drupal registration form?
On the registration page, I want to restrict the domain of the e-mail adress only between a few choices (to limit the use of the site to internal company use only) through a list of choices. **The user, upon registration, would therefore only have to write the characters before the @ sign ; and then choose the correct domain name he uses (for instance yahoo.fr).** The final value of the email registered by Drupal (and thus registered in the database) should be like this one: \[User\_entry\]+\[@\]+\[chosen\_domain\_name\]. I found some functions to verify the e-mail spelling, but I really want users only to have the choice between shown domain names.

I've read some answers talking about `hook_form_user_login_alter()`, but I still don't get how I could make it...

Thks for your replies !

# Answer
I'm not sure if you have any experience in PHP or custom module development but I don't have time to give you a working example. However I will point you in the right direction.

• Create a custom module

• Use `hook_form_alter` to alter the form with the form id `user_registration`

• In your `hook_form_alter` add a custom validation function and ensure it is the first validation function that runs

• In your `hook_form_alter` unset the `mail` element and add two elements for the two parts of your form (the text input and the dropdown list of domains)

• In your custom validation function, use the submitted values of your form elements to create an email address and assign it to the element you unset before, `mail`

• Make sure that in the validation function, you don't allow users to submit blank values

**Edit for a fuller answer to be added**

Ok, apologies for taking my time. This code is untested but should hopefully work for what you want to do. First of all, try to avoid doing things like this in the theme layer. The theme layer should be for themes only, so you want to create a custom module.

To create your module you need to create a `.info` file. Alter the following code and paste it into your text editor and save it as `example.info`. Remember that you can change the names of the files etc to whatever suits you, just replace the word "example" with whatever name you want to give it. Please note that Drupal deliberately omits the closing `?>` PHP tag.

```
name = "Example module"
description = "Gives an example of a module."
core = 6.x
package = Other

```

Next, you want to save a file called `example.module`. Inside this file, you will want to copy the following code. This code follows the instructions that I gave you in my previous answer. I have tried to comment this code as well as possible in order to try to show you what is being done and why. This should do what you want it to do.

```
<?php

/**
 * Implementation of hook_form_alter()
 */
function example_form_alter(&$form, &$form_state, $form_id) {
    // If the form is the user_register form
    if ($form_id == 'user_register') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_example_user_validate');
        // Hide the email address field
        $form['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 60,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#prefix' => '@',
      '#options' => array(
              // These are the possible email address domains
              'yahoo.fr' => 'yahoo.fr',
              'yahoo.com' => 'yahoo.com',
              'example.com' => 'example.com',
            ),
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _example_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['values']['mail'] = $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'];
    }
}

```
> 3 votes

# Answer
Here is what I wrote, I think it's full of errors ! O\_O ^^

```
<?php
    function tatheme_user_registration_form_alter (&$variables) {
        if (!empty($variables['user']['mail'])) {
            unset $variables['user']['mail'];
        }
        print '<input id="mailpart1" value="" class="'.$classes.'" type="text" /> @ <select id="mailpart2" name="mailpart2" class="'.$classes.'"><option value="dede.net">dede.net</option><option value="dede.com">dede.com</option>';

        $syntax='#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';

        $mail = $_POST['mailpart1']+"@"+$_POST['mailpart2'];

        if (isset($_POST['mailpart1']) OR !$_POST['mailpart1']) {
            return false;
        }
        else {
            if (preg_match($syntax,$mail)) {
                return true;
            }
            else {
                return false;
            }
        }

        $variables['user']['mail'] = $mail;
    }
    ?>

```

**CODE UPDATE AT 05/28/11 :**

```
<?php

/**
 * Implementation of hook_form_alter()
 */
function ta_module_form_alter(&$form, &$form_state, $form_id) {
    // If the form is the user_register form
    if ($form_id == 'user_register_form') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_ta_module_user_validate');
        // Hide the email address field
        $form['account']['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['account']['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 40,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#prefix' => '@',
      '#options' => array(
              // These are the possible email address domains
              'blabla.net' => 'blabla.net',
              'blabla.com' => 'blabla.com',
            ),
      '#default_value' => 'blabla.net',
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _ta_module_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['values']['mail']['edit-mail'] = $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'];
    }
}

```
> 2 votes

---
Tags: users
---


# Question
Title: Remove "submitted by" text on teaser only
I read on How do I remove the "submitted by" text on node display? where you can remove this in the content type settings for the node itself, but is there a way to only change the teaser so it does not display "submitted by" text?

I'm looking for a non-preprocess function or module way to do this; I can't use my theme to deal with it.

I was hoping to avoid using Computed Field module for something so trivial.

# Answer
That setting is checked and the information added in template\_preprocess\_node().

Which means that there is no other way than a preprocess function to change this. However, there is nothing stopping you from adding a preprocess function to a module, that works perfectly fine. You just need to make sure that your module runs after node.module by setting the weight in the system table to something higher than node (probably 0).

Code example by will:

In your .install file:

```
db_update('system')
  ->fields(array('weight' => 1))
  ->condition('type' => 'module')
  ->condition('name' => 'moduleName')
  ->execute();

```

And then in the .module file:

```
function moduleName_preprocess_node(&$variables) {
  // Do not display post information on teasers
  if ($variables['teaser']) {
    $variables['display_submitted'] = FALSE;
  }
}

```
> 4 votes

# Answer
If you're comfortable with regex you could use hook\_node\_view to add a '#post\_render' variable to the $node-\>content:

```
function myModule_node_view($node,$view_mode){
  if($view_mode=='teaser'){
    $node->content['#post_render'][]='myModule_post_render_teaser';
  }
}
function myModule_post_render_teaser($rendered){
  $regex='';//This selector would have to grab the rendered "meta submitted" div
  return preg_replace(etc. etc.);
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Why can't I disable or enable the block cache?
In the `admin/settings/performance` page, I (the administrator) cannot enable or disable the block cache. Why?

# Answer
> 5 votes
As reported in that page for that setting:

> Note that block caching is inactive when modules defining content access restrictions are enabled.

If there are modules implementing `hook_node_grants()`, the "Block cache" form field is disabled.

This is the code present in system\_performance\_settings(), which is the form builder for the "Performance" form:

```
$form['block_cache']['block_cache'] = array(
  '#type' => 'radios',
  '#title' => t('Block cache'),
  '#default_value' => variable_get('block_cache', CACHE_DISABLED),
  '#options' => array(
    CACHE_DISABLED => t('Disabled'),
    CACHE_NORMAL => t('Enabled (recommended)'),
  ),
  '#disabled' => count(module_implements('node_grants')),
  '#description' => t('Note that block caching is inactive when modules defining content access restrictions are enabled.'),
);

```

As alternative, there could be a module that is disabling the form field to avoid the option can be selected; I don't know of any module that does that, even if I cannot exclude there is a module that is effectively doing it.

# Answer
> 6 votes
I know you asked *"why?"* not *"can i get around that problem"*... but you can get around that problem without removing modules that use `hook_node_grants()`. Try out the Block Cache Alter module. It allows, among other things, the ability to use block caching even if modules implement `hook_node_grants()`.

---
Tags: 7
---


# Question
Title: Forums 'Add Container' function not doing anything
I have enabled the Forum module and ran into some rather annoying errors:

1. No 'Forum' link comes up in admin, I have to go directly to *admin/content/forum*
2. I click on 'Add Container' or 'Add Forum' and nothing happens
3. When I click on 'Create Content' I cannot see type forum (only when I view content types)
4. When I direct to node/add/forum I cannot create as the Forum dropdown box is empty (as I can't create Containers

I have run cron and update to no prevail. I read something somewhere it helps to manually update the database by incrementing the container row count or something?

# Answer
I flushed the cache and it worked.
I created a flush.php file and ran it.

```
<?php
  drupal_flush_all_caches();
  drupal_set_message('cache flushed.');
?>

```

More information is available here.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to integrate the Piwik web statistics tracking system in a Drupal site?
Right now, I put the Piwik code at the end of `html.tpl.php`.

How I can integrate it in a Drupal site, so that this JavaScript can be aggregated? Or better loaded and keep my template clean?

Can I put this code to an external JavaScript file (+ how?) and then just declare it at `theme.info`?

# Answer
Even better, use the drupal module that does all the hard work - Piwik Web Analytics.

Here is a quote about it (from the module's project page):

> ... Adds the Piwik web statistics tracking system to your website.
>
> The module allows you to add the following statistics features to your site:
>
> * Single/multi domain tracking
> * Selectively track/exclude certain users, roles and pages
> * Monitor what type of links are tracked (downloads, outgoing and mailto)
> * Monitor what files are downloaded from your pages
> * Cache the Piwik code on your local server for improved page loading times
> * Custom variables support with tokens (D7 only)
> * Custom code snippets
> * Site Search
> * Drupal messages tracking
> * Modal dialog tracking (Colorbox)
> * Access denied (403) and Page not found (404) tracking
> * User ID tracking across devices
> * DoNotTrack support
> 4 votes

---
Tags: javascript
---


# Question
Title: Is there a function to output the tag and vocabulary?
```
$terms = db_query('SELECT vid, name FROM {taxonomy_term_data} WHERE vid=:vid', array(":vid" => 2));

foreach ($terms as $term) {
    echo l($term->name, 'taxonomy/term/'.$term->vid);
}

```

I want to get all the term under the vocabulary. and the default tag. If I use the above code to get that, I must know the value of vid, and read the database twice. It's too bad. If someone changes the vocabulary, this will change vid, and my code will not work. Is there a better way to get all the terms in a vocabulary?

# Answer
> 4 votes
There is taxonomy\_get\_tree() which can return all terms in a hierarchical array, you will however still have to display it and hardcode the vid (or use variable\_get() to make it overridable).

Depending on how and where you are displaying this, one of the following alternatives could maybe work better for you:

* If you are displaying this information in a block, consider using http://drupal.org/project/taxonomy\_menu instead. It can create menus based on vocabularies, which you can then be displayed as a block. They will be properly cached and faster than querying them on every page.
* You can also use Views to build a list, tag cloud or similar thing for all terms of a vocabulary.

# Answer
> 0 votes
The function `taxonomy_get_tree()` returns you all terms from a specific vocabulary.

---
Tags: taxonomy-terms
---


# Question
Title: Display Months in dropdown for filtering
I want to create a view over a content type. Over this page I want a select list of Months to filter the content by month.

Is there any module or how can I achieve this by view?

# Answer
> 2 votes
Using the Date project, you can add a "Date: Date (node)" (D7, not sure how it is called in D6) filter, where you can choose the granularity. By setting it to month, it will display a list of months in the filter.

I looks like a "All month" option is however currently missing, so you can't display all months by default, it seems. See http://drupal.org/node/574820.

# Answer
> 1 votes
You could try the Archive module, although it isn't a view. Alternatively, you don't need a module. You could try a View using arguments or even just use the default archive that's built into views. Following the example I linked to will be close to what you need. For more information, see here.

---
Tags: views
---