# Question
Title: Content publishing and confirming comment via email in drupal 7?
I want to provide following functionality:

1. When a user sends a mail to publisher@mysite.com, the subject of email become title of a blog post and body of email become body of blog post and the post should be published if the mail is done by admin
2. If the mail is not done by admin then a mail should go to admin notifying same and if admin replies "publish" then it should be published else it should not be published

# Answer
> 1 votes
Currently there is no module for this functionality afaik.

To implement this one,

* You need to pull the mails from server
* Processing the mails and performing other operations like checking whether the user is an admin
* After the processing create the content
* Finally add a cron job to perform this operation regularly

This article provides info about how to achieve this feature in drupal 7 with combination of several modules.

However authenticating using the sender's mail will be a security risk. For example if the admin mail ID is exposed then anyone can send mails as admin by altering the header information.

---
Tags: 7, users, emails, importing-exporting
---


# Question
Title: Link existing social media accounts to drupal account
Both upon registration and/or user editing later on, how could one give the user the ability to link his acccount with a plethora of social networks such as Facebook, LinkedIn, Skype, Google+, Twitter, etc?

I am not looking for an oAuth solution to (just) log in or register with one of the afforementioned accounts instead of a standart drupal one, I am looking for a way to give the user the ability to log in and/or register with either one of those accounts.

Is that technically possible? If yes, is there a one-in-all solution modulewise?

EDIT: to give some extra clarity, the ability to link your social networks' account(s) is a requirement upon *registration* too. Something like a "field-like" behaviour that will somehow store the connection with the social network account. Kinda blunt but you get the idea.

# Answer
May be you are looking for this module. It supports many providers for register and login integration.

Basic version is free. More details check below link!

http://janrain.com/products/engage/engage-pricing/
> 1 votes

---
Tags: 7, users
---


title: Add message to Add Article page

text:
# Question
Title: Add message to Add Article page
In the Add Article page (while editing), how do I add a custom message right above or below the Save/Preview buttons?

# Answer
> 2 votes
You can use markup module to add html text as fields to the article content type.

If you want to show the html text only in edit page then you need to use hook form alter

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' && arg(2) == "edit") {
    $form['contact_information'] = array(
      '#markup' => 'Your message goes here !',
    );
  }
}

```

---
Tags: nodes, entities
---


# Question
Title: How to manage / consume multiple Queue API queues in a module?
For a site I'm running, I'm going to have a few different queues for message sending. For example: high priority email, low priority email, high priority twitter, low priority twitter... etc.

I have set up queues (like "UrgentEmail", "UrgentTwitter") etc. using Drupal's Queue API, but now I need to work on the queue processing (consuming).

I can simply use hook\_cron in a module to consume one queue at a time, or all of them, as much as possible, but I'd like to be able to maybe have one queue get hit every couple minutes, while the lower-priority queues would only get it once every half an hour or so...

Is this possible without writing up some of my own cron handlers? I know elysia cron for D6 was good at setting options for module-specific cron, but is there a way I could branch out cron in a single module and run different tasks at different intervals? Or is there another Drupal Way™ to do this?

# Answer
> 1 votes
Drupal does not offer anything like this out of the box.

drupal.org uses Jenkins, which then starts drush scripts. Jenkins is very flexible to configure and has good built-in reporting while drush scripts make it easy to run code inside the context of drupal, without having to worry about authentication (as opposed to accessing it over HTTP, for example).

So, in your case, you could create a number of drush scripts (e.g. a script pro type like twitter/mail + an argument for the urgency) and then configure jenkins to run them at various time intervals.

# Answer
> 2 votes
It's possible to achieve this using Ultimate Cron! module.

This module creates a separate entry for each Queue item. Maybe it will help somebody.

# Answer
> 1 votes
It's not possible to run cron queues at different times, but it's possible to assign to each queue the time spent from Drupal to run it.

```
function mymodule_cron_queue_info() {
  $queues['mymodule_low_priority'] = array(
    'worker callback' => 'mymodule_low_priority_worker',
    'time' => 5,
  );

  $queues['mymodule_high_priority'] = array(
    'worker callback' => 'mymodule_high_priority_worker',
    'time' => 45,
  );

  return $queues;
}

```

Both the queues will be executed during cron tasks, but assigning less time to the one you consider a low priority queue means that the queue will take more cron tasks to be completed, if all the queues take the same time to be completed. If the queue you consider low priority contains only two items, then it will be completed before other queues that contain more items.

---
Tags: cron, queue
---


title: Change image extension on submission

text:
# Question
Title: Change image extension on submission
I am using D7.12 with webform 3.18. I want to change the image extension from png to jpg of the image uploaded through the form before saving it to database. I tried mytheme\_webform\_submission\_presave() in template.php but didn't help me. How can I do this?

# Answer
You need to use imagecache actions module to auto convert images from one extension to other.

Module Project page tells it provides

> File Format switcher - If you need tranparency in JPGs : make them PNG. If your PNG thumbnails are 30K each, save them as JPGs. (This is distributed as part of the color-actions submodule)
> 6 votes

---
Tags: webforms, users
---


# Question
Title: Display field collection items together with nodes in view sorted by date
I would like to create a view, which would list all the events of an organization (please look at the mockup). The problem is, that some of the are part of longer series, so I had to group them somehow. So now I have 2 content types (Event and Series of Events), the latter contains Field Collection field with multiple instances, which is used for sub-events. (Please see the scheme)

I use common date field for "Event" nodes and "Sub-event" field collection items, but I can't sort by it, because for "Sub-event" I would need to use relationship, which disables sorting of events.

So my question is: How would you create something like this?

I am using Drupal 7, Wiews 7.3 and latest version of Field Collection.

For better understanding of my problem, please look at following images (sorry, I can't post images because I'm new here):

Scheme

Mockup of view

# Answer
> 2 votes
I would strongly suggest to move away from field collection implementation. Because, Sub - Events are actually events and should be nodes. Right now they are becoming values of a Single Event by using field collection.

Try considering Entity Reference. Add a reference field called Parent Event to the event content type and make it reference to same content type. Make the field optional so that you can create root Events.

In future, above architecture will provide you lot of advantages. Hope you like it!

---
Tags: datetime, views, entities
---


# Question
Title: floating an image above a specific taxonomy termed node
I have to create a website that allows for a "new" tag to be floated above certain pictures that have the specific taxonomy term of "new". I created a view for the "new" where I added an empty div below the image and then floated it above the image and added the actual "new" image with CSS. This is what it looks like For the "new" node.tpl.php the code looks like this:

```
<article class="node-<?php print $node->nid; ?>
<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<div id="new-intro"><?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);
?>

<?php print render($content['links']); ?></div>

<?php print render($content['comments']); ?>

</article>

```

The id="new-intro" is the code that adds the background image to the empty div and places it above the product image. So what I need is a code that automatically adds the id="new-intro" based on whether the product has the taxonomy term of "new" I've found quite a few PHP samples but my knowledge is fairly limited and so I'm not sure that I'm editing them properly. Can any one point me in the right direction?? Thanks so much!!

Edit: So using the code below my code looks like this: template.php:

```
function hayfield_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['new_introduction'] = FALSE;
  if ($terms = field_get_items('node', $node, $field_new_introduction)) {
    foreach ($terms as $term) {
      if ($term['tid'] == 'new') {
        $vars['new_introduction'] = t('!published' == TRUE');
      }
    }
  }
}

```

and the node code looks like this:

```
<article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <div <?php if ($new_introduction): ?> <?php print 'class="new-intro"' ?> <?php endif; ?>><?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

  <?php print render($content['links']); ?></div>

  <?php print render($content['comments']); ?>

</article>

```

But it's throwing major errors :

Warning: Unexpected character in input: ''' (ASCII=39) state=1 in /Users/Candace Morgan 2/Sites/hayfield/sites/all/themes/hayfield/template.php on line 33
*(it doesn't like my argument in the last line of the template.php)*

Fatal error: Cannot access empty property in /Users/Candace Morgan 2/Sites/hayfield/modules/field/field.module on line 936

the Content type is **product\_display**, the field in the content type is **field\_new\_introduction**, the taxonomy vocabulary name is **new** and the taxonomy term name I want to reference is **New Introduction**.

I'm yanking my hair out on this one!! Thank you for any help you can give me!!

# Answer
> 0 votes
I almost fell out of my chair when I took the preprocessor code out and changed my node code and it worked!!! (at least so far so good!!)

```
<article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <div <?php if ($field_new_introduction): ?> <?php print 'class="new-intro"' ?> <?php endif; ?>><?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

  <?php print render($content['links']); ?></div>

  <?php print render($content['comments']); ?>

</article>

```

I just made sure that the field for new introduction field had only one option so that it's either selected or not and I think that's going to do it! (I hope!!) Thanks for your help!!!!

# Answer
> 0 votes
Put this into your themes:

```
function THEMENAME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['new'] = FALSE;
  if ($terms = field_get_items('node', $node, $FIELD_NAME_OF_YOUR_TERM_FIELD_IN_NODE)) {
    foreach ($terms as $term) {
      if ($term['tid'] == THE_TERM_ID_OF_THE_NEW_TERM) {
        $vars['new'] = t('Maybe you can add something new text or simple set it TRUE');
      }
    }
  }
}

```

Then empty the theme\_registry (clear caches) and change the `<div id="new-intro">` to:

```
  <?php if ($new): ?>
    <span class="new-intro"><?php print $new ?></span>
  <?php endif; ?>

```

Using the same ID in one page is not valid. Then you can target using CSS styles.

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


title: Redirect from root and not page itself

text:
# Question
Title: Redirect from root and not page itself
So I want to provide similar redirection logic as we have on drupal.org and redirection to dashboard to logged in users but also allow access to the /front page. I can't seem to get it to redirect ONLY on front page. Here is the current code I have:

```
function MYMODULE_init(){
  global $user;
  if(drupal_is_front_page() && user_access('view own dashboard')){
    drupal_goto('user/'.$user->uid.'/dashboard');
  }
}

```

It is also redirecting the page itself to the dashboard still and not simply the `<root>`

# Answer
> 1 votes
I think you should be using hook\_user\_login instead of hook\_init.

---
Tags: redirection
---


# Question
Title: css and javascript aggregation. Can I still edit files?
Am developing a site using drupal 7.15 I am having problems with displaying a ddblock in internet explorer and I think it may be due to too many css files. If I aggregate them can I continue to edit them? Also, can I still use Firebug to view my css? All the posts I read seem to refer to setting aggregation when you decide to "go live" Sorry to ask such an elementary question.

# Answer
> 4 votes
You can still edit the original files as much as you like, but you won't see the changes reflected in the front end until you clear Drupal's caches.

You can absolutely still use Firebug to inspect your CSS, but keep in mind that the files have been *aggregated*, so you won't be able to pinpoint the original file and line that a rule comes from.

That's pretty much why it's recommended to keep aggregation off during development, unless of course you're testing the aggregation itself.

---
Tags: css-js-aggregation
---


title: How do I create overridable templates?

text:
# Question
Title: How do I create overridable templates?
I have a module and a theme with different names. The module implements hook\_theme() to specify a group of templates with 'template' and 'variables' for each. Template files in the module are working as intended.

In my *theme*, I implement templates/html.tpl.php and templates/page.tpl.php - which both work. But, theme/templates/mytemplate.tpl.php is not overriding the module's template. I have cleared the cache.

What do I have to do so that templates in my theme's templates/ folder will override my own module's templates?

# Answer
> 2 votes
I found the answer in this comment. For Drupal to find the theme's template overrides, I had to change my theme keys to underscore versions of my dashed template names.

```
function mymodule_theme($existing, $type, $theme, $path)
{
  return array(

    'my_theme_key' => array(
      'template' => 'my-theme-key',
      'variables' => array(
        ...
      ),
    )
  );
}

```

---
Tags: 7, theming
---


title: Custom links in Views

text:
# Question
Title: Custom links in Views
For a Taxonomy Vocabulary on my Drupal 7 site, I have added several custom fields for each Taxonomy Term, and want to have two different ways of viewing the Term information: a summary and a detailed view.

I've created the two Views for summary and detailed (`myterm-summary/%` and `myterm-detail/%`). But now the question is how to create a link between them. I'd like a link on `myterm-summary/%` to link to `myterm-detail/%` as a "Read More..." link. Is there some View element I can add to the View to create a custom link, using the dynamic URL variable in the process?

I know I can create a Rich Text block header or footer for the View, but can I refer to the URL variable in that text block somehow?

# Answer
> 4 votes
I've found a solution that you can use the Replacement Tokens to this effect. In order for the field you want to show up as a possible Replacement Token, it must be in the Fields list. So I did:

* Set Format to "Unformatted List"
* Set Show to "Fields"
* Add the "Term ID" field to Fields list.
* During creation (or edit it afterward), check the "Exclude from display" box.
* Create a new Footer element that's a "Global: Text Area" type.
* Check the "Use replacement tokens" box
* Insert `<a href="/myterm-detail/[tid]">More Info...</a>` in the box.

# Answer
> -1 votes
You can use the "Global : Text Area" in the Header or Footer of the view to add the link. You can get the URL variable using a PHP snippet and use that to create a link. The following should work :

```
<?php
$view = views_get_current_view();
print '<a href=\'/myterm-detail/'. $view->args[0] .'\'>Read More..</a>';
?>

```

Make sure you are using the PHP code text format.

---
Tags: 7, views
---


# Question
Title: How to show filesize when content type contains more than one file?
I'm using Drupal 7 and having File 7.14 field installed.I have a content type (named file) containing more than 1 file. I have a view that shows the filesize of all the files of the content of that content type named file. For doing that I have added a relationship in Views to "select File Usage: File" The filesize is nicely shown for content that contains only one 1 file.

However for content containing more than 1 file the filesize is only shown for the first file but not for the 2nd 3th etc.

Here is how my query currently looks like:

```
SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,   file_managed_file_usage.filesize AS file_managed_file_usage_filesize, 'node' AS  field_data_field_file_node_entity_type
FROM
{node} node
LEFT JOIN {file_usage} file_usage ON node.nid = file_usage.id AND file_usage.type = 'node'
LEFT JOIN {file_managed} file_managed_file_usage ON file_usage.fid = file_managed_file_usage.fid
WHERE (((node.status = '1') AND (node.type IN  ('file'))))
ORDER BY node_title ASC
LIMIT 50 OFFSET 0

```

Can anybody explain me how to change the View settings so that the filesizes of the other files are also be visible?

# Answer
> 0 votes
Actually it works fine for me without additional settings

**My configuration :**

1. I used `content-type : Article` and create some fields `file`
2. Your first step is good, you need to add a relationship `select File Usage: File`
3. Then in your fields section you can add : `Content: Title` , `File: Size`, `File: Name`

I have a listing of all the name of the file with their size. If you want you can group by `Articles`.

---
Tags: views, nodes, files
---


# Question
Title: Can error messages be avoided for custom modules in the Update manager?
On my "Available updates" page I get error messages when there are custom modules in use:

> Failed to get available update data for one project.

Is there any way to avoid this? Either by setting up some sort of feed for custom modules (probably not practical in most situations!) or by excluding custom modules from the list?

(As an aside, it seems like a design flaw in the Update manager module to give an error for custom modules. If they are in the `custom` directory inside `modules` then it can easily determine that they are custom, and clearly should not expect to receive update data for them from the same source as contributed modules.)

Is there any solution to this other than filing a bug report and hoping the maintainer agrees with my perspective? (Or hacking the module myself.)

# Answer
> 3 votes
Using the tip that junedkazi gave (please up-vote his answer too if this helps you!), I add this line to the `.module` file for my feature module:

```
include_once('<my_module>.exclude_from_update_list.inc');

```

And in the file `<my_module>.exclude_from_update_list.inc`:

```
<?php
/**
 * @file
 * <my_module>.exclude_from_update_list.inc
 */

/**
 * Implements hook_update_projects_alter().
 */

function <my_module>_update_projects_alter(&$projects) {
  unset($projects['<my_module>']);
}

```

And it worked perfectly. I took the precaution of backing up the database first, and of course I did this in a non-production environment.

This is all pretty obvious once you know about that hook, but I'm putting the code here for sake of a more complete reference, hoping it speeds things up for someone else.

# Answer
> 2 votes
Have a look at hook\_update\_projects\_alter

> for example, if there is a site-specific module that doesn't have any official releases, that module could remove itself from this list to avoid "No available releases found" warnings on the available updates report. In rare cases, a module might want to alter the data associated with a project already in the list.

You should also have a look at hook\_update\_status\_alter

---
Tags: 7, updating
---


# Question
Title: Allowing simple footer customisation in settings?
So, I want to give the client the ability to edit the footer, copyright & legal area. This isn't worth it's own content or block. I don't think....

Is is possible to add a text entry field into setting to customize the footer area or alike areas on the website.

# Answer
In Drupal 6, the Site information settings page at /admin/settings/site-information has a "Footer Information" field that meets your description above. If this field is not empty, and you do a major upgrade of your D6 site to D7, then your footer information will be moved into a block called "Footer message". While it would be possible to re-implement the "Footer Information" field from D6 in D7 with a custom module, or in the settings for your theme (which would be even easier) I think it is clear that D7 designers felt that using a block for this purpose was the best and most general solution.
> 1 votes

---
Tags: 7
---


title: Fixed Block Position CSS Problems

text:
# Question
Title: Fixed Block Position CSS Problems
Hello i was using the floating Block module to keep my right hand main menu in a fixed position as a person scrolls down the page. Then i deceided that maybe its overkill just for one menu and i have tried it with css.

```
#sidebar-left {
 position: fixed;
    top: 0
float:right;
  right:20px;
  width:110px;
}

```

My theme is fixed width but im getting differant results when viewed in differant screen resolutions. I was wanting the block to just appear to the right of the the 2nd right hand block (with the logo). Try as i might though im struggling to achieve it.

You can view my site (and the right hand menu) here- http://onlinebanter.com/welcome

Can anyone help me achieve this?

Thanks

# Answer
I think ive sorted it with

margin-left: 845px; position: fixed; top: 0; width: 110px;

Thanks
> 0 votes

---
Tags: blocks, theming
---


# Question
Title: how to set complete site background to a color or image?
I used this:

# wrapper { background-color:yellow; }

but I want really everything in the background to get colored. how to?

Code above just makes the wrapper background change.

# Answer
Try applying same for body tag !

body { background: yellow; }
> 1 votes

---
Tags: theming
---


# Question
Title: What are the possible exploits if settings.php is writable?
I have recently had to set up Drupal on shared hosting using suPHP. This is a first for me, an install where all the files are writable by the user by default. All the Drupal documentation and the Drupal built in status report will warn you of the folly of having your settings.php writable by the web server process.

Option 1: I can log into the shell and secure the settings.php by making it read-only to my own account (and the webserver account which is running as me).

Option 2: I can log into the shell and make all the files and folders read only to my own account (and the webserver account which is running as me) which may have to be changed every time I want to install a module etc. This will be kind of a pain to maintain.

My question is: Is there a significant difference in the security risk between the two options? What are the specific exploits that are possible due to having the settings file writable by the webserver process vs. the other core files?

# Answer
> 4 votes
Option 2 is marginally better, but if you get p0wned, a hack script will chmod the file before it tries to append to it, which pretty much renders permission-based protection useless.

Personally, I would make up shell scripts to take care of the permissions for you. For deployment, something like

```
find docroot/ private/ -type d -exec chmod 555 {} \;
find docroot/ private/ -type f -exec chmod 444 {} \;
find sites/default/files/ -type d -exec chmod 755 {} \;
find sites/default/files/ -type f -exec chmod 644 {} \;

```

Then, when you want to run drush or make updates

```
find docroot/ private/ -type d -exec chmod 755 {} \;
find docroot/ private/ -type f -exec chmod 644 {} \;

```

You should also read through Securing file permissions and ownership. This article includes a different version of shell script for fixing permissions, and uses a slightly more restrictive scheme.

---
Tags: security
---


title: CSV column with multiple values

text:
# Question
Title: CSV column with multiple values
I'm trying to use the feeds module to import structured data from a CSV file and map the values to node. I'm having an issue with a CSV field that contains multiple values.

e.g. `ingredients['peanut butter', 'jelly',]`

Is there a good way accomplish this with feeds, or would I be better off writing my own custom mapping engine module? I'd prefer to find a way to get the Feeds module to work to avoid having to spend excess time on something that is already done.

# Answer
> 7 votes
I spent a couple hours working on this, and it seems as soon as I posted the question I found an answer. The Feeds Tamper module will do the trick. It provides a lot of preprocessing functionality before the data is mapped to the entity fields. When configuring the data mapping, select the feeds tamper link. The explode plugin will explode the values into an array. Fields can have multiple values within an array map to a single field.

I hope that anyone else that has this problem finds this to save them some time.

---
Tags: feeds
---


# Question
Title: Adding a bulk discount to ubercart without adding a new module
I have multiple sites using the same ubercart module. One of the sites has a new discount that I need to add. If you buy 25 or more you get a 25% discount, if you buy 100 or more you get a 35% discount for example. I don't want to add a new module to ubercart as I don't want to mess with everything that's already working. Plus it's just this one discount on one specific item.

In going through the ubercart documentation, it looks like there are several hooks that may be useful. `hook_add_to_cart`, `hook_line_item_alter` and `hook_order` which are defined here. Am I travelling down the right path or is there another better way or already laid out example that would make piling through this a bit simpler?

# Answer
After digging through various hooks and trying different things, this is what ended up working for me, which was actually pretty simple in the end.:

```
function hook_cart_item($op, &$item) {
    if ($op == 'load') {
        if ($item->nid == xxx && $item->model == 'xxxxxxxxxx') {
            if ($item->qty >= 100) {
                $item->price = round($item->price * .65,2);
            } else if ($item->qty >= 25) {
                $item->price = round($item->price * .75,2);
            }
        }
    }
}

```
> 1 votes

---
Tags: hooks, commerce, ubercart
---


# Question
Title: Views tagging question (bulk update tags)
We have a few taxonomies and don't want users to spend time tagging content. Ideally, we would like to have a view where we could tag content without opening each node.

A module exists for exactly this purpose in D6 but nothing in D7.

http://drupal.org/files/images/views\_tagger\_screenshot.png

Is there any other way to accomplish this??

# Answer
> 2 votes
Found a solution, via the editablefields module!! Here is a quote about it (from the module's project page):

> ... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

---
Tags: views
---


# Question
Title: Using print render($content['taxonomy']); in node.tpl.php
I am having trouble getting my taxonomy terms printed into the containing of my node.tpl.php file. I have named my taxonomy terms for a custom block (books) as field\_tags and I want them to get printed after the $classes array as plain text CSS classes.

Here is the offending line:

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?><?php print $content['field_tags']; ?> clearfix"<?php print $attributes; ?>>

```

The goal here is to have a menu on top of this view of books that can select individual titles based on their individual taxonomy terms. Open to suggestions about that as well if you think this plan is stupid.

# Answer
I think the proper way to do this would be to implement `THEME_preprocess_HOOK()` in your theme's *template.php*.

In that function, just add each taxonomy term name into the classes array. You'll probably also want to cleanse the term names as you put them into the classes array, dig around Pathauto or Transliteration modules to find a function to do the dirty work.

```
function mytheme_preprocess_node(&$vars) {
    foreach ($vars['node']->field_my_taxonomy_field[LANGUAGE_NONE] as $term) {
        $vars['classes_array'][] = pathauto_cleanstring($term->name);
    }
}

```
> 0 votes

---
Tags: 7, views, taxonomy-terms, nodes, theming
---


title: data collection & views

text:
# Question
Title: data collection & views
I have created a website for neighborhood on d7 for a society of 400 apartments. We need to collect data from each user (like is he a tenant or a owner, his profession, his car registration no, members in the family with age, and respective ID cards to verify and arrange facilities membership card, carparking,maid access etc. I had accomplished this questionre by using webform,and only later I understand that this is more meant for survey one way. I cannot again use this data and give user a option of edit. example if the user changes his car / maid he should be able to change it online. Data collection from the users have not yet been started. What would be the best way to collect this type of data and later be used in views, this also has conditions /logic based question example if he is a owner he has a different set of questions and if he is a tenant then different set. Around 3-4 logic questions are involved.

I don't know php. But love drupal.

Thanks.

# Answer
> 0 votes
One way would be to give each user an account / profile. Then add the fields you need to the user profile and the people can provide all the information you need by themselfs. And they can update the data whenever something changes. Or even you can update the data if they're not able to do it or forget about changing them on your site.

An other way would be to have a content type if you dont want user profiles. But in this case, you have to maintain and update the data.

---
Tags: forms
---


title: Organic Groups Help

text:
# Question
Title: Organic Groups Help
I have a website where only users I select can join. When they join I put them in one of three groups.

Team A, Team B, and Team C.

The group is private and the content inside the group is private.

I have a content type called "Announcement" that is a group content. (as seen below)

Any member in a team can create content for that specific team. I also need any member in that team to be able to edit any "Announcement" even if it isn't there own. (as seen below)

Create new Announcement: works Edit own Announcement: works edit any Announcement: **doesn't work** Delete own Announcement: works

I'm having trouble troubleshooting this issue, and it's an integral part of my website. Any suggestions?

# Answer
> 1 votes
Organic groups global permissions (path admin/config/group/permissions) have to be set as well to grant privileges to group roles (in your use case you probably only need to use the default "member" one).

This way the same user could have "administrative" rights in one group and "normal" rights in another.

---
Tags: 7, organic-groups
---


# Question
Title: Paid membership plans on registration page
I am creating a registration based website that has five membership plans.

Based on the selected membership plan, users have to pay the membership fee using Stripe payments.

How can I create membership plans and this kind of payment functionality?

# Answer
> 3 votes
For membership process you can use the (paid for) Moneyscripts module.

> Membership Suite is the most comprehensive subscription software for Drupal on the market and it is designed to seamlessly integrate your site with all of the features of a professional Paid Membership Subscription site. There is no other software available for Drupal that can provide the stability, ease of use, and features that Membership Suite offers.

# Answer
> -1 votes
Why don't you make use of the Commerce distribution and the Commerce stripe contrib module? With commerce you can attach roles to products, so when a user buys your membership plan "A" he/she will automatically get assigned role "A".

---
Tags: users
---


# Question
Title: Depending on the argument passed in url go to specific content type
I have a link "Add Details". suppose when I click on the Add Details, I will send arguments to the urls. such as in url "http://localhost/drupal/video" video will be my argument. When I click on "Add Details" link if argument is video then I want to go to "Video content type".

When I click on "Add Details", if argument passed is "image" in url("https://localhost/drupal/image), Then I want to go to "image content type".

When I click on "Add Details" link depending on the argument passed in URL I want to go to specific Content type.

How to achieve this.

Any help is appreciated.

# Answer
> 1 votes
Use hook\_menu in custom module to achieve this using below code !
Change the links of Add Details to "goto/video" means full url will be localhost/drupal/goto/video

```
function yourmodule_menu() {
    $menus['goto/%'] = array(
        'title' => 'Just Redirect',
        'page callback' => 'drupal_redirect_to_content_type',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $menus;
}

function drupal_redirect_to_content_type($type) {
  drupal_goto("admin/structure/types/manage/" . $type);
}

```

Otherwise,

Instead of above what you can do it directly give Add Details link to admin/structure/types/manage/ . $type instead of drupal/$type

---
Tags: 7, nodes
---


# Question
Title: How to reference a view using entity reference field type?
I have two content types, courses and tutors. Tutors contains a biography and a large photo

Courses contains lots of other information but more importantly contains a tutor field which is a entity reference field type. It creates a dropdown list containing all tutors.

The problem I have is that when I create a new course page and select a tutor from the dropdown list, it displays the full biography and large photo.

What I want it to display is the first say 100 characters of the biography and a cropped version of the tutor photo (I have set up a image style which crops the photo to 100px)

I’m guessing there may be 2 ways of doing this. 1) Customising a teaser 2) Creating a view but I’m not sure how you reference it and how you would get the view to just show the selected tutor (from the dropdown list above)

I am using Drupal 7

Any advice much appreciated.

# Answer
> 2 votes
Sounds like you know what your doing. Like you say either create a 'view mode' in your content type or create a view. All you have to do with the view is create a relationship (under 'relationships' in the advanced section) to get your entity reference and set a filter for the tutor.

Tried to find something similar to your issue, hope it helps. How to use Entity Reference and Views

---
Tags: views, nodes, entities
---


# Question
Title: how do i create a new link in node.tpl.php by preprocess function in drupal?
I have content type in which I have two or three links .In node.tpl.php, all links are displaying from a single variable "$links" in node.tpl.php. i want to remove one particular link from the "$links" variable by preprocess function and assign that link to a new variables , so i can display it where ever I want.

I created a preprocess function to implement it

```
function sample_preprocess_node(&$variables){
  if($variables['type']="product"){
    $node=$variables['node'];
    $create_review=array();
    $create_review=$node->links['review_field_product_review'];
    $variables['create_review']=$create_review;
    unset($node->links['shopping_review_field_shopping_product_review']);
  }
}

```

and I pasted the following code in node.tpl.php

```
print $create_review;

```

It displays "array" in product page and that particular link is not removed from the variable ($links) in node.tpl.php

Can you tell me how to remove the particular link from the "$link " variable in node.tpl.php and display it by another variable in node.tpl.php?

# Answer
> 2 votes
This line will always return true, since you are assigning a value with the '=' operator:

```
if($variables['type']="product"){

```

This should be a comparison, so use '==':

```
if($variables['type']=="product"){

```

# Answer
> 1 votes
```
  $variables['create_review']=$create_review;

```

Should be

```
  $variables['create_review'] = theme('links', $create_review);

```

---
Tags: nodes, theming
---


# Question
Title: how to get email of welcome messge with drupal 7?
After creating new account with Drupal 7 I am getting the message.

> Thank you for applying for an account. Your account is currently pending approval by the site administrator.In the meantime, a welcome message with further instructions has been sent to your e-mail address.

But when I check my email account I am not getting that welcome email.

# Answer
> 6 votes
Follow below steps to solve problem !

* Check your server smtp log or mail log
* Check your spam folders in mail box.
* Make sure smtp or mail server are up & running in your hosting server or local server.
* Check drupal recent log entries for any errors related to same !

---
Tags: users
---


title: Why I can't access to dblog?

text:
# Question
Title: Why I can't access to dblog?
Why I can't access "Recent log messages" (via `/admin/reports/dblog`)?

It's not listed in the Admin Menu. And when I try to get there directly (via `/admin/reports/dblog`), I only see the "Reports", as shown via `/admin/reports`.

I've installed Drupal 7.15 with the OpenPublish Profile.

What could be the solution to this problem?

# Answer
As suggested, Check whether "Database logging" module is enabled in your modules list.
> 2 votes

---
Tags: log-messages
---


title: Theme field output

text:
# Question
Title: Theme field output
I have a field called field\_news\_title. I want to override its output so I created a file called field--field-news-title.tpl.php in my\_theme/templates folder but it's not working. I tried also to put the file in my\_theme root dir and in news content type dir. What am I doing wrong?

# Answer
I tried with field name **field\_article\_current\_rating** and I have created the template file called **field--field\_article\_current\_rating.tpl.php** and it is working.

So I think in your case you should try **field--field\_news\_title.tpl.php**

And one more thing I put this file in

> /sites/all/themes/theme\_name/templates

folder, as I am using Omega subtheme.
> 2 votes

---
Tags: 7, entities, theming
---


# Question
Title: Create a second contact form with redirect after submitting
There is a site wide contact form that's available on https://example.com/contact. I need to add a second contact form, with some custom fields: name and suggestion.

I would also like to have a custom message after the form is submitted. Users go to https://example.com//contact/question, enter name and suggestion, submit the form, and get redirected to a page showing a thank you message.

I just need to send the form content to a specific email address.

It would be nice to avoid using any additional module.

Site is a bit old; I am afraid that installing new modules will create issues.

# Answer
> 2 votes
I think that you need to install the Webform module:

http://drupal.org/project/webform

There might be ways to do this with the Rules module, but I think for overall simplicity, Webform is the way to go.

I'm pretty sure that the version for Drupal 6 allows a custom message to be displayed to the user. In fact, if memory serves, it also has the option to redirect to a particular page.

---
Tags: forms, 6
---


# Question
Title: Adding custom button to Add Article form?
I can't seem to get this to work. In my template.php, I have:

```
if($form_id == 'article_node_form'){

    global $user;

    if (in_array('administrator', array_values($user->roles))) {
        //print "here" --> this prints out just fine so this is getting hit
        $form['actions']['save_send_review'] = array(
        '#type' => 'submit',
        '#value' => 'Save & Send for Review',
        '#name' => 'op',
        '#submit' => array('myFunction_form_submit'),
        '#weight' => 1000
        );
    }
}

```

I can't get the button to appear. What I want to do is:

Have the button appear next to the Save/Preview buttons. Then once clicked, I want it to trigger Workflow to change the status from Creation --\> Review automatically (without saving it as Draft first).

# Answer
> 1 votes
In template.php the form is already build.

You have to create a simple module and a hook\_form\_alter to edit your form or add buttons, fields etc.

---
Tags: nodes
---


# Question
Title: Can a database be tested to see if it is inconsistent?
We all know that Drupal doesn't really support the concept of foreign keys in the database, and likely never will1.

We also know that it is possible for modules to not do the right thing, or that users will periodically do crazy things like

```
DELETE FROM node_revision
WHERE vid = 123

```

in an effort to "keep the database tidy". When this happens, hooks don't run, and there is orphaned data in the database. Mostly, this data is harmless, but occasionally it causes really weird behavior and can bring out bugs in code.

Are there any decent methods for detecting whether you have have dead and/or inconsistent data in your database?

1 The Drupal 7 Schema API supports them for documentation, but not enforcement.

# Answer
> 2 votes
As I was writing up a description for a sandbox project, I ran across a sandbox project for doing this:

http://drupal.org/sandbox/anton\_krechetov/1345066

It currently only works for Drupal 6, and there haven't been any commits since Nov 2011, but it looks promising.

---
Tags: database, testing
---


# Question
Title: Your site was unable to contact Apache Solr server
I have both **Apache Solr Search** and **Search API** modules installed on drupal 7. I have installed **SolrPhpClient** version **r22** (that was recommended in a site vs. r60) in **sites/all/libraries/libraries** folder.

When I place XML files from Apache Solr Search on Solr Server, Search API would not index. When I place XML files from Search API on the server, Search API *seems* to work fine but I get **Your site was unable to contact Apache Solr server** error message on Status Report. In this case I can see mysite:8983/solr/admin but when I click on PING button it shows 500 error message.

Is this supposed to be this way? Can I trust the Search API working fine (is the error message pertained to Apache Solr Search not having its XMLs on server and can be ignored)? Any suggestions to fix this?

Any help would be greatly aprectiated and let me know if you need more info.

Thanks alot.

# Answer
> 1 votes
Some days ago I had a similar problem.

I've download the SolrPhpClient in the .zip file and Search API was not able to connect to the Solr Server (I don't know Apachesolr, I don't use it).

But if I download the .tgz version of the client.. it works. I think that in the .zip version there is some problem with permissions.

So: if you've download the .zip version, try the .tgz.

And obviously try also the r60 version, I use it alwyas.

---
Tags: search
---


title: Printing a map using ViewsPDF

text:
# Question
Title: Printing a map using ViewsPDF
I am using drupal 7 and the ViewsPDF module to generate PDF's from my content. One of my content types has a map that I have done using a geofield. While trying to export the node as a PDF everything gets printed except the map. I've done a bit of asking around before posting this. Anyone with a solution to this?

# Answer
The real problem with such maps is that, the PDF gets generated before the map appears. I'm assuming your map provider is JavaScript based - that means the map appears on the user browser and your server just sets the javascript parameters.

I had to do a similar thing a long time ago, and the only solution that seemed easier was to use Google Maps with static maps. You can embed an image with parameters such as pointer options and geocodes and the maps server will return a static image. Worked in dompdf.
> 1 votes

# Answer
I havent done this, just thinking out load:

Use hook\_views\_pre\_render() to get the view content that should be everything in `#markup` or `#content` value of the Views array that is your Drupal page except the map.

In this hook then try to use php's file\_get\_contents your page directly into memory. This page may or may not have the map in it actually due to javascript usage on the page. But you should be able to either get a .jpg out of it somehow at this level. Or use a further wget to get an image of the map from the javascript now embedded on the page. You can grab a piece of this page using like DomDocument or a similiar scraping libraries. Once you have the image itself simply alter the view `#content` value to include your image url or image essentially.

This sounds like a huge pain. You'd probably want Cache (tutorial) this map information using the drupal api and like `cache_set`. You could maybe write all this in like 1 day :). Good luck.
> 0 votes

---
Tags: 7, views, entities
---


title: Multiple form submit

text:
# Question
Title: Multiple form submit
I have a table of information displayed on a page. Each row of this table has its own submit button. I need to be able to pass information depending on what submit button is pressed.

The form is built like

```
function numberSubmit_form ($form, &$from_submit){
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

```

The rows of the table are built like:

```
$unvalRows[] = array(
            array('data' => '0'.substr($a[0], 2)),
            array('data' => drupal_render(drupal_get_form('numberSubmit_form'))),
        );

```

How am I able to determine which submit button has been used and pass the applicable phone number?

# Answer
> 2 votes
Add the phone number as an argument to numberSubmit\_form and include it in your form array:

```
$unvalRows[] = array(
    array('data' => '0'.substr($a[0], 2)),
    array('data' => drupal_render(drupal_get_form('numberSubmit_form', $phone_number))),
);

```

Then in the form constructor:

```
function numberSubmit_form ($form, &$from_submit, $phone_number){
    $form['phone_number'] = array(
        '#type' => 'hidden',
        '#value' => $phone_number,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

```

It will then be available to you in the submit handler:

```
function numberSubmit_form_submit(&$form, &$form_state) {
    // do something with $form_state['values']['phone_number']
}

```

# Answer
> 1 votes
Same answer as charlie except that `#value` didn't work for me; I had to put `#default_value` in the hidden field as follow:

```
$unvalRows[] = array(
    array('data' => '0'.substr($a[0], 2)),
    array('data' => drupal_render(drupal_get_form('numberSubmit_form', $phone_number))),
);

function numberSubmit_form ($form, &$from_submit, $phone_number){
    $form['phone_number'] = array(
        '#type' => 'hidden',
        '#default_value' => $phone_number,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function numberSubmit_form_submit(&$form, &$form_state) {
    // do something with $form_state['values']['phone_number']
}

```

---
Tags: 7, forms
---


# Question
Title: WYSIWYG and TinyMCE stripping out float: left
I've got the WYSIWYG module installed and the TinyMCE javascript library as well. I've created a text format "Rich Text" which is similar to Filtered HTML but I've added more allowed tags.

I insert an image into my text and I set it to align left which adds `float: left` to the markup. However, when I save and view the page, the `float: left` has been stripped out.

I can't find any options in the WYSIWYG configuration or my "Rich Text" format that allows me to control this. Am I missing it somewhere?

Why is my `float: left` getting stripped out?

# Answer
My solution:

I downloaded a new module called WYSWIWYG Filter. On my Text Format, I turned off the `Limit allowed HTML tags` option and instead enabled the `WYSIWYG Filter` option. Then below in the WYSIWYG Filter settings, I configured the allowed HTML elements like so:

```
a[!href|target<_blank|title],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd,
img[!src|alt|title|style|width|height|typeof],
@[style|title]

```

And I checked all the boxes to allow margins, padding, floating, etc.
> 3 votes

# Answer
You can do some of this (if I remember correctly) from a given WYSIWYG profile preferences. You can add custom classes to apply to elements such as:

```
float left=float_left

```

then you make a CSS rule `.float_left: { float: left } ;`

You may find the WYSIWYG\_Filter module to be helpful in your needs.

Basically the WYSIWYG editor allows only certain things by default for safety. Drupal Input Formats further limit/allow what is allowed.
> 0 votes

# Answer
This does not help your exact question, but it is best to avoid WYSIWYG editors, it can often end up messing up the code or at least putting it in a way you cannot understand or draw sense from.
> -1 votes

---
Tags: 7, media, wysiwyg, input-formats
---


# Question
Title: What could cause remote drush commands to fail with ssh errors when ssh works in all other cases?
I have public and private ssh keys on all of my three servers (dev, UAT, & production) so I can log in remotely, or from one to another. Everything is working perfectly for the `ssh` and `scp` commands.

It does *not* work, however, for Drush. If I execute `drush @dev status` from UAT, for example, I get the server's banner saying the system is "to be used by authorized users only *blah blah blah*", and then I get

> Permission denied (publickey,password,keyboard-interactive).

My `~/.drush/aliases.drushrc.php` file contains:

```
# Development #
$aliases['dev'] = array(
  'uri' => 'http://default',
  'root' => '/var/www/vhosts/dev.www.company.com/current/',
  'remote-host' => 'companya0.company.com',
  'remote-user' => 'myusername'
);

# UAT #
$aliases['uat'] = array(
  'uri' => 'http://default',
  'root' => '/var/www/vhosts/uat.www.company.com/current/',
  'remote-host' => 'companyc6.company.com',
  'remote-user' => 'myusername'
);

# Production #
$aliases['prod'] = array(
  'uri' => 'http://default',
  'root' => '/var/www/vhosts/www.company.com/current/',
  'remote-host' => 'companyc1.company.com',
  'remote-user' => 'myusername'
);

```

***ONLY*** Drush has any problem using my ssh keys. What could be preventing it from working?

# Answer
> 19 votes
Put this line in your drushrc.php file:

```
$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/YOURUSERNAME/.ssh/id_rsa';

```

This will cause Drush to pass these options along to ssh any time it calls your remote system, so you can continue to call Drush via sudo, and still use your login user credentials.

# Answer
> 1 votes
Check here: How to run Drush as Apache

By the sound of it you just need to get the owner/group changed for Drush on your server!

---
Tags: drush
---


# Question
Title: Zen subtheme region templates not being used?
In a subtheme of Zen, I've got a `templates` folder that has `region.tpl.php` and `region--footer.tpl.php` that are copied from the main Zen theme. However, the custom region file is not being used for the regions of my theme; I even changed the contents of the `region--footer.tpl.php` file to just be `<?php exit("Hi!");` to see if it's being called at all, and it appears to not be.

I've cleared the theme cache (it's set to clear every page load); what am I missing to get that custom region template to actually apply?

# Answer
> 1 votes
A few things to check on that might be causing your error:

* Is the footer region populated with a box or content? If no, the region won't show.
* Have you edited the `region--footer.tpl.php` of the main Zen theme or your subtheme? Editing the wrong one won't show the result.
* Is the footer properly actived (not commented) in your subthemes's `.info` file? (`regions[footer] = Footer`)

---
Tags: 7, theming
---


# Question
Title: How can I create a new content type based on an attached format
I'm creating an intranet company portal website and the HR department requests I create a new Content Type/View for employee records. They sent me a document based on the format they would like. I was hoping to get some input on the easiest way of creating this content type/View

I uploaded the format to the following snapshot:

My questions are as follows

1. How can I format the Expiration Date field to align to the right of it's specific corresponding field
2. When adding new content with the HR content type, is it possible for the user to click "Add new Incident/Disciplinary/Recognition field"? For example, start with one field for each but if the employee has earned more rewards etc they can add a new field?

Thank you for your help

# Answer
1) Place each expiration field above the corresponding other field and then add the following CSS rules to your theme:

```
form.node-form .field-name-field-product-EXPIRATION-DATE {
position:absolute;
right:0;
width:200px;
}

```

On the content creation pages, this will move the expiration field to the top right of the field below.

2) Yes, users can add an unlimited amount of values to each field. To enable this go to the desired field in your content type and edit it. There look for "Number of values" near the bottom of the page. Choose the desired amount. Suppose you choose 5, the user creating the content can add up to 5 values for this one field. I hope this works out for you.
> 1 votes

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


# Question
Title: Does the drush up command work on multisite?
I have to update all sites on a D7 multi-site installation. I normally deal with single installation and I use drush up to update the core, modules and db. I have no prior experience with a multi-site installations.

I read this article on how to install drush for multi-site but I would like to know if running `drush -l mysite1.com up` will actually work before running it.

Kindly help if you have prior experience in this matter. Thank you.

# Answer
Yes! But maybe no! Be careful!

If you run pm-updatecode on any code in a given Drupal site, it is necessary to run updatedb afterwards in order to make the database schema(s) match the current schema in code. So, while `drush -l mysite1.com` will in fact correctly run `pm-updatecode` followed by `updatedb` on mysite1, if you have any modules in sites/all/modules that is updated, or if Drupal core is updated, then you will also need to run updatedb on every other site in the multisite install. If you skip this step, then mysite1 will work, but you might break the other sites in the multisite install.

When dealing with a multisite installation, the safest policy is:

1. Copy live to dev
2. Run pm-updatecode on every site in the multisite on dev
3. Run updatedb on every site in the multisite on dev
4. Test! Test! Test!
5. Take all of the sites in the multisite offline on production
6. Push your updated code from all multisites on dev to production
7. Run updatedb on every site in the multisite on production
8. Test again!
9. Bring all of the sites back online

You can avoid doing all sites at once if you know that all of your updated modules are in sites/mysite1/modules, and Drupal core is not updated. In general, though, it is better to avoid multisite installs so that you do not need to worry about the interdependence of the shared code on multiple databases.
> 7 votes

# Answer
Yes! drush @alias works for most everything I have tried so far. Just make sure you have you aliases properly configured. This feature just pretty much works the way it's written on the box. So far I have mostly used if for rsync and sql-sync without problems with multiple aliases.

I have set up all my aliases in .drushrc folder as stated on their manpage. - Make sure you scroll down on that page the good stuff is at the botton.

Hope this helps, good-luck.
> 1 votes

---
Tags: drush, multi-sites
---


# Question
Title: HTML escapes appearing in node titles on bespoke content type — substitutions?
I have a bespoke Content Type pertaining to venues. These are not user-creatable; they are all created from importing a trusted third-party feed, which sanitised the titles before they come to me (so there's no risk of XSS or SQL Injection here). The titles might, however, contain accented characters (`é`, `ô` *etc*), apostrophes (`'`) or ampersands (`&`); these are coming out as HTML escapes (so `'` instead of an apostrophe, `&` instead of an ampersand, etc).

The Content Type `Venue` has a field `title`, which is a Node module element, so doesn't allow me to mess with its display settings. In the Node template page, I can use substitutions in the display of this `title`, but I can't work out how to make it be the raw text version. The `title` is currently set to display as `%node:title` and I tried using `%node:title:raw` and `%node:title-raw` in case one of those would magically work, but they had no effect.

I saw something that looks like a potential solution at Custom HTML in Drupal Node Titles on zerotodrupal.posterous.com, which attaches to the hooks `hook_preprocess_page` and `hook_preprocess_node`, creating a new method like

```
function hhhdarkelegance_custom_title($node) {
    return check_markup(strip_tags($node->title, '<em><em>'));
}

```

but, while that blog post looks like it will work well for named HTML tags, I'm not sure it will necessarily deal with HTML *entities*, which are what my problem is here. I suppose I could do the opposite to the blog-post code and replace out `&` to `&` before display, but that feels really kludgy and, frankly, it would be nice to be able to do this just using a substitution, if possible.

Is there some way of achieving this that doesn't involve cutting code? If so, is `strip_tags` what is causing the HTML escapes? (The function description reads as though it's only causing the removal of HTML tags, which I am fine with either way — they won't occur in my node titles. I *am* wanting to stop escaping the HTML escapes, however.)

So how can I (on a specific Content Type, without worrying about security concerns) prevent Node titles from rendering HTML escape characters to the usual and just write the damn output to the page?

I did scan through several pages of similar-looking questions before posting and I couldn't find one that addressed this, so my apologies if someone has asked this already; if you point me towards it I'll be suitably embarrassed and try even harder next time. Thanks for your help, everyone!

# Answer
Whilst Jon's suggestion of `htmlspecialchars_decode` got me part of the way there, it turns out that the sample code from Custom HTML in Drupal Node Titles was less helpful.

Whereas that blog post suggested I do something like:

```
function modulename_preprocess_page(&$vars, $hook) {
    $node = &$vars['node'];
    if($node->type == 'my_content_type') {
            $vars['title'] = htmlspecialchars_decode($vars['title']);
            $vars['head_title'] = $vars['title'];
    }
}

```

I actually needed to do this:

```
function modulename_preprocess_page(&$vars, $hook) {
    $node = &$vars['node'];

    if ($node->type == 'my_content_type') {
        drupal_set_title(htmlspecialchars_decode(drupal_get_title()), PASS_THROUGH);
    }
}

```

Problem solved!
> 3 votes

# Answer
I've been searching for a solution to this for a client project i've been asked to help out on. Sometimes it's just not feasible to go around using htmlspecialchars\_decode() if the data is supposed to contain HTML entities, such as medical articles etc. Or entities are being introduced by a Triggered Rule configured to create a node and setting the title causes entities to be encoded in the node title. (These are the two situations I seem to run into in D6) Yes I could go around trying to work around all these things, but really it's sometimes just easier to have HTML entities being displayed properly so things work as they should.

I was looking for a solution to handle node titles on the node pages plus and also in Views.

Thankfully it looks like the module HTML Title appears to provide exactly this functionality now. Looking at the code it covers both the node page and displaying the title in Views.

Note that it looks like this module only appeared around July 2012, which is after some of the other answers here. For others looking for a solution this module might be an easier route than writing code to try and catch things. It's available for both D6 and D7. Note: I haven't tried it at all, I just found it and scanned the code right before I found this post, it looks promising and thought it might be useful for anyone else searching for a solution to this.
> 3 votes

# Answer
Would htmlspecialchars\_decode() be relevant then?
> 2 votes

# Answer
First off, there is no such thing as catch-all method to sanitise your data (at least not without losing some of your data) - you need to sanitise it separately for each use case. That means you HTML-escape it before outputting it to a web page, SQL-escape before including it in a database string etc.

The title field is designed to store plain text, so you shouldn't be including HTML entities in it at all - change your import process to call htmlspecialchars\_decode() before they are saved in the field. That way Drupal can HTML escape the field and everything will be good. You're actually introducing a potential XSS vulnerability if someone did find an alternative way of editing the title field.
> 2 votes

---
Tags: views, 7
---


title: 500 Internal server error

text:
# Question
Title: 500 Internal server error
I have a site running Drupal 7, and hosted on GoDaddy.

I use Filezilla FTP client to upload the files, or do any kind of file management on the server.

When I upload a file, the site shows a 500 error. After 25-30 minutes, the site starts working as usual.

This happens every time I upload a file.

# Answer
I have this error number of times while refreshing or uploading modules. it seems to be a server error. because some time server does not respond.
> 1 votes

---
Tags: files
---


title: Use Pictures For Labels

text:
# Question
Title: Use Pictures For Labels
Hello ive been trying to work out how to do this for years and ive a feeling its one of them eureka moments when i go 'oh aye thats how you do it'. I think thats why i have never been able to find anything on it.

Using Views 3 my lists look like this when using total views and total comments-

and i would like to get rid of the label for a wee pic like this-

Could anyone point me in the right direction?

Thanks

# Answer
You can use CSS background image concept to show images instead of Views & Comments text.

It should be very simple & straightforward ! You just need to identify the unique id or class in the html to apply css to that. Below article should be a good starting point for you !

http://stopdesign.com/archive/2003/03/07/replace-text.html
> 3 votes

---
Tags: views, entities
---


# Question
Title: How to intercept the loading of a field?
I have a field called field\_price. How do I get that field on my page to display `Free` when the value is `$0.00`, and the actual value every other time?

I tried to intercept the loading of the field by doing things like:

```
mytemplate_hook_load(){
// do stuff
}

mytemplate_process_field(){
// do stuff
}

mytemplate_preprocess_field(){
// do stuff
}

etc.. etc.. etc..

```

I tried so many different permutations of the above as modules, template, changing function names etc... But none of them ever fire. I know I have the Field module enabled.

What am I doing wrong?

**Note: I am using drupal 7**

# Answer
Ok, i figured it out. I put this code into my template.php of my theme:

```
function johncustom_field__field_price(&$variables) {
        if($variables['element'][0] == '$0.00') return 'Free';
        else return $variables['element'][0];
}

```

I also had to clear the cache several times before this function would fire.
> 4 votes

# Answer
I believe hook\_field\_formatter\_view is the answer for your question. It says

> Build a renderable array for a field value.

Using above hook in a custom module you can change the field value !

For Example, if your custom module name is johncustom then your function inside module file should be

```
function johncustom_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  // Change display type & Check for your field here
  switch ($display['type']) {
    // Override check plain
    case 'taxonomy_term_reference_plain':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#markup' => mymodule_crazy_fun_plain($item['value']),
        );
      }
    break;
  }
  return $element;
}

```
> 0 votes

---
Tags: entities, hooks
---


# Question
Title: Create content type with fields that are content types
I am trying to do something similar to this

I have a catalog content type. I want to be able to add one or more books related to the catalog topic to this content type. These books would be of a custom content type. Each book would only be tied to a single catalog but a catalog may have many books.

I want to create a page for each catalog topic that has the fields of the catalog content type (like description etc) and then a list of all the books related to the catalog topic.

I want authenticated users to be able to add new books ("add book" link) to the catalog and also to be able to create new catalogs for the topics they choose. When a new catalog is created, it should have an "add book" link.

How would do this?

# Answer
> 0 votes
A think you could be interested in Field Collection

---
Tags: entities, nodes
---


# Question
Title: Getting a custom view of Twitter and Facebook posts
I would like to display my client's twitter and facebook posts in a most-recent format in a custom view or block that will be implemented on their site. I was thinking of using the Feeds module, but was told by someone on twitter that cURL was the way to go. Giving these elements custom styling and keeping them listed by timestamp (not type of aggregate) is very important to me, and I was wondering about how to get this done.

# Answer
I have clients who require exactly the same feature, and the best method I have found so far is using Feeds and Feeds XPath Parser.

I create two Feeds importers that import from the RSS feeds of the client's Twitter and Facebook profiles. I set Feeds to create a node for each update (content type 'Social update') and use Feeds XPath Parser to populate the correct fields (title, body, timestamp, etc). I also set Feeds to automatically purge imported nodes after two weeks, and set it to schedule import on cron every hour.

Now I have each new post in a node, and I can display them however I like using Views.

This works ok, BUT I'm not convinced it's an optimal solution. I've looked at modules that interface with the Twitter and Facebook APIs for a better solution (e.g. Twitter Pull, Facebook Pull, Feeds Facebook Parser, Twitter) but they don't seem to provide a method for pulling Tweets and Facebook posts together in a single view or block. I'd love to get some more ideas on this.
> 2 votes

---
Tags: 7, views, feeds, social-network
---


# Question
Title: Attaching more than one feeds url to a single content type
I have a feeds setup in which i have a content type discount travels.I have created a feeds import using xpath xml parser.Now i want to attach one more link to the same content type.I know currently there is no provision for this in the feeds module.Instead we can create one more new feed importer with new link and attach it to the same content type.I doubt is it possible to have 2 unique fileds in the same content type.I have mapped one field from first URL to guid and marked it as unique.Then i mapped another field from second URL to guid and marked it as unique.Then i attached the new import to the same discount travels content type.Has anybody achieved this before using feeds and feeds import.Any help will be appreciated.Thanks in advance.

# Answer
> 1 votes
Instead of using the GUID field method that comes with Feeds, it is possible to use Feeds with the Field Validation module. See the discussion at patch at the bottom of this thread.

I haven't tried it, but Field Validation might let you set multiple unique fields as it provides validation options for every field in a content type.

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


# Question
Title: Let users assign particular roles to other users
How can I let a "subadmin" to **assign only particular roles to other users**?

Just an example: my users can only use the forum if they have the "*forum user*" role. I would like to delegate the right to a "subadmin" to assign the "*forum user*" role to particular users, without letting this subadmin to be able to assign any other roles. Or I also want to let this subadmin assign the "*article creator*" role to others, etc.

Is there a module for that? Or do I have to create my own?

# Answer
> 4 votes
I hope Role Delegation module solves your problem !

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role

# Answer
> 2 votes
You could do this with the Flag and Rules modules.

1. Make a flag for each role.
2. Give the subadmin permissions to flag/unflag.
3. For each flag, add a rule that adds the relevant role on flagging and another rule that removes the relevant role upon unflagging.

---
Tags: 7, users
---


title: can't override nice menus css

text:
# Question
Title: can't override nice menus css
I made a custom stylesheet for my nice menu in `sites/all/themes/mytheme/css/nice-menu-custom.css`

under admin -\> config -\> themes -\> global settings I set the path for my nice menus stylesheet as stated above. After saving this setting, the default css from nice menus actually disapeared from the nice menu block on my site, which obviously verifies that this set up is fine.

other than that, no matter what I do, no css getting processed.

* CSS compression is turned off.
* My problem actually started with my nicemenu class selectors not working in my at that time sole stylesheet `style.css`. So figured I'm going to do overriding by the book before asking the my question. Still to no avail.
* Flushed caches over and over

# Answer
> 1 votes
I think you are making it sound more complicated than it actually is. (smile)

As explained here, you may consider simply registering your custom stylesheet in your theme's .info file:

```
stylesheets[all][] = nice-menu-custom.css.

```

Once that is done, you have the benefit that your custom style-sheet will be loaded with all other application's css and js files, and be optimised by Drupal (when you change your dev settings to prod settings).

You understand that you can then overide any nice menu selector in your stylesheet, as long as your stylesheet loads last it should do the trick. If you want to "delete" an unwanted style, ***do not hack*** *nice-menu.css*, add an empty matching selector selector in your style-sheet.

THen, last but not least you can confirm your custom styles are being loaded by looking through any browser's inspector applet or script viewer, or even view source. Whatever. In dev mode (no caching, no script compression) you should see the changes without needing to drush cc on your instance.

Hope this helps, good luck

---
Tags: 7, theming
---


# Question
Title: Alter the Variables of Code called from template.php when using a tpl.php file
I am trying to clean up my field-FIELDNAME.tpl.php files to cutdown on the wrapper DIVs that are output.

This is how my code looks:

```
<?php if(count($items) > 1 ): ?>
  <div class="field-items <?php if($classes) :?><?php print $classes; ?><?php endif ?>"<?php print $attributes; ?><?php print $content_attributes; ?> >
    <?php foreach ($items as $delta => $item) : ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
<?php else: ?>
  <?php foreach ($items as $delta => $item) : ?>
    <div class="field-items <?php if($classes) :?><?php print $classes; ?><?php endif ?>"<?php print $attributes; ?><?php print $content_attributes; ?> >
      <?php print render($item); ?>
    </div>
  <?php endforeach; ?>
<?php endif ?>

```

Every field-FIELDNAME.tpl.php file looks the same, the only difference is that the element and the classes applied to the element changes. E.g. In some files, `<div class="<Code for printing classes>` is replaced with `<h3 class="title<Code for printing classes>`

As they are all similar, I thought I could put the code into my template.php file as a theme function. Then in my field-FIELDNAME.tpl.php I could call the function and just pass in the bits that change.

Here is how I have adapted the code for my template.php file:

```
function THEMENAME_field($variables) {
  $variables['element'] = '<div>';
  $variables['class'] = '';
  if(count($items) > 1 ) {
    print '<'.$element.' class="field-items'. $classes . $class. '"'. $attributes .'>';
    foreach ($items as $delta => $item) {
      print '<'.$element.' class="field-item'. $delta % 2 ? 'odd' : 'even' .'"' . $item_attributes[$delta] . '>' . render($item) . '</'.$element.'>';
    }
    print '</'.$element.'>';
  }
  elseif {
    foreach ($items as $delta => $item) {
      print '<'.$element.' class="field-items'. $classes . $class . '"'.$attributes . $content_attributes.'>';
      print render($item);
      print '</'.$element.'>';
    }
  }
}

```

And this is how I call the function in my field-FIELDNAME.tpl.php

However, it doesn't quite work the way I expect it to. Could someone give me some pointers as to what I am doing wrong?

Thanks!

**PS I know about Mothership and Semantic Fields but these are not right for my purpose.**

---

Update: new template.php code following vibaiher suggestion:

```
function THEMENAME_field($variables) {
$output = '';
$variables['class']= 'standard';
$variables['element'] = 'div';

      foreach ($variables['items'] as $delta => $item) {
      $items = $item;
      }

if(count($items) > 1 ) {
  $output = '<div class="field-items '. $variables['class'].'"' . $variables['attributes'] .'>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<' . $variables['element']. ' class="'. $classes . '"'. $variables['item_attributes'][$delta]. '>' ;
    $output .=  drupal_render($item) ;
    $output .= '</'.$variables['element'].'>';
    $output .= '</div>';
  }

}

else  {
    foreach ($variables['items'] as $delta => $item) {
      $output .= '<' . $variables['element']. ' class="field-item ' .$variables['class']. '"'. $variables['item_attributes'][$delta]. '>' ;
      $output .= drupal_render($item) ;
      $output .= '</'.$variables['element'].'>';
    }
  }

  return $output;

}

```

field.tpl.php code:

```
<?php $element = 'h3' ;?>
<?php $class = 'headline' ;?>
<?php print $output; ?>

```

---

---

Update following Andy's suggestions:

```
function THEMENAME_field($variables) {
$output = '';
$class = 'standard';
$element = 'div';

      foreach ($variables['items'] as $delta => $item) {
      $items = $item;
      }

if(count($items) > 1 ) {
  $output = '<div class="field-items '. $class .'"' . $variables['attributes'] .'>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<' . $element. ' class="'. $classes . '"'. $variables['item_attributes'][$delta]. '>' ;
    $output .=  drupal_render($item) ;
    $output .= '</'.$element.'>';
    $output .= '</div>';
  }

}

else  {
    foreach ($variables['items'] as $delta => $item) {
      $output .= '<' . $element. ' class="field-item ' .$class . '"'. $variables['item_attributes'][$delta]. '>' ;
      $output .= drupal_render($item) ;
      $output .= '</'.$element.'>';
    }
  }

  return $output;

}

```

---

UPDATE: Further example of what I want to achieve

Let's say I have a field called body text that allows one entry. The output would look like this:

```
<p class="field-item {$class}" {$itemattributes}> My Field </p>

```

I then have a field called intro text that has several entries. The output would look like this:

```
<div class="field-item {$class}" {$itemattributes}>

  <p class="field-item even">my Field 1</p>
  <p class="field-item odd">my Field 2</p>
  <p class="field-item even">my Field 3</p>
  <p class="field-item odd">my Field 4</p>
</div>

```

I then decided to create a new field called welcome text. I would like to be able to just re-use all the code for the other fields, but swap out the P tag with a H3 and swap the classes. That way, if I ever make any changes to my master field function, these changes will show up any new fields I create.

---

**Update: 11/10/12 - Latest Version of Andy's Code:**

```
/**
 * Implements hook_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  $variables['multiple'] = (count($variables['items']) > 1);

  // Add the field-item class.
  if (!in_array('field-item', $variables['classes_array'])) {
    $variables['classes_array'][] = 'field-item';
  }

  // Select the correct tag to use.
  if (($variables['element']['#field_name']['MY_FIELD']) == true) {
    $variables['tag'] = 'h2';
        $variables['classes_array'][] = 'my_title';
  }

else {
   $variables['tag'] = 'b';
}

}

```

# Answer
> 3 votes
Before any theme function or template is run, the preprocess and process hooks are run. This allows additional variables to be set up ready for use in the template/function. If you've created a new theme function called `theme_my_thing()`, you would use `template_preprocess_my_thing()` or `template_process_my_thing()` to set up the variables. For example take a look at `template_preprocess_page()` to see the page variables being set up. If you want to add variables to an existing theme hook, you can use hook\_(pre)process\_HOOK. For example, you can see how shortcut.module modifies the page variables at `shortcut_preprocess_page()`.

So in your case, you could create something like this in your template.php:

```
/**
 * Implements hook_preprocess_field().
 */
function MYTHEME_preprocess_field(&$vars) {
  if (SOME CONDITION) {
    $vars['tag'] = 'h2';
  }
  else {
    $vars['tag'] = 'div';
  }
}

```

Any variable you create in `$vars` will be extracted into the template/function. So the example above makes a variable called `$tag` available in the template/function scope.

Just as you're doing with this question, I try wherever possible to make templates generic and modify the variables before they get there.

I want to mention a couple of points about your example markup (I don't specialise in front-end btw, but think I'm right here!).

1. I'd prefer consistency over minimal styling, and having a wrapper around all of the field items when there are more than one, but nothing when only one, is a bit inconsistent imho. I'd expect this to make your styling tougher.
2. Typically a field has an overall wrapper, a title wrapper, and a content wrapper (which wraps all items), each of which has its own attributes array. For fields, there's also an item\_attributes array for each individual item. If you don't use these in your template then you might have compatibility problems with modules that expect them (I guess this would typically manifest as styling issues, or JS that doesn't work).

So basically I don't recommend doing this (: But, I think the following would work (untested). Field template (for a specific field):

```
<?php if ($multiple): ?>
  <div class="<?php print $classes; ?>"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <<?php print $tag; ?> class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"><?php print render($item); ?></p>
    <?php endforeach; ?>
  </div>
<?php else: ?>
  <?php foreach ($items as $delta => $item): ?>
    <<?php print $tag; ?> class="<?php print $classes; ?>"<?php print $content_attributes; ?>><?php print render($item); ?></p>
  <?php endforeach; ?>
<?php endif; ?>

```

In template.php:

```
/**
 * Implements hook_preprocess_field().
 */
function MYTHEME_preprocess_field(&$vars) {
  $element = $vars['element'];
  // Only act on the field 'some_field_name'.
  if ($element['#field_name'] == 'some_field_name') {

    $vars['multiple'] = (count($vars['items']) > 1);

    // Add the field-item class.
    if (!in_array('field-item', $vars['classes_array'])) {
      $vars['classes_array'][] = 'field-item';
    }

    // Select the correct tag to use.
    if ($some_condition) {
      $vars['tag'] = 'h3';
    }
    else {
      $vars['tag'] = 'p';
    }

    // Add any other classes/attributes.
    // ...
  }
}

```

# Answer
> 0 votes
All variables used in templates (tpl.php) in function THEMENAME\_field(&$variables) are stored in $variables array.

You can create a variable 'output' inside $variables, and add all html.

In your example:

```
$variables['output'] = '';
if(count($variables['items']) > 1 ) {
   $variables['output'] .= "<$element class=\"field-items $classes $class\" $attributes>";
foreach ($variables['items'] as $delta => $item) {
        $variables['output'] .= "<$element .......

```

And then in your tpl.php you only need print `$output` variable

# Answer
> 0 votes
Your function

```
function THEMENAME_field($variables) {

```

should not print anything but just calculate an output value returning in the end by

```
  return $output
}

```

You can use the $variables but adding values is of no use there. See http://api.drupal.org/api/drupal/modules!field!field.module/function/theme\_field/7 as an example. For **adding or manipulating** variables you should use the preprocess function

```
function MYTHEME_preprocess_field(&$vars) {

```

to prepare some existing variable or create new ones which can be used by your field.tpl.php file or function THEMENAME\_field($variables)

By defining a theme function THEME\_field the template file field.tpl.php is never used. Have you cleared the cache and removed the files from the THEME.info file?

---
Tags: 7, theming
---


title: terms of use at login

text:
# Question
Title: terms of use at login
The user has to agree to a terms of use at EACH login, not just at registration. What is the easiest way to do this?

Right now, I have a login page with only a login block on it (asking for username and password); once logged in the users are sent to the homepage. I need a pop up with terms of usage to appear after the login. The user accepts the 'terms of use' and are then directed to homepage, or are logged out.

There are several good modules that do what I want but only at registration, not for EACH login.

# Answer
I'd check out Login Toboggan. There's an example on the project homepage that nearly matches your use case.
> 1 votes

# Answer
You can user Terms Of Use module for integration.

Though this module provides terms of use checkbox at only registration page, But you can achieve the same for login also.

Just overview the code and you can use hook\_form\_alter()

In this module check **terms\_of\_use\_form\_user\_register\_form\_alter()** function. You can use this code and implement your own **terms\_of\_user\_from\_user\_login\_form\_alter()** function.
> 1 votes

# Answer
There is the Legal module, very useful

> Displays your Terms & Conditions to users who want to register, and requires that they accept the T&C before their registration is accepted.
>
> If T&Cs are changed users with an existing account will be asked to accept the new version, and will not be able to log in until they have.
> 0 votes

---
Tags: 7, users
---


# Question
Title: EntityFieldQuery to search Content Type for text and select matching Nodes
I have created Search page which searches Products (Content type) by selecting few option drop down menus (those are selecting taxonomy terms), but also i have an text input field, which is supposed to narrow or define search by keywords.

Now problem is that i need to search several fields at same time.

This script works perfectly (snippet):

```
$keywords=$_POST ['keywords'];
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN')
->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
$result = $query->execute();

```

I got all the product that are matching user entry, even if partial (those %). But i need to query some other fields too (description and name), to search for terms that user may enter.

But, problem is that i must have one input field, and user may target 3 different fields, so three fieldConditions for same term will cause nothing to be found, because selection is excluding all if term is not found in one field.

Could I,some way, write EntityFieldQuery query in a way to tell it to "forget" condition if keyword is not found ? (like in bellow example)

```
$keywords=$_POST ['keywords'];
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN')
->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
->fieldCondition('field_name', 'value','%'. $keywords .'%', 'LIKE');
->fieldCondition('field_description', 'value','%'. $keywords .'%', 'LIKE');
$result = $query->execute();

```

Other workaround could be to look all three fields in one place, if i could get combined fields in one condition query (this could be done by hand, by adding another field only for search terms that will be filled with tags that will be searchable summary of all 3 fields, but i am hoping to find the way not to create more field and content, if possible).

Any suggestions or experiences with that ? Thanks!

# Answer
> 1 votes
Do you mean something like this;

```
$keywords=$_POST ['keywords'];

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN');

if(isset($keywords)) {
 $query
   ->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
}
$result = $query->execute();

```

UPDATE

You can do an OR for each of the field. SO to do this you add a tag to the query which you are building and then you can alter the query using the hook\_query\_TAG\_alter

```
    $keywords=$_POST ['keywords'];

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->addTag('something');

    $result = $query->execute();

function modulename_query_**something**_alter(QueryAlterableInterface $query) {
  $or = db_or()
    ->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE')
    ->fieldCondition('field_name', 'value','%'. $keywords .'%', 'LIKE');

  $query
      ->condition($or);
}

```

This is just and example and you will have to make changes as per your requirements but this OR will definitely help.

Refer to the following links for a good example; http://treehouseagency.com/blog/tim-cosgrove/2012/02/16/entityfieldquery-let-drupal-do-heavy-lifting-pt-1 http://treehouseagency.com/blog/neil-hastings/2011/09/06/building-energygov-without-views http://treehouseagency.com/blog/fredric-mitchell/2012/02/21/or-queries-entityfieldquery

---
Tags: search, database
---


title: Remove jquery script

text:
# Question
Title: Remove jquery script
> **Possible Duplicate:**
> How do I update jQuery to the latest version I can download?

In Firefox I get an unresponsive script error from Google hosted jquery but can't echo the problem on other browsers.

I just looked at the source of drupal and it's loading v1.4 of jquery automatically. I applied my own Google Hosted link to jquery v1.8 in html.tpl.php so in the page is loading 2 versions of jQuery.

I think this could be the reason for the crash. In any case, I still want to remove the redundant script.

How would I go about removing the the automatically added jquery script? I want to print $scripts as some modules have dependents there.

# Answer
> 2 votes
You should use jQuery Update module. Here is a quote about it (from the module's project page):

> Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
>
> Updates:
>
> * Drupal 5 to jQuery 1.2.6
> * Drupal 6 to jQuery 1.3.2
> * Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
> * Drupal 8: TBD

---
Tags: 7, javascript
---


title: Node Hierarchy and active menu trails

text:
# Question
Title: Node Hierarchy and active menu trails
I'm trying to use Node Hierarchy module together with the Menu Block module to create blocks in different regions of my site. My problems is that when a child path is active, the parent path doesn't highlight.

An example of what I want is the path http://example.com/exampleparent/childnode1

My main menu is on the left side of the screen, like so:

* Home
* **Example Parent** \<-- active parent
* About

And the child menu is on the right side of the screen, like so:

* **Child Node 1** \<-- active child
* Child Node 2

But when I'm viewing the child node the parent isn't "active" (bold, in my example).

Is there an option I'm missing, or does the Menu Block module not work the way I think it does?

# Answer
The problem was not that the modules failed to act correctly. The problem was that the theme I was using did not have any CSS for the `active-trail` class that is provided.

To be thorough, there are two classes that get applied to menu items. The `active` is only for the exact menu that you're at. The `active-trail` class gets applied to all the parents of the current menu.
> 0 votes

---
Tags: routes, nodes
---


title: last entry in home page

text:
# Question
Title: last entry in home page
I created a content type and created various entries. Each entry has the following fields: name, photo, date.

How can I put a box on the home page with fields covering only the last entry? (I would also like a page with squares side by side, sorted by date.)

# Answer
You need to use CSS last-child selector to theme last entry as a box ! You need to write css in you active theme style.css.

> I would also like a page with squares side by side, sorted by date.

For above you need to use views module and display nodes in grid format sorted by sort filter date.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to place user control links in the top region of my website (as in stackexchange)?
I would like to have a block, in the top right region of my website, that works pretty much like Drupal Answers. A login/register button for anonymous users and when the users are logged in, their username (and their profile picture) would appear with a dropdown menu giving them access to control features like their profile page, a logout link etc..

I'm fiddling around with tpl files but nothing shows up.

Thank you

# Answer
> I'm fiddling around with tpl files but nothing shows up.

Don't forget to clear your Drupal cache after modifying .tpl.php files.

This can be done at **admin/config/development/performance** or using the `drush cc all` command via the Drush module.
> 0 votes

---
Tags: users, theming
---


# Question
Title: Rewrite results (like trimming titles) won't work at all
I created a view with articles. All I need is to trim titles.
The reason I cannot do this from content types (teaser view) is because the title field is a node module element. (It cannot be deleted, and is too late for that.)

There is an option in views output in the preview mode/contextual menus/rewrite results, but it seems it won't work.

None of the rewrite results options will work. It looks like a bug in the Views module.

# Answer
Clear your Drupal cache by visiting **/admin/config/development/performance** or if you use the Drush module, simply run `drush cc all`

Also make sure you're editing and viewing the correct view. If you're modify the master display but viewing an overwritten display, your master view settings will have no effect.
> 2 votes

# Answer
I was able to successfully trim node titles to 5 characters using the controls you show above.The following view normally produces 'SR 1-1, SR 1-2, SR 1-3'. With trimming enabled I get:

I used versions: drupal-7.9, ctools-7.x-1.0-rc1, views-7.x-3.0-rc1. Perhaps you need to upgrade your views or ctools modules. When you upgrade any module, always be sure to run update.php.
> 0 votes

---
Tags: views
---


# Question
Title: Link to small .php script on drupal page gives 404
I am new to drupal and have a page set up with a bunch of links. When clicked, the links are supposed to open up a php file (player.php, located in the root directory) in a new window. However, all I get is a 404 error. When I try to navigate to the page directly, I also get a 404 error (www.mywebsite.com/player.php).

If anyone has any suggestions on how to fix this, it would be a great help!

# Answer
> 4 votes
Make sure that your file player.php is in the right location; it should be in your Drupal root -- the same folder that has index.php. In my test, a php file at the document root was executed correctly if it was readable by the webserver -- it would run even without execute permissions. chmod 0 player.php gave me an internal server error, not a 404. You should check your permissions, but this seems to not be the issue.

Is this site using your own web server configuration file, or is it on a shared or managed ISP? Check to see if there are any rewrite rules that might be getting in the way.

The workarounds from my previous answer, below, should be unnecessary, but I will leave them here in case they may be of interest or help.

A. Put your file in a different location in the file system, and point at it with an alias.

```
    alias /player /srv/www/player
    <Directory /srv/www/player>
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

```

Put that in your Apache Virtual hosts file. If you cannot edit this file (e.g. on a shared hosting account), then this will not be an option. If you set up your vhost conf file like this, restart Apache and put your code at /srv/www/player/player.php. Access it from www.mywebsite.com/player/player.php.

B. Instead of using a standard php file, write a Drupal menu.

```
function mymodule_menu() {
  $items = array();
  $items['player'] = array(
    'title' => t('Player'),
    'access callback' => TRUE,
    'page callback' => '_mymodule_player',
  );
  return $items;
}

```

Accessing the URL www.mywebsite.com/player will then run the code in the function \_mymodule\_player.

See: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7

---
Tags: navigation
---


# Question
Title: Display Views results in a specific order?
I have a Views result set that I would like to give a very specific order not just 'ascending, descending' or defaults.

Currently I am saving them in reverse order and sorting by date updated descending, but this is somewhat of a pain.

Any thoughts on how to do this? Existing modules? Thanks!

# Answer
You can set arbitratry order on Views using the various ordering modules listed here.

Draggable Views is probably the most popular.
> 2 votes

# Answer
See https://stackoverflow.com/questions/2471361/drupal-sorting-a-view-programmatically ; //

\_views\_pre\_render gives you the opportunity to reorder results
> 1 votes

---
Tags: 7, views
---