title: jQuery Colorpicker Set color

text:
# Question
Title: jQuery Colorpicker Set color
I am using jQuery Colorpicker for some reasons i need to set change the values of the fields directly from javascript.

I found this function HERE in the plug in website

```
jQuery('input').ColorPickerSetColor(color);

```

But no luck. Have you experienced something like this. What is the way to do this? Is there any other modules i can use ?

# Answer
You are setting 'input' which references any input on the site. Use the #id of the input field so that the input field you are targeting is explicit. To find this use firebug, chrome developer tools etc.

Also use Drupal.behaviors to load events where possible. Standard jQuery events do work but you get them all in the one place and clearly namespaced https://stackoverflow.com/questions/3941426/drupal-behaviours.

The code with the specific #id and wrapped in behaviors starts to look like the following, with the field changed to your color field:

```
(function($) {
    Drupal.behaviors.myModule = {
        attach: function(context, settings) {
            $('#edit-field-meeting-date-und-0-value-datepicker-popup-0', context).change(function() {
                // update code here

                $('#edit-field-submission-cutoff-und-0-value-datepicker-popup-0', context).val(formattedMonth);
            });
        }
    }
})(jQuery);

```

Finally, always inspect the code in the browser because javascript caching/optimization may be on. Check that there are no javascript errors in the browser console.
> 1 votes

---
Tags: forms, javascript
---


# Question
Title: Displaying Taxonomy Term Field for Multiple Entries on a Taxonomy Term List View
I'm using a view to override my taxonomy term pages to display content fields. One of those fields is another taxonomy term (applicable divisons). Displaying the titles of terms applied to the content is no problem (multiple field settings).

The problem comes in here. I need to display icons that represent each of those terms that is an image field in the term itself (division icon). I added a relationship to the view (Content:Taxonomy Terms on node). I can then add the field, but it limits it to one of the terms/icons and it doesn't have a "multiple field settings" area.

I've searched for this quite a while and it's probably an obvious answer, but it's one I can't find or figure out.

Answer: This isn't pretty, but it's getting me the data I want. It needs to be cleaned up. Thanks for the help!

```
<?php
foreach($data->field_field_applicable_divisions as $mydata) {
    if (isset($mydata['raw']['tid'])) {
        $term = taxonomy_term_load($mydata['raw']['tid']);
        echo "<div class='term_icon'>";
        echo "<img src='" . image_style_url( 'icon', $term->field_division_icon['und'][0]['uri']) . "' title='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "' alt='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "'class='term-image' />";
        echo "</div> ";
    }
}
?>

```

Also, to get a legend in the header or footer:

```
<?php
foreach(taxonomy_get_tree(7) as $icon) {
    $term = taxonomy_term_load($icon->tid);
    echo "<div class='term_icon'>";
    echo "<img src='" . image_style_url( 'icon', $term->field_division_icon['und'][0]['uri']) . "' title='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "' alt='" . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'] . "'class='term-image' /> - " . $term->field_division_icon['und'][0]['field_file_image_alt_text']['und'][0]['value'];
    echo "</div> ";
}
?>

```

# Answer
> 0 votes
You are going to have to adjust this to your own use case, but the approach I would use is a little different.

First, delete the relationship.

Add (or configure) the term reference field (field\_divisions?) in your query. Set it to no label, and exclude from display. Rewrite the output to \[field\_tags-tid\] . This will give you a list of term id's.

Install and enable the Views PHP module.

EDIT:

The $row variable does not play well with multiple values, so we will switch to the $data variable.

In your view, add a Global:PHP field, and in the Output code box enter something like:

```
<?php
  // Select your field object.
  $obj = $data->_field_data;
  // Then get your field array
  $divisions = $obj->field_divisions[LANGUAGE_NONE]
  foreach($divisions as $division) {
    if ( is_numeric( $division['tid'] ) ) {
      $term = taxonomy_term_load($division['tid']);
      $icons= $icons. "<div class='term-icons'>";

      if (isset($term->division_icon['und'][0]['uri'] )) {
        $icons= $icons. "<div class='term_icon'><img src='" . image_style_url( 'icon_style', $term->division_icon['und'][0]['uri']) . "' class='term-image' /></div> ";
      }
      $icons = $icons . "</div>";
    }
  }
  print $icons;
?>

```

Make sure the PHP field follows the term reference field so the $row values are available to the PHP field. Then style your icons to display as you wish.

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


# Question
Title: what is the difference between render() and drupal_render()?
what is the difference between `render()` and `drupal_render()` anyway ? Is there a reason to use only drupal\_render()?

# Answer
> 32 votes
The docs for `render()` explain it pretty well:

> This function renders an element using drupal\_render(). The top level element is shown with show() before rendering, so it will always be rendered even if hide() had been previously used on it.

`render()` is basically just a wrapper for `drupal_render()`, except that it makes sure the element passed in is set to be shown when passed through to `drupal_render()`.

It also makes sure the element passed in is an array (which is all `drupal_render()` can accept). If it isn't, the element is return back as-is. So it provides a bit of a safety net if you like.

If for any reason you have a variable you need to render, and you don't know if it's a string or a render array, you can pass it straight through `render()` without having to test the variable type yourself.

For some real-world examples of that sort of situation there's a list of calls to `render()` you can look through.

---
Tags: theming
---


title: Altering checkboxes rendering in a form

text:
# Question
Title: Altering checkboxes rendering in a form
I've a drupal website with a custom theme based on Zen.

In a specific page of my website, I've a form rendered by the Finder module (which uses the Drupal Form API).

I want to modify the way Drupal render the checkboxes of this particular form.

Let's say Drupal render my checkboxes like this :

```
<input type="checkbox"> Choice 1

```

I want to modify the html into something like :

```
<input type="checkbox">
    Choice 1
    <div></div>

```

This could allow me to better adjust the layout using CSS.

Can someone point me the right direction to achieve this ?

**Solution :**

Since the finder outputs Checkboxes (and not many Checkbox), using #field\_suffix didn't solve my problem. Why ? Because applying the following code :

```
$form['finder_form']['type']['#field_suffix'] = "<div>field suffix</div>";

```

Results in this :

```
<div class="form-checkboxes>
    <div>
        <input>
    </div>
    <div>
        <input>
    </div>
    <div class="suffix"></div>
</div>

```

So I ended up doing :

```
foreach ($form['finder_form']['type']['#options'] as $key => $value) {
    $form['finder_form']['type']['#options'][$key] = $value." <div class='suffix'></div>";
}

```

If a better approach is found, I will edit this.

# Answer
The input element has no close tag, so this is not really a well-formed question.

That said, what you are probably looking for is hook\_form\_alter() which you would implement in your own custom module to alter this particular form element.

Have a look at the #field\_suffix propery for how you could append some arbitrary markup to your element.
> 3 votes

---
Tags: 7, forms, theming
---


# Question
Title: How can I remove the "Your vote was recorded." message in the polls?
I need to delete the message "Your vote was recorded." when a user votes in a poll.

I tried comment the line containing `drupal_set_message(t('Your vote was recorded.'))` in the Poll module, but if I do this, the Poll Enhancements module doesn't work well.

What other way has Drupal 7 for deleting specific messages?

# Answer
The messages set with drupal\_set\_message() are saved in `$_SESSION['messages'][$type]` as an array of strings (`$type` can be `"status"`, `"warning"`, or `"error"`). The message you see, is set in poll\_vote(), which is the form submission handler used for processing a vote, used from poll\_view\_voting(), the form builder for the vote form.

In order to remove the show string you should:

* Implement hook\_form\_FORM\_ID\_alter() to add a form submission handler that is executed after `poll_vote()`.
* Implement the form submission handler to remove the string added from `poll_vote()`.

Code similar to the following one should work.

```
function mymodule_form_poll_view_voting_alter(&$form, &$form_state) {
  $form['vote']['#submit'][] = 'mymodule_poll_view_submit';
}

function mymodule_poll_view_submit($form, &$form_state) {
  if (isset($_SESSION['messages']['status']) && is_array($_SESSION['messages']['status'])) {
    $messages = array_flip($_SESSION['messages']['status']);
    unset($messages[t('Your vote was recorded.')]);
    $_SESSION['messages']['status'] = $messages;
  }
}

```
> 5 votes

# Answer
Using the drupal api, drupal\_get\_messages() by default clears out messages of the type selected.

The process is then to read the messages drupal\_get\_messages('error', TRUE) drupal\_set\_message() to put all the messages back on that you don't want to filter. This code can be found in the "Disable Messages module" which is more flexible.

The two implementation steps are i) add a function for managing the messages and ii) do the filtering:

```
function osdash_theme_registry_alter(&$theme_registry) {
  $theme_registry['status_messages']['function'] = '_osdash_disable_status_messages';
}

function _osdash_disable_status_messages($display = NULL) {
  // Retrieve messages
  $messages = drupal_get_messages($display);
  if (!empty($messages['status'])) {
    foreach ($messages['status'] as $message_index => $message) {
      if ($message != 'Failed to find the list of invitees from the group.') {
        drupal_set_message($message, 'warning');
      }
    }
  }
}

```
> 2 votes

# Answer
I know the question was posted 4 months ago and the original poster must have found a way, but for future users who might stumble upon this, a good and proper solution is the Disable Messages module . That way you won't need to hack core (no no no!), make a new module or modify your theme.
> 1 votes

---
Tags: polls
---


# Question
Title: Permissions to see all users products, not just the orders on UberCart
I am trying to figure out what permission in ubercart to set that would allow a user to see just the products they put in. It show them orders but not a list of their own items. Any help?

# Answer
> 1 votes
The permission manage products must be turned off. The permission for to create a product, edit and delete own product must be turned on.

---
Tags: ubercart
---


# Question
Title: How do you use hook_query_alter to get inside a query's creation?
I'm getting no love from hook\_query\_alter. I have a simple query to which I want to add a tag, while also adding a `node_access` tag. Thus the whole query looks like this:

```
$the_nodes = db_select('node', 'n')
     ->condition('n.type', 'some_node_type')
     ->fields('n', array('nid', 'title'))
     ->addTag('node_access')
     ->addTag('my_custom_tag')
     ->execute()->fetchAll();

```

I then define a handler in one of my modules and litter it with debugging statements, hoping something will happen:

```
function mymodule_query_alter(QueryAlterableInterface $the_query) {
    dsm("inside mymodule_query_alter");
    dsm($the_query);
    if ($the_query->hasTag('my_custom_tag')) {
        dsm('Found it!');
        // do real work here
    }
}

```

I then clear the system cache. Once I've done this, the following things happen:

* My handler is running, and reports a number of invocations from various system calls.
* The objects being dumped by the dsm calls are all very much alike -- they contain only an `alterTags` array, which typically has entries for either `node_load_multiple` or `file_load_multiple`, but nothing else -- certainly nothing like a full Query object.
* None of the `alterTags` arrays have an entry for `my_custom_tag`.
* The inner "Found it!" message never fires.

Arggh. This is my first encounter with `hook_query_alter()`, and I'm probably just missing something basic about its use. Can anybody clue me in? (BTW, based on some browsing around, I've also tried defining handlers for `my_module_query_my_custom_tag_alter` and `my_module_query_node_access_alter`, but never see anything from them.)

# Answer
Just to close this item out: It appears that my definition of hook\_query\_alter was, in fact, working correctly. My problem was in assuming that I would be able to do things like `dsm($the_query)` and see the components of the query object in preparation for doing stuff with them. This doesn't seem to be the case -- `dsm()` wasn't returning anything of real use other than `alterTags`, but the `orderby()` (and other similar actions) did in fact alter the query. So, I'd argue that it's a bit confusing, but works-as-designed, I guess...
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to deal with exploding node_access queries?
I'm working on a pretty complex workflow site, which has a number of interlocking levels of components (content types, really). To summarize and simplify a bit:

* Users can create Companies.
* Companies can have Projects and Members (other users affiliated with the companies).
* Projects can have tasks.

Each of these things have access controls::

* Companies can be public, private, or member-only
* Projects can be public, private, or member-only (but limited by the company specification)
* Tasks are member-only

This gets (more) complicated in a couple of ways:

* Users can have different roles in Companies and Projects (admin, user, visitor, and such)
* The access rights of the higher-level thing can determine and even override the rights of the lower-level things: If a Project is marked member-only, that Project's tasks can only be seen by other members of the Company that owns the Project. In the same way, changes to Company access rights determine the actual access rights of Projects and Tasks. For instance, if a Company's status is changed from public to private, access to all its Projects and Tasks are blocked to everyone but the company's owner, even if they're marked Public.

I've gotten this working by setting up a collection of node\_access functions for the various components. These install appropriate access rights into the node\_access table based on the components' access settings. A parallel set of node\_grants functions then build up comparable sets of grants for each of the users, based on their roles in the organization.

The good news is that this actually works. The bad news is that the queries being run against the database are getting huge, as the node\_access mechanism produces a very large number of query clauses, each looking to see how the user's roles line up against the various kinds of access rights. For instance, there's a whole string of clauses testing, for each task, whether the user is a member of the project that contains that task. There's then another string of clauses testing whether the user is an *admin* of the project, and another string testing whether the user is a *visitor* to the project. And so on, leading to a future where these queries become larger and larger and worse and worse as the site becomes more successful and people put more projects and tasks into it. Blurgh.

So (finally), my question: Is this just the inevitable cost of living with Drupal and its node\_access architecture? Is there another way I can control access to all these pieces of stuff without having the database calls explode on me the way they seem to be? I'm not looking for a free lunch, but I'm getting more and more worried about the complexity of these access routines and the amount of money I'm likely to have to pour into database servers to keep things running. Any advice out there?

# Answer
> 0 votes
I don't know how much of an answer this is, but: the approach I was taking to node\_access that led to the original post was almost certainly wrong. In particular, I was setting up separate `gid`s for each item I was writing into `node_access`, rather than keeping `gid`s associated with user IDs as they are almost surely meant to be. After a bit of work, I was able to restructure this aspect of the site around this more correct approach, and was able to cut down the number of clauses added by `node_access` by about a factor of 10. Life is a learning experience, I guess; I could probably elaborate a bit if anybody cares...

---
Tags: 7, users
---


title: Validating extensions in file uploads

text:
# Question
Title: Validating extensions in file uploads
I am trying to create a file validator for .csv uploads. This is my code that works at allowing csv uploads (which are disallowed by default):

```
$validators['file_validate_extensions'] = array('csv');
$file = file_save_upload('csv', $validators);

```

However, when I try to upload another file (in this case fizzbuzz.py) I get this error:

```
For security reasons, your upload has been renamed to fizzbuzz.py.txt.

```

How can I change this to being and out right error when a non csv file is uploaded?

EDIT: Did some more testing. This only occurs for my `.py` file. Files with a `.png` extension get rejected and are not uploaded.

EDITx2: Okay, so it also rejects `.bat`, `.gnumeric`, and `.txt` file extensions. It looks like Drupal does not validate two letter file extensions in the same way it validates three(+) letter file extensions.

# Answer
If you take a look at the file\_save\_upload() call, you'll see what's happening with the py files. It seems to be a It will occur with php|pl|py|cgi|asp|js files.

FROM: file\_save\_upload() http://api.drupal.org/api/drupal/includes!file.inc/function/file\_save\_upload/7

```
// Rename potentially executable files, to help prevent exploits (i.e. will
// rename filename.php.foo and filename.php to filename.php.foo.txt and
// filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
// evaluates to TRUE.
if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js) (\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
$file->filemime = 'text/plain';
$file->uri .= '.txt';
$file->filename .= '.txt';
// The .txt extension may not be in the allowed list of extensions. We have
// to add it here or else the file upload will fail.
if (!empty($extensions)) {
  $validators['file_validate_extensions'][0] .= ' txt';
  drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
}

```

}

If you wish to allow these uploads (without converting their extensions), you would set all\_insecure\_uploads to 1 (TRUE), but I doubt you do :)

KMT
> 2 votes

---
Tags: files
---


# Question
Title: jQuery only works if I hard code it into the html.tpl.php
Running into this issue where my custom jQuery code only works in my drupal theme if I end up adding `<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>` in the `<head>` tag of the `html.tpl.php` file.

I tried all the other ways via template, info and still none of them work other then doing this.

Suggestions?

Thanks,

.-C

# Answer
Figured it out. Requires one to enclose all jQuery scripts with:

(function($){

\\ Enter script here ///

})(jQuery)
> 0 votes

# Answer
Drupal core ships with jQuery. You can check the version in your `<drupal_install_directory>/misc/jquery.js` file. If you want to use the later version of the library, you need to install the jQuery Update module.

> Upgrades the version of jQuery in Drupal core to a newer version of jQuery. Updates...
>
> * Drupal 5 to jQuery 1.2.6
> * Drupal 6 to jQuery 1.3.2
> * Drupal 7 to jQuery 1.5.2/1.7.1/1.8.2, and jQuery UI 1.8.11
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: force a different page template based on node id?
Is it possible provide a page with an alternate template suggestion for a certain page?

e.g. i have a landing page. I have the node id. I would like to switch the page template if the node id is a certain number.

If it is how would you go about that in the theme preprocess function?

# Answer
> 3 votes
This ought to do it:

```
function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $vars['theme_hook_suggestions'][] = 'page__node__' . $node->nid;
  }
}

```

And then call your template file `page--node--123.tpl.php`

# Answer
> 1 votes
It is enough you name the page template file as page--node--\[node ID\].tpl.php, if you are using Drupal 7. (Replace \[node ID\] with the node ID.)

As shown in the example reported for theme\_get\_suggestions(), that is one of the suggested templates.

> Build a list of suggested theme hooks or body classes in order of specificity. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, for `$base='page'`, http://www.example.com/node/1/edit would result in the following suggestions and body classes:
>
> * `page__node` `page-node`
> * `page__node__%` `page-node-%`
> * `page__node__1` `page-node-1`
> * `page__node__edit` `page-node-edit`

Similar comment is present in template\_preprocess\_page() for Drupal 6. The difference is that Drupal 6 uses one underscore when Drupal 7 uses two underscores. As consequence, in Drupal 6 the template filename must have a hyphen instead of two.

Keep in mind that the underscore for the suggested template name is replaced from a hyphen, when building the template filename.

---
Tags: theming
---


title: blocks are not translated in Panels

text:
# Question
Title: blocks are not translated in Panels
I have a simple `panel page` containing 4 blocks that are all translated (and set to translatable). However they are always displayed in English (default language).

The taxonomy term is passed as a context and is used to display the page title. And it is also translated (`%taxonomy_term:i18n-name`)

The rest of the page is translated correctly. I unfortunately don't have much more info to share as this is basically it...

What am I missing here? Thanks for your help!

I am using Drupal 7 and Panels 3

# Answer
> 1 votes
This is a known Ctools issue \- there is a patch at comment #49.

---
Tags: blocks, panels, i18n-l10n
---


title: Purpose of Media module

text:
# Question
Title: Purpose of Media module
If I am using the IMCE file uploader combined with CKeditor, is there any point in installing the media module?

Or does media replace the imce when wysiwyg module is used?

# Answer
> 5 votes
The Media Module (2.x) uses the File Entity module. Files become 1st class citizens in your Drupal installation just like a Node or Entity or a variable. A FileEntity can be queried using Views for instance.

IMCE (to my knowledge) is simply a file browser (bridge) for your server compatible with TinyMCE and I suppose CKeditor now. Files are just files on the system and drupal isn't 100% aware of them and their meta-data.

If you only need to browse files then IMCE has its usages. If you want something more meaningful and integrated with Drupal as a whole look at Media, and maybe like Media Browser Plus.

---
Tags: media, files
---


# Question
Title: How can I share session variables across sites?
On my main Drupal site, users need to be able to select a display preference (e.g. 'high visibility'). This will be available to registered and anonymous users but only for their session, so I plan to store their preference in a session variable, for example with `$_SESSION['display'] = $my_preference;`.

Another Drupal site runs on a subdomain of the main site, and needs the same functionality. And if the user visits both sites, it would be great to remember their preference.

I think that if I uncomment this line in both site's settings.php, session variables can be accessed across sites on the same domain?

```
$cookie_domain = 'maindomain.com';

```

So then I could set $\_SESSION\['display'\] on one site, and retrieve $\_SESSION\['display'\] on the other?

Also, one site runs on Drupal 6 and the other on Drupal 7. Will this be a problem? Is caching for anonymous users going to cause problems?

Am I on the right lines, or is this plan flawed?

# Answer
There are two options to do this

* Using session

Use a single session table for both the site using settings.php set up

* Using Cookie

Use same cookie domain for both site and set cookie available in all pages.
> 0 votes

---
Tags: 7, sessions
---


# Question
Title: How to subscribe a user to a group when the OG context is in the commerce order?
I'm trying to allow people to subscribe to an organic group when buying a specific product. The thing is that I need to set the OG context in the order, not the product or anywhere else.

**Use case:** The anonymous user completes an order. The site admin reviews it and then he may or may not grant the anon user the access to a specific role from a list.

**How I´m trying to accomplish that:**

* I've installed Drupal Commerce, Rules and Organic Groups.
* I create an OG audience field inside commerce orders (\*og\_group\_ref\_commerce\*).
* I set a rule with some conditions (if the order is set to "completed", and if the user is an anon...) and some actions (a loop to create the new user and assign him a role).

And I'm adding a special action (which doesn´t work):

*Subscribe user to group*

> User Data selector: account-fetched:0 Group Data Selector:
> commerce-order:og-group-ref-commerce:0

I´ve tried another way, without any success:

> User Data selector: account-created (in and outside the loop that created the user) Group Data Selector: site:og-context--node

Note: As the order doesn´t initially have the group audience context, I have to edit it in order to assign it a group. After saving it (it is still in "pending" status), I edit it again to change it to "completed".

Any ideas?

# Answer
> 1 votes
Try out following these steps

1) Using the Entity Reference module, I've created an entity reference on my product type. It's target type is "Node", and the Target Bundle is the content type of my Organic Group. In my case, that's called "Classroom".

2) I create a piece of content of type "Classroom".

3) I create a new product and a drop-down will show a list of all my Classrooms. I select one of them.

4) Now comes the time to make the rule to automatically add the user to the correct group.

**Conditions**
Event: Completing the checkout process

**Conditions**
Entity has field: commerce-order:commerce-line-items:0 .. Name of the field to check for: commerce\_product

Entity has field: commerce-order:commerce-line-items:0:commerce-product .. Name of the field to check for: field\_og\_reference (this is the name of my entity reference that I put on the product in Step #1).

**Actions**
Fetch entity by property. .. Value: User
.. Property: Email
.. Value: commerce-order:mail
.. Limit result count: 1
.. Variable Label: Fetched Account
.. Variable Name: account\_fetched

**Subscribe User to Group**
.. User: account-fetched:0
.. Group: commerce-order:commerce-line-items:0:commerce-product:field-og-reference:group

***Solution 2*** See tutorial about this, have a look:

---
Tags: 7, commerce, rules, organic-groups
---


# Question
Title: How can I add a class to link around image field
I have a field `field_sidebar_gallery` which outputs multiple images. These images are rendered using image style `gallery_thumb` and the display format on them is using the `lightbox2` module which wraps the rendered image in an `<a>` tag.

What I need to do is add a class to the `<a>` tag which wraps around the image. I could easily do this in the template file for `field--field-sidebar_gallery.tpl.php` and just look at the uri for the image and build the link and image html myself using the relevant functions (`theme()`, `l()` etc). However, taking this approach I then lose all of the configuration abilities of lightbox2 (and I suppose any other modules which may end up manipulating the links in the future)

The output currently is as follows

```
<a title="" rel="lightbox[field_sidebar_gallery][]" href="http://localhost/sites/default/files/styles/large/public/Koala.jpg" class="lightbox-processed">
    <img width="95" height="95" alt="" src="http://localhost/sites/default/files/styles/gallery_thumb/public/Koala.jpg">
</a>

```

I've looked at

With little to no success. I suspect the display formatter kicks in and that's what I should be looking at but I don't really know where to start.

All I need to do is for this particular field (`field_sidebar_gallery`), is to add a class to the `<a>` so that the final output is as follows (note the `class="thumbnail[...]` compared to the above)

```
<a title="" rel="lightbox[field_sidebar_gallery][]" href="http://localhost/sites/default/files/styles/large/public/Koala.jpg" class="thumbnail lightbox-processed">
    <img width="95" height="95" alt="" src="http://localhost/sites/default/files/styles/gallery_thumb/public/Koala.jpg">
</a>

```

If anyone can point me in the right direction, that'd be much appreciated.

# Answer
From the way lightbox does it (line 145), i would think there is not much you can do to alter the link, since it is "hardwired" there.
What you could do (and is surprisingly easy :) is to implement your own handler that would extend the lightbox one and allow you to specify the css class (or submit a patch that would do it in their code).

You might as well specify the class on the parent div (in views "Styles settings" for the field, "Customize field HTML" and "Create a CSS class". And then just sligthly change your selector.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Using a Drop Down and available Dates in a Content Type
I am running an event that spans a week. During the event different vendors are able to have shows that run a few hours each. What I would like to do is create a form for the vendors to fill out with their name, a description of the event and when it is happening. I was originally using the date field, but it allows them to choose any date which has become a problem.

What I would like to do is have the actual days show up as a drop down with "Thursday, Friday, Saturday and the values of "3/1/2013", another one for Hour and a last one for minutes.

I figured out how to handle the views to display the information I want. But what I can't figure out is a way to load this information onto a calendar. I assume I have to combine all that information into a single database date field, but I can't for the life of me figure out how.

Any suggestions would be very much appreciated. I am using Drupal 7 and, while getting better am still relatively new at Drupal.

Thank you.

# Answer
You can use Date module. Read more here: http://drupal.org/node/262062

If you are already using that, then you probably need to change, `widget type` of the field to `Popup-Calender` or `Select List`
> 0 votes

---
Tags: nodes, datetime
---


# Question
Title: menu-mini panels: removing anchor tag from menu item
I've used the menu-minipanel module to set-up some mega menus. The main menu items are set (using the module UI) to show a minipanel with my various menu blocks/nodes.

However I don't want the 1st level menu items themselves to point anywhere, and since I've used the Menu Minipanel option to allow for a click to reveal the minipanel I was forced to use the Special Menu Items module to generate a "#" as an href.

However the problem I'm having now is that when the user clicks on the menu items to open the megamenu, the '#' href takes them to the top of the page.

Can anyone suggest any options here?

Here's the site I'm working on presently as reference.

# Answer
You can use some jquery here, by capturing click event of this menu item, and returning false.

```
$("<selector>").click(function(){
   return false;
});

```

Or try this

```
$("<selector>").click(function(e){
   e.preventDefault();
});

```
> 1 votes

---
Tags: routes, navigation
---


# Question
Title: Getting Views Rows Data in Custom Module
I dont know if im over thinking this but im not making much progress with my function. I am trying to get the values from views rows in my modules for example if I was to use `$row->field`\_name inside of a view.tpl file then it would show the output of that row, except I am trying to do it in a module. Ultimately I am trying to render the image style of the 1st image that loads from the view. This is what I have so far.

```
function custom_module_views_pre_render(&$vars){
    if($vars->name == 'front_page'){
        $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
    }
}

```

**Update 1:** I've attached a image of what I am trying to do seeing how when I use `preview(); execute(); or render();` it makes the function stop working, actually it makes the whole site stop working. If I cant get to the field view result count which counts the the number a current node is then I can say `if($views->view_result_counter == 1)` then render just that node. The function would look something like this.

```
function custom_module_views_pre_render(&$vars){
    $views = views_get_current_view('front_page', 'page');
    if($views->name == 'front_page'){
         if($views->views_result_counter == 1){
            $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
         }
    }
}

```

Here is a image of what I am trying to do, Now I currently have the 1st image rendering as I want it to but it keeps rendering the image of each page instead of it rendering one time only.

Now as for my view is there any reason why execute or render wouldnt work? this is what my view looks like.

any suggestions?

# Answer
> 1 votes
I think you are mixing the hook\_views\_pre\_render with a themeing function. In the hook, there is no `$vars`, you get access directly to the `$view` \- the entire view, not only a row. So you will be able to do something along the lines of:

```
function YOURMOD_views_pre_render($view) {
  if ($view->name == 'YOURVIEW'
    && $view->current_display == 'YOUR_DISPLAY'
    && $view->query->pager->current_page == 0) {
    $row = $view->result[0];
    $row->field_YOUR_image[0]['rendered']['file']['#style_name'] = 'DIFFERENT_style';
  }
}

```

This way you just change the image style of the image and you can let drupal do the rest for you :).

# Answer
> 1 votes
as this site is not about php programming I will not go very deep into this. but what you are probably looking for is http://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/7

to render the view use `$view->render();`

further reference: http://drupal.org/node/342132

# Answer
> 1 votes
You might be over thinking this. If you have working code, but the problem is that the code keeps on working, then the issue is to stop it from working again after it has done its job once.

The way to make a function aware if its previous iterations is to use a static variable. Try wrapping your working code with a static variable and test it like:

```
  // Only process one image.
  static $first_image_done = FALSE;
  if ( !$first_image_done ) {
    ...working code ...
    $first_image_done = TRUE;
  }

```

That way the function knows it has already processed the first image, and will skip the process on further iterations.

EDIT after time in chat:

The satic variable approach is not working because infinite scroll still works as a pager, and separate queries are being made for each page of output.

The current page position is controlled through the $pager (object) property of the $views object. The test for the first page can be accomplished as follows:

```
  $pager = $vars->pager;
  // Check for 'first page' condition
  if ( !isset($pager->current_page) || $pager->current_page == 0) {
     $vars->result[0]->field_field_image[0]['rendered']['#image_style'] = 'front-page-scroll';
  }

```

This should limit the image resizing to the first page of the view.

# Answer
> 0 votes
I'm not exactly entirely following why you're working in your module.

Have you tried using 2 displays in your View? 1 regular display with a limit of 1 row, and an attachment display, displaying all results, but with an offset of 1, so that it skips the 1st row. You can then change the Image preset on the regular View, but keep using thumbnail preset in the attachment View.

Or - I can't try it out right now - isn't there a counter somewhere in the $vars variable that contains what page you're on? If so, you can only intercept & change the row when you're on the 1st page

---
Tags: 7, views, media
---


# Question
Title: How to display the values after submit in drupal 7
I have a three form fields like Name,phone,email now after inserting the values in my db i want to display the values into same page or another page like Name:XXXXXXXXXXX Phone:5545445454 email:yyy@some.com

how can do this in drupal7

# Answer
You can use the function hook\_form\_FORM\_ID\_alter to do that.

Just replace the `FORM_ID` with the `ID` of your form.
Lets say the id of the form is `my_custom_form`, then the values could be printed as,

```
function MODULE_form_my_custom_form_alter(&$form, &$form_state, $form_id){
  //add a new function(submit handler) on submit button.
  $form['#submit'][] = 'new_submit_function';
}

function new_submit_function(&$form, &form_state) {
  // the $form_state['values'] array contains all the
  // values from the fields of the current form stored in it
  drupal_set_message("name : " . $form_state['values']['name']);
  drupal_set_message("phone : " . $form_state['values']['phone']);
  //and so on.
  //the message will be displayed on the page after form submit
}

```

If you are not sure how to find the id of the form, then use hook\_form\_alter to do that, e.g.

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
}

```

this would print the form id of every form you are on, so that you can use the id of the form you wish to change and perform a `hook_form_FORM_ID_alter` to change anything you wish :-)
> 2 votes

# Answer
If it is a custom form then in the submit function where you are inserting the records to the database, you can print the values on that page also. All the values of the form are in the `$form_state` array.

You can display the values in `drupal_set_message()` function or using the `theme()` function.

OR if you want to display the values on another page after submit then you should define the action for your form like `$form['#actions'] = url('node/xxx')`.
> 1 votes

---
Tags: 7
---


# Question
Title: Date Calender Starting Date of Field B should be equals to or advanced from the Ending Date of Field A
I have created a form using webfrom module. The form contains Arrival Date and Leaving Date. I want Leaving date should either be same as Arrival date or higher than that.

# Answer
> 0 votes
Try out Webform Validation module

> This module adds an extra tab to each webform node, allowing you to specify validation rules for your webform components.

OR in other case, write custom code, Use `hook_form_alter()` to apply custom validation

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    print $form_id;

    if($form_id=='webform_client_form_1') //Change webform id according to you webformid
    {
        $form['#validate'][]='mymodule_form_validate';
        return $form;
    }
}

function mymodule_form_validate($form,&$form_state)
{
    $phoneval=$form_state['values']['submitted']['phone'];//where "phone" is field name of webform phone field
if($phoneval=='')
{
form_set_error('phone','Please fill the form field');
}
/** THEN USE REGULAR EXPreSSION TO VALIDATE IT
In above example i have check if phonefield is empty or not
**/

}

```

---
Tags: javascript, datetime
---


# Question
Title: How To Create a Remote Views Search Form - D7
I have overridden the default Drupal /search page with a panel view that is listing users. In this view, users can be filtered by gender, age, location, etc - and it's working quite well! I have paired Contextual Filters and exposed Filter Criteria enabled to allow GET variables to be passed to the view while still allowing for a Filter Criteria fallback. Achieving this took a few experimental patches.

Now I need to place a search form on the home page that has a few of these filter options. This form needs to direct users to the /search page and take with it whatever the user enters. I've tried using the Exposed Filters Block but doing so removes the filters from the /search page entirely and negates the view header and footer which are unfortunately essential to the view.

Creating a basic HTML GET action form that sends users to the /search page works well, but that's a nasty long URL and I would prefer to keep this within Drupal. It seems that changing this form to use POST instead of GET does not work.

Is there some way to create a stripped-down form that leads into this search view? Using the Forms API would be nice but I'm open to any other solutions presented.

# Answer
1. I would suggest writing your own form in a block which you can place on the home page. I don't see anything wrong with writing the form in HTML - though if you generate your form the Drupal way using the Form API then you'll ensure you get consistent themeing across your site, you'll be protected against XSS attacks and so on. How to use the Form API is beyond the scope of a single question ;
2. There is a module that allows you to use POST queries with views exposed filters : http://drupal.org/project/views\_expost \- hopefully this should deal with your long URL problem.
> 1 votes

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


title: Taxonomy / Category

text:
# Question
Title: Taxonomy / Category
I have created Taxonomy with the reference http://www.anilsagar.com/content/drupal-7-tutorial-part-13-drupal-7-taxonomy-vocabulary-terms-tags-categories-concepts .

How to call this in the template file.. Please explain about taxonomy, that is what type of situations we can you taxomomy.. Please help me.

# Answer
> 1 votes
This is an example of taxonomy

When we click on the link it will lead us to all questions under the tag/term.

In Bartik there is taxonomy visible in teaser and full modes. Enable the theme and check your content.

Why youre looking for templates ?

---
Tags: taxonomy-terms
---


# Question
Title: Is it possible to create multiple layers in openlayers using one view with contextual filter?
I have 10~20 content types and need one layer for each content type in openlayers. Is it possible to create one view with one openlayers data overlay, and use contextual filters to provide the 10~20 layers in need?

To put the question in another way, with the above settings I can create a view with one page or one content pane, and by using a contextual filter, I can provide a list of content page for each content type. But it seems to me that in order to provide layers, I must create one data overlay for each content type. The only way I have found to pass contextual filters to data overlays seems to do with filtering at another level, rather than to provide more layers.

# Answer
I'm having difficulty understanding your question completely, but I've worked with OpenLayers and Views 3 so I'll try help you out as best I can.

I see what you mean with regards to using a contextual filter on the View which spits out the OpenLayers Data Overlay co-ordinants, as there is no conventional way of passing arguments to the display.

One thing which you could possible try is using the Views API to alter the query that is generated by your OpenLayers Data Overlay view. That way you could just add a WHERE clause to that specific query, filtering by a content type specified in your own code.

I won't go into the specific syntaxes as I don't have time, but look into firstly how to implement the Views API in a custom module. Once the API is being loaded successfully, look into using the following hook to add a custom WHERE clause:

```
function hook_views_query_alter(&$view, &$query){}

```

In the hook you'll need to check the view name and display ID to ensure you're targetting the correct view before adding your custom WHERE clause.

I hope this helps, and good luck!

**EDIT: Including the code snippet for the method I mentioned in the comments below**

```
/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(&$view, &$query) {

    // this is the name of our View and Display
    if ($view->name == 'my_view' && $view->current_display == 'my_display') {

        //add the where clause to filter the results based on node content type value
        $query->where['1']['conditions'][] = array(
                    'field' => 'node.type',
                    'value' => 'your_content_type_here',
                    'operator' => '=',
                  );
    }
}

```
> 0 votes

---
Tags: views, javascript
---


# Question
Title: Change autocomplete path with hook_form_alter()
I'm trying to change the autocomplete path of a node reference field (References module) with a custom module using `hook_form_alter()`.
I have no problem changing any property of the field except the \["#autocomplete\_path'\]. when I set another value for this, the field loses its autocomplete feature. (The hidden autocomplete field isn't there anymore as well) I find this totally weird, and haven't found anything about this in issue queues or anything like that.

Just FYI, I've setup a new MENU\_CALLBACK path with `hook_menu()` and a callback function, so I'll be able to return JSON suggestions depending on some custom parameters and the value of another field.

# Answer
> 4 votes
On a stock installation of Drupal 7 and references 7.x-2.0-beta3 I was able to use the following form alter to successfully change the autocomplete path for a node reference field on the article content type:

```
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_node_ref'][LANGUAGE_NONE][0]['nid']['#autocomplete_path'] = 'another/url';
  }
}

```

Another option is to ignore the form and use `hook_menu_alter` to change the callback for `node_reference/autocomplete/%/%/%`. Your callback should accept `$entity_type, $bundle, $field_name` which you can use to filter out which requests you want to respond to.

# Answer
> 0 votes
You should ensure your custom callback function is fetching correct json response. we can do so by calling the page callback path from the browser itself.

If its correct then check, The last param is always **string** in the page callback function which you need not to mention in form\_alter or in hook\_menu path but drupal will add the last param automatically while calling the function. I guess you missed the last param in your case.

Menu callback function should be like :

```
  $items['autocomplete/node/%'] = array(
      'title' => 'Custom autocomplete node reference',
      'page callback' => 'pms_custom_node_autocomplete',
      'page arguments' => array(**2**),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );

```

Page callback function should be like :

```
function pms_custom_node_autocomplete($node_type, $string = "") {
  // Get $string here to use in LIKE statement or whatever.
}

```

# Answer
> 0 votes
In my own case (D7.20), I had to set my `hook_form_alter()` like that:

```
function module_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == "event_node_form"){
        $form['field_event_location']['und'][0]['value']['#autocomplete_path'] = 'module/autocomplete';
        return $form;
    }
}

```

---
Tags: nodes, ajax
---


title: Load all Order with Attributes

text:
# Question
Title: Load all Order with Attributes
How can I load all order by using sql queries or by using predefined methods. I have attributes like One Month and Three Month. I want to get orders and the selected attribute with each order.

# Answer
> 0 votes
Try uc\_order\_status\_list

**Parameters**:

**$scope** \- Defaults to all, but you may specify the scope for the order statuses you want listed based on their corresponding order state. Possible values are - all, general, specific, or any order state id.

**$sql** \- Pass this parameter as TRUE to alter the return value for a SQL query.

**$action** \- By default, this is empty. Since order statuses are cached, you can pass in 'rebuild' to reload the contents from the database if you are making changes to statuses on a page load.

**Return value:** The return value will be either an array of status arrays (containing the keys id, title, state, and weight) or a string containing an array of status ids for use in a SQL query.

---
Tags: 7, ubercart
---


# Question
Title: Why would I get a 404 on "Authoring Information" autocomplete?
Below is a screenshot of a 404 I'm receiving on the standard author autocomplete, and I can't figure out, for the life of me, why this would be happening.

# Answer
> 1 votes
Most likely because your autocomplete isn't actually using the standard path for the user autocomplete.

From the image, your autocomplete is pointing to `/login/autocomplete`, a path that doesn't exist in a standard Drupal installation (or indeed one with about 200 contrib modules enabled, I just grepped a couple of large projects).

The correct path for the user autocomplete is `/user/autocomplete`.

Presumably there's some custom/contrib code changing the autocomplete to a different path, but failing to actually implement that path.

The best thing to do would be to search your codebase for the string `login/autocomplete` and go from there.

**UPDATE**

The change might be being made by the User Tweaks module:

```
function user_tweaks_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('view login autocomplete')) {
    switch ($form_id) {
      case 'user_login_block':
      case 'user_login':
      case 'user_pass':
        $form['name']['#autocomplete_path'] = 'user/login/autocomplete';
        break;
    }
  }
}

```

---
Tags: ajax
---


title: Input form to create content type(s)

text:
# Question
Title: Input form to create content type(s)
**Use Case**

We will have users submitting forms that will then be mapped to one of three content types based on the information they've entered. We don't want to burden the user with trying determine what content type to use on their own. They should just enter the data and then we'll make the call based on that.

**Best Approach**

The way I see us doing this is creating a webform that we then hook into with a custom module that programatically creates the new nodes of the appropriate content type.

I wanted to check with the brain trust here that this makes sense for our use case and there isn't a module to use that makes more sense.

Thanks.

# Answer
That sounds like a fine solution. The one thing I would suggest is to NOT use the webform module. I think you should just create the custom form with the Form API.

You'll spend more time overriding the unneeded behavior and features of webform than you would creating the form from scratch with FAPI.
> 1 votes

---
Tags: forms, nodes, webforms
---


title: Colorbox module has no effect

text:
# Question
Title: Colorbox module has no effect
I'd like to use the colorbox module to show the images in my nodes which are comming from flickr.

I'm using the flickr input filter which works fine. Now I'd like to get a colorbox to show one image after the other when the user clicks on one of the images of a set.

I installed the colorbox module and the jquery plugin. If I look at the HTML source file everything looks ok, but clicking on the images leads to flickr instead of opening a colorbox. According to the docs of the flickr module, colorbox support should be built in.

Any ideas what's missing?

You can see the non working page at my blog.

# Answer
After all it turned out that the colorbox integration is available in the dev version only.

For the record: The dev Version gives you the possibility to set the class and rel. Just us the proposed values *colorbox* and *gallery-all* and colorbox gives you a nice view of all your flickr images on the node.
> 1 votes

# Answer
I am not familiar with the flickr integration, but in the included colorbox.js file, it appears that colorbox is looking for images with the `.colorbox` class.

Have you tried adding the `.colorbox` class to the `img` elements in that view? It's possible that the class may have beren removed by a drupal filter.

The relevant Javascript:

```
 $('a, area, input', context)
      .filter('.colorbox') // target class
      .once('init-colorbox')
      .colorbox(settings.colorbox);
  }

```
> 1 votes

---
Tags: input-formats, javascript, files
---


title: post-save case in node api?

text:
# Question
Title: post-save case in node api?
Is there such thing as a post-save type of case in the node\_api function or any other type of function? This question is in reference to a question I posted What operation should I use to write node's information in an email when the node is saved?

I want to be able to have something happen after pressing the save button, but AFTER the saving into the database has been completed. I have tried 'update' and 'insert' and they don't seem to work.

EDIT: heres my code

```
case 'presave':
    {
        if(($node->type == 'team_practice_info') | ($node->type == 'schedule'))
        {

            if(!empty($node->field_alert[0]['value']))
            {
                if($node->field_alert[0]['value'] == 'on')
                {
                    //email out to everyone an email about the content change/update
                    $query = db_query("SELECT *
                                       FROM {content_type_athletics_alert}
                                       JOIN {content_field_team}
                                       ON content_type_athletics_alert.nid = content_field_team.nid
                                       WHERE content_field_team.field_team_nid =
                                            (SELECT field_team_nid
                                             FROM {node}
                                             JOIN {content_field_team}
                                             ON node.nid = content_field_team.nid
                                             WHERE node.nid = %d)", $node->nid);
                    $rows = array();
                    //db_fetch returns an array of the next row in the query
                    while ($row = db_fetch_array($query))
                    {
                        //pull out the email from the array, then send an email to each subscriber
                        $email = $row['field_email_address_value'];
                        $first_name = $row['field_first_name_value'];
                        $last_name = $row['field_last_name_value'];
                        $t_id = $row['field_team_nid'];
                        $t=node_load($t_id);
                        $sport = (current($t->taxonomy));
                        $team = $t->title.' '.$sport->name;

                        alert_message_mail_send($email, $first_name, $last_name, $team, $node);
                    }
                    //reset the alert checkbox to off
                    $node->field_alert[0]['value'] = 'off';
                }
            }
        }
    }

   break;

```

# Answer
If you are having trouble with hook\_nodeapi (though I have never had problems with it), you could try using Rules.

There is a stock event **After saving new content** that you can try. There is also a stock DO action, **Send a mail to a user**. You then get the normalish token-based email form that you can configure.

We have used this on few projects with good luck.
> 1 votes

# Answer
Use the register\_shutdown\_function. Here's the code for drupal 7, modify it for drupal 6 as needed:

```
<?php

function your_module_node_update($node){
    if($node->type == 'your_node'){
        register_shutdown_function('_your_module_send_report_email',$node);
    }
}
?>

```
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: logged in users only for /user in user menu
In my user menu I have a link for /user which produces a my account link which works as expected. In the menu admin (logged in users only) appears next to it.

Now, when I translate the item to produce a link to /user I have found that 'logged in users only' does not appear next to it and that it is shown whether the user is logged in or not.

Is this a known bug? Anyone know how i might solve it?

Thanks,

# Answer
I suppose since /user is open to both authenticated and non authenticated users the other /user is somehow specially defined.

For others looking for a quick fix, I solved this with menu item visibility module.
> 0 votes

---
Tags: users, i18n-l10n
---


# Question
Title: What is the equivalent of "Referential Integrity for CCK" in drupal 7?
Is there a Drupal 7 equivalent for the Referential Integrity for CCK module?

# Answer
> 1 votes
There is a sandbox project for a D7 port that performs cleanup on cron.

Otherwise drupal supports databases that do not enforce referential integrity, so it has not (to my knowledge) been a core issue.

---
Tags: 7
---


# Question
Title: D7 - Multilingual in the admin, only one language for the users
We have a drupal 7 with the following need :

* When the user visit the website, we let drupal chose the best language for the user
* He can then choose to chose another language.
* We have a finite number of language (5 so far)
* Unless he decide to change the language for the whole website, he should only see the content written in the selected language
* all user (except admins) on the website are anonymous (no registration, no login)
* we need the admins to see all languages.
* contents can exist in one or many languages. There is no "reference" language that holds all the contents.

So far we have set the language switcher for all languages, but then on the website the menu for all languages are displayed (which we don't want). Also, search is made on content for all languages. If we set the language switcher to only use the selected language, everything works as intented on the website but then the admin can only see the content matching the current selected language. We need that he sees all content.

We've been looking into some options (including the Administration Language, but unless we overlooked some configuration, it doesn't seem to fit our needs).

Any ideas, hints or suggestion welcome !

# Answer
> 0 votes
We ended up writing various custom modules to solve that issue.

---
Tags: i18n-l10n
---


# Question
Title: Bootstrapping Drupal from the command line
Here is what I'm trying to do :

1. Write a php script that import external data into drupal.
2. Run that script every night with a cron that executes it using `php`, not `wget`.

In other words, I need my import script to run from the command line.

First step is done and working great when run as a module from Drupal. So I took all required bits of it, created a new file, and bootstraped drupal. After fixing a few warnings and errors (path issues mainly), the file is executed but actually no job is done.

So I start adding echo commands to see where everything goes to hell. And it appears that it's right after

```
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

What I mean is that no error, warning or whatever is raised, but it's like the script exit somewhere inside that call.

I tried to lower the boostrap level to DRUPAL\_BOOTSTRAP\_LANGUAGE, but then I get the following error :

> Fatal error: Call to undefined function field\_info\_field() in /www/includes/entity.inc on line 768

I'm a bit lost on what happens and would welcome any suggestion.

Also, here is the beginning of the script that bootstrap Drupal :

```
<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
    chdir('/www/');

    $cmd = 'index.php';
    $_SERVER['HTTP_HOST']       = 'default';
    $_SERVER['PHP_SELF']        = '/index.php';
    $_SERVER['REMOTE_ADDR']     = '127.0.0.1';
    $_SERVER['SERVER_SOFTWARE'] = NULL;
    $_SERVER['REQUEST_METHOD']  = 'GET';
    $_SERVER['QUERY_STRING']    = '';
    $_SERVER['PHP_SELF']        = $_SERVER['REQUEST_URI'] = '/';
    $_SERVER['HTTP_USER_AGENT'] = 'console';

    define('DRUPAL_ROOT', '/www/');
    require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_LANGUAGE);

    // nothing gets executed past this point
    print("0\n");

```

# Answer
> 6 votes
Don't even try this. Use `drush`, it is meant for this type of things precisely.

The `drush php-script` command will allow you to run any PHP script in the context of Drupal, but I would recommend writing those as a proper command inside a custom module.

# Answer
> 1 votes
I agree with Damien. Trying to invoke the bootstrap is not the way to go.

If the data you are importing is in csv or xml format, I would suggest you use the Feeds module. It is tailor made for this and you can schedule it as a daily task.

---
Tags: bootstrapping
---


title: Node list control

text:
# Question
Title: Node list control
I am using Drupal 7.

For example, I do not want to show node uid=28 in the list ($page==0). The list page is a "view" without filtering there. So it shows up all the nodes of a specific content type (I only filter with this content type in view setting).

With this function, I can change its title.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->uid == 28) {
    $node->title = "Do not show me!!!";
    $node = NULL;
    unset($node);
  }
}

```

But I could not work out how to not show up this node at all in the list. I do not want to implement some filtering in view part.

This does not work.

```
$node = NULL;
unset($node);

```

I like to use hook\_node\_view and set more complicated filter logic there.

So basically I like to: implement a view page with only filtering to specific content type that I want; implement a more complicated filtering/selecting method in hook\_node\_view.

# Answer
Perhaps I misunderstood the question. You have created a `view` containing nodes of a special content-type and now you would like to exclude a node with `nid` equal to 28 from the results? If this is the case then I think you ***should*** add a new filter of type `Content:nid` and set it to `not equal` 28 in your views configuration page.

Also, I don't think the `hook_node_view()` can be used to filter the results for a view. You can use the hook to modify or add/remove elements from the node before it's being rendered.

Here is a list of all views hooks.

For example you could use the `hook_views_query_alter()` to add a new filter to the query.
> 0 votes

---
Tags: nodes
---


# Question
Title: How restrict Anonymous users from creating accounts
I am building my first site in Drupal(7), and I would like to restrict unloged users from creating user accounts, so how can I disable new account creating from `{mysiteName}/user?`

Thanks a lot

# Answer
Go to `sitename.com/admin/config/people/accounts`

Scroll down to find **REGISTRATION AND CANCELLATION**

Select appropriate option in **Who can register accounts?** field
> 6 votes

---
Tags: users
---


# Question
Title: Programmatically embed fields of one content type in the create/edit form of another content type and store all
I have drupal 6.x.

How to programmatically (with a custom module) embed fields of one content type (content type X) in the create/edit form of another content type (content type Y) and store all the data for when the node is created/updated (store X and Y data when Y is stored).

If is not possible this in drupal 6.x I could be to work in drupal 7.x.

Thanks in advance.

# Answer
> 0 votes
I think it would be tricky as you would need a way of tracking a relationship between the two nodes as well. You would need to decide on which way the relationship would go if you were to use node reference as its only one way in drupal 6.

This is what I would do 1. Add a node reference field to Y 2. Use hook\_form\_alter to add the required fields (Embedding cck fields will be tricky better of just sticking to fapi fields) 3. add a custom validation handler for the x fields if required 3. Save x field values as a node programticaly when presave is triggered by hook\_node\_api http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook\_nodeapi/6
4. Update the noderefrence in Y with the new X nid 5. Use hook\_node\_api to update X when Y is updated

Another possibility might be to use Rules to create and update for you

# Answer
> 0 votes
http://drupal.org/project/field\_reference There's another cck reference field module that should do the same thing for 6 & maybe 7 I cannot recall the name though.

http://drupal.org/project/nodereference\_field is different sort of thing where you would create a node that both other nodes could reference which can be nice if your referencing several points of data however there's some bloat to your database & extra time to look up and process the queries from a full node. It's also only v6 so no upgrade path.

http://drupal.org/project/references & http://drupal.org/project/entityreference are the 7+ equivalent of nodereference.

Note: modules aren't what's asked for but they should show you the path if you dissect them.

---
Tags: 6, entities, nodes
---


# Question
Title: Send email to specific users using webforms
In a view, everytime a user clicks on a link "click to connect" field, an email has to be sent to the specific username based on its id. I am using webform to send the mail. But, it restricts me to send all mails to the same email address. In order to hide the email to which mail has to be sent, I am fetching the id of the user(to whom mail has to be sent) in a hidden field in webform. But, i cant figure out a way to get the destination email dynamically.

# Answer
Why not activate individual user contact forms, add a User: Link to contact page field to your view, and put your 'Click to connect' in the Text to display?

This will allow users to control whether or not they wish to receive such emails. They will be able to opt out in their account page and the link will not appear in the view.
> 2 votes

# Answer
This won't directly answer your question but

http://drupal.org/project/mimemail will format your mail all pretty like with html goodness.

http://drupal.org/node/37480 v6 & http://drupal.org/project/mailsystem v7 will handle all the heavy lifting.

There's quite a few tutorials on boath google is really your friend there with out more information on how you want to send them. Rules can, triggers can, Cron can, and modules can with hooks. They all can be sent "at a button press" so to speak. Rules though is probably where you want to look if your going for plug and pray sort of approach. A custom module will involve the api & hooks.

Good reading at http://drupal.org/node/1124376 v6/7/8 Please also specifiy which version of Drupal you are asking about since each version has different modules & api.
> 0 votes

---
Tags: webforms
---


# Question
Title: How can I create a hook into an external module
I want to be able to alter a function inside another module like a hook, but I'm not sure if that's what it's called. I want to alter a function inside another module from my module without changing the external modules code.

This is in version 7.x.

Thanks Frank N.

# Answer
PHP offers no mechanism to do that.

If the external function isn't a hook (i.e. it doesn't use `module_invoke()` or `drupal_alter()` to gather data from other modules) then the only thing you can do is patch the function in the external file.
> 2 votes

---
Tags: hooks
---


# Question
Title: Webform 'Save draft' to send a mail with $sid
* I am having a webform and I display the 'Save Draft' buttoan on the form.
* Once I click on the Save draft I need to save all the values in the DB (as it does on Submit event) and should send an e-mail with the submission id (%sid) to the user who works on the form.
* I don't want to do this using "Webform Rules" module, I want to do this using my Own custom module

Thank you.

# Answer
Personally I would use webform rules for this. However if you are wanting to do this in a custom module then I suggest you looks at hook\_webform\_submission\_insert or hook\_webform\_submission\_update depending on whether it's a new webform submission or not.

From there you can use modules such as devel to obtain the information on the submission status you require. I haven't worked with 6 for a while now, so I may be wrong here, but I think it's `is_draft` you need to use. (I haven't got a D6 site to test on). With this information you can write a function to send the mail using drupal\_mail
> 0 votes

---
Tags: 6, webforms, forms
---


title: Autosave form fields example

text:
# Question
Title: Autosave form fields example
I have a form with 3 textareas and some other fields. I would like to put in an autosave functionality and found the Autosave module. But that seems to be specifically for editing nodes and is also too advanced for what I need. I just need to save the contents every 3 seconds or so, no revision support or anything fancy like that.

I'm thinking about a silent form submit that the user doesn't notice or a specific page that receives the contents of the form posted with JavaScript.

But something like this must have been done before, so is there an example or some pointers on how to implement this? I'm using Drupal 7.

# Answer
> 3 votes
Try the Save Form State module. Here is a quote about it (from the module's project page):

> ... provides a way to autosave data entered in any Drupal form without actually submitting the form, which helps if the user is writing an article or a comment and the browser crashed or the power went down, or even if the window was closed accidently.
>
> It works using the jQuery Sisyphus plugin, which is a lightweight jQuery plugin that uses Local Storage to save form fields every specific time span that is configurable from the module settings page.

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


# Question
Title: Is there a way to skip bootstrapping drupal to save load time via drush?
I currently use drush alot to manage my sites, but I was wondering if there was a way to skip bootstrapping drupal everytime drush is run for certain commands that might not need it. This would save significant load time. I tend to do pm-list alot, but sometimes it just takes a long time to load depending on the size of the site. Same goes for enabling/disabling modules.

# Answer
That is hard-coded for each command: The module defining a Drush command sets the bootstrap level required to run the command. For example, cache\_drush\_command() defines cache-clear as the following:

```
  $items['cache-clear'] = array(
    'bootstrap' => DRUSH_BOOTSTRAP_MAX,
    'description' => 'Clear a specific cache, or all drupal caches.',
    'arguments' => array(
      'type' => 'The particular cache to clear. Omit this argument to choose from available caches.',
    ),
    'callback' => 'drush_cache_command_clear',
    'aliases' => array('cc'),
  );

```

To require not bootstrap at all, the "bootstrap" property should be defined as follows.

```
  $items['xkcd-fetch'] = array(
    'description' => "Retrieve and display xkcd cartoons.",
    'arguments' => array(
      'search' => 'Optional argument to retrive the cartoons matching an index number, keyword search or "random". If omitted the latest cartoon will be retrieved.',
    ),
    'options' => array(
      'image-viewer' => 'Command to use to view images (e.g. xv, firefox). Defaults to "display" (from ImageMagick).',
      'google-custom-search-api-key' => 'Google Custom Search API Key, available from https://code.google.com/apis/console/. Default key limited to 100 queries/day globally.',
    ),
    'examples' => array(
      'drush xkcd' => 'Retrieve and display the latest cartoon.',
      'drush xkcd sandwich' => 'Retrieve and display cartoons about sandwiches.',
      'drush xkcd 123 --image-viewer=eog' => 'Retrieve and display cartoon #123 in eog.',
      'drush xkcd random --image-viewer=firefox' => 'Retrieve and display a random cartoon in Firefox.',
    ),
    'aliases' => array('xkcd'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH, // No bootstrap at all.
  );

```

Using `DRUSH_BOOTSTRAP_DRUSH` says to Drush that Drupal doesn't need to be bootstrapped at all.

Clearly, that is not something that can be arbitrarily changed; it depends from the code executed from the command.
> 2 votes

---
Tags: drush
---


title: Sharing content with domain access?

text:
# Question
Title: Sharing content with domain access?
I setup a site with domain access. It has 2 subsites. I want to publish content from the main site to the subsites. This is already working good with send to affiliates. But I want some local admins on the subsites to have the permission to decide if they want to use the content or not. Is it even possible with domain access or is it just one way from top to bottom ?

# Answer
> 3 votes
One solution I did recently in a similar situation was just create a `views xml feed` of the content I want to feed to my subsites. From there my subsites would have the feed\_import module and have to fetch the articles every 10 minutes. Once fetched it will be unpublished but can only be viewed by certain roles for screening.

Now as for the left over imported nodes I would use `node_purge` to delete nodes that are X days old. Obviously this solution wouldn't be ideal for sites with sensitive data as the xml feed is exposed.

---
Tags: users, nodes, domain-access
---


title: Full term path as product url

text:
# Question
Title: Full term path as product url
Im using D7 and UC3. A product is multiple levels down:.

product list = cat1/sub2/sub-sub1/

Now using pathauto i'm trying to make the path of the product cat1/sub2/sub-sub1/product1 however i cant find the right tokens to do this. Best is can get is sub-sub1/product1 loosing the first two steps. In the breadcrum i do see the other levels, so the product knows its nested like that.But i cant seem to get the url to correspond.

# Answer
Taxonomy reference of the content type must be set to 1. New tokens will become availible and differect ways to create a url like the above become possible
> 0 votes

# Answer
This is not something given out-of-the-box, unfortunately. Been through this. I have never used Ubercart, just Commerce, but I assume in both cases we have some kind of product entity and content type for displaying the product.

For the correct path and Pathauto, you'd have to use a pattern like this:

```
products/[product-category-field:parents:join:/]/[product:name]

```

However you might need to install Entity API and enable its submodule called Entity Tokens.

For the breadcrumb paths, I would suggest that you try out Path Breadcrumbs. Even though it requires some setup work for all the context, I found it more reliable than Context or other Taxonomy Breadcrumbs or Menu Breadcrumbs modules out there.
> 0 votes

---
Tags: ubercart, path-aliases
---


# Question
Title: How to consume data about drupal contributed modules?
Is there a feed or feeds that expose data about all drupal contributed modules? I want to consume drupal.org data about modules in a certain category e.g. https://drupal.org/project/modules?f\[0\]=im\_vid\_3%3A59

I would love to get the catagories information e.g "Categories: Actively maintained, Under active development, Administration, Modules, Developer, Site Navigation"

I've seen http://drupal.org/node/63589, but the "Compatible with Drupal core 7.x" (http://drupal.org/taxonomy/term/103/0/feed) only lists about 72 ftp urls when I load it in a web browser. That is not all of the D7 modules...

I also looked at the About page on http://drupalmodules.com for clues about how they get the data, but didn't find anything useful.

Thanks for any pointers!

# Answer
Here's what you do:

1. https://drupal.org/project/modules/categories
2. click on the More link for the Category which you want in your feed
3. Look at the taxonomy id number at the end of the url e.g. https://drupal.org/project/modules?f\[0\]=im\_vid\_3%3A56
4. construct your feed url like this: https://drupal.org/taxonomy/term/56/0/feed
> 0 votes

# Answer
While it is not an rss feed, there is this page:

http://drupal.org/project/usage

which lists usage stats for all the modules **11899** of them. They each appear to have a page that has a bit more detail on it.
> 0 votes

---
Tags: feeds, community-official-site
---


# Question
Title: What meaning do the primary / secondary menu links have when it comes to SEO?
Is there some meaningful difference between the primary / secondary links when it comes to SEO? Do they carry a different weight from a search engines perspective?

Thank you!

# Answer
> 1 votes
Usually there is no meaning other than that you apply. For most sites, Primary links (or Main menu) are used to navigate the content of the site, and Secondary links are more for the infrastructure links (Contact, Site policy etc). You can use them any way you wish in the context of your own site. There should be no SEO impact.

---
Tags: navigation
---


# Question
Title: Can I limit a view mode to show on the "Manage Display" settings page for only one node type?
I have a module that creates a custom node type ("answers") and a custom view mode ("answers\_full\_node") for that node type.

Now, when I look at the "Manage Display" settings page for *any* node type, the custom view mode is available.

Is there a way I can restrict it so that it shows up only for my custom node type?

# Answer
No, view modes are per entity type, not per bundle.
> 2 votes

---
Tags: nodes, entities
---


title: Help with node and field theming

text:
# Question
Title: Help with node and field theming
I am not particularly new to programming, but trying to theme how Drupal 7 outputs entity fields is giving me headaches. I think Drupal is great, but the documentation could be more organized and complete. I have sifted through a lot of material about this, but I'm still struggling to organize the bits and pieces of information into usable representation of how Drupal 7 treats and outputs field values.

This is an example output that one would like to obtain:

```
            <h1>#field value#</h1>                      // Suppose this is the node title
            <h2><a href="">#field value#</a></h2>       // Sub-title
            <div class="">                              // Attributes:
                <div>
                    <h3>
                        #field title#:
                    </h3>
                        #field value#
                </div>
                <div>
                    <h3>
                        #field title#:
                    </h3>
                        #field value#
                </div>
                <div>
                    <h3>
                        #field title#:
                    </h3>
                        #field value#
                </div>
                <div>
                    <h3>
                        #field title#:
                    </h3>
                        <a href="">#field value#</a>    // e.g. Link to Taxonomy term page
                </div>
            </div>

```

`#field title#` and `#field value#`, represent where one would like Drupal to output the field titles and/or values submitted when creating entities/nodes.

The idea sounds straight-forward, but I find it to be immensely complicated in practice.

Some pitfalls I have encountered: Drupal makes presumptions, on how the field should be displayed, it gives it additional markup, which I have been unlucky in managing. When outputting through Panels the UI does not provide ways to separate field value and title. Am I under correct impression that I need separate template files or functions for all fields if I want the above structure?

Please shine some light on the matter. I bet many people would love to hear how more experienced developers approach these problems.

# Answer
> 3 votes
This is probably not a full answer, but you will need to use field template suggestions.

```
**field--[type|name[--content-type]|content-type].tpl.php**
base template: field.tpl.php
Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php
Note that underscores in a Field's machine name are replaced by hyphens. Also remember to include "field-" in custom field names, e.g: field--field-phone.tpl.php.

```

The above is taken from https://drupal.org/node/1089656, so it for more information. As a side note, if there are a lot of fields being displayed or you are using a broad template, you would probably want to use a templating function instead, such an example can be seen in Bartik's `bartik_field__taxonomy_term_reference` (Link here). The functions have a similar naming scheme to the .tpl.php files but with underscors instead of dashes.

**Update:** You can cover all fields of a certain type with `field--field-type.tpl.php` (or `function theme_field__field_type()`), or all fields on a content type with `field--content-type.tpl.php` (or `function theme_field__content_type()`). You can then override these functions by using a more specific template (They have an order of preference). This can really cut down on the number of theming templates or functions required, essentially if a content type has 100 fields, you could theme them all with one template or function, if you so wished.

So you could use 1 function to theme all the fields on a content type if you wished, no matter their type or name. Alternatively you could field all fields of a certain type (eg. taxonomy\_term\_reference in the case of Bartik) no matter what their field names are or which content types they are on.

You could override one of these more general templates or functions with one which is more specific, from the `field.tpl.php` documentation above `field--field-type.tpl.php` will be overridden by any of the ones listed above it, if a relevant function exists. While `field--field-name--content-type.tpl.php` has the highest preference and will not be overridden by any of the others. This is just core behaviour, custom modules may alter the list, including adding new ones, which can lead to quite a powerful set of themeing functionality.

Templates are easier for themers to work with, I am told. I prefer functions because it avoids what may be a large number of includes in some cases.

# Answer
> 1 votes
Drupal supports themeing fields and entities (typically groups of fields) together.

Other 3rd party contributed modules can help you get the output you want, and try to make it not a hassle. See the Display Suite module:

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

Also look at and the Fences module.

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

---
Tags: theming
---


# Question
Title: how to setup blocks that differentiate 'node edit' case from 'node add' case in MULTISTEP forms
Im using Drupal 6 and the multistep module :

I need to display informations in a block apart when my users wether add or edit some of the available multistep forms :

. there's a block that shows up with an EDIT title when EDITING an existing node with information within it for this case :

```
only shows up when :
node/*/edit* page

```

. there's a block that shows up with a CREATE title when ADDING a node :

```
only shows up when :
node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

```

node/*/edit* is necessary for ADDING since when the user finishes the first step of the form, the node is saved and the link which was node/add/m-c-A turns into node/nid/edit.

in both block I use a bit of php ( url arg(), $node) to check content type, to retrieve node info if exists, to decide wether show info for ADDING cases or for EDITING cases. (as there's nothing to show, the entire block DIV does not show up)

I would need to recognize the ADDING case after step 2 of the form... when the node is created but when the progress bar is lesser than 100%.

in other words, to retrieve the 'completion status' argument from the multistep module, the one that tells the progress bar if the form is completed or not.

it appears it's not in the $node array.. ?

EDIT : found a trick, see comment 2.

# Answer
I dont know how to retrieve the multistep completion state from a block but there's a simple way, by testing the published status (not published ? not complete ADD/PENDING - published ? complete EDIT)

in admin/settings/multistep : select Publishing \> at node completion

in the ADD block that must be displayed when adding a multistep node : only display block on the pages below :

```
node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

```

in the ADD block body :

Title : add

```
<?php
$show = FALSE ;
if ( arg(0) == 'node' && arg(1) == 'add' ) {
  if (in_array(arg(2), array( "multistep-content-A", "multistep-content-B" ))) {
    $show = TRUE ;
    $node = False ;
  }
}
elseif ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 0) {
    $show = TRUE ;
  }
}
if ($show) {
  if ($node) print '<center>id : <b>'.$node->nid . '</b></center>' ;
  print "<ul><li>some info about creating this node.</li><li>be sure to complete every step blah blah <i>the italic ones</i></li></ul>" ;
}
?>

```

in the EDIT block :

Title : modify

```
node/*/edit*

```

body :

```
<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 1) {
    print '<center>id fiche : <b>'.$node->nid . '</b></center>' ;
    print "<ul><li>some info about editing an existing node.</li><li>browse directly to the steps you need to modify by using the link below.</li></ul>" ;
  }
}
?>

```

there might be a way to only have one block, that could change its title itself, I didn't investigate.
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: How to translate "New custom content" in a panel?
I have a lot of panels to which I have added bits of text/HTML using the "New custom content" option of the Panels module.

By default, such text does not show up on the Translate Interface screen. How should I go about translating them?

Two approaches I have found are:

* Changing the custom content text format to `PHP code` and printing the string(s) of text using t(). This then allows me to translate the strings on the Translate Interface screen, but I worry that injecting PHP code like this is a bad precedent.
* Since I only have two languages, I can add a second piece of custom content that is localized in the other language. Then, I can add a visibility rule to each piece of custom content in Panels and set each piece to show only when the user's language matches the content language. This works but it is time consuming and ugly on the backend. It would be even worse if I decide to add more languages to my site in the future, which I may do.

Is there a more efficient, maintainable way to translate such custom content?

# Answer
First of all, I would like to explain why this doesn't "just work", so that you have been given fair warning before I give you new problems. :) Consider a custom content pane content like:

```
Welcome %user:name, you have %field_num_messages new messages waiting.

```

The text here would be substituted *before* passed to t(), meaning that for each variation of user and number of messages, you would get an entirely new string to translate. For such panes, go with having two separate panes.

A long term solution is slowly being worked on here: Translatable panel titles: Implement i18n\_strings but focuses on the pane titles initially.

Generally speaking, the solution is to avoid custom content panes, but I also realize that using them can be very convenient at times.

Finally, here's a piece of code I've used to "force" pane titles to become translatable. I will attempt to later modify it better to your situation, but I figured having *a* useful answer quickly was better than not. :) You should be able to use $pane to figure out if this is a custom pane, and then pass the text through t().

```
/**
 * Implements hook_panels_pane_content_alter().
 */
function HOOK_panels_pane_content_alter($content, $pane, $args, $context) {
  if ($content->title) {
    $content->title = t($content->title);
  }
  return $content;
}

```
> 4 votes

# Answer
I use always a basic page, (existent node vs custom content). You will have this way trough Entity translation the opportunity to deal with languages and fallback. To avoid SEO duplicated content issues, install Rabbit hole module and use the redirect to your panel page for those nodes.
> 3 votes

# Answer
If your goal is to export some custom "blocks" (for lack of a better term) to code and translate them, you might consider using the boxes module with i18n\_boxes, which will allow you to translate boxes in the UI (using l10n\_client for example) and export the default language version to code. You can then use the boxes in your panels.
> 2 votes

---
Tags: 7, panels, i18n-l10n
---


# Question
Title: How to use two different image styles on teaser?
I want to use Medium image preset on teaser when the article is featured, then change to thumbnail style after. Is it clear? For example, in a cuisine recipes website I want to show a "Recipe of the Day" with a medium style image and tomorrow that recipe will be change by the newest ("Recipe of the Day") and shown with thumbnail style. Is it possible?

Thanks in advance.

Alex

# Answer
You can use Entity View Modes

It will give you the chance to set up a new view mode and change it from Manage Display page. You can create 2 view modes, one for Sticky e one for Recipes of the day. From views page, open the sticky display, click on "Show -\> Content \> YOUR\_VIEW\_MODE" and repeat it for the Recipes of the day display/view.

In the manage display page you can set up the image style for the View Mode.
> 2 votes

# Answer
Sure,

If it's the first item of the list, you can create a view with the featured items and then you can attach the other views to this creating a new Attachment. if you they are random on the list you should create an if statement to check if it's featured or not and print the right image style through

```
image_style_url('your_style', $node->field_image[LANGUAGE_NONE][0]['uri']);

```

so it will be something like

```
if ($node->sticky == 1) {
print "<img src='".image_style_url('medium', $node->field_image[LANGUAGE_NONE][0]['uri'])."' />; } else
{
print "<img src='".image_style_url('small', $node->field_image[LANGUAGE_NONE][0]['uri'])."' />;
}

```
> 0 votes

---
Tags: media
---


# Question
Title: Why do PAreview/codesniffer gripe about missing "scope modifier"?
I am writing a simpletest file for my Drupal module. It works OK, but when I use PAreview (automatic tool based upon PHP codesniffer to check correctness of Drupal code), I get the following error flagged: \`No scope modifier specified for function "setUp".

My function `setUp` looks like this:

```
function setUp() {
  parent::setUp('realnamereg');
  variable_set('user_email_verification', FALSE);
}

```

Changing into into a public function fixes it:

```
public function setUp() {
  parent::setUp('realnamereg');
  variable_set('user_email_verification', FALSE);
}

```

Do anyone know why PAreview/code sniffer complains about this, and whether making the function `public` makes any difference?

# Answer
As this example blog shows, a testcase is a php class. The definition of `setUp` in the base class is a public function. Your implementation function of `setUp` must/should match the defined definition. So Parview bitches.

```
class MymoduleTestSuite extends DrupalUnitTestCase
{ ... }

```
> 3 votes

---
Tags: 7, testing
---


# Question
Title: Whats wrong with my drush script when using sql?
Im running the following via `drush scr`

```
$query = db_query('select node.nid AS nid from {node} node where (type="feed_item") AND (status="0") limit 1');

```

i am getting this error:

> WD php: PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'feed\_item' in 'where clause': select node.nid AS nid from
> \[error\] {node} node where (type="feed\_item") AND (status="0") limit 1; Array ( ) in include() (line 5 of /home/quickstart/websites/xc.dev/deleteme.php). \[4.77 sec, 97.55 MB\] PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'feed\_item' in 'where clause': select node.nid AS nid from {node} node where (type="feed\_item") AND (status="0") limit 1; Array ( ) in include() (line 5 of /home/quickstart/websites/xc.dev/deleteme.php). Drush command terminated abnormally due to an unrecoverable error. \[4.79 sec, 97.55 MB\]

Whats wrong?

# Answer
i think the problem is in the " / ' , try it this way :

```
$q = db_query("
select node.nid AS nid from {node} node where (type='feed_item')
AND (status=0) limit 1");

```
> 0 votes

---
Tags: drush
---


title: How to disable the cache tables

text:
# Question
Title: How to disable the cache tables
I make a newspaper website from long time using drupal 7 and now its database is very large. Most of the time, the database server is down because of that. The tables that are more problematic are cache, cache\_\*, and watchdog.

Is there any way to avoid those tables are used?
Today I tried deleting the rows in those tables with SQL, but it took more than 3 hours.

# Answer
> 2 votes
I would not recommend to disable the cache; it will make all slower. The DB Maintenance module will do cleanup tasks for you.

> DB maintenance optimizes administrator-selected tables in the database during regular cron.php executions. For MyISAM tables, OPTIMIZE TABLE repairs a table if it has deleted or split rows, sorts table indexes, and updates table statistics. For BDB and InnoDB, OPTIMIZE rebuilds the table. Note, MySQL locks tables during the time OPTIMIZE TABLE is running.

# Answer
> 1 votes
you can definitely switch off the "Database Logging" (dblog) module from core, that will take care of the **watchdog** table. It might be good to check whats there, though - could be you have some missing files and get an entry for each request ...

For caching, you can use other systems, such as APC, memcache, file system.

---
Tags: 7, caching
---


title: Stop markup being pasted into WYSIWYG?

text:
# Question
Title: Stop markup being pasted into WYSIWYG?
Im making a CMS for a client who will be copying and pasting content into the body of nodes. I want to remove certain markup from coming through (eg inline styles) but allow other markup (p and br tags).

With the html filter I can stop certain markup being displayed but its still there in the content when you edit the node. Is there a way of stopping some markup from coming through at all? Thanks

# Answer
> 0 votes
Have a look at Sanitizable and Paste Format (filter, clean-up pasted text). The first cleans up on save, the second actually at paste.

# Answer
> 1 votes
Try out the WYSIWYG Filter module. It allows to restrict all described things.

After installation you will be able to configure its settings in the "Input formats" section.

# Answer
> 0 votes
CKeditor is very complete and you can setup more functions than wysiwyg.

You can even decide with tag you want when you press enter or shift+enter.

It's very complete, have a look at it.

# Answer
> 0 votes
You also may want to look into BU editor. You can set up wyswyg buttons for the type of code to allow.

---
Tags: 7, wysiwyg
---


# Question
Title: htaccess www redirect not working correctly?
I have this line in my htaccess file:

> RewriteCond %{HTTP\_HOST} ^www.mysite.com$ \[NC\]
>
> RewriteRule ^(.\*)$ http://mysite.com/$1 \[L,R=301\]

And it works for the most part. But if you go to www.mysite.com/pagetitle, it redirects you to mysite.com/index.php?q=pagetitle. Why would it not redirect you to mysite.com/pagetitle? Is there another portion of code I need to insert into the htaccess file? I do already have search engine-friendly URLs enabled.

# Answer
> 2 votes
Your RewriteConditions says if starting with www.mysite.com then redirect to http://mysite.com

This rule is not affecting clean urls. Clean urls must enabled at http://mysite.com/admin/settings/clean-urls

---
Tags: 6, .htaccess
---