title: Contact form in content type

text:
# Question
Title: Contact form in content type
I've made a content type User. Each user has a field email. I will not display the email but I would like a way for visitors to contact each user. So I am looking for a way to have a simple contact form inside a content type.

Any ideas?

# Answer
If you use the module Email Field to create your email field you can set the field to be displayed as a contact form. You will find the setting to turn the field into a contact form under Display settings for the field.
> 3 votes

# Answer
You can refer the following modules in addition to Email Field, which performs similar function as you need

Email Contact

> This module provides display formatters for the email field to display email as a link to the contact form, or as an inline contact form. Depends on the Email module.

Views Contact Form

> **Use cases**
>
> You need to create a block, an attachement or a page with a custom URL with a contact form inside that will send an email to a particular person (the recipient is taken from any field you want), you will use this module, Views and/or Panels. You need to create block that will send an email to the author of a content. You need to create block that will send an email to an email field, referenced through a reference in another content. Instead of displaying an email field as an email link (with mailto:), display a contact form instead and the recipient is taken from the field.
> 1 votes

# Answer
Contact Form On Node module add a contact form right under the node. You can choose:

```
to add a contact form on teaser,
to add a contact form on full view,
to add a contact link on teaser,
to add a contact link on full view,
which content types these settings will apply to.

```

or

Author Contact Creates a block that shows a contact form that when submitted, sends a simple contact email to the author of the current node. This might be useful for a multi-user blog or auction site.

or

Node feedback offers a check box on the node form asking the author to allow the visitors of the node to send feedback/request for the node using the personal/site wide contact form. Author can choose which category will be selected when user request the node information or wish to give her/his feedback. Admin can select between the individual contact form and site wide contact form. This is ideal for social networking sites as well as sites maintained by a single user.
> 0 votes

---
Tags: nodes, entities
---


title: Or operator in Views

text:
# Question
Title: Or operator in Views
I've got content-type includes 'field1', field2' and 'field3'. These fields are integer value. Thanks to Views module I created page 'Page1' with contents. In main menu I've got search whit some filters. After filling filters and entering, we can see appropriate contents in 'Page1'. I'd like to create filters or fields in search to allow user to fill in 'min' and 'max' values. After it I want to choose a content only if 'field1' or 'field2' or 'field3' of that content is beetwen 'min' and 'max'. How can I do it?

# Answer
In Views where it says Filter criteria there is a button that says Add, if you click on the arrow to the right you can access "And/Or, Rearrange", click that.

You now have an UI where you can group filters together and use OR between groups of filters.

In the example below the node should be Published or of type flickr\_image. First thing you need to do is click Create new filter group. From there you can drag your filters into your groups. Next select if the operator between the filters should be `AND` or `OR`.

After this add your three fields. Use the filter between, if the filter is exposed it will look like this.

I would keep the first filter exposed and the other not exposed. But then comes the tricky part. The other two filters must inherit the value from the first exposed filter.

I think you need a little bit of glue code to get this going. Put the code below in a custom module. You need to change MYMODULE to the name of your module, MYVIEW to the machine name of your view. And of course field\_1 and field\_2 to their real names.

```
function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'MYVIEWNAME') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_2_value']['value']['min'] = $view->exposed_input['field_1_value']['min'];
    $filters['field_2_value']['value']['max'] = $view->exposed_input['field_1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

```
> 3 votes

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


# Question
Title: Multilingual websites - Hiding site till ready
I am having basic workflow problem in creating translated website in Drupal 7. A site was handed to me which was already live(lets say www.mywebsite.com). It is having two languages already (English-www.mywebsite.com and Finnish-www.mywebsite.fi).

Now I need to add new language translation(Swedish). www.mywebsite.se already point to old D6 site (www.oldmywebsite.se). Also in language interface(admin/config/regional/language) Swedish domain entered is old one(i.e. www.oldmywebsite.se) to help visitor still access old site.

Question: So how can I create new Swedish dev site, something like se.www.mywebsite.com which will be hidden from public but I can still work on translations and it will later replace old Swedish site. Which modules to use or what I need to do at Drupal and domain level?

I have not worked on any translation setup before so I am feeling completely lost. Any help will be appreciated.

Summary :

```
www.mywebsite.com      :   new English
www.mywebsite.fi       :   new Finnish
www.oldmywebsite.se    :   old Swedish site

se.www.mywebsite.com   :   Want to create dev Swedish site which will later replace old swedish site

```

# Answer
> 1 votes
One option would be to password-protect your dev site; I've been doing this with a test subdomain for a while. You want to add something like this to the beginning of your Drupal .htaccess file:

```
AuthUserFile /path/to/.htpasswd
AuthName "Development Site"
AuthType Basic

# Change the below to match your actual domain.
SetEnvIfNoCase host se\.www\.mywebsite\.com is_dev

Order deny,allow
Deny from all
Allow from env=!is_dev
Require valid-user
Satisfy Any

```

You can refer to this if you're unfamiliar with .htaccess password protection or how to generate a .htpasswd file. Anyone who attempts to access the submdomain you have under development will be prompted by the server (Drupal need not get involved) to enter a username and password before they continue.

This could cause conflicts if you have any existing .htaccess-based allow/deny restrictions on your site or any portion of it, but should not conflict with the security restrictions Drupal has later in its default .htaccess file, and it definitely won't interfere with any Drupal modules that restrict access at the PHP/session level.

And as always when editing Drupal's .htaccess, make sure you back up the file and/or copy the changes over whenever you update Drupal core, because odds are it will be overwritten.

# Answer
> 2 votes
As long as you do not add se.www.mywebsite.com to the DNS nobody will find it. You locally can add se.www.mywebsite.com to your hosts file and point it to a IP (maybe your localhost). When ready to be launched you can add a pointer from se.www.mywebsite.com to the IP of the production server.

---
Tags: 7, i18n-l10n, multi-sites
---


# Question
Title: Will the PHP filter prevent SQL injection attacks?
I had trouble getting the form API to work though I am considering re doing all my forms with it. I have some custom html/php forms however I directly insert into the DB using pg\_query. I am looking into replacing that with pg\_query\_params to escape. I was wondering whether the php filter module, if I set it up, would prevent users from doing harm via sql injection? Iwould guess not but thought I would check.

Just looking for suggestions.

# Answer
No, it very much will not!

SQL injection prevention is something that needs to happen in the PHP code itself; the PHP filter won't alter your PHP, so it can't add protection to your code.

I'd be very surprised if there's anything out there that can auto-magically take an arbitrary PHP script and save it from SQL injection. In fact, if you ever see anything that claims to do that I'd go so far as to say "avoid it" it's lying.

Shows what I know :)

As per the comments, ModSecurity is an option if you want to control this at the web server level.
> 11 votes

# Answer
It will **not**, in any way shape or form protect you from injection. Quite the contrary, using the PHP filter is generally a horrible security problem, because it enables arbitrary code to be executed.

Do not use the PHP module, at all.

Greggles mentions the Paranoia module in his answer, which is awesome, consider using it. However, if you have enough control over your server, you could take it one step further, by disabling the `eval` function all together.

In your php.ini: `disable_functions = eval`
> 12 votes

# Answer
The title of the question is about using "PHP Filter" as a way to make queries safe. As others have mentioned:

* No, it doesn't magically make queries safe.
* Even worse, it will make your site less safe. I suggest the Paranoia module to *really* prevent the PHP Filter from doing anything.

But the body of the question gets into two more questions. Using `pg_query` functions directly and how to avoid SQL injection. You also should not be using `pg_query` directly but instead use the Drupal database API.

* Maybe you really love PG right now, but at some point the site has to move to a new database. Using the database API will make that easier.
* Drupal's database API, when used properly, has placeholder handling that will escape any SQL injection attacks

You can find more about this topic at Drupal Database API and the Writing Secure Code for more tips about how and why to use the Drupal database API for portability, security and scalability.

There are other modules and services that behave as an Intrusion Detection System or provide other means to avoid malicious attacks.

* The TinyIDS and PHPIDS modules attempt to detect attacks in every incoming request.
* There are Web Application Firewalls - webserver-level solutions like Apache's mod\_security - which can be configured to block requests with malicious patterns.
* There are commercial services like CloudFlare
> 3 votes

# Answer
The only reliable way to prevent SQL injection is to carefully use only parameterized queries ("prepared statements") and avoid string interpolation in queries. In PHP that means `pg_query_params` or appropriate PDO module use.

Even then, a multi-layered defense is certainly nice. I try to prevent obvious SQL injection attacks from appearing in identifiers where there's no reason for them to be permitted. If you try to set your username to something including `');` I'll just reject the request. Sure, I can safely insert that string and if the check wasn't there the attack would still do nothing, but it means I don't have potential attack code in my DB where it could be *read out and interpolated into another SQL command elsewhere*, perhaps by code that thinks that "this value came from the database so it must be safe".

This might save you if someone wrote a buggy PL/PgSQL function that doesn't properly use `format(...)` or `quote_ident` / `quote_literal`. The data passes straight through your app fine, then successfully executes the attack via the buggy PL/PgSQL function. Similar issues can arise from a badly written automation script, reporting tool, or all sorts of things.

So: even with data from your own DB, treat it as if it could be user-modifiable if it was *ever* user modifiable at any stage in its life-cycle. In fact, treat everything as user-modifiable and untrustworthy unless you have an extremely good reason not to.

So, IMO, much like you'll tend to reject obvious XSS attempts even though you know your code will safely handle them if not rejected, you should reject obvious SQL injection attempts even if your code will survive them fine.

Also, note that `pg_query_params` isn't magic SQL injection protection. If you write:

```
pg_query_params("SELECT blah FROM $tablename WHERE somecol = \$1", array($uservalue))

```

and `$tablename` can be defined by the user, you're still just as stuffed.
> 2 votes

---
Tags: database, security
---


# Question
Title: "IMCE Uploader" module is preventing some file types from being uploaded within IMCE
I have downloaded and enabled the "IMCE Uploader" module at https://drupal.org/project/imce\_uploader

This module allows you to within IMCE to upload multiple files at one time and is working better than the "IMCE plupload" module which I have found has corrupted some files after uploading.

I have configured the Media browser settings at /admin/config/media/browser to include a lot of file types (including jsonp, docx and xlsx) and without having the "IMCE Uploader" module enabled they all display when trying to do an upload within IMCE.

After enabling the "IMCE Uploader" and "IMCE Uploader - Plupload" modules I have noticed that some file types like jsonp, docx and xlsx are not allowed anymore when trying to do an upload within IMCE.

Is there any way that I can allow these additional file types to be uploaded within IMCE when using the "IMCE Uploader" and "IMCE Uploader - Plupload" modules?

# Answer
I am thinking that perhaps your allowed file types has changed in your IMCE profile, or IMCE Uploader has created a new profile for you and is using it by default. Check admin/config/media/imce/ and make sure the profile you are using allows those file types.
> 1 votes

---
Tags: files
---


# Question
Title: Logging into Drupal 7 site with headless browser: why would it fail?
***NOTE*: I've heavily revised the wording of my question to focus more clearly on the problem. There's a ton of really really useful information in the answers below, but not all of it applies to solving the problem of logging in with a headless browser. (Feel free to view the edit history for more details, as well as a more verbose version of the same info.)**

I'm using a headless WebKit browser (from CasperJS to log into my Drupal 7 site, and it is failing for unknown reasons. I first used the Ruby version of the Mechanize library and got identical results: access denied even after filling out and submitting the log in form. I'm pretty sure the problem has to do with Drupal, and some failure on my part to jump through some hoop (that is probably there to prevent spambots and such from submitting to Drupal-based sites).

Since my script loads the log-in form before submitting it, AFAIK it should work just like a normal user logging in. I've looked through the methods mentioned in the answers that details Drupal's form-submission process, but I'm not seeing what would cause my problem.

This question seems to provide clues, though it is D6 and using curl. That person is passing `field_source`, `form_token`, `form_build_id`, and `form_id` as fields. In my form I only see `form_build_id` and `form_id`. *Should* I be passing all those fields, even though they don't seem to be present in the login form? Drupal seems to look for `form_token`, but it's not present on my login form. What's up with that?

***NOTE***: Someone will undoubtedly ask why I'm using these tools when there must be better ways with such-and-such a Drupal module, and the short answer is just that I chose to use tools I'm most familiar with. If you have good module suggestions please leave comments (with implementation details if possible) as I'd love to hear the suggestions, but I'd still appreciate an answer to this question *as it is asked*. Thanks.

# Answer
> 1 votes
> Is there some security feature built into Drupal to prevent submissions by scripts?

Yes, there is.

In order to prevent automated form submission by bots etc.. During form build Drupal generates a token, based on session id, and a unique id, for form cache. These are used during form validation.

See:

In order to successfully submit the form, you would need to retrieve it and then submit it using the same token and form\_build\_id values.

However, there are other ways to submit forms programmatically, such as

drupal\_form\_submit

As well as purely code based methods to log a user in.

e.g, in a very simple form:

```
// Load a user account and assign to global $user
global $user;
$account = user_load(1, TRUE); // Root user
$user = $account; // This "logs" the user in
drupal_session_regenerate();
// Invoke login event
$edit = NULL;
user_module_invoke('login', $edit, $user);

```

# Answer
> 1 votes
> Is there some security feature built into Drupal to prevent submissions by scripts?

Yes, there are. First off, a script that is not bootstrapping Drupal cannot submit a form that has not requested to a Drupal site. Drupal explicitly check that condition is verified, and that task is done from drupal\_validate\_form(), which contains the following code.

```
  // If the session token was set by drupal_prepare_form(), ensure that it
  // matches the current user's session.
  if (isset($form['#token'])) {
    if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
      $path = current_path();
      $query = drupal_get_query_parameters();
      $url = url($path, array('query' => $query));

      // Setting this error will cause the form to fail validation.
      form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
    }
  }

```

\_form\_validate() then verifies there is a correspondence between the values submitted and the form elements contained in the form requested to Drupal. If there isn't an exact correspondence, the submission fails.

```
  if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
    form_error($elements, $t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
  }

```

```
        if (!isset($options[$v])) {
          form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
          watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
        }

```

```
   elseif (!isset($options[$elements['#value']])) {
      form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
      watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
    }

```

> Is there some other reason scripts would fail to log into Drupal on a page where a user in a normal browser would have no problem?

As you are asking for a headless browser, the form submission could be successful if:

* The browser requests the login form
* It inject JavaScript code that fills out the necessary fields, and submit the form back to Drupal

The condition necessary for the operation to work is that the browser is able to keep the session open. In fact, the token used to validate the form is obtained from drupal\_get\_token(), which contains the following code.

```
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());

```

The function used to validate the token is drupal\_valid\_token().

```
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  global $user;
  return (($skip_anonymous && $user->uid == 0) || ($token == drupal_get_token($value)));
}

```

As side note, to create content is not necessary to log in as a specific user: Just bootstrap Drupal, build a node object, and call node\_save().

For example, the following code put in a file in the same directory containing the index.php Drupal comes with would create a node. (The code is for Drupal 7, but a similar code can be written for Drupal 6.)

```
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $node = new stdClass();
  $node->title = $node_title;
  $node->type = $node_type;

  // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  node_object_prepare($node);

  $node->language = LANGUAGE_NONE;
  $node->uid = $user_id;
  $node->status = 1;
  $node->promote = 0;

  // Comments are disabled; change it to COMMENT_NODE_OPEN to enable them.
  $node->comment = COMMENT_NODE_CLOSED;

  $node = node_submit($node);
  node_save($node);

```

Using this code, Drupal would create a node.

If the code is used for a publicaly available site, and you want to avoid everybody runs the file (let's suppose the file is migration.php), you can use the following code.

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('migration_key', 'drupal') != $_GET['cron_key']) {
  watchdog('migration', 'Migration could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('Migration', 'Migration could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  $node = new stdClass();
  $node->title = $node_title;
  $node->type = $node_type;

  // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  node_object_prepare($node);

  $node->language = LANGUAGE_NONE;
  $node->uid = $user_id;
  $node->status = 1;
  $node->promote = 0;

  // Comments are disabled; change it to COMMENT_NODE_OPEN to enable them.
  $node->comment = COMMENT_NODE_CLOSED;

  $node = node_submit($node);
  node_save($node);
}

```

The Drupal variable migration\_cron should be initialized with `variable_set('migration_key', drupal_get_token('update'));`. The script would be then called as http://example.com/migration.php?migration\_key=XYX, where XYZ is the value saved in the Drupal variable migration\_key. As `drupal_get_token()` returns a different value each time the function is called, external *attachers* could not get the value to use to run the script.

The code I shown creates just a node, but using similar code would be possible to migrate content. The code would execute a loop to create a node for each entry loaded from a file, an external database, or returned from a `drupal_http_request()` call to an external site (among other methods). In any case, it is not necessary to first log in to create a node, if the PHP code first bootstrap code.

If you can use Drush, that would probably be a better way to programmatically create content.

As alternative, there are many modules to migrate content. As far as I recall, also the Feeds module is used to migrate content to Drupal.

# Answer
> 1 votes
Try this with CasperJs: Need CasperJs and PhantomJs on your system PATH

```
#filename testCasper.js

var _adminUser = '';
var _adminPass = '';
var _baseUrl = 'local.drupal.dev';

casper.test.begin('Basic BDD: login as Admin and test behavior of interface.', 3, function suite(test) {

casper.start(_baseUrl , function() {
    test.assertTitle("drupalLocal.dev", "homepage title is ok");
    test.assertExists('form#user-login-form', "user login form is found");
    this.fill('form#user-login-form', {
        name: _adminUser,
        pass: _adminPass
    }, true);
});

casper.then(function() {
    test.assertTextExists('Log out', 'User is logged in');
    console.log('location is ' + this.getCurrentUrl());
});

casper.run(function() {
    test.done();
    phantom.exit();
});
});

```

run with:

```
`casperjs test testCasper.js`

```

---
Tags: migrations, security
---


# Question
Title: When I double-click on the publish content tab on a node, I end up on /user instead
This is on a pretty complex site so I have no idea where to start looking for the cause of this behavior.

I have installed the Publish Content module, which creates a little "publish" or "unpublish" tab along with "view" and "edit" on each node, for users that have permission to publish or unpublish content.

When I click on "publish" or "unpublish" once, the expected behavior follows. But if I double-click on that tab (and *only* that tab – others don't do this), then instead of reloading the node, it takes me to my user page.

I tried disabling the devel module but that didn't help. It happens on multiple content types, and as multiple different users with different roles, including user 1.

I have a couple of rule-based redirects in place, but they're only for specific roles and they're only triggered on particular actions (such as login). And none of them redirect to the user's own page.

I have no idea where to start debugging this.

# Answer
> 0 votes
It's because when you double click, most probable case is the second click will try to use an already used token.

Or it could also be due to the fact that the second click might be translated as trying to publish an already published node.

---
Tags: users, redirection, nodes
---


# Question
Title: Omit blank lines when trimming fields with views
I have made a views gets the body field and select:
Formatter -\>summary or trimmed

but the field have blank lines which calculated in the length so I may get empty.

Despite selecting Remove whitespace but still count the blank lines as it is full of text and so I get empty preview.

Please help .

thanks

# Answer
I've had a similar problem in the past, especially when making the summary trimmed to a shorter length.

When it tries to truncate certain tags like tables or images that can be quite long - and the number of characters you allow is reached before the table/image has been fully parsed, you can end up with a blank summary.

What I do is that I strip certain HTML tags from my fields that are trimmed to only display paragraphs, etc - not images and/or tables.

Just click on the field to set up the new configuration, and you'll find the option in the 'Rewrite Results' section:

Let us know if this works!
> 2 votes

---
Tags: views, entities
---


# Question
Title: Drupal Multisite, same module name, different site
We have a module that needs to be the same name, but its functionality will change for each site.

Is it an ok practice to put put them in sites/site1/modules/MODULE\_NAME and sites/site2/modules/MODULE\_NAME

Will this cause any problems with drupal if they have the same name, but are in different sites?

# Answer
As long as they are in the individual sites' directories, the are only visible to the sites they are associated with. Should be no problem.
> 1 votes

---
Tags: 7, multi-sites
---


# Question
Title: Fielded Relation's Field not showing in Views
I'm trying to implement a "rating" system with Relation module. I have a Relation Type defined from a user --\> node. The Relation Type has an Integer field to hold the rating.

I want to produce a view that shows the number of ratings and average rating. To start, I created a view with a list of nodes. I previously created a few "rating" relations between users and the nodes in the view, which can be seen in the Relations tab in content.

In views UI Advanced section, I added the Relationship from the node to its Relation. I added a view field for the Integer field on the Relation.

The label for the rating field shows, but the number is empty, even for relations I know are there.

Here is an export of the view:

```
$view = new view();
$view->name = 'offer_ratings';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Offer Ratings';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Offer Ratings';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Relation: rated by (node → relation) */
$handler->display->display_options['relationships']['relation_base_right_rated']['id'] = 'relation_base_right_rated';
$handler->display->display_options['relationships']['relation_base_right_rated']['table'] = 'node';
$handler->display->display_options['relationships']['relation_base_right_rated']['field'] = 'relation_base_right_rated';
$handler->display->display_options['relationships']['relation_base_right_rated']['r_index'] = '1';
$handler->display->display_options['relationships']['relation_base_right_rated']['entity_deduplication_right'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Relation: Rating */
$handler->display->display_options['fields']['field_rating']['id'] = 'field_rating';
$handler->display->display_options['fields']['field_rating']['table'] = 'field_data_field_rating';
$handler->display->display_options['fields']['field_rating']['field'] = 'field_rating';
$handler->display->display_options['fields']['field_rating']['relationship'] = 'relation_base_right_rated';
$handler->display->display_options['fields']['field_rating']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'offer' => 'offer',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'offer-ratings';

```

# Answer
> 0 votes
Joe,

The best way to do a rating system in Drupal is to use Five Star: https://drupal.org/project/fivestar.

It comes with views integration out of the box. You add a rating field to your content type, place it in the display, render your entity in a view, or create a fielded view if you prefer the Drupal 6 way, and you're done.

---
Tags: views
---


# Question
Title: How to prevent users from accessing content?
Newbie doing tutorial.

I want to deny anonymous access to my site. My Tutorial (not up to date for V7) says unCheck "Access Content" to disallow access. This permission does not exist (or I could not find it).
Is unChecking "Access Content" the same as unChecking "View Published Content"?

Have I found the wrong permission?

# Answer
You want to uncheck the **View published content** permission for anonymous user. So yes you have found the right permission.
> 3 votes

---
Tags: users
---


# Question
Title: A taxonomy-provider module: enable/disable vs install/uninstall
If a module provides a taxonomy vocabulary, what should happen in `hook_install`, `hook_enable`, `hook_uninstall` and `hook_disable`?

My main concern is how `hook_uninstall` should differ from `hook_disable`. Should we just `taxonomy_vocabulary_delete()` in both hooks? Should the existing nodes referring to the terms just lose the references upon disabling as well as uninstalling of the module?

# Answer
There is at least one core module that creates a vocabulary that we can use as a guide: Forum.

It creates the vocabulary "Forums" in `hook_enable()` (see `form_enable()` function).

It **does not** remove the vocabulary in `hook_disable()` or `hook_uninstall()`. (see `forum_uninstall()` function \- Forum does not have a `hook_disable()` function.

So, to answer your question, **create the vocabulary in `hook_enable()` and don't delete it.**

One other note gleaned from the `forum.install` file that is probably relevant to your module is that you need to make sure your module is loaded after the Taxonomy module. You can do so by settings the module's weight to `1`.
> 1 votes

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


title: Filtering contents in Views

text:
# Question
Title: Filtering contents in Views
I've got content-type with 3 integer field. I use Views module to display contents. I've got search. I'd like to create input in that search. After filling that input and entering I want to display contents whose at least one field is equal given value. How can I do it?

# Answer
> 0 votes
Sounds like exposed filters are what you're looking for. Just check for the "Expose" control when you're edited any filter item in your view.

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


title: Pre and Post event on AJAX call

text:
# Question
Title: Pre and Post event on AJAX call
In a form, using #ajax to add a callback when a button is pressed. When the button on my form is pressed, I wish to call some JavaScript when the button is pressed and once again when the AJAX call is complete. can anyone suggest?

# Answer
The "duplicate" I linked to above gives you almost all of your answer, but this adds the "complete" function that you asked for.

In a custom js file in your module (this assumes that your module is named `ajax_example` and that the ID of the element being clicked is `#edit-submit`):

```
Drupal.behaviors.ajax_example = {
  attach: function (context, settings) {
    // Overwrite beforeSubmit
    Drupal.ajax['edit-submit'].options.beforeSubmit = function (form_values, element, options) {
      console.log('before');
      // Add your on click code here
    }
    // Overwrite complete
    Drupal.ajax['edit-submit'].options.complete = function (form_values, element, options) {
      console.log('after');
      // Add your on complete code here
    }
  }
}

```
> 1 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: Installing Drupal 7.22 fails at database configuration step on Win7
I succeeded to install drupal 7.22 on my production server but still fail to have it running on my local EasyPHP running on win7 64b.

At database configuration step of the install process I have the following message:

```
Warning: in DatabaseConnection->__construct() (line 304 of C:\Program Files (x86)\EasyPHP-5.3.2i\www\drupal-7.22\includes\database\database.inc).
In order for Drupal to work, and to continue with the installation process, you must resolve all issues reported below. For more help with configuring your database server, see the installation handbook. If you are unsure what any of this means you should probably contact your hosting provider.
Failed to connect to your database server. The server reports the following message: .

```

You might note that no error message is actually reported.

The mentionned line 304 is opening the connection:

```
// Call PDO::__construct and PDO::setAttribute.
parent::__construct($dsn, $username, $password, $driver_options);

```

I verified db name, credentials, and other settings by connecting on the database with MySQL Workbench which succeed to connect to db.

I tried editing myself the default.settings.php:

```
$databases = array(
  'driver' => 'mysql',
  'database' => 'drupal-7.22',
  'username' => 'datagrmdb',
  'password' => 'mypassword',
  'host' => 'localhost',
  'port' => 3306,
  'prefix' => 'drupal_',
  'collation' => 'utf8_general_ci', // also checked that DB is configured this way
);

```

but that still failed.

I tried editing settings.php directly and reloaded the install process to continue but it stop saying that "Database is already installed". It suggest to empty the db but it is already empty.

Back to drupal wizards I also tried using 127.0.0.1 instead of localhost and setting 3306 manually but that did not changed.

There is another drupal database (another version) in mysql but I assume that should not cause any problem.

EDIT: I verified php\_pdo.dll and php\_pdo\_mysql.dll exist in the php/ext directory

Any hint?

# Answer
Thanks Clive for the suggestion.

Writing www/test\_pdo.php:

```
<?php
try{
    $dbh = new pdo( 'mysql:host=127.0.0.1;port=3306;dbname=drupal-7.22',
                    'mydb',
                    'mypassword',
                    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>

```

proved the connection worked for "127.0.0.1" but not for "localhost", my initial setting.

So I changed sites/default/settings.php and reloaded and that worked.
> 1 votes

---
Tags: 7, database, installation
---


# Question
Title: Homebox column number different on mobile?
I have created a 3 column homebox site with rss feeds in an attempt to roll my own replacement for google ig (which is to shut soon). It works perfectly for what I want. Is there a simple method to serve up a 1 column version of the same site to mobile users? I have been investigating browscap and adaptive theme (AT) but I was hoping there was a simple method of serving the same site with 1 column instead of three (must use homebox)?

Desktop: Mobile:

# Answer
> 1 votes
Add the following to your css.

```
@media screen and (max-width:740px){
    .homebox-column-wrapper{
          width:100%!important;
          clear:both;
    }
}

```

---
Tags: theming, dashboard
---


title: Change admin menu item

text:
# Question
Title: Change admin menu item
How would I unset this menu item: Content \> Add Content \> Article

I would like to programmatically disable that path-page (node/add/article), or even better use that path for another page. I tried using **hook\_menu\_alter(&$items)**. Does not work for that path, while on others custom menu items that I created using hook\_menu it does work.

Update: This is simple code that I tried (unset the $item key):

```
mymodule_hook_menu_alter(&$items) {
     unset($items['node/add/article'])
}

```

# Answer
Admin menu is an yet another menu, which builds programmatically. So you can modify items using hooks registered for any menus.

If you would like to disallow atricle creation by specified role, just remove appropriate permission.

If this does not helps, look at admin\_menu\_menu\_alter() and theme\_admin\_menu\_links().
> 0 votes

---
Tags: routes, uri
---


# Question
Title: Render the first image of an image field which allow to enter multiple images
I have a template file for my blog page that renders a single image when the blog posts are listed. Originally, the field was for a single image, but it has been changed to accept more than one image and render only the first image. I would like to do within a template file instead of a view.

In that template file I used the following code, which doesn't work anymore since the image field has been changed.

```
<div class="image"><?php print render($content['field_blog_images']); ?></div>

```

Instead of that, I tried the following code, which doesn't work too.

```
<div class="image"><?php print render($content['field_blog_images'][0]); ?></div>

```

How should I render the first image of a field that accepts multiple images?

# Answer
It's all about the structure of the image field. You're automatically going to the 0 index, but I bet if you were to do a dump of that variable, you'd find you were at the wrong position in the array. You'll need to loop through it or target the very specific element you're looking to render.

Check out this documentation comment for details and modify for your example. That comment shows the following code to loop through the images.

```
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_NAME');
foreach ($image as $key => $value) {
  $output = field_view_value('node', $node, 'field_NAME', $image[$key], array(
    'type' => 'image',
    'settings' => array(
      'image_style' => 'thumbnail', //place your image style here
      'image_link' => 'content',
    ),
  ));
  print render($output);
}

```

That code is showing how to loop through the images in a different context, but the `foreach()` loop is the same that should be used in your code.

For that reason, it could be worth taking this up to template.php inside `hook_preprocess_node()` to avoid adding logic in a template file.

```
function mytheme_preprocess_node(&$variables) {
  if($variables['node']->type == 'blog' {
    // My crazy logic to assign my image variable.
    $variables['blog_image'] = render($somevalue);
  }
}

```

The template file then just needs a single code line.

```
print $blog_image;

```
> 2 votes

# Answer
If you insist on `not to use Views` for theming your blog teasers, you can use template preprocess\_node function to create the hook suggestion and variables for the template file which you're going to use.

Example:

```
/**
 * Override or insert variables into the node template.
 */
function YOURTHEME_preprocess_node(&$variables) {

  $node = $variables['node'];

  // it allows to use templates for the type and view_mode e.g: node--blog--teaser.tpl.php
  $variables['theme_hook_suggestions'][] = 'node__' . $node->type . '__' . $variables['view_mode'];

  // blog teaser
  if ($node->type == 'blog' && $variables['view_mode'] == 'teaser') {
    $images = field_get_items('node', $node, 'field_blog_images');
    if ($images) {
      $blog_image = field_view_value('node', $node, 'field_blog_images', $images[0],
        array(
          'type' => 'image',
          'settings' => array(
          'image_style' => 'thumbnail',
          'image_link' => 'content',
        ),
      ));
      $variables['blog_image'] = $blog_image;
    }
  }
}

```

Now you can use `node--blog--teaser.tpl.php` file for theming your blog teasers and print the image:

```
<div class="image"><?php print render($blog_image); ?></div>

```
> 0 votes

---
Tags: theming, media
---


# Question
Title: What are the significant differences between the Sharethis, Addthis, and Service Links modules?
These three modules appear to be very similar in terms of functionality. AddThis has about double the number of the installs compared to the other two, but Service Links and ShareThis each have over 10,000 installs, which is not too shabby.

What, if any, are the significant differences among these modules?

# Answer
There is some detailed information on each of these, and others, over at Comparison of Social Network connectors/Sharing modules. It would be best to add any new information to that wiki page so that we have something that's always up-to-date.
> 2 votes

# Answer
The most significant difference is that AddThis isn't maintained since nearly 1 whole year now. For D7 there only are alpha, beta and dev releases.

ShareThis is kind of light weight compared to Service links, which comes with much more available options.
> 1 votes

---
Tags: social-network
---


title: Removing text from main page

text:
# Question
Title: Removing text from main page
In the main page I've got text "The front page". I managed to change that text but unfortunately I don't rembember appropriate place.

How can I remove that text?

# Answer
"Find Content" (/admin/content) then Edit the node.
> 0 votes

---
Tags: 7
---


# Question
Title: not able to display the real name of the users
First of all, I am not a techie and have picked the codes mentioned below from various sources. I have added two new fields to the user profile - 'firstname' and 'surname'. I am using a custom theme and on one of the places (on a node), I need to display the real name (making some code changes) instead of the username.

I am replacing the existing code -

```
<h3><?php print $node->name ?></h3>

```

With this -

```
<h3><?php
     $profile = user_load($node->uid);
     $profile = user_view($profile);
     $firstname = render($profile['field_firstname']);
     $surname = render($profile['field_surname']);
     print $firstname.' '.$surname; ?></h3>

```

However, a strange thing is happening. I am able to print the surname correctly but the firstname is blank every time, even when I tried to print only the firstname (or the surname). Why is it that the firstname is not getting picked? What changes should I make?

# Answer
> 1 votes
You can load the node object from the nid and from the node you can get user object.

With user object we can able to get firstname and lastname field values, if there is one. usually a node submitted by anonymous user will have no name.

you can try this code.This works in drupal7.

```
<?php
    $node = node_load($nid);
    $profile = user_load($node->uid);
    $firstname = $profile->field_first_name['und'][0]['value'];
    $surname = $profile->field_last_name['und'][0]['value'];
    print $firstname.' '.$surname;
?>

```

# Answer
> 2 votes
Did you try real name module before write your own code?

I did not use 6.x version, but i guess it will be more flexible than your solution.

---
Tags: entities, users
---


# Question
Title: change weight of fileds programmaticaly in drupal 7
I have a registration form with different attribute like

Captcha and security questions which are coming from different modules.

I want to change the display order of form elements.

and i am using this code in my custom module

```
function tenantwallet_form_user_register_form_alter(&$form, &$form_state){
    $form['#pre_render'][] = 'tenantwallet_form_alter_weight';

}
function tenantwallet_form_alter_weight($elements){

    $elements['field_first_name']['#weight'] = -50;
        $elements['field_last_name']['#weight']= -49;
        $elements['field_company_name']['#weight']=-48;
        #field_company_number, field_secondary_number, field_mobile_or_landline,field_gst_number, field_share_my_info, field_company_logo,field_facebook_id, field_mobile_conformation_code,field_date_of_birth,, field_gender, field_id_proof,field_secondary_id_proof, field_mobile_number,field_promo_emails_notifications,field_sugar_id, captcha,
        $elements['captcha']['captcha_widgets']['#weight']=-50;
        $elements['pass']['#weight']=-47;
        $elements['questions'][0]['question']['#weight']= 45;

    return $elements;
}

```

But this is not working. Can anybody tell me how to solve this. Thanks

# Answer
> 1 votes
it seems there are different scope in your form . Like question and captcha are in different scope. Try to give weight for each scope too. Then it will work for you. Like

```
 $elements['questions']['#weight']=50;

```

# Answer
> 0 votes
I don't have the possibility to test now, but you should be able to do that directly in the `hook_form_FORM_ID_alter()` like:

```
function YOURModule_form_FORM_ID_alter(&$form, &$form_state) {
  $form['elements']['field_name']['#weight'] = 10;
}

```

---
Tags: 7
---


title: date format in database of quiz module

text:
# Question
Title: date format in database of quiz module
I make a quiz with quiz module and the start date is 1/8/2013 4:30 and the close time is 10/8/2013 4:30. In the database it stored as this=\>

```
1375315200(quiz open)
1376092800(quiz close)

```

which one is year, month and day?

# Answer
> 0 votes
Use PHP's `date()` function.

Example:

```
echo date('m/d/Y', 1299446702);

```

Check Unix Timestamp Conversion Tools online

---
Tags: 7
---


# Question
Title: Possible to pull the validate hook on forms not in form api
Is it possible to utilise the validate hook from within a node rather than a module? The code below works within a module calling a form with the form API. But if i was to have a variable in a node page, could i utilise the same function within the nodes html/php? if so how? or a similar validate function?

```
$mynumber= $_POST[mynumber];

```

e.g.

```
function form_example_form_validate($form, &$form_state) {
      if (!is_numeric($form_state['values']['mynumber'])){
form_set_error('mynumber', t('Validation: You must enter a valid number for the number field.'));

```

# Answer
> 0 votes
The validate handlers for forms aren't hooks as such, they're just functions that use a naming convention provided by the FAPI (small point, but worth mentioning).

*Technically* speaking, you might get away with putting said function in PHP in the body of a node. If you have a form called `MYMODULE_form_test`, and declare a function called `MYMODULE_form_test_validate` in the body of a node, the processor might well pick it up in time, and Drupal might call it during form validation. But you'd probably get some strange, incorrect results when you turn caching on.

Either way, I wouldn't rely on it working forever more; it's certainly not an advisable workflow, and keeping code in the node body is considered very bad practice.

Creating a module only takes a couple of minutes, and this sort of functionality is exactly what they're designed to contain.

---
Tags: forms, nodes
---


# Question
Title: Drupal 7: Can't Update node using php script
I'm trying to update a node-\>body using a php script in my root directory of my Drupal 7.22 installation.
I call the script through a browser (firefox) with \[http://MYSITEURL/nodeupdate.php\]
But somehow I don't get it to work. Here is the code I use:

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$nid = 9; // YES node 9 exists.
$node = node_load($nid); // where $nid is the node id

echo "$node->title <br>"; // Just to make sure it changes the right node and it does.

$node->body[$node->language][0]['value']   = "Test updated";

if( $node = node_submit($node)) {
    node_save($node);
    echo "Node with nid " . $node->nid . " updated!<br>";
}

print_r($node); // Check if we see any changes.
?>

```

The script executes fine without any errors. Through the print\_r function I can see that the "changed" field and "revision\_timestamp" field are changing.
However the body doesn't change!
I have been googling and found many posts from which I gather that this is the way to do it.
What am I missing?

# Answer
> 1 votes
Make sure you're logged into the site as a user with permissions to update the specified content type, because that session will carry over to your bootstrapped script. If you're logged out, you're essentially attempting to update the node as an anonymous user in your script, and permissions will come into play.

Try adding...

```
global $user;
print_r($user);

```

...to your script and see what, if anything, that outputs.

# Answer
> 0 votes
Solved without knowing why.

If I use
`$node->body[LANGUAGE_NONE][0]['value'] = "Test updated";`
it works, and if I use
`$node->body[$node->language][0]['value'] = "Test updated";`
it doesn't.

---
Tags: 7, nodes
---


title: Breadcrumb splits my node title

text:
# Question
Title: Breadcrumb splits my node title
If I have a title that is longer than one line, then the bread crumb trail in the middle of it.

Example: http://www.energyjustice.net/node/1948

I want the bread crumb trail to either come before or after the title.

I'm using Drupal 7.19

# Answer
> 0 votes
To start with, get rid of this:

```
#wrapper #container .breadcrumb {
  position: absolute;
  top: 15px;
  left: 35px;
  z-index: 3;
}

```

The absolute positioning is where you're falling over. Unless an element's parent is explicitly using `position: relative`, `position: absolute` is nothing but a pain in the backside.

After that, you just need to add a clearfix. If you Google clearfix, then you'll get a slew of results, however here is my favourite:

If you only want to support IE8+:

```
.breadcrumb:after {
  content: "";
  display: table;
  clear: both;
}

```

If you want to support IE6/7

```
.breadcrumb:before,
.breadcrumb:after {
    content: "";
    display: table;
}
.breadcrumb:after {
    clear: both;
}
.breadcrumb {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

```

This'll put the breadcrumbs above your page title, as per your request :)

# Answer
> 0 votes
Just add this style to your CSS file

```
#squeeze .right-corner .left-corner .breadcrumb {
  position: static;
}

```

This will position your breadcrumbs div according to the normal flow of the page.

---
Tags: breadcrumbs
---


# Question
Title: How to populate a dropdown list from array in FORM API
Hopefully this is clearer, and my last question in a long time!

Using PDO I have connected to an external DB, I can query this and return an array of values, Using html/php I can populate a standard select box. However I am unsure how to do this in the Form API, taking the array from the second paragraph, or do I query within the form item that produces the drop down? I want to take the name and the id, display the name. So that I can store the ID later.

```
      $stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
$stmt->setFetchMode(PDO::FETCH_OBJ);
$user_list = array();
foreach ($stmt as $row) {
    $user_list[$row->adminuser_id] = $row->admin_name;
}
}

$form['user_list']=array(
    '#type'=>'select',
    '#title' => t('Users'),
    '#options' => $user_list,
    '#multiple' => false,
    '#attributes'=>array('size'=>4),
    '#weight'=>8,
);

```

# Answer
In a while looping over your result, populate array.

```
$user_list = array();
while ($row = $stmt->fetch()) { // See this line in your original code
   $user_list[$row->user_id] = $row->name;
   // Apply transformations and conditions here, if needed
}

```

Or, as Clive suggested:

```
$user_list = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

```

Then simply use this array

```
'#options' => $user_list,

```

---

By the way, if you really want to make assignment in condition, proper way to write it is:

```
while ( ($row = $stmt->fetch()) )

```

As you can see, assignment is wrapped in double parentheses. It is the way to say future developers and code review tools "yes, it is not a typo, I really wanted it this way, I did not forgot about second `=`".
> 3 votes

---
Tags: forms, theming
---


# Question
Title: Programatically create 'Send this user a a private message link' for user pages
I know that this question had been asked several times, but it seems like all existing answers only apply to ealier versions of Privatemsg module. I am running 7.x-2.x-dev and I would like to programatically render the "Send this user a private message" link. The PHP code is supposed to be the `$block['content']` of a programatically created block that will be displayed on user pages.

Somebody suggested to use

```
if ($account = menu_get_object('user') ) {
      if ($url = privatemsg_get_link(array($account))) {
        $block['content'] = l(t('Send this user a private message'), $url, array('query' => drupal_get_destination()));
      }
}
```
but this is doing absolutely nothing.

I also want that the link is only displayed if the *viewed* user has enabled the "Enable private messages" option in his/her account settings and if the *viewing* user has permission to send messages. Any ideas how to achieve this?

# Answer
> 1 votes
For an example of how to do this, you can see the integration with the Author Pane module in `privatemsg.author-pane.inc`:

```
  global $user;
  $account = $variables['account'];

  if ($account->uid != $user->uid) {
    $url = privatemsg_get_link($account);
    if (!empty($url)) {
      $variables['privatemsg'] = l('<span>' . t('Send PM') . '</span>', $url, array('attributes' => array('class' => array('author-pane-link'), 'title' => t('Send @name a private message', array('@name' => privatemsg_recipient_format($account, array('plain' => TRUE))))), 'html' => TRUE));
    }
  }

```

This isn't a cut-and-paste solution, but since Author Pane provides a block that allows you to PM given users, and this respects the Privatemsg permissions (the link should not be rendered if the recipient does not have appropriate permissions to receive or the sender does not have permission to send), this should be a useful reference.

# Answer
> 2 votes
Hope this will help you,

In Drupal 7, you can use privatemsg\_get\_link.

* **privatemsg\_get\_link** \- Returns a link to send message form for a specific users. ````
  if ($enabled_private_messages) {//check user private message settings
    if ($account = menu_get_object('user')) {// Get user object. You can also use user_load to get user object.
      if (is_object($account) && privatemsg_user_access('write privatemsg')) {
        if ($url = privatemsg_get_link(array($account))) {
          return l(t('contact user'), $url, array('query' => drupal_get_destination()));
        }
      }
    }
  }

````

---
Tags: privatemsg
---


title: drush make on local gitweb raw url

text:
# Question
Title: drush make on local gitweb raw url
I moved a git repo from github to local gitweb and want to access the raw build make file

http://git.mycompany.com/?p=workflow.git;a=blob\_plain;f=build-workflow.make;h=170f5329b413bea0efb1ec33bebdc1549403cc3e;hb=HEAD

opening that url in browser is fine: raw code same as in github

But drush make complains about missing core and api entries.

So I checked with wget and it saves a \`index.html?p=workflow.git' which is a complete html page.

How is that supposed to work on gitweb ??

# Answer
So I found the solution : the shell is interpreting the semicolons and cuts the URL so it has to be quoted. Here for example http://sourceforge.net/apps/trac/sourceforge/ticket/9358 it is explained.

my drush cmd should be:

```
drush make "http://git.mycompany.de/?p=workflow.git;a=blob_plain;f=build-workflow.make;h=170f5329b413bea0efb1ec33bebdc1549403cc3e;hb=HEAD"

```
> 0 votes

---
Tags: version-control, drush
---


title: How to add content-language

text:
# Question
Title: How to add content-language
How can i add this meta tag in my website :

`<meta http-equiv=“content-language” content=“en-us”>` ?

I am using metatags module but i dont see any option about this. Is there any other way to do it?

Thank you

# Answer
> 3 votes
Hope this will help you,

In Drupal 7, you can achieve it using **template\_page\_alter**

```
    function THEME_NAME_page_alter($page) {
        global $language;
        $lang_name = $language->language;
        $meta_language = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'http-equiv' => 'content-language',
            'content' => $lang_name
          )
        );
        $meta_content_language = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'http-equiv' => 'language',
            'content' => $lang_name
          )
        );
        drupal_add_html_head($meta_language, 'content-language');
        drupal_add_html_head($meta_content_language, 'language');
    }

```
* Folder listing of **active theme** folder
* **template\_page\_alter** inside **template.php** file

Source

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


# Question
Title: How can I select which tags should be stripped from the footer?
In Drupal 6, the footer message is stripped of some HTML tags. In my case I want to place `<img>` with a `<map>` tag so the image would link to different sections. Drupal strips off the `<map>` tag, even if I add it to the accepted HTML tags in "Filtered HTML" data type.

Is there a way to enable the `<map>` tag in the footer?

# Answer
> 1 votes
I assume you are talking about a custom block that you add in the footer region of the site. In that case, you need to include all the HTML tags used to create a map image, which are `<area>`, `<img>`, and `<map>`.

I have tried with a block contained the following HTML.

```
<img src="http://www.w3schools.com/tags/planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun">
  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus">
</map>

```

Once I enable those HTML tags for the *Filtered HTML* input format, the HTML added to the page for that block is the following.

```
<div id="block-block-1" class="clear-block block block-block">

  <div class="content"><p><img src="http://www.w3schools.com/tags/planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap" /></p>
<p><map name="planetmap"><br />
  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun" /><br />
  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury" /><br />
  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus" /><br />
</map></p>
</div>
</div>

```

Keep in mind that, since the function Drupal used to filter out HTML tags is filter\_xss(), the HTML you pass to the *Filtered HTML* input format is altered to:

* Remove characters and constructs that can trick browsers
* Make sure all HTML entities are well-formed
* Make sure all HTML tags and attributes are well-formed
* Make sure no HTML tags contain URLs with a disallowed protocol (e.g. `javascript:`)

Then, also \_filter\_xss\_attributes() is called; that means also tag attributes are filtered.

---
Tags: 6
---


title: End-user Documentation Generation

text:
# Question
Title: End-user Documentation Generation
Is there a way to automatically generate end-user documentation (likely in a stubbed or skeletal format) for content types that you have setup?

Perhaps there is a module that does this?

# Answer
> 1 votes
Drupal has an API for documentation and comment standards that allow you embed comments in the code using a special syntax that will automatically generate documentation for the module, including modules that create content types.

This is the system that is used to automatically generate the online API reference found on http://api.drupal.org and other similar sites.

The API module used to generate these pages parses documentation and code in PHP files, and it expects documentation to be in a format similar to other code/documentation parsing systems such as PHPDoc, JavaDoc, etc. The system was originally based on doxygen, but it has evolved into something that has its own set of tags and Drupal-specific functionality.

---
Tags: 7
---


title: Date popup select wrap

text:
# Question
Title: Date popup select wrap
I want to wrap date popup selects in `<div>` to customize drop-down button of the select. But I can't find where to wrap it. I don't want to use jquery for such.

# Answer
You're going to need to override an existing theme function in order alter the HTML output for the date popups. You can override a theme function either from within your template.php file within your theme, or from within a custom module.

Whenever I need to identify the correct theme function to override in a hurry, I use a module called Devel Themer. It allows you to click on any on page element, and provides you with a great break down of all the theme functions and variables associated with the element you're trying to override.

Hope this helps.

**EDIT: including theme function link**

The theme function you need to override is theme\_select
> 1 votes

---
Tags: datetime
---


# Question
Title: White Screen of Death, From Apache to Litespeed
I'm facing a White Screen of Death on some backend(admin) pages after migrating to a new server. Apache---\>LiteSpeed. New domain. When I migrate to a different server running Apache I don't have any issues.

I get WSOD when I click "Flush all caches" or after enabling a module.

The link to configure AWS for PHP module is missing from the admin menu.

**Recent logs messages:**

* page not found 2013-08-01 18:19 build/mediaelement-and-player.min.js
* page not found 2013-08-01 18:20 favicon.ico

May you help?

# Answer
> 0 votes
You want to increase your memory\_limit and max\_execution\_time in your php.ini file.

Here is a link that tells you more about that

---
Tags: migrations, wsod
---


# Question
Title: What module do I turn off to hide or remove the voting widget in Drupal Commons?
Our client wants this voting widget turned off? At worst, I could hide with CSS but I'd like to turn this off. What module produces this? Should I remove/hide a field from the content type?

# Answer
> 1 votes
Nevermind. I found it was the Rate module.

---
Tags: 7, rating
---


title: Pass query string to Webform text field

text:
# Question
Title: Pass query string to Webform text field
I have a webform (www.mysite.com/myform) ad I want to be able to pass a URL string to a text field in the webform when a user visits the page and submits it. For instance, the URL provided to "customer A" might be www.mysite.com/myform?customer\_name=customera and the URL provided to "customer B" might be www.mysite.com/myform?customer\_name=customerb. I would like for the value of the text field "Customer Name" to be auto-populated with "customera" or "customerb" depending on the URL used to access the webform page.

Is this possible? If so, how can I accomplish this?

Going a bit deeper... if this is possible, is it also possible to pass two strings via the URL so that two separate fields are auto-populated? For instance, www.mysite.com/myform?customername=customera?customer\_type=lead would auto-populate "Customer Name" with "customera" and would auto-populate "Customer Type" with "lead".

Thanks!

# Answer
You can set a default value for each field on your webform. The default value you would use would be

**For Webform v3 and under:**

```
%get[customer_name]

```

**For Webform v4+:**

```
[current-page:query:customer_name]

```

To get a first and last name you could do something like:

URL:

```
http://mysite.com/myform?first_name=John&last_name=Doe

```

First Name Default Value:

```
%get[first_name]                 //webform <= v3
[current-page:query:first_name]  //webform >= v4

```

Last Name Default Value:

```
%get[last_name]                 //webform <= v3
[current-page:query:last_name]  //webform >= v4

```
> 26 votes

---
Tags: webforms, tokens
---


title: Duplicate subdirectory in path aliases

text:
# Question
Title: Duplicate subdirectory in path aliases
I have an odd bug that isn't on other drupal install for other domains on my server.

Basically, menus work fine.

However links in the content will look like this:

```
https://example.com/content/content/node/123

```

instead of this

```
https://example.com/content/node/123

```

which is how it should be.

Interestingly enough this persists in using the `l()` function in Drupal 7 templates or in views even if I use rewrite output.

This doesn't happen on another Drupal 7 install with a different domain and web directory. I've changed `base_url` in `settings.php` and it does nothing and `RewriteBase` in `.htaccess` and it does nothing. I flushed all caches. I even changed to a basic theme. None if it made any difference. I'm stumped and about to resort to outputting variables from core. Any help?

With the duplicate sub directory in the URL, or without it, confusingly enough, the node does display and everything works. What is going on?

# Answer
I figured it out. I installed pathauto to try and force it to work and realized that the url aliases set on every node had content/ prepended to them as part of a mass import.

I ran this in the mysql console to update them correctly:

```
update url_alias set alias = REPLACE(alias,'content/node','node');

```

And problem fixed.
> 1 votes

---
Tags: 7, path-aliases
---


# Question
Title: Exposed filters in Block for Page View do not filter results
I have below content types with following related fields setup in a Drupal7 setup.

Activity Fields: Name, Body and Image.

Event Fields:

* Date
* Location: Term Reference for Taxonomy Location
* Activity : Term Reference for Taxonomy Location
* Organiser: Entity Reference for Organizer node (as 1 event will have only 1 organizer)

Organiser Fields:

* Location: Term reference for Location taxonomy
* Activity: Entity Reference for node Activity.

I have setup a Page View named Experience, with Listing of Events on right sidebar and on left sidebar i want to display the Filters.

I have managed to Expose the filter with BEF, however these filters don't give any result after changing value. Though they are set to Use Ajax.

Also other filters like Organiser and Location are autocomplete fields, these fields do not show-up any value on entering text.

Kindly help

UPDATE: Here's the SQL Query

```
SELECT node.nid AS nid, node.title AS node_title, node.created AS node_created, 'node' AS field_data_field_event_date_node_entity_type, 'node' AS field_data_field_event_image_node_entity_type, 'node' AS field_data_field_event_location_node_entity_type, 'node' AS field_data_field_event_amount_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_event_club} field_data_field_event_club ON node.nid = field_data_field_event_club.entity_id AND (field_data_field_event_club.entity_type = 'node' AND field_data_field_event_club.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('event')) AND (field_data_field_event_club.field_event_club_target_id IS NOT NULL ) ))
ORDER BY node_created DESC
LIMIT 12 OFFSET 0

```

# Answer
Is your views filter is working when you disable ajax submit?

if No then `enable -> Show the SQL query`

from URL `www.yourdomain.com/admin/structure/views/settings`

then check query which is generating on submit of the form, you will get solution there only

try and let know status.
> 0 votes

# Answer
This issue has been resolved, the problem was with the Operator that i had selected for the fileds.

I had selected `"Is not empty (NOT NULL)"` which wasnt giving any results, later i changed it to "Is one of" and it populated the field values correctly and the filters work.
> 0 votes

---
Tags: views
---


title: Tabulation order in Display Suite

text:
# Question
Title: Tabulation order in Display Suite
Display suite (http://drupal.org/project/ds) allows you to modify the form display appliyng template layouts. But if i chose (say) a 3 column layout, with say 6 field, the tab order is per column and not per field weight.

example:

left-----middle---right

field1 - field2 -field3

field4 - field5 -field6

if i press tab, the focus shift from field 1 to field 4, and not on field 2 as expected. it's possibile to set a tab order per row and/or per field weight?

# Answer
> 0 votes
You could probably do this if you use something like javascript or jQuery and using the tabindex attribute. Take a look at the below link at Stackoverflow as an example:

https://stackoverflow.com/questions/2894539/how-to-set-tab-order-in-jquery

# Answer
> 0 votes
Check out Renderable elements module.

You can also see a demo here.

---
Tags: display-suite
---


# Question
Title: Modify output on a page created with the View module
I'm pretty new to Drupal and I'm also pretty sure this is a noob question.

I'm trying to build my theme, and in particular I'm trying to manipulate node output to the page, before using the View I simply implemented `myTheme_preprocess_page` hook and got the content doing `$nodes = $variables['page']['content']['system_main']['nodes'];`. From that I made all the needed modification.

Now, I want to order the node using the modification date (or whatever parameter) and the View module seems to do just what I want. The problem is now that in my `preprocess_page` hook I don't have an array of nodes, but all the markup coming from the node.tpl.php file (with missing field of course, because I haven't had the chance to make modification to the output), e.g. insted of `$variables['page']['content']['system_main']['nodes']` I have `$variables['page']['content']['system_main']['main']['#markup']`.

What am I missing? Shouldn't the `preprocess_page` function return the nodes fro the database (as it did without using View) instead of the markup? Is there another hook I don't know about that allows me to do my preprocessing stuff?

# Answer
If you want to access modify date and render data so you can use `hook_views_pre_render(&$view) $view->result` to access result nodes.

and you want to change query condition the you can use `hook_views_query_alter(&$view, &$query)`
> 1 votes

---
Tags: views, 7, hooks, theming
---


# Question
Title: DIV covering over the login buttons in commons-origins theme
We're using Commons 3. It uses a sub-theme of Adaptive Themes (AT). There appears to be a DIV that is blocking users from clicking on the signup | login area.

Should I file a bug on this or work around it with CSS?

# Answer
The following is a work around.

```
#block-search-form  .block-inner {
    height: 30px;
}

```
> 0 votes

---
Tags: theming, 7
---


# Question
Title: Drupal 7 vbo, is there an option to input text to operations?
Im using VBO with drupal 7. If I have an action which creates a new node/update a new/create a comment etc. How can I manually type the title/body text or what ever it is I'm setting?

Thanks for any help.

# Answer
> 1 votes
You can do this with Rules for example, every "Action set" Rules component that you create is exposed to Views Bulk Operations and all the parameters you configure for your action set will be available for use in the view.

I've created a simple view listing all nodes and an action set that exposes the title so you can modify it with a textbox.

Here's the view:

```
$view = new view();
$view->name = 'vbo_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'VBO_Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'VBO_Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'views_bulk_operations' => 'views_bulk_operations',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'views_bulk_operations' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Bulk operations */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['label'] = '';
$handler->display->display_options['fields']['views_bulk_operations']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_message_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_goto_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'rules_component::rules_vbo_test' => array(
    'selected' => 1,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['display_result'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['merge_single_action'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['force_single'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'vbo-test';

```

And here's the action set:

```
{ "rules_vbo_test" : {
    "LABEL" : "VBO_TEST",
    "PLUGIN" : "action set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "title" : { "label" : "title", "type" : "text" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:title" ], "value" : [ "title" ] } } ]
  }
}

```

More info can be found in this nodeone screencast: http://nodeone.se/en/using-rules-components-with-vbo

If you need to update the value of a field that is not available in the action set, you can expose "Rule sets" as well to VBO, that allows you to use conditions, particularly the Entity has field condition that will pull the field out of the entity and make it available to Rules UI:

```
    { "rules_test_rule_set" : {
    "LABEL" : "Test Rule set",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "node", "type" : "node" },
      "text" : { "label" : "text", "type" : "text" }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_options" } }
          ],
          "DO" : [
            { "data_set" : { "data" : [ "node:field-options" ], "value" : [ "text" ] } }
          ],
          "LABEL" : "my rule"
        }
      }
    ]
  }
}

```

You can do this with arbitrary fields based in a data type that rules have info about, what I don't think you can configure is the widget exposed for this operation.

---
Tags: views
---


# Question
Title: Where do i change the settings of the redirected URL after a new user registers on my drupal 7 site?
Where can i change the destination of the redirect after a user registers on my site? Currently it just hits them back to the homepage.

# Answer
> 3 votes
Hope this will help you,

In Drupal 7 you can achieve it many ways

* Using Rules, create a RULE with **Event - After saving a new user account** and **Actions - redirect the page** and if you want you can also add **Conditions**, as per your requirement.
* Using **hook\_form\_alter**

```
function HOOK_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
      $form['#submit'][] = 'custom_user_register_submit';
    break;
  }
}
function custom_user_register_submit($form, &$form_state) {
 $form_state['redirect'] = **'YOUR_REDIRECT_PATH_HERE'**;
}

```
* By using **destination parameter**

+ More simpler you can also using **destination parameter**. Just add the destination parameter in the URL where you want to **redirect it**. You can achieve it by using theme\_menu\_link. You can refer this answer
    + `YOUR_DOMAIN/user/register?destination=**YOUR_REDIRECT_PATH_HERE**`

Note : Instead of writing the code or installing the module you can use **Destination parameter** OR **RULES** .

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


# Question
Title: Exposed filter in views to filter users by age
I have the Birthday module installed that displays the age of users. I am trying to create an exposed filter in a view that will allow users to select from $age1 to $age2. Of course this requires two filters (one min age and one max age) so the view will display all users who fall into that bracket. The Birthday module computes age "on the fly." Any guidance on how to proceed with this will be greatly appreciated. Thanks. :)

# Answer
You can use the contextual range filter module. to create a filter range for your age field.

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter, not just by a single value, but also by range.
>
> Numeric, alphabetical (string) and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on the "created" (posted) and "updated" (last modified) node properties is also supported, provided you use the correct format as dictated by Views. So, YYYYMMDD for full dates or one of the shorter year+month, year-only, month-only, week-only and day-only formats.
> 1 votes

---
Tags: views
---


# Question
Title: How to disable page redirect on node edit?
Thank you for reading my question.

I have a node type and all I want is it not to redirect to the node on edit submission.

Currently, when on the node edit page submissions are sent through ajax, however when the node is submitted it also redirects to the node page, making the ajax pointless :( ...

How do I stop the edit page redirecting on submission.

Thanks for any help

# Answer
> 5 votes
I am not sure what the ajax is doing in your specific case, but if all you want to do is redirect back to the `node/###/edit` page instead of `node/###`, you are wanting to swap out the submit handler with one that doesn't do the redirect.

The core one, assuming your hook-nodeapi tag implies Drupal 6 anyway, looks like this....

```
function node_form_submit($form, &$form_state) {
  global $user;

  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);
  $node_link = l(t('view'), 'node/'. $node->nid);
  $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
  $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

  if ($insert) {
    watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been created.', $t_args));
  }
  else {
    watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been updated.', $t_args));
  }
  if ($node->nid) {
    unset($form_state['rebuild']);
    $form_state['nid'] = $node->nid;
    $form_state['redirect'] = 'node/'. $node->nid;
  }
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
  }
}

```

So, if you created almost a duplicate of it in a custom module...

```
function YOURMODULE_node_form_edit_submit($form, &$form_state) {
  global $user;

  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);
  $node_link = l(t('view'), 'node/'. $node->nid);
  $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
  $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

  if ($insert) {
    watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been created.', $t_args));
  }
  else {
    watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been updated.', $t_args));
  }
  if ($node->nid) {
    unset($form_state['rebuild']);
    $form_state['nid'] = $node->nid;
    // $form_state['redirect'] = 'node/'. $node->nid; // just remove or comment out this line
  }
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
  }
}

```

with the only change being the removal or commenting out of the redirect, you are halfway there. Now you need to have this one called when you are editing nodes, which is done with a form\_alter, something along these lines...

```
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {

  if ($form_id=='TYPE_node_form') { // TYPE is the machine name of the content type you are dealing with here

    if (arg(2)=='edit') {

      foreach ($form['buttons']['submit']['#submit'] as $h => $handler) {
        if ($handler=='node_form_submit') {
          $form['buttons']['submit']['#submit'][$h]='YOURMODULE_node_form_edit_submit';
        }
      }

    }

  }

}

```

and now, assuming no copy/paste typos, you should be able to edit that node type and if you hit submit, it does not redirect to the node page but rather redirects back to the `node/#/edit` page.

Now, if somehow your ajax stuff is doing something similar like swapping out the various handlers, then you will have to do something different yet similar, and the above should be able to guide you a bit. (The point I am trying to make here is that hitting submit causes drupal to go to/load another page unless that button itself has been ajaxed or otherwise modified)

UPDATE:

I changed the name of the handler from `YOURMODULE_node_form_submit` to `YOURMODULE_node_form_edit_submit` because, as I just found out, if you happen to have a module and content type of the same name, drupal goes all recursive on you upon trying to submit the edits of those node types due to hooking into `TYPE_node_form_submit` automatically.

---
Tags: nodes, ajax
---


title: Updating custom module

text:
# Question
Title: Updating custom module
I created custom module and I installed it on "Add Module" page. I've got that module in sites/all/modules. I changed that module (I went to that location and I recoded it). What should I do to update that module. It seems to me that only after recoding that module Drupal doesn't notice changes.

# Answer
> 2 votes
When you edit an installed and enabled module, Drupal will not notice you added new hooks, since the list of the hooks implemented by a module is cached from Drupal. In order to make Drupal notice you edited the module and added new hooks, you need to disable and re-enable the module, without uninstalling it.

The reason why this is necessary is that module\_implements(), the function that returns `TRUE` when a module implements a hook, contains the following code.

```
  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

```

---
Tags: 7
---


# Question
Title: How to attach email from a private folder(outside root)
I'm trying to attach a file to an email. It's part of job application so a person goes to a node, presses apply and it sends an email to the creator of the node. I want to attach a CV & cover letter to it.

The problem is I'm storing the CV & cover letter in a private folder outside of drupal root. (Personal info security and all that.) The code below works for public folders. How would I got about altering it to access private ones?

```
function tellafriend_mail($key, &$message, $params) {

        global $base_url;

        $message['subject'] = t('Your friend thought you might like this site');

        $message['body'][] = t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
        $attachment = array(
          'filecontent' => file_get_contents('http://localhost/private/counciltax.txt'),
          'filename' => 'test.txt',
          'filemime' => 'textplain',
        );
        $message['params']['attachments'][] = $attachment;
   }

```

# Answer
You can use the drupal private file directory notation:

```
file_get_contents('private://counciltax.txt')

```
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How do i show a not-equals operator for rules while setting up commerce shipping conditions?
I am setting up my commerce shipping conditions and i need a NOT Equal operator so i can target all international countries. how can this be done?

# Answer
> 2 votes
Choose "=", then at the bottom of your condition, enable "negate". It's just below where your screenshot is cut-off.

---
Tags: 7, commerce, rules
---


# Question
Title: Generate fields in content from other content values?
I want to generate fields in a content from the values of other content.

Specifically, I have a list of "players" stored as a content type, and a separate content type called "Events". Events list the rank of each player that participated. On the "player" content, I'd like to be able to display the players wins by searching all the "events" content. Is this possible?

Also, in Views, is it possible to generate a list of all the events a player has won, as well as how many?

# Answer
> 0 votes
Yes, this is possible. On approach is to use the Entity Reference module. This allows one field to reference another content type. With this approach, on your *Event* content type, you could have a field **Winner** that is an entity reference to the player(s) who won.

In Views, you could then easily a list of events a player has won by using a contextual filter to limit the wins displayed to those of the player URL. You could create a second view and attach it to the first to show how many.

These all require a fair bit of configuration and may be hard to set up at first, but it's definitely possible.

---
Tags: views, nodes
---


# Question
Title: Commerce- Show a base price (MSRP) and a discount (the real price)
I have a number of products for which I would like to display the MSRP (with a line through it) and then the discount price (my store's actual price).

**I do not want to actually discount the products; the "discounted" price is the real price in the system.** Rather, I want to also show the MSRP (to show what a good deal my customers are getting). This is similar to what Amazon.com does (they always have the original price with a line through it, and next to that is the Amazon.com price).

What is a sane way to do this? Should I add another field of type *price* to products? Should I add that field instead to my *product display* content type? From the perspective of long-term maintenance, I'm not sure how to approach this.

Here's an example from Amazon:

# Answer
> 3 votes
Use the Commerce Price Savings Formatter module.

> This module is an extension of Drupal Commerce that provides a display formatter for the Commerce Price field which shows the amount of savings when a discount is applied.

---
Tags: commerce
---


# Question
Title: Programmatically enable Mollom protection for a form
I want to enable Mollom protection for a number of forms in my development environment, and then export that configuration to QA and to Production without touching the Admin interface in QA or production.

I can export the Mollom settings via Features + Strongarm, but it doesn't appear to export the configuration for forms protected by Mollom.

I see that I can use hook\_mollom\_form\_list and hook\_mollom\_form\_info to make new forms available in the UI with default values, but I can't get hook\_mollom\_form\_info to fire without enabling protection for the form in the UI.

I am trying to add a captcha to the registration form and password reset form, do text analysis on comments, and do text analysis for my custom node submit form. It appears that the mollom module already has definitions for all of these forms, but I don't see any way to enable them.

# Answer
> 1 votes
This is very simple if you have a custom module. Use the code in `YOURMODULE.install` (where `comment_node_episode_form` is the form id you are wishing to protect):

```
/**
 * Adding mollom captcha protection to episode comment form.
 */
function YOURMODULE_update_7001() {
  $mollom_form = mollom_form_new('comment_node_episode_form');
  $mollom_form['mode'] = 1;
  $success = mollom_form_save($mollom_form);
  if (!$success) {
    throw new DrupalUpdateException('Cannot add Mollom Captcha to the Episode comment form.');
  }
}

```

# Answer
> 1 votes
I didn't find a better way, so I did inserts directly into the DB.

In mymodule.install:

```
function mymodule_update_70001() {
  # CAPTCHA on registration form
  db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'user_register_form',
      'mode' => 1,
      'checks' => 'a:0:{}',
      'discard' => 1,
      'enabled_fields' => 'a:0:{}',
      'strictness' => 'normal',
      'module' => 'user',
    ))
    ->execute();

  # CAPTCHA on password reset form
  db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'user_pass',
      'mode' => 1,
      'checks' => 'a:0:{}',
      'discard' => 1,
      'enabled_fields' => 'a:0:{}',
      'strictness' => 'normal',
      'module' => 'user',
    ))
    ->execute();

  # Text analysis of comments
  $response = db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'comment_node_mynode_form',
      'mode' => 2,
      'checks' => 'a:2:{i:0;s:4:"spam";i:1;s:9:"profanity";}',
      'discard' => 0,
      'enabled_fields' => 'a:2:{i:0;s:7:"subject";i:1;s:27:"comment_body][und][0][value";}',
      'strictness' => 'normal',
      'module' => 'comment',
    ))
    ->execute();

  # Text analysis of submission
  $response = db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'mynode_node_form',
      'mode' => 2,
      'checks' => 'a:2:{i:0;s:4:"spam";i:1;s:9:"profanity";}',
      'discard' => 0,
      'enabled_fields' => 'a:4:{i:0;s:5:"title";i:1;s:19:"body][und][0][value";i:2;s:32:"field_projectpage][und][0][value";i:3;s:33:"field_downloadpage][und][0][value";}',
      'strictness' => 'normal',
      'module' => 'node',
    ))
    ->execute();
}

```

# Answer
> 0 votes
I would try to go for the features way with the patch provided in this issue. Hopefully it will be committed soon to the module.

---
Tags: features, advertising
---