# Question
Title: Is it reasonable to run hundreds of sites by one Drupal core?
There are more than 100 sites that are supported by our company and they can be presented as sub domain as well. from technical perspective is it reasonable to run all of these sites using only one Drupal core? is there any drawback in doing such thing? or we should have multiple cores?

# Answer
Technically, there shouldn't be. But even if I had enough server resources, I'd reconsider my approach. A few problems I can think about. Note that they are really small annoyances and there are workarounds. If each site of your network has to be a very serious site, and all you are expecting is less files on the server and ease of updates, I think it's a bad idea.

1. Your `sites.php` file will get larger. You can specify which settings.php file should be used in the `sites/sites.php` file. That file will get larger with the number of sites in your network. However, in a age that you store 100 configurations in `$GLOBALS`, this shouldn't be a problem.
2. Your modules page will load slower if you put all modules in `sites/all/modules` folder, but only want to use them in a few sites.
3. In core or shared module updates, make one wrong move and everyone will know.
4. You can't use different robots.txt.
5. In fact, you can't use just about any "known files". favicon.ico, apple-touch-icon, Bing verification file, oh gosh.
6. Say hello to the complicated vhosts file and `.htaccess` for me. I'm a fat guy and so they should be.
> 6 votes

# Answer
Certainly, there is a cap where it makes more sense to separate the stacks for performance reasons.

@Ayesh K made several good points. There are ways to deal with most of these issues:

1. sites.php isn't required.
2. This is true. Sorry :) However, you can put modules only needed for \[siteA.com\] in `/drupal/sites/siteA.com/modules/`. Then those modules won't show up in the other sites' module list.
3. So true. Definitely use drush to do updates. It will make backups beforehand and auto-rollback on failures.
4. As @Drupalist mentioned: https://drupal.org/project/robotstxt.
5. I think there are solutions here, at least for favicon.
6. Modular-style includes for your http server can help this. (look at what Aegir does for Nginx as an example).

Something that stood out in my mind in this discussion is OPcode caching. Using opcache, APC or similar, I think you will benefit from the single stack (multi-site).

It would largely be determining:

* How you want to best utilize your hardware for performance.
* If you can solve the issues mentioned by Ayesh (or they aren't an issue for your use).
> 5 votes

---
Tags: i18n-l10n, multi-sites, installation, subsites
---


# Question
Title: How to remove content for specific page?
I'm trying to remove some regions if the page is admin like this:

```
function mytheme_page_alter(&$page) {
if (current_path() == 'admin') {
unset($page['content']);
unset($page['highlighted']);
}
}

```

But it's not removing the contents and highlighted regions from `localhost/drupal/admin`

# Answer
> 2 votes
I dont see any issue with the code. I tried the exact same code in my custom module and it works as expected.

Can you check what the base\_url is in your case? I am guessing the current\_path in your case is returned as drupal/admin and this is not matching the if condition you added. You may want to print the value for current\_path() using the statement drupal\_set\_message(current\_path()); to confirm the same.

# Answer
> 0 votes
you may want to create a template file instead of making all these changes in a hook. Refer to this link for more details.

---
Tags: 7
---


# Question
Title: How to hide profile2 field label and captcha label in registration form
I've tried using 2 different functions, where both successfully sets the value to 'invisible' with a dsm($form) check. However, the label is still being displayed.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
          case 'user_register_form':
              $form['profile_users']['field_username']['#title_display'] = 'invisible';
              $form['captcha']['#title_display'] = "invisible";
   break;
  }
}

```

and:

```
function MYMODULE_form_profile2_edit_PROFILETYPE_form_alter(&$form, &$form_state){

     $form['profile_PROFILETYPE']['field_username']['#title_display'] = 'invisible';

}

```

I do not encounter this problem for the username, password and email fields.

Edit: I've also tried:

```
$form['profile_users']['field_username']['und']['#title'] = '';
$form['profile_users']['field_username']['und']['#title_display'] = "invisible";

```

# Answer
> 0 votes
you can use this code instead:

```
$form['captcha']['#title'] = '';

```

---
Tags: users, forms
---


# Question
Title: How to modify the add node forms using hook_form_alter
This is the `$form_id` of a content type: `q_a_node_form`. I'm trying to change its `add/content` form (the title field) using `hook_form_alter`. this is my code in `template.php`:

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id){
switch ($form_id){
    case "q_a_node_form":
        $form['edit-title']['#size'] = 10;
        break;
    }
}

```

I'm sure that the case option happens, I already print something in it and it works. why it doesn't work?

# Answer
See below code which works.. Form element is **title** instead of **edit-title**.. print $form array to investigate form elements...

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id){
switch ($form_id){
    case "q_a_node_form":
        $form['title']['#size'] = 10;
        break;
    }
}

```

If you have installed devel module you can see elements using below code

```
dpm($form);

```
> 2 votes

---
Tags: theming, nodes, forms
---


# Question
Title: Rules 'Execute custom PHP code' to set DB Values
I wish to use rules to set some values in my database. I have the following php code working correctly as a function called when cron is run:

```
/**
 * Implements hook_form_alter
*/
function custom_reset_page_logs_cron() {
   // GROWTH
   // UPDATE field_data_field_growth_pageviews SET field_growth_pageviews_value = 0;
   $growth_updated = db_update('field_data_field_growth_pageviews')
   ->fields(array('field_growth_pageviews_value' => 0))
   ->execute();

   // EXPORT
   // UPDATE field_data_field_export_pageviews SET field_export_pageviews_value = 0;
   $export_updated = db_update('field_data_field_export_pageviews')
   ->fields(array('field_export_pageviews_value' => 0))
   ->execute();

   // INVESTMENT
   // UPDATE field_data_field_investment_pageviews SET field_investment_pageviews_value = 0;
   $investment_updated = db_update('field_data_field_investment_pageviews')
   ->fields(array('field_investment_pageviews_value' => 0))
   ->execute();

   // EXPORT
   // UPDATE field_data_field_workforce_pageviews SET field_workforce_pageviews_value = 0;
   $workforce_updated = db_update('field_data_field_workforce_pageviews')
   ->fields(array('field_workforce_pageviews_value' => 0))
   ->execute();
}

```

However I want this code to run on a rule, rather than on a cron run. I would have thought that it is straightforward to add this to a PHP rule using 'Execute custom PHP code. However when I paste the following into a rule, and trigger the rule nothing happens:

```
   // GROWTH
   // UPDATE field_data_field_growth_pageviews SET field_growth_pageviews_value = 0;
   $growth_updated = db_update('field_data_field_growth_pageviews')
   ->fields(array('field_growth_pageviews_value' => 0))
   ->execute();

   // EXPORT
   // UPDATE field_data_field_export_pageviews SET field_export_pageviews_value = 0;
   $export_updated = db_update('field_data_field_export_pageviews')
   ->fields(array('field_export_pageviews_value' => 0))
   ->execute();

   // INVESTMENT
   // UPDATE field_data_field_investment_pageviews SET field_investment_pageviews_value = 0;
   $investment_updated = db_update('field_data_field_investment_pageviews')
   ->fields(array('field_investment_pageviews_value' => 0))
   ->execute();

   // EXPORT
   // UPDATE field_data_field_workforce_pageviews SET field_workforce_pageviews_value = 0;
   $workforce_updated = db_update('field_data_field_workforce_pageviews')
   ->fields(array('field_workforce_pageviews_value' => 0))
   ->execute();

```

I have set a second action to 'Show a message on the site' and this is being shown, so it is clear that the rule is being run. I am clearing the cache before I check the database values.

Any ideas why my action isn't working? Thanks

# Answer
> 0 votes
Actually the above code works for every user except the user triggering the rule. Scheduling the rule rather than having it activated by a pageview means it is applied to all users

---
Tags: rules
---


# Question
Title: Photo Gallery attached to Story - How to Create
I figured out a way to add a photo gallery to the bottom of a story using a custom content type for the photos, then creating a view with clickable thumbnails and saving it as a block. The problem is I can't reuse this for the next story. I would need to create yet another content type and another view. How can I set it up so I can post a different gallery to a different story?

Is there a module that might help with this? I tried Views Galleriffic, but it doesn't seem to work as a block. I couldn't find any way to make the gallery appear at the bottom of a story.

# Answer
> 0 votes
I ended up add the images directly to the story with new fields so they could be shown as a gallery of thumbnails with a block. I used a view with a grid and followed directions to create a contextual filter from this helpful post: http://www.drupalwoo.com/content/blog/easy-gallery-image-option-your-content-editors-drupal-7

---
Tags: blocks, media
---


# Question
Title: How do I fix the "Access denied" error in Organic Groups when I am logged in as admin?
I am logged into my site as `uid=1` (admin) but I cannot edit the `/admin/config/group/roles/node/team` page ("Team" is an Organic Group content type), due to getting an

> "Access denied - You are not authorized to access this page."

I have cleared the cache, rebuilt the permissions, and tried a number of other tricks to gain access, all to no avail. Any ideas?

# Answer
If you temporarily disable og\_workbench and it's still happening, you have a bigger problem. Was OG upgraded from 1.x -\> 2.x?

I've found myself in this situation a few times during og upgrades. First, check to make sure all the OG Migrations have been run at admin/content/migrate. There is a migration named OgMigrateRoles that is often 0 of 0. Even though there is nothing to migrate, it still needs to run. If you do that and you still don't have access, check admin/config/group/permissions/node/\[OG-ENABLED-CONTENT-TYPE\]

You should see 3 columns w/ checkboxes for roles... NON-MEMBER, MEMBER, and ADMINISTRATOR MEMBER. If you see the rows permissions, but no checkboxes or roles your og\_role table may be "hosed" for lack of a more technical term.

It is possible to manually repair this table by inserting rows for the 3 default roles for each of your og enabled content types. Something like...

```
INSERT INTO og_role (rid, gid, name, group_type, group_bundle) VALUES
(1, 0, 'non-member', 'node', 'group'),
(2, 0, 'member', 'node', 'group'),
(3, 0, 'administrator member', 'node', 'group');

```

The rid must be unique and 'group' should be replaced by your og enabled content type's machine name. Trying to manually repair the table isn't recommended and should only be used if you can't re-install... and even then only if you know your way around MySQL and on a test version of the site.

The good news is I've always been able to fix this with enough time and comparing the hosed og to a working OG2 install.
> 8 votes

# Answer
I just saw this problem when, for the first time, I added og\_views to the group fields of a new group type. I created a group of this new group type and was then unable to edit the new group, even when logged in as admin. The reason was made clear when I visited the og group permissions: the check-box columns for the three default roles were missing. I hypothesized that og\_views was to blame. I disabled it, uninstalled it, and removed the og\_views module files from my file. I then succeeded in creating the group type, albeit without the field for group\_views; and I was able to create and edits group of this type. I do not claim to have a proof that og\_views was to blame; this is just a data point that seems to support the hypothesis. If your experience tends to affirm the hypothesis, please add your voice here. If a few people see the same thing, then we probably know where to look for the root cause.
> 0 votes

# Answer
I had this problem and I tried the fix running 5.7. It wasn't throwing the correct error. I found that the sessions table was corrupt. If you look in the logs you will find

Error - Can't open file: 'sessions.MYI'

Check and see if you can select from the sessions table. If not, then run

sql\>repair table session;

FIXED
> 0 votes

---
Tags: organic-groups, users
---


# Question
Title: Memcache not being cleared on cache flush
When clearing the cache, either through /admin\_menu/flush-cache or `drush cc all`, the cache isn't cleared, without errors. I've tried doing it directly through telnet, on memcache, getting "OK" as result, but old pages are still being presented to users.

I am using the Memcache module 1.10; in the settings.php file, I added the following.

```
$conf['cache_inc'] ='sites/all/modules/memcache/memcache.inc';
$conf['memcache_servers'] = array(
  '127.0.0.1:11211' => 'sessions',
  '127.0.0.1:11212' => 'cache',
);
$conf['memcache_bins'] = array(
  'cache' => 'cache',
  'cache_form' => 'database',
);

```

Although the session bin is configured, it's not in use. I also have http://livebookmark.net/journal/2008/05/21/memcachephp-stats-like-apcphp/ set up, tried using the "Flush this server" option, and get OK as result.

# Answer
> 0 votes
Turns out it wasn't a memcache problem but a LESS preprocessor issue.

---
Tags: 6, caching
---


# Question
Title: how to do mapping user to user in drupal
I created 4 user in my site.

```
1)contributor1
2)contributor2
3)validator1
4)validator2

```

Contributor can able to create a node and validator can able to review the node

I am using workbench module for content moderation.

My question is?

When contributor1 create a node, then he send the node to validator1 for review and contributor2 create a node , then he send the node to validator2 for review

So please let me know, how can I do the user wise mapping

contributor1 create node1 through content type 1 , then only node1 access only validator1 user and he can publish the content same as
contributor2 create node2 through content type 2 , then only node2 access only validator2 user and he can publish the content..

you have any idea please let me know

# Answer
So you have 4 user roles and 2 different content types. The first 2 user roles work with content type 1 and the other 2 user roles with content type 2.

I believe you'll find the answer to your question on this page as it explains:

* How to configure Workbench Moderation states
* How to configure and check Workbench Moderation transitions for each role

So you can set additional States according to your needs but the three default States of "Draft", "Needs Review" & "Published" seem to do the job for your case. You can also set what transitions between which states should generally be available and then configure the transition permissions for every role according to your needs.

Applying those guidelines, a Contributor1 user would create a node of content type 1 (in "Draft" state), given that they have the proper content creation permission. After that, Contributor1 would not be able to do the transition to other states for that content type. On the other hand, Validator1 should be given permissions to do the transition from "Needs Review" to "Published" for content type 1.
> 0 votes

---
Tags: hooks, users, workbench
---


# Question
Title: How to tell whether the current request is part of a cron run?
I have a module that needs to behave differently when its hooks are invoked during a cron run. (For example, my module should redirect normal page requests, but avoid redirecting during a cron run, so that the cron run is not interrupted.)

How can I programmatically determine whether the current request is part of a cron run?

# Answer
Implement `hook_cron_queue_info()` to set a global flag indicating that the current request is part of a cron run.

```
/**
 * Implements hook_cron_queue_info().
 *
 * hook_cron_queue_info rather than hook_cron, to ensure it executes before
 * any hook_cron implementations.
 */
function mymodule_cron_queue_info() {
  global $mymodule_in_cron;
  $mymodule_in_cron = TRUE;
}

```

Then, elsewhere in your module, you can check this flag:

```
global $mymodule_in_cron;
if (!empty($mymodule_in_cron)) {
  return;
}

```

This works both when invoking cron via the web server and via `drush cron`.
> 0 votes

---
Tags: 7, cron
---


# Question
Title: Injected javascript in google DFP module drupal 7
Currently I am setting up the Google DFP module and I have been trying to work out how the JavaScript is working. In the module there is a section for injecting JavaScript which is what Google DFP will give you to place in the head tag on the website. When I place the JavaScript in the form where it tells me to place it, when I load the page up it shows some of the JavaScript at the top in the body (using the DFP module).

So I experimented around with this and took the JavaScript out. I was expecting the adverts to stop displaying, however they kept displaying after taking out the JavaScript and deleting the cache and I am confused as to how it is displaying the correct adverts.

Sadly I can't give a link to the website because I am using eclipse to test things out.

The module I am using is: Doubleclick for Publishers (DFP)

What I would like to know is how is this working? The JavaScript isn't there so how does it know what adverts to get? The only thing the module knows is the network ID and the advert tags using the `[dfp_tag:slot]` token.

# Answer
> 1 votes
you can take a look at these functions (\_dfp\_js\_global\_settings and \_dfp\_js\_slot\_definition) that are used to inject inline javascript in the page, I believe that javascript loads the ads remotely and inject them in their spots

---
Tags: 7, javascript
---


title: Drupal Webform Customization

text:
# Question
Title: Drupal Webform Customization
I'm using drupal 7, and I'm having a lot of trouble using the webforms.

I have a set of radio buttons, but each radio button needs to have an associated input field with it.

Code example:

```
<input type="radio" name="derp" /> option 1 : option 1 quantity desired: <input type="number" />

```

Note that this would span multiple rows, and is just to show the "layout" I am trying to achieve.

How can I add a "set" of input elements to a webforms radio select field?

Optional to answer but extra question: when I try to inject javascript into the webform using the markup option, my code is simply printed out onto the screen instead of being interpreted. Anybody know why?

# Answer
> 0 votes
You'll have to create your own webform component to ensure that validation and saving work as you intend. Look at an exisiting webform component to see how its done.

---
Tags: javascript, theming
---


# Question
Title: Webform Mail not arriving at gmail address
I'm having problems with the mailing of the Webform Module.

I have an online website where you can fill in a form. The results will be sent to the email-address the user gave in and the user of the site.

When the user fills in an email like `myname@hotmail.com` or `myname@mycompany.com` there are no problems. They receive the results perfectly. But when they use a gmail address like `myname@gmail.com` they DON'T receive the email. So it never works with a Gmail address.

The user of the site (who normally also receives the results) then gets an error like this:

> Subject: Undelivered Mail Returned to Sender

```
This is the mail system at host myhost.com.

I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can
delete your own text from the attached returned message.

                 The mail system

```

> : host gmail-smtp-in.l.google.com\[ip-adres\] said: 550-5.7.1 \[ip-adres 12\] Our system has detected that this message is 550-5.7.1 likely unsolicited mail. To reduce the amount of spam sent to Gmail, 550-5.7.1 this message has been blocked. Please visit 550-5.7.1 http://support.google.com/mail/bin/answer.py?hl=en&answer=188131 for 550 5.7.1 more information. 44si1984154eef.10 - gsmtp (in reply to end of DATA command)

What could be the problem with this?

# Answer
From the link in your bounceback message:

"A message might be blocked if it contains suspicious-looking or spammy text or if the sending IP has had a history of sending unsolicited messages."

Either one of these possibilities might be the issue. To rule out "suspicious-looking or spammy text" you should look at the emails your webform generates. Is there any text they have in common that might be triggering gmail's spam rules? If you send such a message to a gmail address manually, do you get the same bounceback?

The more likely explanation is that the sending IP has had a history of sending unsolicited messages. This is especially likely if you're running in a shared web hosting environment. If this is the problem, there's likely little you can do about it, other than asking your host to move your account to a different server.
> 2 votes

---
Tags: forms, webforms, emails
---


# Question
Title: How do i remove main menu title once it's in sidebar,
Why is so dang difficult to style the main menu once you put in the sidebar in Drupal 7?!?

i also want to remove those annoying leaf classes! first leaf, leaf, last leaf etc.

on the page template file i see the main nav code and where it spits out title, but in the same file, all the side bar code is in one variable. how do i access that?,

i don't mind php coding. can someone please advise how to do this?

big thanks in advance

# Answer
> 0 votes
Welcome to the wild world of theme functions, friend. You're going to need to do some overriding of the main menu in a file called "template.php" which should be included in whatever base theme you're using. Create a function in that file that looks something like this:

```
function MYTHEMENAME_menu_link($variables){ // Code here }

```

Use this link as reference to understand how to change what's there: https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_link/7

And for a real brain buster on everything you want to know about how to theme menus, check out this answer by Sheena, who's basically a genius: Advanced menu theming in Drupal 7

---
Tags: theming, routes
---


# Question
Title: Targeting text field on node edit form from ctools modal
I have a multivalue image field, and using FileField Sources, I've added a link that displays a ctools modal window that allows a user to search Apache Solr for images. The results are displayed in a table in the form. Each row in the table has a link that when clicked, should write the path to the returned image to the image field. Here's what I have so far:

```
/**
 * Drupal form to be put in a modal.
 */
function imgsearch_form($form, $form_state) {
  $form = array();

  $form['search_terms'] = array(
    '#type' => 'textfield',
    '#title' => t('Search text'),
    '#description' => t('Enter the search terms'),
  );

  $form['replace_div'] = array(
    '#prefix' => '<div id="imgsearch-replace-div">',
    '#suffix' => '</div>',
    '#weight' => 6,
  );

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

  return $form;
}

/**
 * Drupal form submit handler.
 */
function imgsearch_form_submit(&$form, &$form_state) {
  // Generate the new link using the submitted text value.
  $link = _nb_alters_make_link($form_state['values']['new_link_text']);

  // Search Solr for images.
  $images = nb_alters_search($form_state['values']['search_terms']);

  if (is_array($images) && count($images > 0)) {
    // Theme the results as a table.
    $header = array(t('Image'), t('Content'), t('Add to field'));
    $rows = array();
    foreach ($images as $image) {
      // Create image style derivative for each image.
      $imagestyle = array(
        'style_name' => 'thumbnail',
        'path' => $image['filepath'],
        'width' => '',
        'height' => '',
        'alt' => '',
        'title' => $image['filename'],
      );
      $styled_image = theme('image_style', $imagestyle);

      $rows[] = array(
        'image' => $styled_image,
        'name' => $image['filename'],
        'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fieldname, t('Select')),
      );
    }

    $output = theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('imgsearch-table'))));
  }
  else {
    $output = '<div class="no-results>No images found</div>';
  }

  // Tell the browser to replace the old link with the new one.
  $form_state['ajax_commands'][] = ajax_command_replace('#imgsearch-replace-div', $output);
}

/**
 * Implementation of hook_menu.
 */
function nb_alters_menu() {
  $items = array();

  $items['imgsearch/%ctools_js/imgadd/%'] = array(
    'title' => 'Add Image',
    'page callback' => 'nb_alters_add_image',
    'page arguments' => array(1, 3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 *  Menu callback. Add the selected image to field_images
 */
function nb_alters_add_image($js, $fieldname) {
  if (!$js) {
    // We don't support degrading this from js because we're not
    // using the server to remember the state of the table.
    return MENU_ACCESS_DENIED;
  }
  ctools_include('ajax');
  ctools_include('modal');

  $commands = array();
  $commands[] = ajax_command_html("#edit-field-images-und-3-imgsearch-file-url", "filepath");

  // Tell the browser to close the modal.
  $form_state['ajax_commands'][] = ctools_modal_command_dismiss();

  print ajax_render($commands);
  exit;
}

```

The problem I'm having is when I click the "add" link, the form goes back to its original state (terms field and button, no results) and doesn't close. This is primarily because the page callback for my menu item - nb\_alters\_add\_image() - isn't getting called. I've rebuilt the menus, and I've verified in the menu\_router table that my menu item (imgsearch/%ctools\_js/add/%) is there, so I know that's not the issue.

Can anyone tell what I'm doing wrong and what else I need to do to write the path to the image field and close the modal?

Thanks.

**UPDATE**: Well, it always helps to concatenate strings and variables properly (see the 'add' array item in the table array). Once I fixed that, it started hitting my page callback, but the modal isn't closing, and the value isn't being written to the image field.

**UPDATE 2**: After an IRC conversation with merlinofchaos where he pointed out my pretty obvious code errors, I've re-written my ajax function like so:

```
function nb_alters_add_image($js, $fieldname) {
  if (!$js) {
    // We don't support degrading this from js because we're not
    // using the server to remember the state of the table.
    return MENU_ACCESS_DENIED;
  }
  ctools_include('ajax');
  ctools_include('modal');
  $imagepath = 'http://mybucket.s3.amazonaws.com/styles/thumbnail/s3/images/2010/July/MainPhoto.jpg';
  $ajax_commands = array();
  $ajax_commands[] = ajax_command_html("#edit-field-images-und-2-imgsearch-file-url", $imagepath);
  // Tell the browser to close the modal.
  $ajax_commands[] = ctools_modal_command_dismiss();
  print ajax_render($ajax_commands);
}

```

This works in that it closes the modal and writes a value (both hardcoded for the moment just to get this part working), but the problem is that it adds a after the input element instead of writing the data to the textfield itself. Is there a different command I should be using to write the image path to the text field?

# Answer
> 0 votes
See my eventual resolution to this issue in the ctools issue queue.

---
Tags: ajax, chaos-tool-suite, javascript
---


# Question
Title: How to flag term reference without flagging term?
I need do something like the skills system in linkedin.

The logged user with role "employee" have a profile2 called "employee". In this profile I need add a term reference field where the user can add his skills or create some skills new by Autocomplete term widget (tagging)... Like in linkedin.

After that, the other authenticated users can confirm the single skill of a user.

I tried to do this with taxonomy, term reference field (in the profile2 "employee") and flag... The problem is that if a user add the skills by term reference field, eg. term1, term2, and an other user confirms (flags) that skills, the terms are flagged for all users. So if an other user add term1 and term5 the current user visits his page and the term 1 is alredy flagged.

Can you help me?

# Answer
> 2 votes
You may use the Relation module.

Relation allows you the create relations between entities that *are* entitties too. So the scheme will be:

* Create a relation between your users and the skills entities (they can still be taxonomy terms).
* Because these relation instances between your users and the skills are entities you can create a flag for this relation entities. So, when a user adds a skill to the profile you will have to create one relation entity with the user (or profile2\*) and the skill.
* When anotheruser wants to aprove this user's skill she will flag that entity relation. No other user is affected.

I checked Relation time ago and I remember that creating relations was a little bit tricky. I don't remember how to make relations so I can't help you in this point, sorry. You may need some custom code to achieve what you want.

\*: to decide between Profile 2 or user take into account how are you going to show this information. For example, think which options fits better with Views.

---
Tags: users, flags, taxonomy-terms
---


title: Attaching files in Drupal Commerce

text:
# Question
Title: Attaching files in Drupal Commerce
Selling files online with the following pieces:

Commerce 7.x-1.8 Commerce File 7.x-1.0 Mime Email 7.x-1.0-beta3

I would like to provide people with a document attached to an email. The commerce-checkout-rules almost gets there. What is the token replacement that 'provides a list of files; one per line'? Or otherwise, how do we attach the files being checked out?

# Answer
> 0 votes
Resolved it.

The trick was to create a new variable in the rule.

1. Store \> Configuration \> Checkout Settings \> Checkout Rules.
2. Edit the rule : Send an order notification email.
3. Create a loop over each commerce-order:commerce-line-items.
4. Add a variable to the loop.

This was the trick.

The data selector is: list-item:commerce-file-line-item-files:0:file

Don't worry about the the 0 - the loop is sending 1 email per document. The result could be cumbersome, but means that if people order 20 documents and they are large, they should still get through.

I called the variable: added\_commerce\_file\_licence\_items.

6) Create a Send HTML e-mail rule. Put it in the loop.

The attachments field contains:

\[added-commerce-file-licence-items:path\]

7) Make sure that the permission "Send arbitrary files" is set.

I could also send by hook\_mail\_alter(&$message), which allowed me to try a few different things such as permutations of the URL and get a working version without too much experimentation.

```
function commerceemaildoc_mail_alter(&$message) {
  if (array_key_exists('attachments', $message['params'])) {
    foreach ($message['params']['attachments'] as $attachment) {
        $file_content = file_get_contents($attachment['filepath']);
        $mime_type = file_get_mimetype($attachment['filepath']);
        $attachment = array(
            'filecontent' => $file_content,
            'filename' => basename($attachment['filepath']),
            'filemime' => $mime_type,
        );
        $message['params']['attachments'][] = $attachment;
    }
  }
}

```

---
Tags: emails, commerce
---


# Question
Title: Creating a List View and Thumbnail view in Drupal 7 view
I created a view but I am hoping to create two possible viewings of it.

Basically, it's showing it in either `List View` or `Thumbnail View`. Now, one option would be to create two views and showing one of them by default and hiding the other; hence toggling each when the button is pressed. But I was hoping to find some more efficient less resource intensive solution.

## Thumbnail view

## List view

Thanks.

# Answer
> 1 votes
You could create one view with 2 pages or blocks depending on how you are setting up your view. Then have one show list view and the other show thumbnail view. You could then use tabs to switch between the 2 views.

# Answer
> 1 votes
I agree with @n30r3b3l. The easiest way to do this is to create multiple "displays" within a single view. To do this, simply click the add "+ Add" button in the top left are of the views edit page. You can rename each display. You will need to watch out for one thing, though. When you edit things in one display, the default setting is that the change will affect all displays.

You can override this setting on the edit form. Like so:

---
Tags: views
---


title: Same node different template via url

text:
# Question
Title: Same node different template via url
I want to use different node templates if the url is appended with ?template=x

Content type is called image

**Default Node template using node--image.tpl.php:**

* blakedesign.co.nz/testsite/node/1

**Same node with different template via URL possibly node--image--templateX.tpl.php:**

* blakedesign.co.nz/testsite/node/1?template=2
* blakedesign.co.nz/testsite/node/1?template=3
* blakedesign.co.nz/testsite/node/1?template=4

How do I go about doing this?

# Answer
You can create custom template suggestions for node using hook\_preprocess\_node... In your case it should be below code in your theme template.php file... You can read query arguments using $\_GET variable..

```
function YOURTHEME_preprocess_node(&$variables) {
  if ($variables['type'] == "image" && isset($_GET['template'])) {
    $variables['theme_hook_suggestion'] = 'node__image__template' . $_GET['template'];
  }
}

```

Your template file should be...

```
node--image--template1.tpl.php

node--image--template2.tpl.php

node--image--template3.tpl.php etc...

```
> 4 votes

---
Tags: 7, nodes, theming, uri
---


# Question
Title: TinyMCE - Drupal 7 - Insert images not functioning
I'm having trouble inserting images via TinyMCE (I've also installed WYSIWYG). I can insert images into an article just fine and all looks as it should while I'm editing an article, but if I preview or save the article and then view it, the image doesn't show up, instead I see:

\[img\]/sites/default/files/myimage.png\[/img\]

I've tried making the content with full html, and I've installed the media module and selected an option under text formats that is supposed to convert media tags into html.

What am I missing?

# Answer
Disabling the BBCode option in my TinyMCE Wysiwyg profile worked for me.
> 2 votes

# Answer
Use the Bbcode module to convert the bbcode to HTML tags. Here is a quote about it (from the module's project page):

> ... adds a BBCode filter to Drupal. This allows you to use HTML-like tags as an alternative to HTML itself for adding markup to your posts. BBCode is easier to use than HTML and helps to prevent malicious users from disrupting your site's formatting.
>
> See the help screen of the module (or the code) for information on which tags and variants are supported. This implementation is not necessarily the same as the original BBCode implementation.
>
> Note that this filter also recognizes and converts URLs and email addresses to links automatically.
>
> The quicktags module can be used in conjunction with this module to provide a BBCode formatting bar above all text areas.
> 1 votes

# Answer
I ended up using CKEditor instead of TinyMCE; it worked like a charm.
> 0 votes

# Answer
Disabling that BBcode was the key for me. I have been searching for some time for this problem and came across everything from permissions to .htaccess and setting.php.

Thank you localstatic for you are the hero of the day if not the week.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Ubercart review order button redirects to cart page, does not allow checkout
I am using Ubercart 3.3, Secure Pages latest dev, and Drupal 7.18.

When I go to the site, login, and add a product to my cart all goes well. I then go to the cart page which shows correctly and I click checkout. It then redirects me to the checkout page where I fill in my information and choose paypal as my payment of choice. When I'm all done I click review order at the bottom of the form and it redirects me back to the cart page instead of the review order page.

To make matters worse, after that happens I can no longer get back to the checkout page, every time I click checkout it just redirects me back to the cart page.

Some things i've checked:

1. User 0 is in the database
2. Clearing cache
3. Truncating the cache tables
4. Try a different product
5. Applied patches Secure Pages requires
6. Adding `$conf['https'] = TRUE;` at the bottom of my `settings.php` file

# Answer
> 3 votes
It actually turned out that I **had a product in my cart that was no longer on the site**, and my theme did not have the proper messages outputting. I switched the theme back to Bartik and got a message saying there were products in my cart that were no longer available.

# Answer
> 1 votes
Some other things to try -

* Check your webserver logs (eg Apache log) for errors
* Check your Drupal watchdog logs (admin/reports/dblog - you may need to enable this and then repeat the issue to log errors)
* Check your Paypal processor is configured correctly, and that no errors are showing in Paypal admin interface
* Switch to another payment processor (eg test gateway) & disable Paypal

These aren't answers, but they may help you find your own solution.

# Answer
> 0 votes
In my case changing the theme to Bartik, everything works fine. So there must be something in the custom theme that is preventing submission. Of to check now.

# Answer
> 0 votes
In fact, you need to add stock to make it work. If the stock is set to 0, there is nothing to buy.

---
Tags: 7, ubercart
---


# Question
Title: Change User Profile Fields from modules - $form fields not available - Ubercart Roles
I have been attempting to change various fields on the user profile to make it more user friendly, most of it going well. However, when I try to access $form for the main user profile via `dpm($form)` in `MODULE_NAME_form_alter` not every field rendered onto the page is available. I have been trying to alter the profile forever with no luck!

```
function admin_dashboard_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'user_profile_form'){
        //change main user profile "Ubercart Roles" form field
        $form['uc_roles']['#title'] = t('Member Expiration');
        $form['uc_roles']['#collapsible'] = FALSE;
        $form['uc_roles']['#collapsed'] = FALSE;
    }
}

```

# Answer
I figured it out! My module name was alphabetically before the other modules..."A" (admin\_dasboard) comes before "U" (ubercart\_roles). I was able to go into the drupal\_system table and set my modules weight to 1, where before it was set to 0, the same as Ubercart. Hope this helps someone.
> 0 votes

---
Tags: ubercart, users, forms
---


# Question
Title: dd a class="" to anchor on the "read more" links of a node
How I can add a class="" to anchor on the "read more" links of a node. Im use a bootstrap theme and i need add de btn-default class to anchors, thanks

`

 <<<<<<<< SET A CLASS IN THIS ANCHOR ? >>>>>>>>>>

 Read more
  sobre Noticia 2

`

# Answer
> 0 votes
Add template.php file to your theme directory if it doesn't exist. Then, add template\_preprocess\_node() to it like so, replacing template with your theme name.

```
function template_preprocess_node(&$variables) {

  $variables['links']['node']['#links']['node-readmore']['attributes']['class'][] = 'btn-default';
}

```

---
Tags: nodes, theming
---


# Question
Title: Module weight not being respected in order of execution
Trying to do something fairly simple, using the Panopoly distro.

Basically, I'm trying to implement hook\_wysiwyg\_editor\_settings\_alter(). Within the Panopoly distro, the panopoly\_wysiwyg module also implements the hook.

So if I have this structure,

/profiles/panopoly/modules/panopoly/panopoly\_wysiwyg /sites/all/modules/contrib/wysiwyg\_button\_order /sites/all/modules/custom/my\_module

**No matter how I set the module weights**, the hook fires in the order

* sites/all/modules/contrib
* sites/all/modules/custom
* profiles/panopoly/modules/panopoly

Within the directory, execution is in alphabetical order. I've tested this by moving my\_module into sites/all/modules/contrib and profiles/panopoly/modules/panopoly.

Is this a bug in Drupal? Am I missing something? I've tried to use hook\_module\_implements\_alter() but that doesn't fire at all.

If I call modules\_list(), it shows the modules in the expected order, but the hook doesn't fire in that order.

Any ideas?

# Answer
The module weight can be updated in multiple ways

1) Using the Module Weight module which gives you an option to change the order of modules. This module allows only reordering of non core modules 2) Directly updating the weight field in the table "system". Refer to this link for more details.

Lesser the weight the module floats on the list and gets executed early
> 0 votes

---
Tags: 7
---


# Question
Title: saving programmatically without changing the author
I made a script to change some node fields that is run by cron.

When it saves the nodes, the author changes and becomes "Anonymous".

Is there a way to save programmatically a node without changing its author?

---

Since you are asking the code, I suppose that my question is not clear. It's not important what I change in the node. What I need is to leave the author as it is and not changing that to Anonymous.

---

Finally thanks to one comment I get that node\_save() doesn't change the author. It should be something else. Thank you.

# Answer
> 2 votes
Saving the node using `node_save()` does not change the author. Example:

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

$node->field_xyz['und'][0]['value'] = 'your changes';
//make the changes to field
 node_save($node);

```

---
Tags: 7, cron, nodes
---


# Question
Title: Users unable to view orders even with permissions set
I have a Drupal 7 site with Ubercart. When users log in, and check their "My Orders" tab, it says there are no orders even when their should be. Users are showing correctly for admin, and permissions are set correctly for them to view.

Any ideas what could be causing this?

# Answer
> 0 votes
Since you said the permissions are set right you can do a quick test for this using views;

Create a new view with "show" Orders and use the Filters(users) to check if you can find the orders of different users.

---
Tags: 7, users, ubercart
---


# Question
Title: multisite multilingual over different directory
I have multi-site over directories.

xx and yy are made symbolic links are linked to same Drupal directory

domain.tld/xx domain.tld/yy

And on .htaccess it requires to have different Rewritebase

RewriteBase /xx

or

RewriteBase /yy

which is not possible.

Any other way to solve using someother RewriteRule?

Note: It is also multilingual website

Update: It is Drupal 7.26

# Answer
> 0 votes
I was solved this problem . May be use to you for only Multisite

Solution:

```
Give Symbolic link form mulitsite to site1
Executed that command line
ln -s /var/www/multisite /var/www/site1

Rename example.sites.php to sites.php
// 192.168.1.99 local IP address
$sites['192.168.1.99.site1'] = 'site1';

put this line in sites.php

```

No need to use RewriteBase /xx

If you have any problem in symbolic link use this link https://superuser.com/questions/68685/chown-is-not-changing-symbolic-link

and also How do I setup multiple sites with one database in Drupal 7 (or) Multisite Apache configuration with Drupal

---
Tags: .htaccess, uri
---


title: how to customized user login page

text:
# Question
Title: how to customized user login page
My question is when i browse my admin site www.example.com/user a simple login page will appear.

Here in this login form there is no option for forget password .so I need option to request new password and new password can be send through email.

# Answer
You can make a template to alter your user login form.

In template.php:

```
function YOURTHEMENAME_theme(){
    return array(
        'user_login' => array(
            'arguments' => array('form' => NULL),
            'render element' => 'form',
            'template' => 'templates/user-login-form',
        ),
  );
}

```

Then create user-login-form.tpl.php in your template folder and print the login form using

```
print drupal_render_children($form);

```

Don't forget to clear cache
> 0 votes

# Answer
Customizing the user login, register, and password reset pages is fairly simple, and uses the following concepts:

```
preprocessing to set variables
registration of functions in the theme registry
creation of one or more theme templates.

```

Step 1. In the site theme directory, create or edit your template.php file.

Step 2. The first step is to implement hook\_theme for your theme. In the template.php file for your theme, look for a function named yourtheme\_theme() and modify it to add these return values. If the function doesn't exist, add the following:

For D6:

array( 'template' =\> 'user-login', 'arguments' =\> array('form' =\> NULL), ), 'user\_register' =\> array( 'template' =\> 'user-register', 'arguments' =\> array('form' =\> NULL), ), 'user\_pass' =\> array( 'template' =\> 'user-pass', 'arguments' =\> array('form' =\> NULL), ), ); } ?\>

Notes about that code:

```
Change the function name by replacing "yourtheme" with the name of your theme
The template can be the same for all three. The example above uses a different template for each case: user-login, user-register, and user-pass
The template names must use a dash, not an underscore
Note: It's user_pass not user_password

```

For D7:

'form', 'path' =\> drupal\_get\_path('theme', 'yourtheme') . '/templates', 'template' =\> 'user-login', 'preprocess functions' =\> array( 'yourtheme\_preprocess\_user\_login' ), ); $items\['user\_register\_form'\] = array( 'render element' =\> 'form', 'path' =\> drupal\_get\_path('theme', 'yourtheme') . '/templates', 'template' =\> 'user-register-form', 'preprocess functions' =\> array( 'yourtheme\_preprocess\_user\_register\_form' ), ); $items\['user\_pass'\] = array( 'render element' =\> 'form', 'path' =\> drupal\_get\_path('theme', 'yourtheme') . '/templates', 'template' =\> 'user-pass', 'preprocess functions' =\> array( 'yourtheme\_preprocess\_user\_pass' ), ); return $items; } ?\>

Notes about the D7 version:

```
The 'path' lines tell Drupal where to find the .tpl.php files. This is optional, and in the code above, 'path' tells Drupal to find the files in the templates subdirectory of the theme's base directory.
Note the "_form" added to the user_register element.
Note: As it is the case for D6, it's user_pass not user_password

```

Step 3. Now you implement three preprocess functions. There may be more concise ways to code this, but this works very well and is easy to read, so here we go!

For D6:

Notes about that code:

```
Change the function name by replacing "yourtheme" with the name of your theme
The line $variables['intro_text'] adds the text that follows to the $variables array, which gets passed to the template as $intro_text
The second line renders the form and adds that code to the $variables array, which gets passed to the template as $rendered

```

For D7: The code is even simpler for D7 because we don't need to pass a variable containing the form content we want rendered. The variable exists already in the $vars array and can be rendered in the .tpl.php file.

The above preprocess functions simply add a variable into the $vars array that is then displayed in the .tpl.php file. Much more complex manipulation of the content of the render array is possible.

Please note, that the preprocess functions should go into the template.php file.

Step 4. Create template files to match the 'template' values defined above.

For D6 We need the following template files (make sure to use a dash, not an underscore) :

```
user-login.tpl.php
user-register.tpl.php
user-pass.tpl.php

```

For D7 As for D6 but with user-register-form.tpl.php for the register form.

Step 5. Paste the following into user-login.tpl.php. Modify as necessary for user-register.tpl.php (D6) and user-register-form.tpl.php (D7):

For D6:

For D7:

***Add the forgot password link, HTML Tags, Css & JS.***

Note the change to the syntax for causing Drupal to render the form. Also, the D7 sample uses a different class for the div, but that's just a matter of preference.

Step 6. Save your template.php file to the theme's main directory. Save your .tpl.php files in the same place for the D6 examples, or, in the case of the D7 examples, to the directory you specify in the 'path' element of the $items array.

Step 7. Rebuild the cache. Go to Administration \> Performance and click on "Rebuild Cache" on the bottom of the page.

Now, the user login page will contain the new text from the preprocess function, and the tpl.php file(s) can be modified to suit the site's needs.
> -1 votes

---
Tags: users
---


# Question
Title: Set default value radio button in template
I'm trying to set a default value in a template file for a radio button on my register form.

Female has value 0 and male has value 1. This is the code I use to set a default value:

```
    $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = '1';

```

I also tried

```
    $form['field_personal_details']['und'][0]['field_gender']['und']['#value'] = '1';

```

This should check the radio button as male, but it doesn't work. Whenever I set the default value to male through the UI it does work and I get the same outputs when I do a dpm.

What am I doing wrong?

# Answer
> 1 votes
Add direct user registration form alter and try to change "1" to 1.

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

  $form['field_gender']['und']['#default_value'] = 1;
    <---or --->
  $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = 1;

}

```

# Answer
> 0 votes
You need to use `hook_form_alter()` (or `hook_form_FORM_ID_alter()`) to alter forms:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['field_personal_details'][LANGUAGE_NONE][0]['field_gender'][LANGUAGE_NONE]['#default_value'] = '1';
  }
}

```

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


# Question
Title: Altering the views Sorting Criteria, to display first ISSET fields
Ia am working on a view that displays search results for nodes of a certain content type. In this Content Type there is a field "photo". Some of the nodes have a photo, some of them not. Is it possible to display (in the search results), first the nodes that have that field filled and at the bottom the nodes where the field photo is not set?

I tried to achieve it with custom sorting in the PHP field, using a snippet that i found here : https://drupal.org/node/727418#comment-3827246

```
$query->orderby = "CASE WHEN myFieldName IS NULL THEN 0 END, myFieldName ASC"; }

```

but it didn't work. Any ideas?

# Answer
Why not order by quantity of elements in photo field, or delta ?
> 1 votes

---
Tags: views
---


# Question
Title: Bartik theme: How to extend text/content below blocks in sidebar 1 and 2
Am using the Bartik theme on my site. I noticed that whenever i place a block in the sidebar 1 and sidebar 2, all the space below the block becomes 'redundant' (i.e. content is limited to the middle of the page.) All the text on the page becomes restricted to the middle of the page.

Please, is there a way to make the content/text extend below the blocks in side bar 1 or 2?

# Answer
> 0 votes
Edit your page.tpl.php Cut and paste both the sidebar sections into the content section. Content section starts with: `<div id="content" class="column"><div class="section">`

I mean these parts:

```
<?php if ($page['sidebar_first']): ?>
    <div id="sidebar-first" class="column sidebar"><div class="section">
      <?php print render($page['sidebar_first']); ?>
    </div></div> <!-- /.section, /#sidebar-first -->
  <?php endif; ?>

<?php if ($page['sidebar_second']): ?>
  <div id="sidebar-second" class="column sidebar"><div class="section">
    <?php print render($page['sidebar_second']); ?>
  </div></div> <!-- /.section, /#sidebar-second -->
<?php endif; ?>

```

I think you will need some extra CSS to make it look nice.

---
Tags: theming
---


# Question
Title: why drupal webform form setting shows mysql errors in dblog?
I have created one webform in Drupal 7 in which some form components are present. But when I'm going to view that webform the components(fields) are not displayed. Then I checked in form setting that form was closed but when I'm going to change the form setting to open and saving that form I'm getting error *"The website encountered an unexpected error. Please try again later"*. Then in dblog there was the following mysql error.

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '39055' for key 1: INSERT INTO {webform} (nid, confirmation, confirmation\_format, redirect\_url, status, block, teaser, allow\_draft, auto\_save, submit\_notice, submit\_text, submit\_limit, submit\_interval, total\_submit\_limit, total\_submit\_interval) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13, :db\_insert\_placeholder\_14); Array ( \[:db\_insert\_placeholder\_0\] =\> 39055 \[:db\_insert\_placeholder\_1\] =\> \[:db\_insert\_placeholder\_2\] =\> full\_html \[:db\_insert\_placeholder\_3\] =\> \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> 0 \[:db\_insert\_placeholder\_6\] =\> 0 \[:db\_insert\_placeholder\_7\] =\> 0 \[:db\_insert\_placeholder\_8\] =\> 0 \[:db\_insert\_placeholder\_9\] =\> 0 \[:db\_insert\_placeholder\_10\] =\> \[:db\_insert\_placeholder\_11\] =\> -1 \[:db\_insert\_placeholder\_12\] =\> -1 \[:db\_insert\_placeholder\_13\] =\> -1 \[:db\_insert\_placeholder\_14\] =\> -1 ) in drupal\_write\_record() (line 7194 of /home/indiawaterportal/public\_html/includes/common.inc).

Please help me to solve this issue.

# Answer
> INSERT INTO {webform} (nid...

tries to insert the nid of the webform (got from auto-increment in the node table) in the {webform} table. So, every nid inserted in nid column of webform table should be unique. But it seems that the newly-created webform node got a nid that already exists in webform's nid column.

So I guess there's something wrong. Find that nid in webform table, see if it exists in node table, that must be the trick.
> 0 votes

---
Tags: webforms
---


# Question
Title: template to add a h2 tag around a field group title
I have a field group in my content type. I want to wrap an h2 tag around the title of the field group. I have tried looking at the node.tpl.php and field.tpl.php for a way to wrap just the title, and have not succeeded.

Where can I target this?

# Answer
The way I dealt with this was to change the wrapper in the Manage Display section from a fieldset to a div. Then, options for the label element could be changed from inside the UI.
> 0 votes

---
Tags: theming
---


# Question
Title: how to export nodes and their referencing entities
I have a site which has some content types which have custom entities which refer to them.

The exact example we are using is https://drupal.org/project/registration. We have event nodes which have registrations. I need to export all the nodes and the entities which reference them. The Node Export module works fine for nodes but misses these entities. And of course, besides for actually exporting them, we need to maintain the node/registration relationship.

What is the best way of doing this?

# Answer
My solution for this was to use the Migrate module. It is very powerful and you can create update classes for custom entities when one doesn't exist from the producer of the contrib module. I would highly recommend it.
> 0 votes

---
Tags: entities, importing-exporting
---


# Question
Title: Get image's URL as a token for use in Views' replacement pattern
I need to get an image's full URL path as a token that I can use as a replacement pattern in Views.

I'm trying to have one thumbnail image link to a larger image. I have the larger image excluded from view so I can use it as a token. When I try to export the thumbnail image as a link using the larger image's token, the token is apparently the `<img>` tag instead of the path.

I think I can do this if I change the field type of the larger image to a File, but I want the benefits that come with the Image type (cropping, scaling, etc).

# Answer
> 7 votes
I ended up using a module to create a custom formatter. Image URL Formatter http://drupal.org/project/image\_url\_formatter . It created a new formatter option called "Image URL," and I can use that as a token.

# Answer
> 4 votes
Old, but I think:

```
[node:IMAGEFIELD_TOKEN:file:url]

```

would do it

of in case of a multiple image field:

```
[node:IMAGEFIELD_TOKEN:IMAGEFIELD_IDX:file:url]

```

Where

* IMAGEFIELD\_TOKEN is your image field token, like field-image, field-images, etc.
* IMAGEFIELD\_IDX (for multiple fields) is your 0-based index. 0 for the first image, 1 for the second and so on.

# Answer
> 1 votes
The contents of the token in this case is controlled by the formatter that renders the image. Perhaps the formatter has a setting to render the image as a direct link instead? I haven't tried doing this in Drupal 7, but with imagefield in D6 there was a direct link option.

If not, the best way to solve this is to add such a formatter.

---
Tags: views, media, tokens, uri
---


# Question
Title: Warning: in_array() expects parameter 2 to be array, string given in _drupal_http_use_proxy() (line 1100 of /var/www/html/includes/common.inc)
Whenever I add any content on my website, I get this warning.

> Warning: in\_array() expects parameter 2 to be array, string given in \_drupal\_http\_use\_proxy() (line 1100 of /var/www/html/includes/common.inc)

I am not sure why it does that, and how do I solve it? Can anyone help?

PS: I don't know what tags should I use for this question.

**EDIT1:** Executing

> dpm(variable\_get('proxy\_exceptions'));

# Answer
This is the code for \_drupal\_http\_use\_proxy

```
function _drupal_http_use_proxy($host) {
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
}

```

The status message warns that $proxy\_exceptions is not an array.

You can configure this setting on your settings.php file, this way:

```
$conf['proxy_exceptions'] = array('127.0.0.1', 'localhost');

```

Have you changed this variable to anything other than an array?

```
 $conf['proxy_exceptions'] = '127.0.0.1'; // For example

```

Maybe there is a contributed module which do this...

Try to insert a dpm on $proxy\_exceptions or execute this on /devel/php to show the value of this variable:

```
dpm(variable_get('proxy_exceptions'));

```

If you want to reset this variable:

```
variable_set('proxy_exceptions', array());

```

or

```
variable_del('proxy_exceptions');

```
> 3 votes

# Answer
I couldn't solve why I used to get the error messages, but I hid the errors and warnings for the everyone except admin using Disable Messages module. It's quite good, all I had to do is install the module, and change the permissions according to roles.

I will update my answer if I found the way to solve this warning.
> 1 votes

---
Tags: forms
---


# Question
Title: Dynamically adding a CSS class to a view row with template.php
I've actually reached the bottom of Google trying to figure out how to add a css class to each row of a view. The trick is that I need the class for each row to be dynamically determined based on some of the data from the node that the view pulls from. The function that pulls this off neatly for the node is -

```
function pgc_preprocess(&$variables) {
  $node = $variables['node'];
  if ($node->type == "event") {
    $variables['event_class'] = '';
    $num_trainers = $node->field_number_of_trainers[0]['value'];
    $count = count($node->field_trainer);
    if($count < $num_trainers) {
        $variables['event_class'] = 'red';
    } else {
        $variables['event_class'] = 'green';
    }
    return $variables;
  }
}

```

The point of this is to color code an event that hasn't had enough folks sign up. There will be a list of events on the front page, and I need them to be color coded also. I really hope there some simple solution along the lines of -

```
function pgc_preprocess_views_view_unformatted(&$variables) {
  // Magic here, preferably having something to
  // do with the function I already wrote.
}

```

Just dropping `<?php print $event_class ?>` in the view .tpl doesn't do it.

# Answer
```
function pgc_preprocess_views_view_unformatted__home_listing(&$vars) {
  // Borrowed this bit from http://drupal.org/node/312220
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($rows as $id => $row) {
    $data = $view->result[$id];
    $event_class = get_the_classes($data->nid);
    $vars['classes'][$id] .= ' ' . $event_class;
  }
}

function get_the_classes($nid) {
  $node = node_load($nid);
  global $user;
  if ($user->uid != 0) { // Not for anon users.
    $event_class = '';
    if ($node->field_trainer[0]['uid'] == NULL) {
        $event_class= 'red';
    } else {
        $num_trainers = $node->field_number_of_trainers[0]['value'];
        $count = count($node->field_trainer);
        if($count < $num_trainers) {
            $event_class = 'red';
        } else {
            $event_class = 'green';
        }
    }
    return $event_class;
  }
}

```

Don't know if it's pretty. Don't know how it performs. But it works.

EDIT (02-01-2012): after working with Drupal for another year now, I'd have tried to find some other way to do this besides running `node_load()` on every row of the view.
> 10 votes

# Answer
your solution is great! To make sure that the classes will be really added to the views row classes you should add

```
$vars['classes_array'][$id] = implode(' ', $vars['classes'][$id]);

```

after

```
$vars['classes'][$id][] = $event_class;

```

And the preprocess function will be:

```
function pgc_preprocess_views_view_unformatted__home_listing(&$vars) {
  // Borrowed this bit from http://drupal.org/node/312220
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($rows as $id => $row) {
    $data = $view->result[$id];
    $event_class = get_the_classes($data->nid);
    if($event_class != '') {
        $vars['classes'][$id][] = $event_class;
        $vars['classes_array'][$id] = implode(' ', $vars['classes'][$id]);
    }
  }

```

}
> 0 votes

---
Tags: views, theming
---


title: Contextual Filters using YYYY and MM

text:
# Question
Title: Contextual Filters using YYYY and MM
I am attempting to set up a list of articles that will display like so

2014 January February

2013 January Feb

I've set up my view, but once I use the YYYY contextual filter, it simply sorts it

2014 2013

And I cannot get the months to display. Any suggestions would be greatly appreciated

When I print the array the \[url\] returns /posts-by-date/2014

I am trying to have the array return posts-by-date/2014/\[month\]

# Answer
I have done this by setting up two displays of my view

Display 1 is a page display, with the path 'foo/date/%/%'. This then gets a pair of contextual filters, the first is for the year (the first argument). The second is for the month (the second argument).

Display 2 is a page display, with the path 'foo/date/%'. This gets a single contextual filters, the year.
> 0 votes

---
Tags: views
---


title: Custom content in auto generated menu

text:
# Question
Title: Custom content in auto generated menu
I have been working on a website that contains a main dropdown menu generated by Drupal (7.28). Is there any way I can add a link to it between the other links that shows content generated by me in the dropdown? So instead of: fetch pages, fetch something else (defined by me).

Thanks in advance =\]

# Answer
Every module on your site can be found in the list on /admin/structure/menu. just click 'list links' and then 'add link' to add a link to a menu.
> 0 votes

---
Tags: nodes, routes
---


# Question
Title: Selecting content type using panels/pages
We want to select a content type in panels with a specific URL \[tgeink.com/latest-news\]. Here's why:

We are using panels for several content type 'home pages', like news, articles, etc. They all rely on a view that displays recent posts in the various content types, along with an exposed menu so that users on the 'news' page only get news when they select a topic. Currently we are creating different views for each content type because we can't see how to select content type in panels -- we do it in views.

\[It's easy if you are using panels for /%node. We use that to display and edit nodes, with variations for the different content types.\]

We'd LIKE to be able use one view for all 'home' pages, and use panels to select the content type. However, we cannot see how to do this when the panel is referencing a URL such as TGEink.com/latest-news. Thanks for any help.

# Answer
> 1 votes
You can use views for that solely too you know... Don't use a content pane as described below but a page with path /latest-news/%type.

But for panels: Create a views content pane that gets all types of nodes @ once. Set contextual filter to node-\>type and choose raw value from url 2.

Create a page in pagemanager with this path: yourdomain.com/latest-news/!type Don't set up a context.

Add the contentpane as content in the page. Now if you visit latest-news/article it shows all article-nodes. If you visit latest-news/page it shows all page-nodes.

Now you can have all benefits from panels together with a view.

---
Tags: nodes, panels
---


# Question
Title: Drupal 7 clearing validation error messages
When an image upload fails validation an error message is thrown on the form, when I then upload an image that passes validation, the previous error message is not cleared from the form. How is this accomplished? Thanks.

# Answer
The reason being after you enter the value the form needs to be submitted for the error to clear out. So if you want the validation removed as the user starts entering values you should look into the Clientside Validation module.
> 1 votes

# Answer
This is a core issue with Drupal 7 . You can find a solution in the following link http://drupal.org/node/1792032
> 1 votes

# Answer
I think you should look at drupal\_set\_message().
> 0 votes

# Answer
In my case I was doing some additional validations on user registration form (user\_register\_form) and in case of errors using form\_set\_error('field\_name', t($preparederrmsg)) which all worked very fine.

Problem began when the form had no errors but the old messages were still there and the solution was to render the form again.

```
    function mymodulename_form_submit_handler($form, &$form_state){
     //all my code here
     $output = drupal_render($form);
     return $output;
     }

```
> 0 votes

---
Tags: forms
---


# Question
Title: Add Profile 2 -> Field Colleciton -> Taxonomoy into Facet (Search API)
I'm trying to display a Facet block , which uses Term reference (Taxonomy) of Field Collection of Profile 2. Since I am new to Search (API), I have tried all sort of things but nothing worked.

For example:

* Use Facet display of View: Rendered entity, Field..
* Use Facet Block from Search API
* Config options in Search /Search API..

In *Home » Administration » Configuration » Search and metadata » Search API » View index*

I added Facets the followings:

* Vocabulary: Facet blocks look good in the picture below
* Profile2-\>Field Collection: look good in the picture below
* Profile2-\>Field Collection-\>Vocabulary(Taxonomy): bad,It always shows empty

---

##

**My Question is:**

How can I make this happen? or Is it possible to do it?

# Answer
I found out the solution from Search API Drupal Recruiter here

In short, I have to click "+Add index" to make a new index based **Profile**

---

For example, Please take a look at the picture below to understand how to solve this issue.
> 0 votes

---
Tags: taxonomy-terms, search
---


# Question
Title: Specific Content Access only after successfull checkout
I'm creating a website where user can buy content & can view that content online.Suppose user buys a book online.Now after user successfully completed the payment process,that book should be added to user account page from where user can access the content page.Just like E-book read online,where user can only read books user purchased. I'm using Drupal Commerce module.

# Answer
> 1 votes
You can actually accomplish this with no code using the Entity Reference, Content Access, and Access Control List modules. I just implemented this for a client! I added an entity reference field to my product type that I used to point to the node the customer should be granted access to upon successful purchase of that product. I then added a rule when an order is first paid in full that grants access through the access control list to the referenced node.

The trick is to configure your node type used for the premium content so that those nodes are only visible to administrators and then depend on the access control list to grant access to users on an individual basis. One advantage of this, too, is that you could create an "all you can eat" subscription using a user role that may also have access to view any content of that type if you wanted to.

To show a list of content the user has access to on their profile, you can simply create a list of nodes of the specified type, and Views's automatic inclusion of access control on node queries should ensure users only see the nodes in the list they have access to.

---
Tags: commerce, rules, users
---


# Question
Title: What's the relative path to a user's profile?
I've created a clickable block with Views and rewrote the fields with HTML like this:

```
<a href="user"> some divs... </a>

```

Clicking the block should refer the logged-in user to his/her profile. As the code mentions, I'm using `user` as relative link, but a problem occurs when the user clicks the link when he/she is already visiting his/her profile: the link is then turned into `mysite/user/user` instead of `mysite/user`.

Using `/user` doesn't work either, because it redirects the user to `localhost/user` instead of `localhost/mysite/user`.

What's the correct way to construct a path that takes into account either being relative or the `$base_path`?

# Answer
> 3 votes
There is no, and can not be always correct relative path.

Relative path is relative, and there is no infinite amount of paths to user profile, to be in the same relation with each and every path in your system. There cannot be. What you need is to **properly generate an absolute path instead**.

So instead of the code you are using, use Drupal's built-in link generator, `l()`:

```
<?php print l('some divs', 'user'); ?>

```

or, if above is not feasible, `url()`:

```
<a href="<?php print url('user'); ?>"> some divs... </a>

```

# Answer
> 0 votes
if you create it with 'user/\[uid\]' it will be added to the current url.

Create it with a / in front to make it start at your domain, use '/user/\[uid\]'.

@Gregory: he is using a \[token\] so it's no code. More like a block in views or something.

To clarify my comment:

`<a href="/user">profile</a>` or /user in views as a link is always user specific. It brings anonymous users to the register/login page and logged in users to their own page. No need to put \[uid\] or !1 or something behind it.

# Answer
> 0 votes
```
<a href="/user/!1"> ... </a>

```

will do the trick.

---
Tags: 7, users, uri
---


# Question
Title: Location / distance based calculated field in views results?
Modules in use:

* Drupal 7.12
* Views 3.3
* Location 3.x-dev
* (and lots more of course)

I have a pretty standard view which has a user entered proximity filter for distance from a zip code, used to shows stores near a certain location (your standard dealer/store locater search). I would like to add a calculated field (or something) to show how far each store is from the entered zip code. This field would only be used in the view, and would not need to get saved to the node it represents, since this distance will change depending on the entered zip code.

Can anyone point me in the right direction?

Thanks!

# Answer
> 5 votes
I guess I should have looked through the module better. Here's the answer (tip: it's built right in!):

* Go to your view (it needs to be a node based view I think)
* In the "fields" section choose "add"
* In the search box type "distance" and then choose the "Location: Distance / Proximity" field
* Choose miles or kilometers to suite your needs
* Then choose "Use Distance / Proximity Filter" from the drop down list (assuming, like me, you have an exposed filter in your view for users to enter a distance and a zipcode)
* Adjust the label if you'd like, then click "apply"
* In the "sort criteria" section, choose "add"
* In the search box type "distance" and then choose the "Location: Distance / Proximity" field
* Then choose "Use Distance / Proximity Filter" from the drop down list (assuming, like me, you have an exposed filter in your view for users to enter a distance and a zipcode)
* Choose descending (most likely, anyway) and if you want to expose it, then you can click that check box also

And that does it!

# Answer
> 0 votes
just add the "Location: Distance / Proximity" field to your view. That should show the distance from the selected location and either the current user or a specific location. The other answer is wrong... doesn't actually answer the question, just explains how to set up the view *without* showing each result's distance.

Also note this only works with Field display... beware of using Display Suite as it would require a complicated custom code field.

---
Tags: 7, views, location
---


# Question
Title: How to remove a fieldset from around a Mailchimp Subscription field?
I have added a Mailchimp Subscription field to an entity form using the Mailchimp module. I'm having difficulty in removing the fieldset around this subscription field.

I have installed the Devel module and used the `dpm` function to display info on the form. But I can't seem to find what theme function I need to override to remove the fieldset.

I have an existing form alter applied to this form, what would I need to add to my existing form alter to remove the fieldset around the field?

# Answer
> 0 votes
You need to use YOURTHEME\_form\_alter of YOURMODULE\_form\_alter https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7

there you can alter that form. dpm or print\_r $form and see where that fieldset is defined and you can unset it

you will see something like

```
array(
   'some_field' = array(
    '#title' = 'some title',
    '#type' = 'fieldset',
  )
)

```

then you can do

```
unset($form['some_field']['#type'])

```

that should do the job

---
Tags: emails, forms
---


# Question
Title: #block-system-main with no content interrupting my layout
I have a drupal page with three blocks beeing rendered and floated besides each other in a content area. In the middle of these, Drupal renders out a block called #block-system-main with an empty content div. It breaks my floats, and I have no idea where this div is coming from or how to remove it.

Any ideas as to what could cause this and how I can remove it?

# Answer
> 1 votes
I dont know where it comes from. Probably best would be if you can find that. But if you want to quick fix it. You could unset it in page preprocess

```
function YOURTHEME_preprocess_page (&$variables, $hook) {
  unset($variables['page']['some_region']['block_id']);

```

---
Tags: blocks, theming
---


title: Node Permission

text:
# Question
Title: Node Permission
I have a custom content type, called List (for example).

All members can create new list node from their account, but the admin can also do the same.

What i am looking to get done is, make it so that the node created by admin is shown on top of their list and also could not be deleted except by the admin itself.

Could some one please help me determine the right process to accomplish this?

Thanks in advance

# Answer
> 2 votes
it can be achieved in 2 steps:

1. Fix permissions. go to admin/people/permissions and for that user group allow only to delete their own content. Don't check List: Delete any content. Then users will be able to delete only their own content.
2. You need to create rule "After saving new content" add condition "User has role" select your role (you need to create one and add for admin). Add action "Node: make content sticky"

---
Tags: nodes
---


# Question
Title: "Access denied" whenever trying to edit IMCE User-1 profile
After reinstalling IMCE, I am trying to see the User-1 profile by accessing the "admin/config/media/imce/profile/edit/1" URL. But it shows following error "Access denied. You are not authorized to access this page."

I have verified (URL admin/people/permissions) that administrator has privileges for IMCE module. Also rebuilding permissions is not helping here.

# Answer
> 0 votes
Earlier I changed the Drupal admin from the mysql database. I simply done undo on this operation. Have a look in your database.

---
Tags: users
---


# Question
Title: Administrative form to create new entities of a custom entity type
I have created a custom entity type NOTE: it is based on an existing database structure and so ECK is not (according to Programming Drupal 7 Entities p. 84) able to deal with exposing an "existing database table\[s\] to Drupal".

I now need to create pages for users to create/edit/delete these entities themselves.

Surely there is something out there that allows me to just say "This is the entity type, this is the entity id, load all the columns in the database as $form fields and take care of it for me"?

EntityForm seems to me to want to make forms that are themselves entities.

entity\_ui\_get\_form() seems to me to be about getting fieldable entities, but I'm trying to get the values as one can get by doing this...

```
$entity = entity_load('custom_entity', array($id));

...

$wrapper = entity_metadata_wrapper('custom_entity', $entity);

```

If this isn't something that can be done with only a few lines of code, what is the best approach? I got lost walking through the `hook_menu()` callbacks for `node/add`.

Thanks

# Answer
> 0 votes
As far as I can see, the Entity Creation Kit module provides these create/edit/delete forms out-of-the-box. Although you should probably redefine your entities with help of that module.

Otherwise, you can perhaps take a look at the ECK module source code and use the relevant parts for your custom module.

---
Tags: forms, entities
---


title: How to wrap a whole view in a tpl file?

text:
# Question
Title: How to wrap a whole view in a tpl file?
I created a view and I'd like to wrap it with a link in a template file. I've never worked with custom template files for views, so I've no idea where to start.

How can I do this?

# Answer
> 1 votes
In views under advanced-\>theme you can see template naming conventions you can use. Copy the views-view.tpl.php to your themes templates folder and rename it to one of the suggested names in views-\>advanced-\>theme. Clear your cache and the template will be used. Now you can alter the output of the whole view.

You can also do this for the fields as a whole, or a specific field.

Mind that views has so much power through UI that you seldom need to go through themefiles.

Wrapping the views field(s) in a link can be done also by rewriting field output.

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


# Question
Title: Problems linking Image to product display node
I'm trying to implement something like what's referenced here Image redirection problem, but I closer to the mark with this method http://www.drupalcommerce.org/node/556. The problem I'm having is that this sends me to a 404 page somehow the path is corrupted to this "localhost/drupal//drupal/node/437"

This was done by adding the field Content:Path to my view and excluding it from the display, placed it first in the field order, and then changed the image field by rewriting the result, exporting as link, and using the \[path\] token as the link itself.

I also tried the same thing with Content: Nid, first field but excluded from display, ditto with the image field but I used the \[nid\] token. This got me a cleaner path "localhost/drupal/437" but it's still going to a 404 page.

So in the first instance it's writing too much of the path into the link and in the second instance it's not inserting enough of it.

# Answer
This problem is solved by changing the Content: Path rewrite options to using absolute path.
> 1 votes

---
Tags: commerce, tokens
---


title: What's the advantage of view blocks?

text:
# Question
Title: What's the advantage of view blocks?
Instead of creating a block for each view, I simply display the master views in the panels on my website. As that works perfectly until now, I'm wondering why one should create a view block. Do they have any advantages over master views? Is my way of acting risky in a sense?

# Answer
> 0 votes
There are a couple of methods to control the layout of your site, and to arrange different elements into a page. Panels is one method. If you don't use Panels, the system of regions and blocks is probably your primary tool. (BTW, you can also mix panels and blocks.)

Personally I'm not a panels user, but I guess it's very possible that you will never need block views if you use Panels.

# Answer
> 0 votes
I wonder how you embed the View in your site. (I'm aware of views\_embed\_view() or any other PHP method. We good people don't even enable the PHP module do we?)

1. Block caching. Views exposed the Views to the blocks system, so they can cached, altered, and just about anything regarding blocks can be done.
2. If you want to have multiple blocks/displays out of the same View, you do have to create blocks. More views = more headache.

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


# Question
Title: Practical concerns for changing text on the "add to cart" in Drupal Commerce to use it as a "wishlist"
Apologize for the roundabout question, just not sure how to get at this more directly. I'm developing a commerce site where our clients will be submitting inquiry lists that we will respond to, rather than orders. In essence, what I need is the shopping cart, minus the payment gateway (which is where the site is headed). As a quick fix, I was thinking of just changing the text on the "add to cart" and "check out" buttons, as the basic functionality we need is there out of the box without a payment gateway. Is there a glaringly obvious reason not to do this? I am developing a parallel wishlist application with flags, but I haven't hacked the functionality I need into that yet.

# Answer
> 1 votes
So, upon conducting a lot of research, modifying the existing architecture in DC is possible, but appears to be non-trivial to apply. The checkout process has many hard coded titles and elements that, while instructive to research and attempt to modify lead me to believe that this implementation as a work-around is probably more effort than just throwing together a custom module for the functionality I'm looking for. If anyone reads this from the Drupal Commerce team: the internet is LOADED with requests on how to modify this stuff through the admin functions of DC, great work and much appreciated, but this noobs head hurts.

```
function bartik_form_alter(&$form, &$form_state, $form_id){
dpm($form_id);
dpm($form);
if (commerce_form_callback($form_id, $form_state) == "commerce_cart_add_to_cart_form"){
    $form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value']=t("Add to Inquiry List");
    }
if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
    $form['actions']['submit']['#value'] = t("Update List");
    $form['actions']['checkout']['#value'] = t("Submit List");
}
if(strpos($form_id, 'commerce_checkout_form_checkout')===0){
    $form['buttons']['continue']['#value'] = t('Proceed to final list submission.');
    }
if(strpos($form_id, 'commerce_checkout_form_review')===0){
    $form['buttons']['continue']['#value'] = t('Submit your inquiry list');
    }

```

}

---
Tags: commerce
---


# Question
Title: Drush Bootstrap Error on Multi-Site Install
I'm getting the "needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command." error.

I know this means that Drush is not able to find the settings.php file because it is not in the Drupal root directory. I'm working with one site that is part of a multi-site install on a university server. Am I getting this error because I'm in my site's specific root as opposed to the Drupal core root?

Any help would be much appreciated, Drush seems extremely useful!

Thanks, Kai

# Answer
There are several ways to specify which Drupal site Drush will target. The most basic option is fairly verbose; run:

```
$ drush --root=/path/to/drupal --uri=http://mysite.com status

```

You can do the same thing with a slightly different syntax:

```
$ drush /path/to/drupal#mysite.com status

```

You can also specify the Drupal site implicitly, by setting the cwd to the folder that contains the settings.php file for your site:

cd /path/to/drupal/sites/default # or /path/to/drupal/sites/mysite.com, as appropriate

```
$ drush status

```

In all of the cases above, if settings.php is in a folder called "default", then you do not need to specify the --uri component; you may, for example, cd /path/to/drupal followed by drush status, and the correct Drupal site will be found. If settings.php is not in a folder named 'default', then you will need to either specify --uri, or cd to the folder that contains the settings.php file.

You might also want to investigate Drush site aliases, which are another way to conveniently specify which site you'd like Drush to target.
> 0 votes

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


# Question
Title: Are ids strictly sequential i.e. does later added content always have higher id?
I thought that ids (user id, node id, ...) are strictly sequential which ensures that later added content has always higher id that a previously added one. So that when I have a hierarchy (lower element has a reference to its parent) and the 'reference' is not editable (set on creation) I can safely assume that a child has higher id that a parent.

The problem is that in this question @berdir (who I believe knows a few things about Drupal) says that it does not have to be the case...

I know that gaps might appear in the sequence (e.g. when an entity is deleted) but I'm not sure that he meant just that (and I'd rather be sure).

So my question is, how is in reality and when can I not the sentimentality of ids?

//DISC: The hierarchy system is quite complex and (of course) doesn't rely on ids comparison, the aforementioned concept is used just in one case due to optimization.

# Answer
User IDs and Node IDs are automatically incrementing (mysql, postgresql, sqlite) fields. Once an id has been used, it should not be used again (in the case of deleted content).

The higher the number, the later it was ***inserted*** into the database.

You could always end up with imported content that is older, but now has a higher Node/User ID because it was inserted at a later time.

You may want to look to the Relation module, or even Drupal's own menu system to define hierarchies. This depends completely on your use case of course.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Is there a way to load the current entity object?
Is there a way, from anywhere in drupal, to get the current entity object? I'm using the hook hook\_filter\_FILTER\_process() and I'd like to replace things in the $text with data from the entity, but it doesn't look like there is a way to access the entity without doing something like

```
if (!empty(arg(0)) && is_numeric(arg(1)) {
    $entity = entity_load(arg(0), array(arg(1)));
}

```

This works most of the time, but sometimes (like taxonomy terms) it doesn't. On top of that, this is really messy as it makes another call to the database.

Is there a better way to do this?

# Answer
> 8 votes
I think `menu_get_object()` might be helpful:

> menu\_get\_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu\_get\_object() will return that. Normally, it is necessary to specify the type of object referenced, however node is the default. The following example tests to see whether the node being displayed is of the "story" content type:

```
<?php
$node = menu_get_object();
$story = $node->type == 'story';
?>

```

You can use this with any router-loaded object so it stands to reason that on entity pages (including taxonomy term pages) that this would get you the correct object:

```
$entity = menu_get_object($entity_type);

```

**UPDATE**

On further inspection you still have to pass the position of the ID in the URL as a parameter to menu\_get\_object() so it's pretty much the same as using `arg()`, but it's arguably a bit cleaner. For taxonomy terms the path is `taxonomy/term/%` so you would call:

```
$term = menu_get_object('taxonomy_term', 2);

```

It's worth bearing in mind that `entity_load` will only incur a database call if the entity hasn't previously been loaded in the current page request. If it's already been loaded, it will be served from the static cache.

**UPDATE 2**

Just to add an example of the static pattern to avoid reloading the entity over and over again if you're getting memory errors:

```
$loaded_entity = &drupal_static(__FUNCTION__, NULL);
if (!$loaded_entity) {
  $loaded_entity = menu_get_object();
}
return $loaded_entity;

```

# Answer
> 2 votes
The proper way is using `menu_get_object()`.

# Answer
> 2 votes
Created this agnostic current entity loader function...

```
<?php
function my_module_menu_get_any_object() {
  // Figure out how this entity is loaded.
  $type = FALSE;
  $item = menu_get_item();
  $vals = array_values($item['load_functions']);
  $load_function = $vals[0];
  $arg_position = array_search($load_function, $item['load_functions']);

  // Compare to entity types.
  $entity_info = entity_get_info();
  foreach($entity_info as $i => $e) {
    if ($e['load hook'] == $load_function) {
      $type = $i;
    }
  }

  // Many happy returns.
  if($type && $obj = menu_get_object($type, $arg_position)) {
    if(is_object($obj)) {
      return $obj;
    }
    else {
      return FALSE;
    }
  }
  else {
    return FALSE;
  }
}

```

# Answer
> 0 votes
Input filters don't have any way to get the entity for which they are called to render.

Actually, an input filter could also be called in situations where an entity is not involved at all. For example, the Views module allows you to set the header of a view, and gives you the following options.

When you select *Global: Text area*, the following options are the following ones.

When an input filter is called in this case, there isn't an entity associated with the header of the view; if you would use `menu_get_object()` you would probably get the wrong entity, or you would not get an entity at all. To get the correct entity with `menu_get_object()` you need to know which entity is associated with the viewed page, and where the entity ID is stored in the URL.

As general guideline, input filters should not take assumptions about how they are used, as they could be used to render any text obtained as input from the user; the view's header used from the Views module is just an example, but there is nothing that would stop another module from using the same method.

---
Tags: 7, entities, input-formats
---


# Question
Title: Redirect only after inserting a new node?
I had a rule of 'After saving new content' of type, redirect to url. I need to add second submit button to the content type so I decided to add the redirect to a custom module so I can have different actions depending on the button. The redirect works on the submit button but I only want this to happen when adding/inserting a new node. Right now it redirects every time the submit button is clicked.

In mymodule\_form\_alter:

```
$form['actions']['submit']['#submit'][] = 'submission_form_submit';

```

Then:

```
function mymodule_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'info-received';
}

```

Code suggestions needed. But if there is a way to have rules perform different actions based on which button is clicked I can use that advice also.

ETA: the code used for the second button

```
$form['actions']['submit_another'] = array(
  '#type' => 'submit',
  '#name' => 'save_another',
  '#value' => t('Save, and Add Another.'),
  '#submit' => array('node_form_submit','submission_form_create_duplicate_form_submit'),
  '#weight' => 40,
);

```

ETA2: Trying is\_new

```
function mymodule_form_submit($form, &$form_state) {
  $node = $form_state['node'];

  if(isset($node->type) && $node->type == 'submission') {
    dsm('Reached Node Type Check!'); // <- this works

    if (isset($node->is_new)) {
    dsm('Reached New Node Check!'); // <- this does not work
    $form_state['redirect'] = 'info-received';
    }
  }
}

```

Changed the if statement checking for new node to

```
if ($node->is_new) {

```

Results in 'Notice: Undefined property: stdClass::$is\_new in mymodule\_form\_submit()'

It seems the value for is\_new is not set.

# Answer
> 1 votes
You could use hook\_node\_insert() under this hook should use drupal\_goto() for redirect. The hook\_node\_insert() only trigger when a new node inserted. If you also want to update. You could use hook\_node\_update().

# Answer
> 0 votes
In your $form or in your $form\_state, you have the node object, in which you can check if it's a new node by the key **is\_new**, the value being a boolean.

You can base a condition for the redirection on this.

---
Tags: 7, nodes, rules, redirection
---


# Question
Title: How to use checkbox under description of any webform field?
I am using webform module where I have a text field named Mobile Phone Number.

I wanted to use checkbox under the text field as shown below:

The content can be written in the description of that text field. But how do I use the checkbox as I shown above.

*Note: I tried to enter the html form tags in the description but didn't help.*

# Answer
I created a select field form component with label name as 'agree' and tick marked multiple so that checkbox will appear and provided a *single key|value pair* as shown below.

*Keep this select component under the mobile phone number component. It will appear exactly next to mobile phone number component then just hide the label, make proper alignments using **css**.*
> 1 votes

# Answer
You will create a check box component fields below mobile phone number fields after "yes|I am providing my express..." in **OPTIONS** . Create Check box -\> Options -\> "yes|I am providing my express..." and align with CSS code
> 2 votes

# Answer
use hook\_form\_alter hook to alter the form (in template.php):

```
function MY_THEME_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'MY_WEBFORM_FORM_ID' /* you can find formid with dpm function from Devel module or you can also use PHP's debugging functions, e.g. dpm($form_id) */) {
    $form['my_checkbox'] = array(
      '#type' => 'checkbox',
      '#title' => 'Your Long Description',
      '#weight' => 50, /* this value must be something like `phone number field's weight + 1` */
      ...
    );
  }
}

```

and flush the cache..
> 1 votes

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


# Question
Title: Drush command to show installed modules but not being used?
In the process of developing a site I inevitably install modules thinking they are the ones I want but they are not. I am looking for drush command to find these modules to disable them and reduce my resource overhead. Can anyone point me in the right direction?

maybe something like \[drush resource cleaner\];

# Answer
Drush has no way of knowing if a module might have some hook that is performing an active service for the site, even in the absence of any configuration information, so no, this feature is not available.
> 1 votes

# Answer
Not possible with Drush, but try the Master module. Here is a quote about it (from the module's project page):

> ... provides utilities for controlling the module status of all modules in the whole installation by a single Drush command. The configuration is done by defining "master modules". "Master modules" are (in most cases) custom modules or features, that provide dependencies to all modules that are needed to run the site. In combination with Features and maybe some custom code and scripts the whole site configuration can be managed via that approach.
> 0 votes

---
Tags: drush
---