# Question
Title: Custom login redirect failed in hook_user_login
I'm trying to redirect to the user edit page just after the user logged in from the login block in the sidebar. I implemented hook\_user\_login, but no luck. It seems to me that `drupal_goto()` or `$edit['rediect']` cannot take precedence over `$_GET['destination']`

```
function mymodule_user_login(&$edit, $account){
    if ( user role is employee and user has not completed profile yet ) {
        // both failed to redirect, although my condition is true
        $edit['redirect'] = 'user/'.$account->uid.'/edit';
        drupal_goto('user/'.$account->uid.'/edit');
    }
}

```

I was at my home page ( mydomain.com ) and tried to log in, but when I `exit` in my hook, I found that the URL was changed to mydomain.com/node?destination=node. My home page path is blank in site information.

**\[Edit\]**
My condition for redirect is that **if the logged in user has empolyee role and his profile is not completed yet**. My usecase is very similar to this, but i don't use content profile.

I think the way of overriding $\_GET\['destination'\] would fix my issue.

# Answer
> 6 votes
drupal\_goto() will use `$_GET['destination']` when it is set. The following is the code used from the function.

```
  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }

```

Setting `$edit['redirect']` inside `hook_user_login()` doesn't have any effect.
What you can do is changing `$_GET['destination']` in `hook_user_login()`. If you want to be sure the user is redirected to the path you set, you should be sure your hook is executed last, for example by increasing the weight of your module.

# Answer
> 2 votes
You have a shortest way,with `rules` module . **update:**

Steps

1- **Create a new rule**

First we have to start a new rule. For this go into the rules admin center, click on "Triggered rules" and on the tab "Add a new rule". Select the event "User has logged in", set the label "On login redirect to account page" and click "Submit". Now we have created a new rule, which is still empty. Every condition and action that we add to this rule, will be evaluated on the event "User has logged in".

2- **add your condition** in condition section `add condition`, in `Select the condition to add` choose **Php** `Execute Custom php code` (be sure your **PHP filter** is installed). check your condition in the condtion section.

3- **Create the redirection action**

To do so, click on the "Add an action" link, under the section "System", select the action "Page redirect" and click on "Next" button. In case you have the token module installed, the "Page redirect" action allows you to use token replacements. This allows us to place the user's id in the redirect path. So call the action "Redirect to the users account page" and set the path user/\[account:uid\]. Then activate the checkbox "Force redirecting to the given path, even if a destination parameter is given" - which is necessary, because Drupal always sets a destination parameter to the current page, if a user logs in. So, that our redirection applies, we need to activate this. Check the option, and click on the "Save" button.

# Answer
> 0 votes
I think Login Destination module is also giving the same functionality. Apart from that it also provides some more features. It is worth to try.

---
Tags: 7, hooks, users, redirection
---


# Question
Title: Altering the text after a checkbox using the Drupal Form Api
I got the following issue. A clients wants that the text after checkboxes are links to other pages and thus between ...

I have the following code:

```
$form['boxes_brands'] = array(
    '#type' => 'checkboxes',
    '#title' => '<div id="title-container">Merken</div>',
    '#options' => $brandArr,
    '#default_value' => $_SESSION['filter_brands_cat'],
);

```

`$brandArr` is an array of brands.

I looked in the Form API of Drupal but I did not find an option to do this. I could alter the values in `$brandArr` but of course that changes the value of the value attribute of the input object too.

Using the prefix and suffix options won't work either because I don't want the checkboxes in the tags too.

Is there a clean way to do this?

# Answer
You can give the $options as an array of value and label. And the label can then be given as a link using l().

```
'#options'       => array(
  'facebook'     => l(t('Facebook'), 'http://www.facebook.com'),
  'twitter'      => l(t('Twitter'), 'http://www.twitter.com'),
),

```
> 1 votes

---
Tags: 7, forms
---


title: Send email of form data?

text:
# Question
Title: Send email of form data?
I have a block module that looks like this:

Created in the following way:

```
function VL_newsletter_signup_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Enjoy Stories? - Newsletter Signup'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function VL_newsletter_signup_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      //$block['subject'] = t('Block Name');
      $block['content'] = VL_newsletter_signup_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function VL_newsletter_signup_contents() {
  return '<div class="col4 stories nobile">
    <h2>Enjoy stories?</h2>
    <h3>Sign up to recieve regular news</h3>
    <form>
        <input type="text" name="first" placeholder="First name">
        <input type="text" name="last" placeholder="Last name">
        <input type="email" name="email" placeholder="Email" >
        <input class="send" type="submit" name="submit">
    </form>
    </div>';
}

```

At the moment my form is static HTML as can be seen, but I plan to use Drupal Form API to render it. My question is: on pressing send, how can I email the form data to a designated admin email address. Can I use triggers somehow or is there another function in Drupal API that could achieve this?

# Answer
> 2 votes
You can use drupal\_mail() function to send the mail data. You can also use HTML Mail module to integrate nice email templates.

I have shown drupal\_mail() function.

```
$params = array('current_conditions' => $data);
  $to = 'user@example.com';
  $message = drupal_mail('example', 'notice', $to, $language, $params, FALSE);
  // Only add to the spool if sending was not canceled.
  if ($message['send']) {
    example_spool_message($message);
  }

```

---
Tags: 7, blocks, emails
---


# Question
Title: Is there a problem defining a View using a path alias? Or did I just miss something?
**CONDENSED SUMMARY OF ISSUE:** I have a view with a path of `/taxonomy/term/%/something` that responds to a URL alias of `/spec/ID/` so entering `/Spec/ID` or `/Spec/ID/Something` displays what is in the View. If I clone the View and change the paths from /taxonomy/term/%/something to `/Spec/%/Something` entering a URL of `/specs/ID` will no longer display the view.

**ADDITIONAL INFO:** I have created a View (D7 Views3) with several pages each with the path `/taxonomy/term/%/sub-category` where subcategory is a label for a subgroup of content for the specified term. A filter in each page limits the content to match the subcategory label.

I have created an alias for a vocabulary `/specs/[term:field_specno]`. The field, attached to the term, provides a unique ID for the terms relating to a client's set of standards.

If I enter a URL for `/specs/term1`, the view will display the correct content for term1 on a page display, with operating Menu Tabs I have defined for each page in the view. It works great except that if I select another Menu Tab, the URL changes to `taxonomy/term/%/subcategory` format used in the view. This would be confusing if a user uses the URL and gets the cryptic tid instead of his ID system. It I clone the view and change the paths to `spec/[term:field_specno]/sub-categories`, the view no longer displays the pages and tabs correctly.

Is there a fundamental problem in Drupal doing this or have I screwed up somehow? Has anyone done something similar successfully?

# Answer
> 1 votes
It could be, that I'm still having difficulties understanding your question, but I have no idea why you would expect that to work?

/path/to/%term contains an argument, and as such there is essentially an infinite number of variations that could "fit" into that path. A path alias "/pageone" to "/path/to/aterm", does not match "/path/to/otherterm", nor any other path in the system.

Each path alias must point to a specific path, and there is to my knowledge no way to automatically "Create all possible path-aliases to for a path /path/with/%arg". There is a feature request for such a tool though.

# Answer
> 1 votes
**Letharion's answer:**

> Drupal translates the URL alias to the actual URL very early in the request sequence so it cannot find the View defined with an alias path.

Path Auto creates an alias for a URL and Drupal translates the alias into its true path and then executes the URL action. In the example in the question, the URL contains `/specs/ID` which Drupal changes to `/taxonomy/term/[tid]`. Since the view path is defined as `/taxonomy/term/%`, the view is called and works as designed. In the second case, the view path has been changed to `/specs/%` and Drupal, having already changed the URL request from `/specs/[ID]` to `taxonomy/term/[tid]` does not associate the view definition with the URL request, so the View is never called.

My reason for attempting this was so that the alias URL would be visible after the view is called and a user could use the URL alias to change to another view in addition to a special menu. Unfortunately, when the view is called, the url for the view is displayed (`/taxonomy/term/[tid]`). I do not see any work around for this at this time.

# Answer
> 1 votes
For those, who still searching issue... Creating path alias for your term-related view seems good idea. You can do it in hook\_node\_presave().

For Example:

I have page view with path node/%/tours and menu tab "Tours" for node 123 i have alias: node/123 -\> country/Greece. When opening country/Greece, we can see "Tours" tab with node/123/tours link. After adding alias node/123/tours -\> country/Greece/tours tab link will be country/Greece/tours

Just found: Extended path aliases module.

# Answer
> 0 votes
So the way I understand this questions is such:

You created a view, with a path that has an argument. Then you created aliases for each variance?

Like, if my View path was /animals/% you would just make aliases for /animals/cats to just /cats, /animals/dogs to /dogs.

Then you went and changed the view path from /animals/% to /creatures/% and you wonder why your aliases no longer work?

If that's the case it's because aliases are static and don't know when the thing they are aliasing changes. You'd have to go back and correct your aliases so they now point to /creatures/% since that's now the path your view is operating on as /animals/% no longer exists.

---
Tags: views, path-aliases
---


# Question
Title: Hide CCK fields for users without references with node
I have a role "worker".
I have one content type "task" that can be viewed just by "workers".
"Task" has 3 fields:

1. field-A: a user reference field to select a "worker" user;
2. field-B: one textfield that can be view from any "worker";
3. field-C: one textfield that can be view just from "workers" related to the node using field-A.

How can I set permissions to let users view just the fields they are allowed to?
Content\_permission just has a per role granularity, so I can't use it in a dynamic context and with many categories.
User Reference Access just set permission to the whole node.
I'm looking for something like Taxonomy Access, but with a per field granularity.

# Answer
Have you checked the Field Permission module which allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 1 votes

---
Tags: 6, entities, users, taxonomy-terms
---


# Question
Title: Views: Return the nodes either side of current node
Is there a way in views to return 1 node that was published before the current node being viewed and the 1 node after?

Currently I have a view using a contextual filter which is the current NID from URL but I can't find a way to pass that to the filter criteria.

Is it possible? It can be split in to 2 views if needed so in 1 I get the previous node and the other I get the next one.

e.g.

current nid = 2

View returns 1, 3

# Answer
You can use Previous/Next API to get the previous and next nodes of particular nodes. It also provides Views plugin to display Previous/Next links in View.
> 0 votes

---
Tags: views
---


# Question
Title: Node reference to show only author of node
I have create two content types as Game and Video. For the Video content type, I have created a node reference field that will be referring to the Game type.

Suppose I have 2 users (e.g. user1, and user2) on my site. User1 has created the following nodes:

* Game1 (content type: Game)
* Game2
* Game3

User 2 has created the following nodes:

* Game4
* Game5

Suppose User1 is going to create one Video node. On the node reference selected list, I just want to see Game1, Game2, and Game3, but it is displaying all Games.

How can I solve it?

# Answer
> 1 votes
Use views integration option in Node Reference Field Settings... You can connect the node reference results with the view results.. When you edit node reference field settings you can see the setting to select view with which Reference Field pulls results...

You need to build a view first that will display all games created by logged in user... Then select this view in node reference field settings....

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


title: Adding autocomplete to a CCK text field

text:
# Question
Title: Adding autocomplete to a CCK text field
I have a form with a field which I would like to be an autocomplete field.

I've tried the form\_alter hook:

```
function autocomplete_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == office_node_form) {
    $form['field_office_name'][0]['#autocomplete_path'] = 'autocomplete';
  }
}

```

The autocomplete path is correct because I use it elsewhere for another field in another form but the field it's not working as autocomplete.

Anything else I should change in the form\_alter hook in order to make it work?

# Answer
Why don't you try Autocomplete Widgets for Text and Number Fields

This module adds 3 autocomplete widgets for CCK fields of type Text and Number.

* Autocomplete for allowed values list: This widget can be used for Text and Number fields and it takes candidate values from the defined list of Allowed values of the fields. You can even generate your allowed values list using PHP, so the limit to provide a widget with autocomplete features is your imagination!
* Autocomplete for existing field data: This widget can be used for Text only and it takes candidate values from existing values in the database for that field.
* (7.x only) Autocomplete for predefined suggestions: This widget can be used for Text only and allows an admin to provide a list of suggestions but still allows users to enter anything they want in a text field. Use this widget to help avoid (but not prevent) variations of the same value. Ex: burger, hamburger, Burger ...
* (7.x only) Autocomplete for existing field data and some node titles: This widget works just like the "existing field data" widget above except it will also suggest node titles for nodes of a specific content type(s).
> 3 votes

# Answer
Replace your code:

```
$form['field_office_name'][0]['#autocomplete_path'] = 'autocomplete';

```

With:

```
$form['field_office_name'][0]['value']['#autocomplete_path'] = 'autocomplete';

```
> 3 votes

---
Tags: entities, ajax
---


# Question
Title: Advice: change the name of the author by his role in a comment
I would like to have some advice about my preprocess function i made this morning.

My goals was to replace the name by the role of the author in a comment.

I have many questions because i think my code isn't optimize and i would like to improve it:

* I don't know, as a beginner, if it's better to do what i want to achieve in a module or in a preprocess function?
* I used this path to change the comment author name : `$variables['author']` It works but is it this variable we have to use if we want to alter the comment author.
* I made my request inside my preprocess function, is it good to do that? I have only few comments for now, but when i'll have hundred of comments, do you think i'll have a problem of performance? Is there a way to improve it?

```
function bartik_extended_preprocess_comment(&$variables) {
 $result = db_query("SELECT users.uid AS uid, role.name AS  role_name
              FROM {users} users
              LEFT JOIN {users_roles} roles_id
                ON (( (users.uid = roles_id.uid ) ))
              LEFT JOIN {role} role
                 ON (( (roles_id.rid = role.rid ) ))
              WHERE (( (users.uid = :uid ) ))", array(':uid' => $variables['elements']['#comment']->uid));
$store = array();
foreach ($result as $row) {
  $store['uid'] = $row -> uid;
  $store['role'] = $row -> role_name;
}

if($variables['elements']['#comment']->uid == $store['uid']) {
   $variables['author'] = check_plain($store['role']);
}
}

```

Thanks,

# Answer
> 1 votes
1. Module VS preprocess function - modules can use preprocess functions as well. I guess that the question in your case is whether or not to do the changes in a custom module or theme. It's up to you, but generally speaking, keep the specific UI improvements in the theme and let the module do the hard work you will need in any case (if you change the theme for example). Also, it's better to pack the things you might need somewhere else in a module as it's easier to drop it to another site.
2. You can load the user object with `user_load($uid);`. This will also load all roles with role IDs and names. I suggest installing Devel and calling `dpm($user);` to have a better understanding of what you get in the user object.
3. If by request you mean database request - yes, it's alright, if there's not a way to do so already. As I mentioned in 2. you can use user\_load function - this will reduce the code and also load the user object from cache. I think that Drupal already called user\_load for rendering the comments, so calling it again will just get everything from cache and won't impact performance.

Hope this helps.

---
Tags: 7, comments
---


# Question
Title: What is the best practice to exchange variables between page calls
I am trying to display a list of objects related to my custom node, by showing one node on the node's page and also giving a "next" button which will call the same page but with the id/index of the next objects to display.

Is there a custom/better way to do it than with a GET parameter added to the url of the page call and then the reading of this parameter in the template file via `$_GET[]`?

# Answer
You should never read the value of the `$_GET` param in a template file directly, that logic should be separated out into a process/preprocess function.

Other than that, no...there isn't really anywhere 'better' for page parameters to go. The alternatives are to use something session based, or to set something up to POST variables to the second page. Or use temporary database storage which seems like overkill for this.

Your use case sounds like the archetypal situation where URL parameters would be acceptable. For example, it's the same way Drupal core handles paging (the `page` parameter is added to URLs).

If you're worried about separating these pages up for SEO benefit, that's a different matter, and you should look at creating unique paths for each piece of content (provided of course that the page changes enough to not be seen as a duplicate with the URL parameter available).
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Computed field module: value of field when creating new content
for my content type I have this computed field code and when I update existing node everything is ok, but when I create new node, menu\_get\_object return empty values and drupal display this error message "EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7562 of /var/www/dev/testpage/includes/common.inc)." and nothing was saved. When I used dpm() in devel it show me that after creating new content $node is empty, but when I update node created before everything is OK.

```
$node = menu_get_object();
$start_time = field_get_items('node', $node, 'field_start_time');
$start_time = $start_time[0]['value'];
$entity_field[0]['value'] = '$start_time';

```

thanks a lot for your reply

# Answer
> 1 votes
> menu\_get\_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu\_get\_object() will return that.

From: http://api.drupal.org/api/drupal/includes!menu.inc/function/menu\_get\_object/7

It returns empty upon creation because you add the node from "node/add/\[content-type\]" page but update it from "node/\[nid\]" and it can use the nid to load the node.

If you need just to duplicate the value from the start\_time field of the same node, use this:

```
$entity_field[0]['value'] = $entity->field_start_time[0]['value'];

```

---
Tags: entities
---


# Question
Title: How can I add an entity reference to a list entity refences of a node with rules?
I have a node with a entity reference field with multiple values.

How can I add an entity reference to a this list with rules?

# Answer
> 1 votes
You didn't post your setup and where you want to trigger the rule, but you would do this with PHP code added as a rule action:

```
$node = node_load(YOUR_NODE_ID);
$node->field_you_want_to_save[]['target_id'] = NEW_ENTITY_REFERENCE_ID;
$node->save();

```

---
Tags: rules, entities
---


# Question
Title: Adding additional option under node publish options
In add /edit node page under publish options there are four option available

Published Promoted to front page Sticky at top of lists Create new revision

Is there a possibility to add a 5th one for example Active and can use that option in views so that only the nodes which are they appear other nodes must not.

I am a themer not a coder so, I would really appreciate if your answer can also contain the code or reference or descriptive how to steps.

Thanks in advance

# Answer
I think you can do it without adding the 5th option, if you familiar to Views module, and Taxonomy module, you can simply add vocabulary(in Taxonomy configuration) and add Term - for example *Active*, next you can add field to your Content Type(Article or whatever) and now if you want to post an article you can chose - Active term. Next step, create new view, add whatever you want(body, title, etc) and in Views/**Contextual filters** add new filter -\> *has Taxonomy term ID* input the Active id, and now you are done.
> 1 votes

---
Tags: views, hooks, users, nodes
---


# Question
Title: Can I highlight an invalid form field without assigning a message for it?
I have a form which presents three input fields which are later combined into a single phone number. When that phone number doesn't validate (doesn't match `/^\d{10}$/`), I want to show a single message saying the phone number is incorrectly formatted, but I want to highlight all three input fields. Is this possible? The best I have come up with is this:

```
form_set_error('firstBox', $theMessage);
form_set_error('secondBox', " ");
form_set_error('thirdBox', " ");

```

This way, all fields are highlighted and I get the message only once, but I still get bullet points for the *empty* messages...

Is there a better solution for this?

# Answer
D'oh. In Drupal 6 at least, just call form\_set\_error(FIELD) without the message and it should highlight the field and not set a message. You are sending a space, so you are getting a space as a message.

Code in Question:

```
function form_set_error($name = NULL, $message = '', $reset = FALSE) {
  static $form = array();
  if ($reset) {
    $form = array();
  }
  if (isset($name) && !isset($form[$name])) {
    $form[$name] = $message;
    if ($message) {
      drupal_set_message($message, 'error');
    }
  }
  return $form;
}

```
> 1 votes

---
Tags: 6, forms
---


title: Why is search cron so slow?

text:
# Question
Title: Why is search cron so slow?
Search cron on my sites takes about 2-3 minutes, no matter how frequent I run it. I was under the impression only new nodes added since the last run get added to the index. Apparently it's working differently?

Would a SOLR search index update be quicker?

# Answer
Check how many nodes you are indexing per cron run. If the number is high, it will definitely take more time to process.

On the other hand, the search cron shouldn't take that long if there are no nodes to index. You can always check the number of not indexed nodes at search settings (admin/config/search/settings). If the number is 0 and search cron still takes that long, you might be having some problems or something else is causing the issue.

Take a look at Elysia cron for fine tuning when, how often and what is executed.

And regarding your last question - as far as I remember SOLR is doing that in the background - so yes, the search index update will be quicker.

\[EDIT\]

Thinking about this - it might have to do with the number of fields (because it invokes node\_load on every node) and on the length of the body field.
> 1 votes

# Answer
One quirk that I have run into is that everything that happens during a `node_load` and `node_view` happens during indexing. Take a look at `_node_index_node` start tracing backwards to see the process.

This means that any expensive operations that happen when a page gets viewed also happen when a page gets indexed.

For example, I had a site a while ago that queried an external webservice during `node_load` and I also noticed that search indexing was **slow**. In my instance, the external webservice calls were adding up and not needed during indexing. I solved it by doing something like

```
function foo_node_load ($nodes, $types)
{
  if (arg(0) != "node") return;

  // rest of hook
}

```

So, I would take a look at what else could be going on in your hooks and preprocess/process functions that could be slowing the process.
> 3 votes

---
Tags: 7, search, cron
---


title: Display node title in view comment type

text:
# Question
Title: Display node title in view comment type
I have created a view (using views 2) with type = comment (displaying comments). Now i can display comment author, comment post date fields, but i can't create a node title field which belongs to comment.

Tried using views customfield, but `$data` variable isn't allowed here, only `$comment` variable. Please throw me in a right directions, thanks.

# Answer
Try setting up a new Relationship within the View.

1. Add a new relationship to "The node the comment is a reply to."
2. Check box that "requires this relationship"
3. You should now be able to add a new field for the node title
> 2 votes

---
Tags: views
---


# Question
Title: Show only specific fields on Edit page when a Term is selected
How do I show on (content type) Edit page only specific fields? For example if I have selected the Laptop term then I should see Procesor, RAM and HDD fields and if I select TV term then I should see Screen size, Brand, Screent type fields.

# Answer
conditional fields is very powerful you can achieve your need with it. read **README.TXT** file carefully
> 2 votes

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


# Question
Title: Peer-to-peer recognition system using User Points and Rules modules
I would like to build a recognition system in the team where peers can recognize the effort of each other. I'm using User Points module.

**For example:**

1. UserA recognize the testing effort done by UserB.
2. UserA login to the recognition system and add 1 point to UserB in "Tester" category.
3. UserA get 1 point in "Supporter" category since he's recognizing others' effort.

**The problem:**

1. How to limit the points to be only +1; not more, not less, negative values shouldn't be allowed, more than 1 is not allowed.
2. How to automatically add +1 point to UserA who add point to UserB. I tried using Rules module but it always refers to the UserB.

# Answer
> 0 votes
To solve problem #2:

> How to automatically add +1 point to UserA who add point to UserB

In the rule Do section:

1. First, add action "Load current user account" and set User Id: \[:global:user-id\]. Name it as "Current user".
2. Then, in the "Grant points to a user", refer to "Current User" as User argument

---
Tags: 6, rules, userpoints
---


# Question
Title: Pass value of a field to another content type in Drupal 7
I have a content type 'Exhibit' with fields 'uuid'(text with single value), 'name'(text with single value), 'description'(long text and summary), 'section'(text with unlimited values). I have used views to display 'Exhibit' in table format.

Now when i click on Add section. I want the field Section in Exhibit view to be uuid values in Section content type. I want the uuid values as a drop down . so that customer can select one uuid and enter the details for that uuid. How can i achieve this? Please help.

# Answer
> 3 votes
I think it would make sense if your 'exhibit' content type references sections, which are themselves nodes (through nid reference fields) or through a reference field on the section that points back to the exhibit. Then you can build the view with relationships to look however you want.

The point of having everything be a node is that you can take advantage of a lot of built-in functionality, as well as a lot of contrib modules which are **geared towards nodes**.

So if you create the structure as I mentioned above, you can add sections to exhibits with this module: Node Reference URL, which allows you to automatically fill in the nid reference field.

Does that work?

---
Tags: 7, entities
---


title: Mass translate taxonomy terms

text:
# Question
Title: Mass translate taxonomy terms
I have around 400 taxonomy terms; very complicated hierarchical stuff.

I wonder if anyone knows about a plugin (taxonomy manager style) that can help me do it without having to dive into taxonomy and translated one by one.

Thanks !

# Answer
> 2 votes
Translation Table:

> This module presents your taxonomy terms or menu items in a table, and each language has a corresponding column. Just fill out the translations and click Save.

---
Tags: taxonomy-terms, i18n-l10n
---


title: URL tags not converted to <a> HTML tags

text:
# Question
Title: URL tags not converted to <a> HTML tags
I have been using CKEditor, but didn't like the table editing capabilities so attempted to move to TinyMCE. Having done this, all links now appear as plain text in the following format :

```
[url=http://somedomain.com/page]Page[/url]

```

It looks as if a filter has been dropped, or it is incorrectly configured, but I don't know how, or why. Can anybody help?

# Answer
> 1 votes
Disable the *BBCode* plugin in Tinymce settings.

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


# Question
Title: How to prevent from getting spammed in a contact form
I have the captcha image module and an email address keeps spamming me in a website feedback contact form. I do not know how to get their IP address and I do not want to take down the form for the public. Any suggestions?

# Answer
That is why Mollom exists: http://drupal.org/project/mollom

> Mollom may block a post outright if it is from a known spammer. If Mollom is unsure how to classify a post, it may require the completion of a CAPTCHA to accept the post. Posts that do not match a "spammy" text pattern and do not originate from known spammers are accepted without the need to complete a CAPTCHA.
>
> A stand-alone CAPTCHA solution, which neither considers user behavior nor point of origin, can never achieve this level of informed protection, and generally requires users to solve a CAPTCHA on every post. Using Mollom's text analysis, users must only solve CAPTCHAs when Mollom is unsure about a post.
> 4 votes

# Answer
Try the reCAPTCHA module. It's worked brilliantly for me.
> 2 votes

# Answer
You can try out the Honeypot module. It basically adds a hidden field to your forms, and then makes sure it is empty upon submission.
> 2 votes

---
Tags: forms, advertising
---


title: Content type always use view

text:
# Question
Title: Content type always use view
So I have a content type called `MyContentType` and two views: `mycontents` and `mycontent/%`.

`mycontents` shows all `MyContentType`s with a pager. `mycontent/%` shows a single `MyContentType` based on node id.

How do I make it so when clicking on a content's header in `mycontents` (or any other way of displaying `MyContentType`) takes it through to `mycontent/[nid]`?

# Answer
> 3 votes
Use Views 'rewrite output' feature for the `Field: Title` field on your `mycontents` view.

First, make sure you have added the `Content: NID` field to your view. If you don't want this to be visible on your View, you can 'Exclude it from display\` as noted in the graphic below.

You will also need to reorder your views fields to ensure `Content:NID` is listed before your title so you can access it in the next step.

It's very important to to note that the `Content: Nid` field is *above* the `Content: Title` field.

Next, edit `Content: Title` and scroll down to and open the 'Rewrite Results' section.

Note: You may need to uncheck the 'Link this field to the original piece of content' checkbox for the `Content: Title` field.

In the 'Rewrite Results' section, check the box titled 'Output this field as a link.' In this section, if you scroll down, you will see a link titled 'Replacement Patterns.' This is where we will get the variables we need for our URL.

In the 'Link Path' box, enter your destination URL: `mycontent/[nid]`

Don't forget to save your view, but your titles should now be linked properly.

---
Tags: 7, views
---


# Question
Title: How do I limit a particular search result from being indexed
I have a content type called "product". This "product" has an on/off checkbox to flag whether or not the product in question is able to be viewed on the web. I would like to index only the products that have this "web\_catalog" field turned on. I have tried using preprocess\_search\_result to limit the returned result to no avail. Any ideas or suggestions would be greatly appreciated, thank you.

# Answer
I wanted to thank everyone for their input. In the end we created a small module that will alter the query instead of trying to alter the index of the site. To do this we utilized hook\_query\_alter() to add a subquery to the search. Below is the final version of our hook for reference should someone else have a similar issue.

```
function product_view_display_query_alter(QueryAlterableInterface &$query) {
  $is_search = FALSE;
  $tables =& $query->getTables();
  foreach($tables as $table) {
    if ($table['table'] == 'search_index') {
      $is_search = TRUE;
    }
  }
  if ($is_search) {
    $subquery = db_select('field_data_product_web_catalog','pwc')->fields('pwc',array('entity_id'))->condition('product_web_catalog_value',1);
    $query->condition('n.nid',$subquery,'IN');
  }
}

```
> 2 votes

# Answer
Maybe not publishing the node can help you. It wont appear on your search results, or anywhere on your site to the "end users". Administrators can still view the unpublished content, but it wont appear for the normal users.

OR:

You can do this with Views. In your view use the "Filter Criteria" to show only the products that have their "web\_catalog" field checked. And even the Administratos wont see the hidden products.

It seems like you are new into Drupal and Views is the most installed module for drupal. You must learn it so you can unleash the true Drupal power. Seach on youtube about views tutorials or visit this page http://nodeone.se/en/taming-the-beast-learn-views-with-nodeone.
> 0 votes

---
Tags: search
---


# Question
Title: Change drupal font color based on variables
I had a content type=score This "score" content type had "field 1", "field 2" in integer. Can I customize the font color based on variables.

ex: when the users fill in \<50 then show red color, When the users fill 50-70 then show orange color, When the users fill \>70 then show green color.

Any contributed modules can do that function? Thanks

# Answer
Yes, you can achieve this with jQuery.

In a custom module add the following code.

```
function custommodule_form_alter(&$form,$form_state,$form_id) {
  if ($form_id == "yourcontent type form") {
    $form['field_field1']['#attributes'] = array('id' => 'field1_id');
    drupal_add_js(drupal_get_path('module', 'custommodule') . '/jsfilename.js', ));
  }
}

```

Put this in jsfilename.js.

```
(function($) {
  Drupal.behaviors.custommodule = {
    attach: function (context, settings) {
      // I suppose your field1 html elemet ID=field1_id
      $('#field1_id').change(function() {
        if($('#field1_id').val() < 50) {
          $(this).css("color","yellow"); // you can add class to it and in css file style it  ex:$(this).addClass('class1');
        }
        else if($('#field1_id').val() > 50 && $('#field1_id').val() < 70) {
          $(this).css("color","red");
          $(this).css("color","yellow"); // you can add class to it and in css file style it  ex:$(this).addClass('class1');
        }
        // …
      });
    }
  }
}

```
> 1 votes

---
Tags: javascript, theming
---


title: Printing a term using custom formatter

text:
# Question
Title: Printing a term using custom formatter
On a custom template for a taxonomy view, I want to render the current term (the one being viewed) using my custom taxonomy term formatter, how do I do that?

I have looked at the `field_view_field` function, but it's not clear to me how I would use its parameters `field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL)` \- esp. the `$field_name` part is not clear. I am afraid this is not the right function... Any help please?

# Answer
> 1 votes
if you want apply specific display formatter to some field like taxonomy terms, the best way is to write a display formatter module, and apply it to your entity\_type via display setting on specific view mode, so if you want do this completely programmatically you need:

1. write display formatter moule
2. define view mode if necessary (e.g. for node we have `full`, `teaser` and ...)
3. add configuration to field instance setting

if you need some sample code to write display formatter module, let me know...

EDIT: if you want pass field instance setting to `field_view_field` you have something like this:

```
$display = array(
    'label' => 'hidden',
    'type' => 'colorbox',
    'settings' => array(
        'colorbox_node_style' => 'simpledeal_company_medium',
    ),
);
field_view_field($entity_type, $entity, $field_name, $display, $langcode = NULL);

```

this example code is about colorbox display formatter, should be replaced by yours

to do above via admin you should go to vocabulary display setting `admin/structure/taxonomy/VOCAB_NAME/display`, in `CUSTOM DISPLAY SETTINGS` check `Taxonomy term page` and set your display formatter, in this way you may do not need to change taxonomy-term.tpl.php

# Answer
> 0 votes
Use a helper module like Custom Formatters. Here is a quote about it (from the module's project page):

> ... allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.

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


# Question
Title: Change node author on node save with rules
I have a very simple rule with **Event** "*Before saving content*" and **Elements** "*Content is of type* (page)" and would like the action to be something similar to "*Change node author to UID X*", which would be the UID I want.

I can't seem to be able to achieve that with the actions exposed. To test my rule I've been trying to display a message on the site when triggering the rule and it works just fine.

Any idea how to do that without having to write code?

This is on Drupal 7 (latest) with latest stable Rules version.

# Answer
I think you can do this by adding a new action - "Fetch entity by ID", then selecting users and using that to update the node.
> 5 votes

# Answer
I have a suggestion for you for achieve this.(Its tested by myself).
create a new rule and in create node event(or every event you want ) , in action use *Php*(Execute custom PHP code)(make sure you php filter module installed).
and in there write this

```
 $mynode=node_load($node->nid);
 $mynode->uid='user_id_want';
 node_save($mynode);

```

**-------------update------------**
put your user id instead 'user\_id\_want'; as example

```
   $mynode=node_load($node->nid);
   $mynode->uid=20;
   node_save($mynode);

```
> 1 votes

---
Tags: rules
---


# Question
Title: Global variable, visible only inside the module
I have several modules, that implement very close functionality. And the SQL requests are almost the same, except for the table name. So I wanted to create a global variable, inside each module:

```
$GLOBALS['module_name'] = __FILE__;
$regexp = "/.*" . "\\" . DIRECTORY_SEPARATOR. '(.*)\.module/';
$GLOBALS['module_name'] = preg_replace($regexp, '$1', $GLOBALS['module_name']);

```

$GLOBALS\['module\_name'\] will contain the current file name, which is the same as name of the table.

And then use it in the requests:

```
$query = db_select($GLOBALS['module_name']);

```

But global variables are shared among the modules, and the definition from a different module rewrites the correct value.

I tried to use hook\_init

```
function my_module_init()
{
   $GLOBALS['module_name'] = __FILE__;
   $regexp = "/.*" . "\\" . DIRECTORY_SEPARATOR. '(.*)\.module/';
   $GLOBALS['module_name'] = preg_replace($regexp, '$1', $GLOBALS['module_name']);
}

```

But without success.

Is it possible to have global variables with the same name in many modules, but each will be visible only inside the appropriate module?

# Answer
If you use the same global variable, its value is shared between all the enabled modules because global variables are globals by definition. Every PHP file that is loaded will see the same global variables, such as the global `$user` that is used from Drupal for the account of the currently logged-in user.

The same is true if you use constants defined with `define()`; they are global, and two modules cannot define the same constants. Try defining the `REQUEST_TIME` in Drupal 7, with `define('REQUEST_TIME, 'test')`: You will get an error, as the same constant is already defined from Drupal (see REQUEST\_TIME).

The same is true for Drupal variables defined with variable\_set(). Every module that is using `variable_set($name, $value)` (where `$name` has the same value for all the modules) is setting the same variable.

Even if you would be using &drupal\_static($name, $value) in different modules, the modules will be altering the same static variable.

I would rather use a constant defined with `define()`, but every module needs to use a different constant.
See the Drupal coding standards about naming conventions.
> 4 votes

# Answer
why you dont use `variable` ? `variables` is good feature in drupal and working wth them is safe and easy.

variable\_set('module\_name',**FILE**); variable\_set Doc

and those variable provide everywhere you want just need get them

variable\_get($name, $default = NULL);

variable\_get Doc

I suggest you use `variabled` instead global variables.
> 0 votes

---
Tags: 7
---


# Question
Title: User to send a list of selected nodes via e-mail to the admin
I would like the users on a site to be able to select certain nodes and send a list of those nodes to one specific e-mail address.

Gathering the nodes is easy with Nodequeue or Flags, so is sending a mail with Action when a node is flagged. The problem is sending an email with the list when the user want to, when the list is final.

Do you know any solid solution for this problem?

# Answer
> 2 votes
If you don't have a custom module created yet, make one (always good to have at least one custom module for misc tasks).

Create a menu callback for sending the node information in you hook\_menu().

```
function hook_menu(){
  return array(
    'user/%/sendNodes'=>array(
      'type'=>MENU_CALLBACK,
      'page callback' => 'hook_send_nodes',
      'page arguments' => array(1),
    ),
  );
}

```

Create the callback function to send the nodes.

```
function hook_send_nodes($uid){
  // Fetch all flagged nodes from database for this $uid.
  // Send this node information through drupal_mail().
  // After your nodes have been sent, use drupal_goto().
}

```

So now, you can create a link to the URL user/UID/sendNodes and that will send the nodes. Obviously this is all pseudo-code, but the idea is there.

# Answer
> 1 votes
I don't know a posible way with a module.

Wha I will do is this.

In a module I will build a form to send the nodes. To build this module Only need hook\_perm hook\_menu a form with a submit button. Flag to all the modules you want to send. Hook\_mail to send the mail with the nodes. And take a look at flag to "un -flag" all the nodes sends by that person.

It's not easy, and you have to build you own module

Oskar

# Answer
> 0 votes
I think your idea is the best one.

You can take a look at newsletter, and use rules to send the newsletter to a e-mail. Also can use views into the newsletter to get all the nodequeue.

Oskar

# Answer
> 0 votes
Have you tried with Views Send module ?

Create a view and add at least one column containing e-mail addresses.

Create a "Page" display and set the style to "Bulk Operations". On "Bulk Operations" style configuration, under "Selected operations", select Send mass mail (views\_send\_mail\_action). For Drupal 7 Add the "Global: Send E-mail" field to your view. This field provides the checkboxes that allow the user to select multiple rows.

Create a "Page" (or "Block") display. Save the view, load the page, use exposed filters to build the list, select all or some rows and choose "Send mass mail".

Fill the message form to configure the E-mail. Use tokens to personalize your E-mail. The module provide also row-based tokens, taken from the current row of the view. For example, if the view has a column with the key users\_name (the user name) you can use this replacement token **\[views-send-users\_name\]**. Preview and send the message.

---
Tags: nodes
---


# Question
Title: Single on/off checkbox default value not work
I have a boolean user profile field which is single on/off checkbox, says 'field\_user\_flag'. Its **On** value is 1 and **Off** value is 0. But I could not set `#default_value = 1` from `hook_form_alter` to save "1" into its table `field_data_field_user_flag` and `field_revision_field_user_flag`.

When it is 0 and unchecked in user/\*/edit, I would like to set it to 1 and checked. Thus, I did it in my hook\_form\_alter as below.

```
$form['field_user_flag']['#default_value'] = 1;
$form['field_user_flag']['#attributes'] = array('checked' => 'checked');

```

But, it did not work. I created the field in account settings (admin/config/people/accounts/fields/) without using Profile 2 module.

# Answer
> 3 votes
I tested it and worked for me:

```
$form['field_user_flag'][LANGUAGE_NONE]['#default_value'] = 1;

```

You can also set a default value of this field (in field settings in field managment).

---
Tags: 7, entities
---


# Question
Title: 3 Level dependent dropdown. The 3rd list won't update while first one changes
I am trying to create a 3 level dependent dropdown select.

Lv1 Options \> Lv2 Options \> Lv3 Options.

e.g: AUDI \> Coupé \> A5

BMW \> SUV \> X5

I followed Examples module and this answer to create a custom module. (I know there is Hierarchical Select module does the job, I prefer do it with custom module)

My problem is that when level 1 option selected, level 2 options DID update, however, level 3 options DID NOT update to reflect level 2's change. I have to manually pick an option in level2 to make level 3 update.

Ideally, if level 1 dropdown select updated, level 2 options will update and level 3 options should also update.

Here is my code, dependent.module :

```
<?php

/**
 * Implementation of hook_menu().
 */
function dependent_menu(){
  return array(
    'dependentselect' => array(
      'title' => 'A page to multi level dependent select',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('dependent_page'),
      'access callback' => TRUE,
    )
  );
}

/**
 * A form with a dropdown whose options are dependent on a
 * choice made in a previous dropdown.
 */
function dependent_page($form, &$form_state) {
  // Get the list of options to populate the first dropdown.
  $options_first  = dependent_first_dropdown_options();
  $options_second = dependent_second_dropdown_options();

  $value_dropdown_first  = isset($form_state['values']['dropdown_first'])  ? $form_state['values']['dropdown_first']  : key($options_first);
  $value_dropdown_second = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : key($options_second);

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'First Dropdown',
    '#options' => $options_first,
    '#default_value' => $value_dropdown_first,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'dependent_first_ajax_callback',
      'wrapper' => 'dropdown_second_replace',
    ),
  );

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Second Dropdown',
    // The entire enclosing div created here gets replaced when dropdown_first
    // is changed.
    '#prefix' => '<div id="dropdown_second_replace">',
    '#suffix' => '</div>',
    '#options' => dependent_second_dropdown_options($value_dropdown_first),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'dependent_second_ajax_callback',
      'wrapper' => 'dropdown_third_replace',
    ),
  );

  $form['dropdown_third'] = array(
    '#type' => 'select',
    '#title' => 'Third Dropdown',
    // The entire enclosing div created here gets replaced when dropdown_first
    // is changed.
    '#prefix' => '<div id="dropdown_third_replace">',
    '#suffix' => '</div>',
    '#options' => dependent_third_dropdown_options($value_dropdown_second),
    '#default_value' => isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : '',
  );

  return $form;
}

/**
 * Selects just the second dropdown to be returned for re-rendering
 *
 * @return renderable array (the second dropdown)
 */
function dependent_first_ajax_callback($form, $form_state) {
    return $form['dropdown_second'];
}

/**
 * Selects just the second dropdown to be returned for re-rendering
 */
function dependent_second_ajax_callback($form, $form_state) {
    return $form['dropdown_third'];
}

/**
 * Helper function to populate the first dropdown. This would normally be
 * pulling data from the database.
 *
 * @return array of options
 */
function dependent_first_dropdown_options() {
  return array(
    'colors' => 'Colors',
    'animals' => 'Animals',
  );
}

/**
 * Helper function to populate the second dropdown.
 *
 * @param key. This will determine which set of options is returned.
 *
 * @return array of options
 */
function dependent_second_dropdown_options($key = '') {
  $options = array(
    'colors' => array(
       'red' => 'Red',
       'green' => 'Green',
       'blue' => 'Blue'
    ),

    'animals' => array(
      'dog' => 'Dog',
      'cat' => 'Cat',
    ),
  );

  if (isset($options[$key])) {
    return $options[$key];
  } else {
    return array();
  }
}

/**
 * Helper function to populate the third dropdown.
 *
 * @param key. This will determine which set of options is returned.
 *
 * @return array of options
 */
function dependent_third_dropdown_options($key = '') {
  $options = array(
    'red' => array(
    'darkred' => 'Dark Red',
    'lightred' => 'Light Red',
    ),

    'green' => array(
      'darkgreen' => 'Dark Green',
      'lightgreen' => 'Light Green',
    ),

    'blue' => array(
      'darkblue' => 'Dark Blue',
      'lightblue' => 'Light Blue',
    ),

    'dog' => array(
        'bigdog' => 'Big Dog',
        'smalldog' => 'Small Dog',
    ),

    'cat' => array(
        'bigcat' => 'Big cat',
        'smallcat' => 'Small Cat',
    ),

  );

  if (isset($options[$key])) {
    return $options[$key];
  } else {
    return array();
  }
}

```

# Answer
Just went through the docs again, realize that since I want to manipulate multiple elements.

I should use a 'bigger' wrapper for ajax replace.

> You can easily replace the entire form if that is easiest. Just add a
>
> # prefix and #suffix to the entire form array, then set that as the #ajax\['wrapper'\]. (This will allow you to change multiple form elements via a single ajax call.)

-- http://drupal.org/node/752056
> 0 votes

# Answer
You've set #ajax callback event as **'changed'**, but it is not called for the 2 element after it changed, because your ajax callback returns the whole element(changed event is envoked only if you change selected option). I'm not sure about proper solution, but as for me, I would have either added custom JS to change element after update, or experiment a little with changing #options for select. One more variant is to return both form selects on first one change.
> 1 votes

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


title: nothing return using select statement

text:
# Question
Title: nothing return using select statement
I'm using this code in a views PHP field and I can't figure out how to select a column using a date condition

```
$year = $_GET['field_mstudent_date_value']['value']['year']; //get the year from date filter

$month = $_GET['field_mstudent_date_value']['value']['month']; //get the month from date filter

if (strlen($month) == 1) {
    $month = '0' . $month;
}

$resault = db_query("SELECT entity_id FROM {field_data_field_exp_date} WHERE
  YEAR(field_exp_date_value) = $year
AND MONTH(field_exp_date_value) = $month
AND revision_id = $entity_id;"); //field_exp_date_value is date field yyyy-mm-dd hh:mm:ss format

foreach ($resault as $value) {
    echo $value->entity_id;
}

```

Why do I get no results?

# Answer
> 2 votes
According to MySQL Docs the `MONTH` function does not return zero-padded values for single-digit months. Your code tries to use zero-padding, however. In case you really would like to use zero-padding, you should use quotes around your condition value.

Additionally, you don't specify in your code sample where you get the `$entity_id`, so what kiamlaluno said in his answer (now deleted) about the entity ID being different from the revision ID might well be valid as well.

A good starting point is to use a more generic tool for database access, for example `drush sqlc`, to debug your query.

As for putting variable values into the query without using placeholders, I have to agree with kiamlaluno: You open up for SQL injections.

---
Tags: 7, database
---


# Question
Title: Can you create new users without entering email, then prompt user upon first login?
I want the site administrator to be able to create a user, submitting only a username and a dummy password.

This information would then be 'manually' sent by the administrator to the user, whom upon their first login, is forced to enter a verification email and change their password.

How can this be done through modules or otherwise?

# Answer
Use Force Password Change module.

This module allows administrators to force users, by role, individual user, or newly created user, to change their password on their next page load or login, and/or expire their passwords after a period of time.
> 6 votes

---
Tags: users
---


# Question
Title: Why variable_get() returns all values of checkboxes list, even if checkbox is not selected?
I have checkboxes list in system settings form:

```
$form['mymodule_menu_perm_menus'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Menus'),
    '#options' => menu_get_menus(TRUE),
    '#default_value' => variable_get('mymodule_menu_perm_menus', array()),
);

return system_settings_form($form);

```

I submit this form with two checkboxes selected.

But on other page `variable_get('mymodule_menu_perm_menus'`) return all values :/

Clearing cache doesn't help

# Answer
Because Drupal doesn't actually filter out empty checkboxes values, it sets them to zero. I think this is so you get an accurate representation of what options were available when the form was submitted, and what was actually chosen by the user.

It's easy to get the filtered array though, using `array_filter()`:

```
$values = array_filter(variable_get('mymodule_menu_perm_menus', array()));

```
> 6 votes

---
Tags: 7, forms, configuration
---


# Question
Title: How to alter menu parent select list on node form?
I would like to modify select list for choosing menu parent for creating node (from the Menu tab). I am looking in `$form` variable but I don't see this list data. How can I alter this select list?

# Answer
> 1 votes
Menu module does form alter to add the Menu Fields to the node creation form using function menu\_form\_node\_form\_alter in menu.module

Check your custom module weights to catch this data in your custom module to do form alter...

There is a new drupal 7 API called hook\_module\_implements\_alter() which lets you alter the execution order for a given hook WIHOUT altering the module weights table.

---
Tags: 7, forms, routes
---


title: Add a gallery for every user in a block

text:
# Question
Title: Add a gallery for every user in a block
I want to be able to add a gallery for each user. I understand how to create a content type. I considered building an image content type. I then thought I could add a view which would only display each user.

Is this best practice for creating a gallery for each user?

I am using Drupal 7, if this makes any difference.

I can get it working in a view but it doesn't seem to work in a block

# Answer
Yes, you are on a right path. The Views module, and content types can be used to build a simple gallery for a user.

1. Create a content type called Image Gallery.
2. Add a image field to above content type.
3. Create a view called user gallery.
4. Filter by Content Type Image Gallery.
5. Filter by Node author: Logged in user, if you want to show logged in users Gallery.
6. Add the contextual filter Author UID, if you want to dynamically pass the user ID from the URL and filter the Gallery Images.
7. For above your view page path should be user-gallery/% where % will be user id.
> 5 votes

# Answer
The answer shows how you can control the output of a block so for example each user gets a different gallery. I found out this method for drupal 6 views 2. http://drupalsn.com/learn-drupal/drupal-questions/question-2650

**Drupal 6**

Here’s how i’d do it: 1) In the view admin page under arguments click on the User:name argument and scroll down the page where you’ll see some options for that argument under “Block: Configure Argument User: Name”.

2) Under “Action to take if argument is not present” select “Provide default argument” then under “Default argument type” select “PHP code” now we can enter some custom PHP code to get the username from the page URL assuming your username is the second argument in the URL ie. publications/USERNAME

3) Now in the “PHP argument code” box enter the following PHP:

Again I’m assuming the URL is publications/USERNAME and what we are saying here is if the first URL argument is “publications” and the second URL argument is not blank then use the second argument as the views username argument. 4) You should select “hide view / page not found” in the “Action to take if argument does not validate” under “Validator options” that way views will check the user exists and find the view/block is they don’t have any content.

5) Lastly save the view and assign your block to the publications/USERNAME page.

That should do it, let me know if it works, i loaded up views and tested it so should be fine.
> 0 votes

---
Tags: nodes, media
---


# Question
Title: Modules ".module" file not being called when anonymous user
I think I have a persmissions problem but I'm not sure how to resolve it.

I've made a custom block in a module called "people\_passed". When I'm logged in the block displays fine, when I'm logged out the block HTML displays but the CSS does not. I've figured out that this is because people\_passed.module is not being called and so the CSS is not displayed.

Here is the contents of my people\_passed.info:

```
name = People Passed
description = A block that shows how many people passed in the last year.
package = Other
core = 7.x
files[] = people_passed.module

```

# Answer
If your module file defines a block, but isn't being parsed, then the block wouldn't work at all; you'd get all sorts of fatal errors, not missing CSS.

You've probably got page and block caching turned for anonymous users...that'll be why your exit code doesn't run. Try clearing the caches, it should make a difference.
> 4 votes

---
Tags: 7, blocks, users
---


title: Overwrite add/edit form

text:
# Question
Title: Overwrite add/edit form
What I would like to do is to have a ?.tpl.php file in which I can write my own HTML content. A minimal example would be:

```
<div class="my-class">
      <?php drupal_render($input_label); ?>
      <br />
      <?php drupal_render($input_text); ?>
</div>

```

# Answer
As far as I know, path templates are built-in Drupal 7, so just do this:

page--node--add--blog.tpl.php (for blog)
page--node--add--story.tpl.php (for story)
etc. etc.

Clear cache!
> 1 votes

---
Tags: 7, theming
---


title: Webform custom validation red highlight

text:
# Question
Title: Webform custom validation red highlight
How can I add the red error border to a webform component programmatically?

I am doing so custom form validation when the form submits and I need to set the red border on under rules very specific to my module.

Currently, I am doing the following:

```
form_set_error('email_address', 'Please supply matching email addresses');

```

It adds an error message and stops the form from being submitted but it does not highlight the form field I am validating. That makes it difficult for the users to see the problem area at a glance

# Answer
> 2 votes
You can use Webform Validation. This module includes a lot of validations for webform elements.

Alternatively, you can code your own validation yous adding your validation function to the desired forms. Then use form\_set\_error to mark wrong element with red border.

Webform puts the fields inside a group, so if you need to mark a field as not valid you must provide the full hierarchy.

For example, for this field in $form:

```
$form['submitted']['form_contact_data']['form_contact_email'] = array(
...
);

```

You can mark it as erroneous with:

```
form_set_error('submitted][form_contact_data][form_contact_email', 'Error message');

```

In this example the filed is inside two groups: the first, 'submitted' is the main Webform group. The second, 'form\_contact\_data', is a field group created where I've placed contact data fields for this webform.

---
Tags: webforms, forms
---


# Question
Title: Multistep registration form for two roles
Goal:

I have two different user roles:

1. Borrower
2. Provider

There are 5 categories for these users to choose(they can select all if they want):

1. Market 1
2. Market 2
3. Market 3
4. Market 4
5. Market 5

Each roles have different registration forms depending on the categories they picked. Let say:

For Borrower role:

```
If Market 1:
  step one:
    form A
  step two:
    form B:

If Market 2-5:
  step one:
    form A:
  step two:
    form C:

```

For Provider role:

```
If Market 1-4:
  step one:
    form A:
  step two:
    form D:

If Market 5:
  step one:
    form A:
  step two:
    form E:

Where:
  form A = generic registration form
  form B = specific for Borrower role selecting Market 1
  form C = generic form for Borrower role selecting Market 2 to 5
  form D = generic form for Provider role selecting Market 1 to 4
  form E = specific form for Provider role selecting Market 5

```

Question: Is there any module that can do this? Any thoughts how can I achieve this using Drupal API's?

# Answer
> 2 votes
These modules might help you:

---
Tags: 7, forms, users
---


title: How do I fix these installation errors?

text:
# Question
Title: How do I fix these installation errors?
I'm installing D7 on Ubuntu 12.04. I've been following the procedure explained in this page. And this is the error I'm getting:

I've already made MySQL database called 'drupaldb'.

I've also checked PHP and it's installed and it's running. I'm configuring NGINX to run D7 on it.

Please help!

# Answer
To install gd library in ubuntu:

> $ sudo apt-get install php5-gd

Above command will install PHP gd library in Ubuntu.

Refer this question from Server Fault to install mysql-pdo driver in ubuntu
> 9 votes

# Answer
you can install LAMP server in just one command

```
sudo apt-get install lamp-server^

```

don't forget `^` after `lamp-server`. This will install the missing extensions and database support (LAMP was specially designed for PHP applications running on Apache server with MySQL database). After that you can place your drupal folder in `/var/www/`, and it should install smoothly after that.
> 6 votes

# Answer
You need to enable GD extension and PDO extension for PHP.

It might mean you need rebuild your PHP install, contact your server admin who should be able to enable those extensions easily
> 5 votes

---
Tags: 7, installation
---


# Question
Title: Is there a way to remove tabs inside panels?
This is a simple question, i know that there are many modules who can alter tab like tab tamer.

But i would like to avoid to install another module in my site because he's already slow and my server he's limited, it's why i'm asking this question.

I alter the `user template profile`, so i just want to remove the tabs : `view and edit`, i didn't find any setting to do that but maybe i missed something?

# Answer
From memory, I believe the answer is no, because the tabs are rendered outside of the area that Panels is responsible for.

If you use Panels everywhere, then you can simply leave the tabs out however, "In panels". If you don't, the rendering is probably happening in page.tpl.php instead.
> 1 votes

---
Tags: 7, panels
---


title: More than one pager in the same page

text:
# Question
Title: More than one pager in the same page
I have a Page that contains two views one that list the latest news and the other list the latest event

The problem now is that each view has a pager but when I change the page of one of them both view will change. i.e If I want to see page number 3 in news view,the event view will also change to page number 3

Is there is a way to make that even programmatically also I don't want to make it ajax because I need to share the url

Thanks

# Answer
> 5 votes
In *Pager options* There is a field named *Pager ID*. Setting a different value for each view should solve the problem.

# Answer
> 0 votes
Make View Results Ajaxified.. Enable the AJAX Feature in the view settings. You can do this by editing the view and make the **Use AJAX** setting under **Other** settings in the view to YES.

With out using AJAX you can solve this using the **Pager ID** setting in the pager settings. For first view leave the Pager ID to default 0. For the second view in the same page, edit the view and set the pager ID to 1. Make sure all the views in a single page have different pager ID's.

# Answer
> 0 votes
You have a very tutorial on nodeone.se about what you want to achieve.

But it's almost the same answer than H.NiK...Only difference,he only changed the id pager of one view (the block not the page)

Maybe this video will be helpful.

---
Tags: 7, paging
---


# Question
Title: How to add a form to $node in hook_node_load()?
I want to add a form to a node before it is passed along to the theme layer.

My module has a hook\_node\_load, as follows:

```
function gp_shop_node_load($nodes, $types) {
  foreach($nodes as $nid => $node) {
    //Determine if we should process. aka: only run on Record->type() types.
    if (!in_array("product", $types)) {
      continue;
    }

    $nodes[$nid]->gp_shop_order_button = "[BUTTON]";
  }
}

```

This works: the text *\[BUTTON\]* is added to $node if it is type "product";

However, when placing an actual form, it breaks in a `Maximum function nesting level of '100' reached, aborting!`-error. An endless loop of some sorts. As follows:

```
    $nodes[$nid]->gp_shop_order_button = drupal_get_form("gp_shop_order_button", $node);

```

Edit: In the final code, I problably have to wrap this in a `drupal_render()` even; for now it makes no difference. The relevant line would then be:

```
$nodes[$nid]->gp_shop_order_button = drupal_render(drupal_get_form("gp_shop_order_button", $product));

```

And then with the callback-hook for the form.

```
function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Order',
  );

  return $form;
}

```

The part about passing along the $nodeis not very relevant and is not causing the problem. Just left it in my examples here, to illustrate that passing along parameters *is* a requirement.

What am I doing wrong?

# Answer
> 2 votes
Not entirely sure why `hook_node_load` does not work, but some trial and error (in contrast to the documentation) led me to a working solution using `hook_node_view` instead.

The example code being:

```
function gp_shop_node_view($node, $view_mode, $langcode) {
  if ("product" == $node->type) {
    if ($view_mode == 'full' && node_is_page($node)) {
      $node->content['gp_shop_order_button'] = drupal_get_form("gp_shop_order_button", $node);
      }
    }
  }
}

function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Order',
  );

  return $form;
}

```

---
Tags: 7, forms, nodes
---


title: About Drupal interact with Android

text:
# Question
Title: About Drupal interact with Android
Requirements:~

* Android app post json data to a certain url.
* Drupal can receive the json data and then verify the json data and return result data in json format.

My question is on receive Json data and return Json data steps. What module or api can I use?

It would be greater help if you can share a sample.

# Answer
Services module is what you are looking for. It supports json data. More about the module:

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

It also has an extensive documentation.
> 4 votes

---
Tags: 7
---


# Question
Title: can I use db_update to update a field ( appending a string to the current string in the database )
Is it posible to do something like:

```
db_update('my_module_table')->fields( array('myfield' => <myfield> + 'newstring') );

```

Or do I have to load the field value first by using db\_select() ?

Maybe someway with db\_query() ?

# Answer
You can still use `db_update()` just with an `expression()` instead of `fields()`, e.g.

```
db_update('my_module_table')
  ->expression('myfield', 'myfield + :newstring', array(':newstring' => 'Some string'))
  ->execute();

```

Although it strikes me that still wouldn't work as you're trying to concatenate strings (the `+` operator doesn't perform string concatenation as far as I know). This should do it:

```
db_update('my_module_table')
  ->expression('myfield', 'CONCAT(myfield, :newstring)', array(':newstring' => 'Some string'))
  ->execute();

```
> 7 votes

# Answer
You can use the following,

```
db_update('my_module')
    ->condition(<condition>)
    ->expression('field', "concat(field, 'new String')")
    ->execute();

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: How to create a map like the one used on the drupal.org homepage?
I want to know how to create an interactive map like the one used on the home page of drupal.org.
Thank you very much

# Answer
Perhaps this is useful: How the Drupal.org home page map works

This is the actual module: HTML5 user geolocation
> 8 votes

---
Tags: google-maps
---


title: Create a print tpl for page views

text:
# Question
Title: Create a print tpl for page views
I'm working with print and I would to create a tpl for a specific view (for a "page" display). Is it possible, using the naming convenction?

# Answer
> 1 votes
I think you can only style the view for print adding in your theme a print css hiding some field with css.

```
stylesheets[print][] = css/print.css

```

# Answer
> 0 votes
In the views ui, click the 'advanced' link to view options. Click on 'Theme : information', here you will get some tpl suggestions. The suggestions you get are for different levels of theming your view from top level down to theming just a particular field.

```
Display output: top level
Field Content: [FIELD_NAME]: field level

```

Create your tpl file in your theme directory and flush caches.

---
Tags: theming
---


title: Change order of fields per node

text:
# Question
Title: Change order of fields per node
So i know how to order fields when creating/editing a content type. But say i have three fields in a content type:

* name
* last name
* nick

and want these to be draggable when a user creates a new node.

Any suggestions?

Thx!

# Answer
For Drupal 7, you can use the Field Weight module to change the field order per node.
http://drupal.org/project/field\_weight

I've used it with no trouble.
> 2 votes

# Answer
In cck you can change order of content type fields, and with Field display weights module you can have different order of fields **per node** . by default drupal **not have a module for ordering field in view** (we should order them in back-end part .
I think if you want fields be dragable in view(fornt-end) you should to use jquery ui dragable plugin

This link help you to provide your needs
> 0 votes

---
Tags: entities
---


title: Using views_embed_view() in View

text:
# Question
Title: Using views_embed_view() in View
I have created a View page, and added a "Global:PHP" field to embed a View block from another View using the following code:

```
<?php  print views_embed_view('VIEW_NAME','VIEW_BLOCK_NAME', $data->tid);?>

```

Now, it worked perfectly, but there's no detail or variables I can find in the print\_r($data)/dsm($data) about this View block's content.

My purpose is that, if there's no result in view block, then I will hide a particular custom field. In short, "if views\_embed\_view() return empty then hide field A

Wondering how to go about it. Please advise. Thanks!

# Answer
> 1 votes
I would instead use `views_get_view_result()` if all you are concerned with is if there is a result. More information on it can be found here.

---
Tags: views
---


# Question
Title: How to set root term in Hirerchical select
I have a vocabulary like the following:

Parent 1 Child 1 Child 2

Parent 2 Child 3 Child 4

I want the dropdown only to show Parent 2 and its childs, so I changed the root\_term id to parent id

'root\_term' =\> termid, // Enter a term ID here if you want to display only terms below the term with that ID.

function mymodule\_alter\_form\_alter(&$form, &$form\_state, $form\_id) {

```
if($form_id == 'myform_node_form')
{
  $form['field_myfield']['und']['#config']['params']['root_term']= termid;
}

```

Please let me know how to achieve this ??

# Answer
As I explained in this link ,this is bug in `HS` module.

finally i found your mistake in your code , in hs\_taxonomy.module in function hs\_taxonomy\_hierarchical\_select\_root\_level($params) you don't consider $params\['root\_term'\] and in every hs this item bypassed by 0 value

```
<?php
$terms = _hs_taxonomy_hierarchical_select_get_tree($params['vid'], 0, -1, 1);
?>

```

must be

```
<?php
$terms = _hs_taxonomy_hierarchical_select_get_tree($params['vid'], $params['root_term'], -1, 1);
?>

```

if user not set parent in content\_taxonomy settings for term reference it passed 0 by default.

please apply this patch to your module. just notice for this work correctly you want select (not duplicate second level select option) Save term lineage in Hierarchical Select configuration in Save lineage part. i test it ,working like a 'BENZ'
> 1 votes

---
Tags: taxonomy-terms, forms
---


# Question
Title: Getting the apartment cleaning and dish washing to work properly with Omega Theme?
I have enabled the setting under themes for the option, "It also helps you to clean your appartment and wash your dishes." Although double and triple checked, there appears to be no change.

I looked through the code to see if there was anything I could fix but unfortunately I'm a little light on my life-theming capabilities. I haven't yet been able to integrate Drupal with reality as of yet.

Am I missing an extra setting or is this a known bug?

# Answer
> 3 votes
check settings for filth and grime under settings.php, these settings override any other setting in omega be sure they are both are set to active. Run update.php.

It's possible that your filth and grime settings are set too low so you may need to adjust these in your ini.php file. (i have mine set to "CDC alert")

Any use of hand-sanitizer or disinfecting sprays can cause the omega settings to malfunction, this is a known issue.

---
Tags: theming
---


title: Attempts at client side rendering?

text:
# Question
Title: Attempts at client side rendering?
What attempts are there (successful or otherwise), to move the heavy work in templating to client side javascript?

# Answer
> 2 votes
If I understand your question, the only projects that I am aware of are

There is a related discussion in Using Javascript frameworks like Backbone with Drupal and some of the work for Spark could probably count, too.

I don't have direct experience with any of these, but I am in the early process of determining whether Backbone is a good fit for a particular project.

---
Tags: theming, javascript
---


title: Need Help using hook_views_query_filter

text:
# Question
Title: Need Help using hook_views_query_filter
I am using hook\_views\_query\_filter to append my own where clause condition with the where clause of the query generated by the view.

So for this I am using this hook.

Here is my code

```
   function mymodule_views_query_filter(&$view, $query) {
 if($view->name = "myview") {
 $query->where[1] = array(
            'clauses' => array(
                            '0'=>"field_test_value=0",

                             ),
            'args' => array('0' => 'test1', '1' => 'test2'),
            'type' => 'OR',
            );
}
print_r($query);
}

```

So the where clause becomes like this after print\_r() funtion.

```
[where] => Array
    (
        [0] => Array
            (
                [clauses] => Array
                    (
                        [0] => node.type in ('%s')
                        [1] => node.status <> 0
                        [2] => term_data.name = '%s'
                        [3] => term_data_term_node__term_data.name = '%s'
                    )

                [args] => Array
                    (
                        [0] => test1
                        [1] => test2l
                        [2] => test3
                    )

                [type] => AND
            )

        [1] => Array
            (
                [clauses] => Array
                    (
                        [0] => field_test_value=0
                    )

                [args] => Array
                    (
                        [0] => test1
                        [1] => test2
                    )

                [type] => OR
            )

    )

```

Where the 0 index of the where clause is coming from the view query and the 1 index of the where is clause is coming from my code. But it only executes the 1 index of the where clause and display the results only if Where field\_test\_value=1 and I want something like this.

```
Where (node.type in ('%s') AND node.status <> 0 AND term_data.name = '%s' AND term_data_term_node__term_data.name = '%s') OR field_test_value=0

```

# Answer
You shouldn't alter the query objects properties directly. You need to use the methods it provides. In this case, you need to use `add_where()`. I think you want to consider something like this:

```
<?php
$clauses = array("field_test_value='%s'");
$args = array('test1');
$query->add_where(1, $clauses, $args);
$query->set_group_operator('OR'); // this is the operator that goes between WHERE groups
?>

```
> 0 votes

---
Tags: 6, views
---


# Question
Title: Ubercart shipping quotes silently fails on server migration
I'm having a hard time figuring out why shipping quotes are failing after migrating to a new server.

I can clone the repo in my local machine, and shipping quotes come in fine. I can't find anything in the AJAX request/response headers that tells me why they're failing on the development site. They work on the live site. (It uses Drupal 7.7, while the development site is using Drupal 7.15.)

They work on my local machine (cloned from the same, updated the repository as development).

I get the following error messages on the watchdog log every time I try to get a shipping quote.

> Type: Rules
> Location: /system/ajax
> Referrer: /cart
> Message: Unable to evaluate condition data\_is

> Type: Rules
> Location: /system/ajax
> Referrer: /cart
> Message: Unable to apply data selector order:delivery-address:country: Unknown data property delivery\_address

I enabled the Rules UI module to view active/disabled rules. And it looks like some rules are based on parameters that no longer exist, perhaps due to updating the Ubercart module. This is confusing because I did the upgrade locally, and I did not find this issue.

These are the active rules with errors:

* E-mail an order update notification
* Machine name: uc\_order\_update\_email\_customer
* Weight: 0
* Error: Data selector order:order-status for parameter data is invalid

* Complete non-shippable order after payment received
* Machine name: uc\_checkout\_complete\_paid
* Weight: 0
* Error: Data selector updated\_order:order-status for parameter data is invalid

# Answer
Ok, I eventually traced the issue back a module called "UUID", which is required by Node Export.

Disabling UUID module solved my issues. The errors in the rules UI (admin/config/workflow/rules) simply went away.

Would love to know more about why this is. I don't need node export at the moment so it doesn't matter to me.
> 1 votes

---
Tags: 7, ajax, ubercart, rules, migrations
---


# Question
Title: How can I set a response URL to use https?
I have a json response that I need to force to use https when on the live server.
So I need to detect if the response URL is using http or https.
If it's using http I need to switch it to https.

How can I force the header to use https?

# Answer
The best way to handle this is when the user requests the JSON over HTTP, redirect it to HTTPS, and then the response will come back as HTTPS.

The Secure Pages module does just this. It will let you create regex patterns on paths, so you can have portions of your site use HTTPS, but not others. You would just need to add the paths for your JSON.

Note that the Drupal 7 version requires two patches against core, but I have clients who have these patches on live sites.
> 1 votes

---
Tags: 7, uri
---


# Question
Title: How to find the ID of a views block that is not assigned to a region?
The title pretty much says it all. I need to find the ID of a Views block that is not assigned to any region, in Drupal 7.

# Answer
you can edit that view, move your mouse on the "block" that you need to analyze and see the url.Like this one:

http://mydomain.ext/admin/structure/views/view/flag\_bookmarks/edit/page\_4

The last url path is the page id: page\_4. In your case all start with "block\_".
> 1 votes

---
Tags: views, theming, blocks
---


# Question
Title: What's the best file permission to drupal's files and directories?
> **Possible Duplicate:**
> What are the recommended directory permissions?

I want to know what's the best file permission under a linux system to my drupal's files and directories including the files directory and the core either.
Thank you very much

# Answer
Drupal has already a well documented page with all informations you are looking for.
> 2 votes

---
Tags: security, files
---


# Question
Title: Which Drupal functions can be called in hook_requirements('install')?
Generally, implementations of hook\_requirements() don't use any Drupal function, when they are invoked during installation. node\_requirements() uses some Drupal functions for whatever phase it is invoked.

```
  $requirements = array();
  // Ensure translations don't break at install time
  $t = get_t();
  // Only show rebuild button if there are either 0, or 2 or more, rows
  // in the {node_access} table, or if there are modules that
  // implement hook_node_grants().
  $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
  if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
    $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
  }
  else {
    $value = $t('Disabled');
  }

```

Which Drupal functions can be called in `hook_requirements('install')`?

# Answer
I've made severals tests and I found that depending on modules that you've installed or other things the list of available functions is quite different.

So, IMHO the best way to see which functions you can access at that moment its to list them with the PHP function get\_defined\_functions. Below it's the small code that I used to list all the functions you can use.

```
<?php
if ($phase == 'install') {
  $funcs = get_defined_functions();
  file_put_contents('./functions.txt', var_export($funcs['user'], 1));
}

```
> 0 votes

---
Tags: hooks
---


# Question
Title: Display message or block when View Page is null or empty
I have a `Content Type : Events` and i have created 3 events they are currently `published` and displayed in `Page` ie `Display as View`. If there are no published `Events` then it should display a custom message as "No Events" or a "block".

I am trying to work on views with null values but i could not get it. Is there any thing like this.

# Answer
On your configuration Views in the right you've "Advanced" zone, if you click on it you will see more options and "No results behavior" that will let you do what you want when the view doesn't return results.
> 1 votes

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


title: Drupal WYSIWYG editor

text:
# Question
Title: Drupal WYSIWYG editor
I want to have a simple WYSIWYG when people add comments and when people edit the body of a basic page.

Something that looks like this:

Any ideas?

# Answer
> 1 votes
I used ckEditor, it works fine.

You can also install wysiwyg which manage many wysiwyg editor like ckeditor and others. You can try simple editor too.

# Answer
> 1 votes
You can install the WYSIWYG module. This will allows you to install severals other WYSIWYG, like CKEditor, TinyMCE, etc..

Once you've done it, you can create a new filter format and a new profile with your settings (so you can show only the buttons you want). The you just have to set that format into the fields. For that I think Better Format module will help you.

---
Tags: 7
---


title: Views Link to Teaser

text:
# Question
Title: Views Link to Teaser
I'm using JCarousel with Views. I've been able to get my content working fine and linked properly to their nodes in a modal window using colorbox-load. I'd like to be able to open up only the teaser content in the window. How can I do this?

# Answer
> 0 votes
If the link in your View is something like that `node/XXXX` I think it not possible, or at least you should modify the node.tpl.php and add a condition inside to show only teaser or full content according the context (from jCarousel or not).

Another solution it's to create another view, that will display only the Tease and point your links (from the view jCarousel) to that view. This view need to show node (tease) and accept an argument (nid).

---
Tags: nodes, javascript
---


# Question
Title: How to change the revision uid on node save
I need to change the revison uid of 7000 nodes on a site. So I am using Views Bulk Operations to perform this action, by publishing or saving the the 7000 nodes concerned. Then I use the hook\_node\_presave to update all contents. But unfortunately, the field revision\_uid isn't properly updated. By cons the field log is properly updated..

```
$field_uid = field_get_items('node', $node, 'uid');
    if($field_uid){
         $node->log = $node->uid;
         $node->revision_uid = $node->uid;
    }

```

The revision id is still the one I'm using to make this operation (1 to admin..). How can get around this problem??

# Answer
> 5 votes
You'll have to impersonate a user while performing your operation:

```
<?php
//Save current user data/session
global $user;
$original_user = $user;
$old_state = drupal_save_session(FALSE);

$field_uid = field_get_items('node', $node, 'uid');
    if($field_uid){
         // Load new $user data
         $user = user_load($node->uid);

         $node->log = $node->uid;
         $node->revision_uid = $user->uid;
    }

// Fail safe - if your code fails session won't be saved
$user = $original_user;
//Rever to old user and save session
drupal_save_session($old_state);
?>

```

References:

# Answer
> 3 votes
I was able to solve my problem by using a direct db\_update, here is my simple code:

```
function hook_node_update($node) {

  $node->log = $node->uid;
  $node->revision_uid = $node->uid;

  $revision_uid_updated = db_update('node_revision')
  ->fields(array(
    'uid' => $node->uid,
  ))
  ->condition('nid', $node->nid, '=')
  ->execute();

}

```

With this, I was able to reassign the revision ownership to the author of each content

---
Tags: entities, hooks, nodes
---


# Question
Title: How to query Nodes by a referenced Term Value (via EntityFieldQuery)?
I have to query my content types (firm\_unit) based on different fields conditions, and for that I came to use EntityFieldQuery.

```
$query = new EntityFieldQuery;

$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type = 'firm_unit')
  ->propertyCondition('status', 1);

```

This is nice when I want to query conditions on direct content fields, like these:

```
$query->fieldCondition('field_name', 'value', $keyword, 'CONTAINS');
$query->fieldCondition('field_sector', 'value', $sector, '=');

```

It seems to be unable to directly access, and then query by, referenced contents, like names/titles and fields of referenced terms (it just can access their tids).

Which is then the way I may query my node contents based on term referenced values?

Should I query the tid before (is the \_taxonomy\_get\_tid\_from\_term func the proper to use?), and then query the content like this?

```
$my_tid = _taxonomy_get_tid_from_term ($term_to_match);<br/>
$query->fieldCondition('term_fieldname', 'tid', $my_tid);

```

# Answer
`EntityFieldQuery` can not, as you have noticed JOIN tables, because it may run queries against a backend where JOIN does not make sense.

You will need bridge this gap in code, which is what your own suggestion is doing, it looks fine to me.

However, if you don't intend to run on MongoDB or some such, my personal preferance is would be to ditch `EntityFieldQuery` in favor of a SQL-query with db\_select instead. This mostly because MySQL provides the ACID, while all the "no-sql" db's needs to break atleast one of those.
> 1 votes

# Answer
You should probably use the taxonomy\_get\_term\_by\_name() function.

```
$terms = taxonomy_get_term_by_name($your_term_name);
$tid = $terms[0]->tid; // Assuming you have one term with that name.

```

Your query would then contain:

```
$query->fieldCondition('term_fieldname', 'tid', $tid);

```

So basically your question contains the answer already.
> 1 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: How do I programmatically get a styled version of an image via imagecache in D7?
I want to save locally to the server, a styled version of an image attached to a node. "Styled" as in filtered through a custom image style that I have already configured. What is the correct function, I can't find it anywhere.

I have file\_unmanaged\_copy() of the original image working fine, I can't see how to retrieve a styled version.

# Answer
theme\_image\_style. Imagecache is replaced by image style in Drupal 7. Example:

```
print theme('image_style',array('style_name' => 'thumbnail', 'path' => 'path/to/image'));

```
> 15 votes

# Answer
image\_style\_url() ended up being the closest match to what I was looking for. It doesn't include the full html markup for the image, so I didn't need to do any additional work to get to it.
> 5 votes

---
Tags: 7, media
---


# Question
Title: How do I update a node's file field from within a module?
I have a file: `/tmp/new.zip` and I have a node, `$node`, that has a file field, `field_ios_file`. Currently, `old.zip` is the file saved in to the `field_ios_file` field. I'd like to put `/tmp/new.zip` there.

What I have now:

```
$file = file_uri_to_object('/tmp/new.zip');
print_r($node->field_ios_file);
$node->field_ios_file['und'][0] = $file ;
print_r($node->field_ios_file);
node_save($node);

```

the `node_save()` fails here because `$node->field_ios_file['und'][0]` should be an array, not an object. I would imagine there is a function that looks something like `field_update($node, $my_field, $data)`, but I can't find anything like that.

# Answer
> 2 votes
The file field type has a `fid` column (file ID); you just need to save the file so an ID is populated, and add it to the node like this:

```
$file = file_uri_to_object('/tmp/new.zip');
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$node->field_ios_file[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);

```

---
Tags: 7, files
---


title: Apache Solr 6.x-1.2 re-index

text:
# Question
Title: Apache Solr 6.x-1.2 re-index
We have 90,000 nodes and it is currently re-indexing every hour (via cron) 200 pieces of contents. How can we have it do it all at once?

# Answer
> 1 votes
You could start by setting the number of items to index per cron run at 1000, and set the solr index cron hook to fire every 5 minutes using a drupal cron management module such as Elysia cron, which will allow you to set different intervals for all the other cron jobs on your site.

That's a reasonable setting to start with, which would be a big win over what it's currently set to, and would complete overnight. From there you could monitor for errors while tuning those 2 settings to see what the overhead on your system is.

*Or* you could just set that cron batch size variable on your Solr index to "**-1**" which is the magic setting that ***tells cron to index everything at once***. Obviously, this has performance implications. Apache Solr Search in Drupal also has an "Index items immediately" option to force update the entire index as soon as you save the setting, and not wait for a cron run.

---
Tags: search
---


title: Double digit values for date

text:
# Question
Title: Double digit values for date
I can not figure this out for the life of me, I am trying to have doubt digit values for the day and month in my module using form api, I have tried this with the date api and still no luck,

my function looks like this

```
function set_dob_year_range($form_element) {
$form_element['year']['#options'] = drupal_map_assoc(range(1900, 2012));
return $form_element;
}

    $form['dob'] = array(
        '#type'  => 'date',
        '#title' => t('Date Of Birth'),
        '#default_value' => array(
            'month' => format_date(time(), 'custom', 'm'),
            'day' => format_date(time(), 'custom', 'd'),
            'year' => format_date(time(), 'custom', 'Y'),
        ),
        '#after_build' => array('set_dob_year_range'),
        '#required' => TRUE
    );

```

using in on the month should count the months values as 01 02 03 but instead its using 1 2 3, thing for the days it should be 01 02 03 instead its using 1 2 3.

Any help is greatly appreciated.

EDIT: The date formats are not passing through to the values for anyone that is confused.

# Answer
You should try, i think it will work

```
format_date(time(), 'custom', 'm');
format_date(time(), 'custom', 'd');

```
> 2 votes

# Answer
Where do you see the output with the missing leading zeroes, are they going into the database like that? If not whatever is pulling the values is probably turning them into integers.
> 0 votes

# Answer
Please try this and tell me changes,

```
function set_dob_year_range($form_element) {
$form_element['year']['#options'] = drupal_map_assoc(range(1900, 2012));
return $form_element;
}

    $form['dob'] = array(
        '#type'  => 'date_select',
        '#title' => t('Date Of Birth'),
        '#default_value' => array(
            'month' => str_pad(format_date(time(), 'custom', 'm'), 2, "0", STR_PAD_LEFT),
            'day' => str_pad(format_date(time(), 'custom', 'd'), 2, "0", STR_PAD_LEFT),
            'year' => format_date(time(), 'custom', 'Y'),
        ),
        '#after_build' => array('set_dob_year_range'),
        '#required' => TRUE
    );

```
> 0 votes

---
Tags: forms
---


# Question
Title: How Can I get fields of entity in hook_entity_presave
According hook\_entity\_presave I can perform an act before entity save or update.

I want to get a list of fields used in that entity. Is there any way to figure out the fields of that entity?

# Answer
With this method you have access all fields used in your content types.
entity\_get\_info Doc and field\_info\_instances Doc gave me ideas on how can I got them.

```
function custommodule_entity_presave($entity,$type) {
    $allFields=field_info_instances('node');
    $savedFields=$allFields[$entity->type];
}

```
> 0 votes

---
Tags: entities
---