# Question
Title: Token Not Working On Auto Node Title and Auto Entity Title
I am using drupal 7, auto node title 7.x-1.0, and token 7.x-1.4. I am trying to hide content type title field and set title value based on other field value, so i use auto-node title and token module. But, when i try to set the default value of the title using token, the token didn't work.

Then, after searching for a while, i've found this post: Token replacement pattern is not working

So, i try to install auto entity title 7.x-1.1 module and disable my auto node title. But, the token still not working. Anyone could help me?

Thanks in advance.

# Answer
This won't work indeed... It has to do with the way Drupal saves nodes. It starts with the title, and then reads and writes the rest of the fields.

The quick and dirty way is to use the rules module, and on node creation or edit, save the node again. I have been using this technique and can confirm it works.
> 1 votes

---
Tags: 7, tokens, nodes
---


# Question
Title: How to allow arbitrary query string with url alias?
Using Google Custom Search and as part of it's configuration I specify a callback url on my site (e.g., www.example.com/search). I setup my page www.example.com/search as a Basic Page.

When someone searches for something they are taken to the url I specify and arbitrary query string parameters are appended (e.g., www.example.com/search?cx=partner&ie=UTF-8&q=dom&sa=Search&siteurl=www.example.com/search).

However this results in a page not found because Drupal appears to treat the entire request path as a url alias which it can't find.

How can I allow arbitrary query strings?

# Answer
Drupal doesn't treat the query string as part of the URL alias, the problem is that your URL has the `q` parameter as part of it (`q=dom`).

Google obviously uses that for some purpose, but Drupal uses `$_GET['q']` to determine the path of the page that should be shown. So when you visit a URL with `q=dom` in the query string, Drupal will try to find a page with the path `dom`...which obviously doesn't exist on your server.

Short of some crazy hacking of Drupal core (and probably dozens of contrib modules) I think the only way you're going to solve this is by somehow changing the original query string and removing the `q` parameter from it.
> 1 votes

---
Tags: 7, uri
---


# Question
Title: Handling mobile images in responsive theme
Sorry for the open-handed nature of the question, but I don't know where else to get an answer to this. I'm deciding whether or not go full-force into a responsive Drupal 7 theme, probably the Omega framework.

One issue that keeps nagging at me is that the mobile devices have to download all the large images (not to mention everything else...).

Is there an easy way to serve up smaller images for mobile devices?

# Answer
> 9 votes
There are many modules to handle responsive images, including;

1. Responsive Images
2. Client-side adaptive image
3. Adaptive Image Styles (ais)
4. Adaptive Image
5. Borealis

# Answer
> 1 votes
Use different `imagecache` presets immediately comes to mind, eg, a set of them for the main, desktop theme, and another parallel set that creates smaller versions for the mobile theme, or if in the same theme, sets that toggle based upon the user agent of the user's browser.

# Answer
> 0 votes
I had been searching for a proper way to get adaptive images. Finally Client-Side Adaptive Image worked. You just have to make a few image styles. Then if you select image formatter as adaptive image then you can assign an image style for every breakpoint. You can even configure the no. of break points you want. Great module! Great Solution!

---
Tags: 7, media
---


# Question
Title: Automate creation of taxonomy terms for use with migration module
How do i script the creation of my taxonomy terms - do people normally do this with features?

# Answer
> 1 votes
depends when you want to create them, in a new site or importing them into an existing one?

If you're building an install profile you could write an install script to create the taxonomy and terms as you need.

If you're trying to export/import into existing sites then it might be a bit harder.

features can't export taxonomy terms by itself because they have sequential ID values and so don't have a UUID that can be safely ported across sites.

that said, there are other modules out there helping to fix that problem - http://drupal.org/project/uuid is somewhere to start your research. Fair warning, you might have test a few patches for existing modules to get the solution you're after..

# Answer
> 0 votes
If you're importing a site from WordPress the wordpress\_migration module will bring them in for you.

---
Tags: taxonomy-terms, migrations
---


title: Install drupal without node module?

text:
# Question
Title: Install drupal without node module?
I know this is achievable in Drupal 8 but is there a way to do this in Drupal 7? I've looked into drupal modules, core files but couldn't find anything reliable. I'm asking this because I might want to have a light installation with custom entities and I don't need Node module.

# Answer
> 2 votes
The node module is marked as

```
required = TRUE

```

in the node.info file, so the developers are basically saying that as far as they're concerned the node module is imperative for Drupal 7 to function correctly.

You could try patching the info file to remove that line, then disabling the node module to see what happens...in fact if you do that you should write a blog post about it or something, it would be very interesting to find out the effects; I've never heard of anyone trying to do this before :)

---
Tags: 7, nodes, installation
---


# Question
Title: How can I display a taxonomy term's parent ID in Views?
I am using a JSON plugin to Views to output taxonomy terms as a JSON object for Javascript manipulation. I was to be able to include the parent ID in this output.

In view I see "Taxonomy term: Parent term" under relationships and I have added that to the view. But under "Fields" -\> "Add" there is still no "Parent term" listed in the available fields. I'm pretty sure the "pid" should be available. Is there some other way of accessing that field via the Views UI?

# Answer
> 13 votes
Thanks Clive! Yes - I just found the solution. I took the following steps:

1. Under "Relationships" add "Parent term" and untick "Require relationship"
2. Under "Fields" add "Taxonomy term: Term ID" and under that select from the "**Relationship**" pulldown "Parent"

Since the relationship is not required, it will correctly show both top-level terms and all children term. Top-level terms has parent ID of 0.

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


# Question
Title: How do I add <div> tags to the output of a view list?
The output of a view I am using contains the following code.

```
<li class="views-row views-row-1 views-row-odd views-row-first">
  <div class="views-field-field-cimg-fid">
    <span class="field-content">....</span>
  </div>

  <div class="views-field-field-yma-value">
    <span class="field-content">...</span>
  </div>

  <div class="views-field-field-price-value">
    <span class="field-content">....</span>
  </div>

  <div class="views-field-changed">
    <span class="field-content">....</div></span>
  </div>
</li>

```

I want to add `<div id="test">....</div>` around the following snippet.to group two fields

```
   <div id="test">
    <div class="views-field-field-yma-value">
      <span class="field-content">...</span>
    </div>

    <div class="views-field-field-price-value">
      <span class="field-content">....</span>
    </div>
      </div>

```

the loop

```
 <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <<?php print $field->inline_html;?> class="views-field-<?php print $field->class; ?>">
    <?php if ($field->label): ?>
      <label class="views-label-<?php print $field->class; ?>">
        <?php print $field->label; ?>:
      </label>
    <?php endif; ?>
      <?php
      // $field->element_type is either SPAN or DIV depending upon whether or not
      // the field is a 'block' element type or 'inline' element type.
      ?>
      <<?php print $field->element_type; ?> class="field-content"><?php print $field->content; ?></<?php print $field->element_type; ?>>
  </<?php print $field->inline_html;?>>
<?php endforeach; ?>

```

how to add the div tags to the loop?

# Answer
In the View edit screen, click Advanced. At the very bottom of that, you'll find a bit called: Theme: Information. Click the Information link and a new window will pop up, showing you theme overrides for the view. Each category changes different parts of the view.

All of the file names listed on each type will show the available filenames which could be used to override this view, in order of least specific to most specific. So if you pick the first one, it will probably override all of your views, while if you pick the last one, it will only override that view in a certain display.

Once you've picked what you're going to override, click the link and copy all of the code shown there to the clipboard. Then go to your theme directory and make a file with the filename you picked from before and paste in the code you copied. Now just add the `<div>` tags you want wherever you like.

You'll need to click the "Rescan template files" button for Drupal to pick up your new theme override file. Views shows you which one it will use for the view by putting the one it will use in bold.

**Edit:** When writing this, I was going through the steps for Drupal 7, but I believe the steps are very similar for Drupal 6.

**Next Edit:** From the code you have pasted, it looks like the most appropriate place to put the new div tags would be (see the asterisks):

```
**<div id="my-custom-div">**
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <<?php print $field->inline_html;?> class="views-field-<?php print $field->class; ?>">
  <?php if ($field->label): ?>
    <label class="views-label-<?php print $field->class; ?>">
      <?php print $field->label; ?>:
    </label>
  <?php endif; ?>
  <?php
    // $field->element_type is either SPAN or DIV depending upon whether or not
    // the field is a 'block' element type or 'inline' element type.
  ?>

    <<?php print $field->element_type; ?> class="field-content"><?php print $field->content; ?></<?php print $field->element_type; ?>>
    </<?php print $field->inline_html;?>>
<?php endforeach; ?>
**</div>**

```

I normally experiment a bit with this, so it's a bit difficult to tell you the *exact* spot offhand, but hopefully the above will be close...
> 6 votes

# Answer
@Frederik's answer didn't work for me. If you just want to wrap a div around certain fields in your view you have to build some logic in. I think that code will just wrap an additional div around the entire view loop. This worked for me:

```
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>
  <?php if ($field->class=="title"):?>
    <div class="extra-savoir-faire">
  <?php endif; ?>
  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
  <?php if ($field->class=="field-space"):?>
    </div>
  <?php endif; ?>
<?php endforeach; ?>

```

The key was using the `$field->class` as an identifying thing to check against per field. So this allowed me to throw a div before the Title and after the "field\_space" view field. I saved this as the most specific tpl.php file listed in my theme information for "Row style output" using `views-view-fields.tpl.php` as a starting base.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Overriding node-view-VIEWNAME.tpl problems
Hello i am trying to override a node view without much success. I dont know if its just the syntax for my view thats wrong.

When i go to theme information the Row Style output tpl suggestion is

views-view-row-node--taxonomy-term--page-3.tpl.php

i can override that fine but it suggests it would be better to overide node-view-VIEWNAME.tpl.php

So i have a tpl file named

node-view-taxonomy-term-page-3.tpl.php

but it doesnt seem to want to override. Am i missing maybe a '-' somewhere in the tpl title?

I am using Views 3 and D6. I have the tpl in the same folder as my node.tpl.php

all help appreciated thanks.

# Answer
The best way to do this is to see what your available theme suggestions are for that node.

In your theme add the following snippet and clear cache, refresh page, etc.

```
function YOURTHEME_preprocess_node(&$vars) {
   var_dump($vars['template_files']);
   //dsm($vars['template_files']); // if devel module installed
}

```
> 2 votes

---
Tags: views, theming
---


# Question
Title: Which is more performant: entity_metadata_wrapper or field_get_items?
To get values from entities, there are two ways:

* Use `field_get_items` and get the value of a field
* Use `entity_metadata_wrapper` and get the value of a field

Although `entity_metadata_wrapper` abstracts away the language differences, its API is still awkward sometimes, especially when using PHP 5.3. For example, getting the value of a long text field usually goes this route:

```
$field = $wrapper->field->value();
print $field['safe_value'];

```

Fortunately, PHP 5.4 supports this syntax: `print $wrapper->field->value()['safe_value'];`.

But my question is more concerned about performance. How do they both work? Do they query the database every time they request a value? Does `entity_metadata_wrapper` requests everything at once? (Making `field_get_item` more suited to single-value-retrievals.)

I'm not brave enough to dive deep into Drupal source.

# Answer
> 12 votes
**The short answer: field\_get\_items() is more performant than entity\_metadata\_wrapper().**

Check out the code for these functions:

Both require that you pass along the entity, ***which has already been loaded from the database***. For example:

```
$node = node_load(123);
$items = field_get_items('node', $node, 'field_my_field_name');
print $items[0]['value'];

```

or, as you've already suggested:

```
$wrapper = entity_metadata_wrapper('node', $node);
$field = $wrapper->field_my_field_name->value();
print $field['safe_value'];

```

Both of these instances kind of bother me because of the silly logic in trying to get a value that's already available to you, but they are certainly useful in lots of cases.

You could just do `print $node->field_my_field_name[LANGUAGE_NONE][0]['value'];` but that would throw PHP notice errors if the field doesn't have a value, since you're trying to access arrays that may not exist (i.e. `[LANGUAGE_NONE][0]['value']`). I find myself doing this quite often lately:

```
if ($field = field_get_items('node', $node, 'field_my_field_name')) {
  print $field[0]['value'];
}

```

which is a lot cleaner than doing:

```
if (isset($node->field_my_field_name[LANGUAGE_NONE]) && isset($node->field_my_field_name[LANGUAGE_NONE][0])) {
  print $node->field_my_field_name[LANGUAGE_NONE][0]['value'];
}

```

If you look at the code for `field_get_items())` you'll see that it's doing nothing more then ensuring that the field's array has data in the curent language and then returns it. So, the overhead of running such a tiny function is negligible, but if you are really concerned with performance you can just do your own check if the data exists and then print it.

**Edit:** Since `field_get_items()` runs `field_language()` there would actually be a bigger performance hit than just checking the language, so, if you already know that $entity-\>language exists, you could just write your own super-performant function:

```
function my_super_performant_field_value_getter($entity, $field_name) {
  return isset($entity->{$field_name}[{$entity->language}]) ? $entity->{$field_name}[{$entity->language}] : FALSE;
}

```

---
Tags: performance, entities
---


# Question
Title: How to create nodes "emulating" form submit
I usually create and edit nodes, programmatically, using node\_load and the node\_save, and addind data to fields in this way:

```
$node->field_custom['lang'][0]['value'] = 'My value';

```

But in this way I've to check lang, and even if my node is "it" same fields (as terms, or other fields) need "und" and something like this.

Is there way to create and edit nodes loading the form and the submitting the form with new values?

# Answer
> 2 votes
Yep, look at drupal\_form\_submit.

> Retrieves, populates, and processes a form. This function allows you to supply values for form elements and submit a form for processing. Compare to drupal\_get\_form(), which also builds and processes a form, but does not allow you to supply values. There is no return value, but you can check to see if there are errors by calling form\_get\_errors().

```
// register a new user
$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account');
drupal_form_submit('user_register_form', $form_state);

```

I find the easiest way to see what the form takes is to use the Net Panel in Firebug. Turn on `Persist` in Firebug and post your form, then look at the POST keys and values.

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


title: Creating fake (test) data

text:
# Question
Title: Creating fake (test) data
Is there a module or part of devel module that will auto populate (with fake data) a Content Type a create a dozen or so nodes?

# Answer
> 7 votes
If you installed the Devel module, there should be a submodule on the admin/modules page called **Devel generate**:

Enable it, and you should have some new menu entries in admin/config/development for generating fake conent, menus, terms, users, and vocabularies.

# Answer
> 1 votes
This article from lullabot explains exactly what you will need. You will need / can use the following modules;

* http://drupal.org/project/simpletest This module is a Drupal extension to the Simpletest project for general PHP unit testing. The Drupal module adds a wealth of tools and convenience for Drupal specific unit testing. For example, it has the ability to create new users and nodes, set configuration variables, and submit Drupal forms.
* http://drupal.org/project/simpletestauto provides a system for running test suites automatically and reporting the results. The Simpletest automation is also capable of applying patches to Drupal code, and is thus an essential tool for vetting patches in the issue queue.
* http://drupal.org/project/simpletest\_automator extends the convenience of writing tests even further by allowing you to click through your site as it records your actions as a macro. This macro can then be used as the basis for a unit test that you can run automatically at a later time.

> What is unit testing
>
> Unit testing is the art and practice of taking a small portion of code, a unit, and subjecting it to programmatic tests to prove its correctness. The smallest units in PHP code are usually functions, and the unit tests will run the functions with sets of controlled parameters, and then make assertions about the return values of the function, or about the state of the application before and after the function has run. For example, if the function is designed to validate email addresses, the unit tests would pass in known valid email addresses and assert that they validate correctly. The tests would also pass in a number of invalid email addresses as well and assert that they do not validate.
>
> Why is unit testing useful?
>
> Writing unit tests helps produce higher quality code on many levels.
>
> The availability of tests helps detect the introduction of bugs whenever the programmer adds new features or refactors the code. This is called regression testing. Tests also serve as a source of documentation about what code is really expected to do. The act of writing the tests challenges the programmer to consider possible edge cases and their consequences. Last but not least, the act of writing tests encourages the programmer to write code in small chunks that can be tested independently.

---
Tags: debugging
---


# Question
Title: "Translate" tab does not appear for every content
I have installed the Localization module in my drupal project. All was working fine until now but i just noticed the "Translate" tab isn't visible for all my contents...

What i'm doing is simply :

-I go to content management -content -edit

-\> Translate tab isn't visible...

On the other hand, when i try to translate another content of another content type, translate appears...

did anyone else face this problem previously? thanks in advance

# Answer
The "Translate" tab is handled by the Translation module that comes with Drupal; the Internationalization module that handles the translation for nodes just overrides the page callback for that tab.

```
function i18n_node_menu_alter(&$items) {
  if (isset($items['node/%node/translate'])) {
    $items['node/%node/translate']['page callback'] = 'i18n_node_translation_overview';
    $items['node/%node/translate']['file'] = 'i18n_node.pages.inc';
    $items['node/%node/translate']['module'] = 'i18n_node';
  }
  // Take over node/add pages for string translation
  $items['node/add']['page callback'] =  'i18n_node_add_page';
  $items['node/add']['file'] = 'i18n_node.pages.inc';
  $items['node/add']['file path'] = drupal_get_path('module', 'i18n_node');
  // @TODO avoid iterating over every router path.
  foreach (node_type_get_types() as $type) {
    $path = 'node/add/' . str_replace('_', '-', $type->type);
    if (isset($items[$path])) {
      $items[$path]['title callback'] = 'i18n_node_type_name';
      $items[$path]['title arguments'] = array($type->type, $type->name);
    }
  }
}

```

In order to have that tab visible for a node, the multilingual support for the content type must be set to *Enabled, with translation*.

In Drupal 8, that is done in `admin/structure/types/manage/<content type ID>`, but the option is titled *Enable translation*. The route is defined from the *Content Translation* module, which must be installed.

>

In Drupal 7, that is done in `admin/structure/types/manage/<content type ID>`.

>

In Drupal 6, it is done in `admin/content/node-type/<content type ID>`.

>
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: Clearing or changing styles with the TinyMCE WYSIWYG editor in Drupal 6
On the TinyMCE tool-bar you can select a style to apply to the selected text (from a list of CSS classes that you create). However if I want to change to a different style, when I select a new style form the drop-down list, it just adds another class so the text ends up with having multiple competing classes attached.

Is this the normal behaviour - does any one else get this?

Does ayone know if there is a way to clear all styles on the selected text?

# Answer
***Edit*** I'd thought that the optional Remove Format button (below) would do remove styles.

Actually, turns out it doesn't - not in the version I'm using, anyway.

So it seems re-clicking on the styles that is already selected in the dropdown is the only way to deselect them, short of writing a custom plugin.
> 1 votes

---
Tags: 6, wysiwyg
---


# Question
Title: Checkboxes Defaulting to Selected When Not Desired
This is going to be sound like a real stupid question, but for the life of me I don't know how to fix it. I have inherited some code that I need to maintain, and the issue I am experiencing is that a form containing checkboxes is displayed, and they are always all selected. The code for the checkboxes is as follows:

```
$license_result = db_select('licenses')
  ->fields('licenses', array('code', 'name'))
  ->execute();

foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $selected_licenses,
  ),
);

```

I though that by having an empty array for #default\_value would deselect all checkboxes. Am I reading the form API wrong in this regard? Eventually I would like to set the default values but right now I want to make sure they start off as unselected.

Thanks.

# Answer
I think you have to set the value in each checkbox, so probably this would be it :

```
foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
  $licensevalues[$license->code] = 0;
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $licensevalues,
  ),
);

```
> 0 votes

---
Tags: 7, forms
---


title: Strip overlay context from File field

text:
# Question
Title: Strip overlay context from File field
I have a basic File field set up to allow my users to attach files to nodes.

However, the File field widget in the node edit form displays files as a link to the file, and the URL contains `#overlay-context=`. Thus when users right click to copy the URL to the file, the URL includes the overlay context, and the link doesn't work (or images don't display).

How do I stop the Overlay module from adding that on to the File URLs on the node edit form?

I have the Insert module, IMCE, and IMCE WYSIWYG bridge enabled to provide users with other options, but some users (including myself) still prefer to right click the file name and copy the URL.

# Answer
The only thing I can think of offhand is to play with hook\_url\_outbound\_alter() and make a regex to alter only the file paths url in question (not just any and all urls on the site) and strip out the context.

There might be a better way to do this ... maybe like theme\_link or theme\_links overridden for the given region ?
> 0 votes

---
Tags: 7, files
---


# Question
Title: Access denied for unpublished content in drupal 7
When i unpublished a content in drupal 7, I am getting an access denied message. But for some other unpublished content i am getting page not found message. I need page not found message to all unpublished content. How can i do that? Thanks

# Answer
> 0 votes
Few things to check for to figure out the problem based on your configuration:

1. Are you logged in or logged out while accessing the content?
2. Which user are you logged in with? Is this user the author of this content?
3. Check the permissions of this user (the ones related to unpublished content)...

Let us know if you need help or more details on any of the above.

Cheers.

**UPDATE**: if you want to customize the message that is displayed when access is denied, you can create a new page containing the custom message and then go to "Administration -\> Configuration -\> System -\> Site information -\> Default 403 (access denied) page" and set the path to your created page.

---
Tags: users
---


# Question
Title: Is there a way to send a newsletter to those users who share a taxonomy term in there profile
I need to be able to collect newsletters for a specific type of content. This content will have tags that the user will also check on when the sign up or edit their account information. I then need to send this newsletter to all those associated with that taxonomy list.

# Answer
It sounds like you want something that simplenews doesnt do right out of the box. You can create newsletters (and a block for subscription links) -- but it doesnt appear to based off of Taxonomy terms directly.

Simplenews supports Rules, you could maybe define rules that achieve your goal.

I have not used simplenews, but I have a website for student surveys which has various email templates that remind students if they have additional surveys to complete, all running off of cron tasks -- you could code this type of newsletter functionality by hand without many helper modules if need be.

Sometimes manipulating a contributed module to suite your needs is harder than just doing it yourself for your project.
> 2 votes

---
Tags: taxonomy-terms, users, nodes, emails
---


# Question
Title: Views Relationship/Contextual Filter for sibling nodes
I have a content type 'property' and a content type 'park'. I'm using an Entity Reference field in the property to reference a park. The park is essentially a parent or neighborhood or that contains the property.

On the property page, I want to display the sibling properties (the ones that share a common park/parent). I'm able to show child properties on the park page, but can't for the life of me figure out the relationship/contextual filter combo to use to get this working. I see many examples online that use taxonomy, but this is an entity reference relationship. Setting up a relationship I have options for `Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field_master_park` and `Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Content via field_master_park` and I assume I use (at least) one of these combined with a contextual filter?

Anyone able to at least point me in the right direction?

# Answer
There are two ways to do this that come to mind:

## Option One

You could create a node template for nodes of type property and use an Entity Field Query in a manner roughly following this pseudo-code:

```
  $park = $node->field_park['value'];
  $query = new EntityFieldQuery();
  $query
     ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'DESC')
    ->fieldCondition('field_park', $park)
    ->range(0,10);
$result = $query->execute();

```

This will load a list the NIDs of all nodes that have field\_park matching the value of $node-\>field\_park\['value'\] (or wherever the node object stores your actual field value). To get more info than just the NID, you will want to do some kind of `foreach($result)` that does a `node_load($nid)` on each NID returned by the EFQ.

## Option Two

Option two is no-code: you could create a View and embed it on your node with something like Insert View. You would create the view with the following steps:

1. Add a contextual filter that takes the node ID. This is so you can pass it a value so you get a view specific to each node you want it to appear on. Exactly how to do this is out of the scope of this question.
2. Add a field for the node title. You can remove this later but it will keep you from getting confused while making the view. Give it a label if you want, make it grouping field number one, and exclude it from the view.
3. Add a relationship. Choose "Entity Reference" for the relationship type, and then select "entity that is referenced via field\_park" or whatever your node reference field is called.
4. Add another content: title field. Under relationship, choose the relationship you just created. Set it to group by that field, create a label called "park:", and set it to exclude from display.
5. Add another relationship. Choose type "Entity Reference" and this time choose "referencing entity": "entity that is referencing Content via field\_park"
6. Add another field for node: title and this time select the relationship you just created. Give it a label like, "sister property:" if you want.

Violá. Now you have a view that will allow you to pass an NID and will tell you the title of that property, its park, and all sister properties.
> 3 votes

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


# Question
Title: Setting permissions via drush make; auto-copy settings.php?
I'm using drush make to build out an installation profile, and it's working great, however, settings.php doesn't get created and files has the wrong permissions.

Is there any way to automate this further by creating settings.php and chmod'ing files?

Thanks!

# Answer
When you call `drush make site.make` you can pass database urls and the site-name as well, and admin credentials.

You have a permissions issue with your webroot and/or drush configuration to not have drupal makes these files for you properly.

Typically when you call drush from the command line you want to do so as your ssh or terminal user -- assure you have proper permissions or are a member of the correct groups (eg, `www-data` if under Linux and using Apache configured thusly).

If for instance you call drupal cron via drush using `drush cron` from a crontab entry; then in that case you usually want drush to run as the webserver user.

In short -- check your permissions, because they sound wonky.
> 1 votes

# Answer
make sure you go through all the options available at `drush help make` . This option should help you :

> --prepare-install Prepare the built site for installation. Generate a properly permissioned settings.php and files directory.
> 3 votes

# Answer
To set permissions after `drush make`, see http://drupal.org/node/990812. The most recent patch if functional, but a new simplified version is in the works (same thing, fewer options), and will be committed when ready.

There is also a bash script to set permissions available at http://drupal.org/node/244924
> 2 votes

---
Tags: drush
---


# Question
Title: In Taxonomy View, how do I get the count of relationships associated with that term
In a View based on a Taxonomy Term, is there a field which shows a count of how many relationships that tag has?

I'm pulling a list of Academic Years in this situation. If there is no Nodes tagged with these years, I'd like to omit them from the list.

# Answer
> 3 votes
You can solve this two ways:

1. You can create a view of nodes, create a relationship to their taxonomy term, and display the terms. This will only display terms that can be pulled up through a node by views.
2. You can keep your taxonomy display and add a relationship. Add "Taxonomy: content with term" and the check the box labeled "Require this relationship". This will give you duplicates so you also need to go down to "Query Settings" and check the box for "Distinct".

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


title: Segmentation fault at search_cron()

text:
# Question
Title: Segmentation fault at search_cron()
Whenever I try to run cron on the search, using

```
drush php-eval 'search_cron();'

```

I get 'Segmentation fault' error. I have not this problem for any other tables. The site contains hundreds of text-heavy nodes. So I appreciate your hint to cope with the problem.

# Answer
I believe that is a memory error. If increasing your memory limit doesn't work, you might get relief from lowering the number of nodes to index per cron run on the search settings page.

It could also be caused by running an out-of-date version of PHP.
> 0 votes

---
Tags: search, drush, cron
---


# Question
Title: Why my stylesheet won´t load into my node/add forms? (D6)
I wanted to have a special template for all my node/add forms, in my Drupal 6 installation.

So, I´ve added this code to a little module:

```
function modding_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add')) {
    $vars['template_files'][] =  'node-add';
  }
}

```

My `node-add.tpl.php` template looks like this:

```
<h1><?php print $title ?></h1>
<?php print $content ?>

```

The thing is that **all styling has gone**.

The style sheets won´t load, and I don´t understand why. It looks as ugly as it can get when no style whatsoever is loaded.

I may add that **I´ve cleared cache more than once, and as this is a testing site, all performance caching has been disabled**.

Thanks for your help!!

# Answer
> 1 votes
I´ve found the solution:

```
<?php
      if ((arg(0) == 'node') && (arg(1) == 'add') || (arg(2) == 'edit')){
    $node = node_load(array('nid' => arg(1)));
    print $title;
    }
?>

```

Thanks to nevets, who gave me the hint that I needed! :)

---
Tags: 6, theming
---


title: Drupal nodes VS direct database

text:
# Question
Title: Drupal nodes VS direct database
I am writing my first Drupal module and am having a little bit of a hard time wrapping my head around when I should use nodes vs storing data directly in the database. Is there any documentation I can read on this subject or does anyone have any advice on this?

I've actually already written most of the module entirely using direct database access and my own tables. I am planning on open sourcing it but I want to make sure I'm following common Drupal development standards and I think this is the most glaring error I made. So now I am trying to figure out how much I need to move from my own tables into nodes.

What started me down this path of looking a nodes is that I need to implement permissions. The module has a bunch of projects and I need to be able to control which users have access to each individual project and all the data related to it. It's not obvious to me how to do that using nodes so I was considering doing this as yet another table in the database.

# Answer
Typically Nodes are content. Permissions in a webapp are typically not content. Content is a piece of factual text, an image, an uploaded pdf.

It sounds like you want to look at the Organic Groups module.
> 0 votes

---
Tags: nodes, users
---


# Question
Title: How to programatically add attachments to a user (securely)
To any Drupal 7 gurus out there... I have hundreds of PDFs that need to be uploaded to users as their own private attachment. I've created the PDFs in the folder:-

../website-files/userfiles-{**uid**}/filename.pdf *(There's one for each **uid**)*

My **field\_data\_field\_attachments** table has the "**field\_attachments\_fid**" column with the id relating to the **file\_managed** table.

This is all pretty self explanatory, until... I find the **file\_managed** table has two mysterious columns:-

> \__pk
> \__unique\_uri

Both seem to be MD5 checksums, e.g:-

> 4A448458-860C-4E16-B901-F8841136C17D

So my question is; how do I correctly generate these two values for each attachment I import to the DB?

Thanks, Darren

# Answer
OK, I've given up trying to do it in raw SQL due to the intricate referential integrity of the Drupal datamodel (OK, I admit defeat!! :)

The following code bootstraps drupal, then moves files from an input directory to the private-files folder on the local drive and uses the Drupal file\_save() API to create the Drupal file registers, then updates the user profile custom field (in my case called "field\_attachments").

hope it helps anyone trying to do the same. (I created a standalone PHP file called "importuserfiles.php" in the root of the drupal folder using the code below)

```
<?php
define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost"; // Necessary if running from command line
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$local_from_path = 'c:\\inputfiles'; // root folder of your input folders.
$drupal_private_base = 'c:\\website-files'; // root location of Drupal's private website files.

$di = new RecursiveDirectoryIterator($local_from_path);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {

    $user_id = explode('-', $di);   // the userid is held in the folder name (userfiles-uid)
    $uid = $user_id[1];             // so pull the second value from the array (after userfiles-)

    echo $filename . ' - ' . $file->getSize() . ' bytes. Attaching to user: ' . $uid . '<br/>';

    $local_to_path = $drupal_private_base . '\\userfiles-' . $uid . '\\' . basename($filename); // the destination folder on the local file system for this user.

    $drupal_to_path = "private://userfiles-" . $uid.'/'.basename($filename); // the private files folder URI for this user.

    echo "Moving file: " . $filename . " To: " . $local_to_path . '</br>';

    mkdir($drupal_private_base . '\\userfiles-' . $uid); // make the destination folder in case it doesn't exist.

    //move the file to the new location
    if (!rename($filename, $local_to_path)) {
    echo "failed to move $file.. </br>";
        break;
    }

    $user = user_load($uid); // load the user object

// create the file object for Drupal...
$filetosave = new stdClass();
$filetosave->filename = basename($filename);
$filetosave->filepath = $filename;
$filetosave->uri = $drupal_to_path;
$filetosave->filemime = file_get_mimetype($filename);
$filetosave->filesize = filesize($filename);
$filetosave->display = 1;
$filetosave->description = basename($filename); // just use the filename as the description
$filetosave->uid = $uid;
$filetosave->status = FILE_STATUS_PERMANENT;
file_save($filetosave);  // save the file so Drupal registers it.

$user->field_attachments['und'][] = (array)$filetosave; // add the file to the file field called "field_attachments"
user_save($user);
?>

```
> 1 votes

# Answer
You want to try and use the drupal api to move these files into drupal. Since you talk about private files, I assume you've enabled a private filesystem ... or else this discussion is pointless as all your files with be public :).

Once you've done that you could take your hundreds of files and put them in your server someplace and use file\_move to place them into the drupal private filesystem using a small php script.

A module tutorial with a private file upload widget can be seen at this blog post and uses the drupal api to store a private file. Private files typically use hook\_file\_download which that blog post also shows to allow access to the file.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Commerce Kickstart - items won't float side by side
I'm developing a store using the new Commerce Kickstart 2. All of a sudden my items in the store are floating one on top of the other instead of items within the same collection floating side by side. For example I have multiple headings of "Notebook Computers" above each notebook computer product and they all float one on top of the other all the way down the page instead of One header and all the products floating side by side.

I took my CSS back to the default and it didn't make a difference. Has anyone else come across this? I'm not sure if a module I may have installed caused this or a setting within the view may have caused this. I'm hoping someone else has come across this.
Thanks! Candace

# Answer
> 0 votes
AAAAh! The answer is to shut down the site, shut down localhost, and re-start everything back up again. It must have been a memory issue!

---
Tags: commerce
---


# Question
Title: View of Taxonomy with titles above the terms
Does anyone know if I have a view of a Taxonomy Vocabulary - How do I get titles above all the term results? Here is my page: `http://64.34.70.141/~henryl/bloom-size` I'd like to have titles like this website: http://demo.commerceguys.com/ck/collection/drink But I can't figure out how they've added the titles - I've tried to look through the view selections of the site but I can't get mine to match.
Can anyone help? Thanks!

# Answer
> 0 votes
You have an unformatted list view of node teasers. Just click Format settings on view edit page, and turn on Force using fields. After that this result will be shown as teaser, but you can add fields.

Add your taxonomy term field to the Fields, and you can use it in Format settings Grouping field Nr.1. If the teaser doesn't contains this field, you have to add a relationship to the proper taxonomy term too.

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


# Question
Title: Add type='tel' attribute to webform field
I want to add the html5 tel attribute to a particular field in my webform form in order to prompt mobile devices to display the appropriate keyboard.

I was trying this:

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

    /* add html5 phone type for phones and smarter devices to use */
    /* usage: just include the word 'phone' in the field title and have the field of type 'textfield' */

    foreach ($form['submitted'] as &$field){
        if (is_array($field) && isset($field['#title']) && stristr(strtolower($field['#title']), 'phone') && isset($field['#type']) && ($field['#type'] == 'textfield')){
            $field['#attributes']['type'] = 'tel';
        }
    }
}

```

but the attribute doesn't get applied and the resulting field has the type of "text"

I suspect there may be a hook for webforms that will let me adjust the output, I just can't find it.

# Answer
> 7 votes
Drupal 7 core field doesn't support HTML 5 form elements.

You should try the Elements module to do that.

> This module intends to become a repository for advanced form elements. Supports HTML 5 standards like: (url, email, search, tel, number, range)

---
Tags: webforms
---


# Question
Title: Error in Submit handler for custom node add form
Trying to theme my own node add form with hook\_theme() in my own module. In the \*.tpl.php page for the node add form, submit button is not actually adding the content to database.

Issue: Why is "php print render($buttons);" not adding the right submit handler that actually adds a node (Content) entry.

In my stories.module file:

```
 /* Implements hook_theme().
 */
/*
function stories_theme($existing, $type, $theme, $path){
  return array(
    'stories_node_form' => array(
      'render element' => 'form',
      'template' => 'stories-node-form',
      'path' => drupal_get_path('module', 'stories'),
    ),
  );
}
*/

function template_preprocess_stories_node_form(&$variables){

    $variables['sidebar'] = array();   // Put taxonomy fields in sidebar.

    $variables['sidebar'][] = $variables['form']['field_tags'];
    hide($variables['form']['field_tags']);

    // Extract the form buttons, and put them in independent variable.
    $variables['buttons'] = $variables['form']['actions'];
    //hide($variables['form']['actions']);
 }

```

In stories-node-form.tpl.php:

```
    <div id="stories-add-wrapper">
<div class="nicname_and_category">
    <?php //print drupal_render_children($form); ?>
    <div class="input_auteur">
        <?php print render($form['field_nicname']); ?>
    </div>

    <div class="input_cat">
        <?php print render($form['field_email']); ?>
    </div>
</div>

<div class="title_and_category">
    <div class="title">
        <?php print render($form['title']); ?>
    </div>

    <div class="category">
        <?php print render($form['field_category']);  ?>
    </div>
</div>

<?php print render($form['field_share_your_story']);        ?>

<?php print render($buttons); ?>
    </div>

```

# Answer
> 0 votes
Found the solution. Needed to add `print drupal_render_children($form);` to the end of `stories-node-form.tpl.php`

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


title: Totally override a menu

text:
# Question
Title: Totally override a menu
I'm trying to get a menu with my custom classes.

I would like to be able to

```
<ul class="my-menu">// class of the whole ul
<li class="with-sub">// add class "with-sub" if has children
<a href="#">submenu</a>
<ul class="sub-menu"> // add class sub-menu to sub menu ul
<li class="title-of-the-parent">// add the title of the parent as first item of the list
<a href="#">TITLE OF THE PARENT</a>
</li>
<li class="my-submenu-item">// add a class to all sub-menu items
<a href="#"> Submenu item</a>
</li>
</ul>
</li>
</ul>

```

For the first level it's fine. I can use menu\_tree and menu\_link to get what I want.

**I would like to know how to use $sub\_menu = drupal\_render($element\['#below'\]) and customize the sub menu list.**

I don't want to use any module, I want to do all through the template.php.

Thanks in advance

# Answer
> 0 votes
I've solved in this way:

Drupal adds a class menu to the main menu use the preg\_match to find it.

```
function my_theme_menu_tree__menu_block_3($variables) {
  if (preg_match("/\bmenu\b/i", $variables['tree'])){ // if class is menu
    return '<ul class="main-menu">' . $variables['tree'] . '</ul>';
  }
  else {
    return '<ul class="submenu">' . $variables['tree'] . '</ul>';
  }
}

function _menu_link__menu_block__3(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $parentclass = '';
  $liclass = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $parentclass = "sub";
  }
  if ($variables['element']['#original_link']['depth'] == 1) {
    $liclass = "top";
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  $list_menu = '<li class="' . $liclass . ' ' . $parentclass .  '">' . $output . $sub_menu . "</li>\n";
  return $list_menu;
}

```

Other implementations are welcome.

# Answer
> 2 votes
Take a look at `theme_menu_tree()` and `theme_menu_link()`. It should be all you need.

Sorry for the lack of examples, but `theme_menu_tree` is rather self-explanatory, and the page for `theme_menu_link` provides several examples.

---
Tags: routes
---


# Question
Title: user_login_finalize() logins the user, but I remain anonymous
I'm using `user_login_finalize()` in my code to login a user (right before the review page), and this works because I can see the log in `drush watchdog-list`. However, it only works behind the scenes: the browser session remains anonymous. The browser has a new anonymous session though.

It's almost like a new PHP thread is spawned for the user instead of using the old one (thus, Drupal logs the user and spawns a new thread, so the user is still anonymous even though Drupal has logged the old user). I don't know whether it does that, but that's what it looks like.

I know this doesn't help you per se, but I'd like at least to know *how* to debug that. I'm really lost there.

FWIW, here is the `drush watchdog-show 66341` for the login:

```
 Wid        :  66341
 Type       :  user
 Message    :  Session opened for dsdsdsdsdsdsdsdsdsd@sdsdsds.com.
 Severity   :  notice
 Location   :  http://test.lxc:81/checkout/11
 Referer    :  http://test.lxc:81/checkout/11
 Hostname   :  192.168.120.1
 Date       :  08/oct 16:20
 Username   :  dsdsdsdsdsdsdsdsdsd@sdsdsds.com

```

More information: I'm using the following code where I call `user_login_finalize`:

```
global $user;

$account = new stdClass();
$account->is_new = TRUE;

$edit = array(
  // More to come later, but this is the only constraint
  'name' => 'some random name',
);

$user = user_save($account, $edit);

// Checking $user here, it has the correct UID of a new user.

user_login_finalize();

```

# Answer
> 0 votes
I ended up bypassing `user_login_finalize` and invokes the hooks myself with `module_invoke_all('hook_user_login');`.

# Answer
> 0 votes
You mean that the user remains anonymous in the browser session, right? (In Drush, you must pass `-u uid` on every invocation to specify the user, because Drush is stateless.)

Make sure that the Drupal session cookie is being set in the browser. If, for example, you set the cookie in the secure context (https) and then redirect to http, the cookie will be inaccessible, and the user will remain anonymous.

**Edit:** user\_login\_finalize requires a $form\_state parameter; see: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_login\_submit/7 It's hard to see which fields of the form state are relevant, since it is just passed to user\_module\_invoke. However, if you compare what is in $form\_state during a normal Drupal login, and supply the same information in your function, then it should work fine.

---
Tags: 7, commerce, drush, debugging
---


# Question
Title: How to import Panel configuration from versionned code
I have a Panel in my D6 website and I have exported it using the Panels Export Section and I want to know if it is possible to use this code from i a module so I can have a version control over the Panel configuration. How can I do that. Is there any Panle API I can use??Or how can I export panel export in features??

Thanks

# Answer
Try using the Features module.
> 1 votes

# Answer
Try to use Panels Import or Features module. I think it's a best way for you.
> 0 votes

---
Tags: 6, panels, importing-exporting
---


title: Display Profile2 fields in another view

text:
# Question
Title: Display Profile2 fields in another view
How can I display Profile2 fields in a view that has a content type as filter?

Later edit(example):

I have a view which displays a content-type X. I have a profile Y with different fields. I would like to be able to add fields from profile Y to the view which already has fields from content-type X.

# Answer
> 0 votes
First you need to add User relationship, “Content: Author” for example. After that you will be able to add new relationship “User: Profile” on base of User relationship.

Now you can add fields from user and user profile. You must not forget that SQL query becomes heavier with each new relationship.

---
Tags: views, users
---


# Question
Title: Prevent email from being sent using hook_mail?
I'm trying to implement an access check (a 'do-not-send' list query) just before emails are sent. I see how to modify the message, but how do I stop a message?.

```
HOOK_mail ($key, &$message, $params) {
   if (TRUE) {
      // -- Stop Message From Being Sent Here -- //
   }
}

```

Is `break;` adequate?

# Answer
> 8 votes
You can do the access check from `hook_mail_alter` instead of `hook_mail` (let it prepare the default message based on parameters, and alter it later) by something like:

```
function HOOK_mail_alter(&$message) {
  // can add additional check for particular mails here,
  // by checking the value in $message['id']
  if (TRUE) {
    $message['send'] = FALSE;
  }
}

```

**Note:** You should clear the cache in order to make the changes effective.

---
Tags: 7, hooks, emails
---


# Question
Title: HTML corrector doesn't close quotation marks in teaser
In Drupal6, I have a WYSIWYG input filter with the HTML Corrector filter enabled. When the body is automatically truncated for use in the teaser, sometimes the break occurs in the middle of an attribute value in an HTML tag (e.g. in the middle of the url in an anchor's href), resulting in an unclosed quotation mark. The HTML corrector appears to balance the unclosed tags appropriate, but it doesn't close the quotation mark.

For example, if my content body is the following one:

```
<ul>
  <li><a href="http://google.com">google.com</a></li>
</ul>

```

The teaser breaks in the middle of the URL:

```
<ul>
  <li><a href="http://goog

```

Then the tags are closed but no closing quote or the end of the opening tag:

```
<ul>
  <li><a href="http://goog </a></li>
</ul>

```

The result is a broken theme. Am I doing anything wrong? Is there anything that is mis-configured?

# Answer
> 3 votes
Doesn't look like it's a problem on your side. You can try the following:

```
drush php-eval '$text = "<ul><a href=\"http://goo"; print $text . "\n"; print _filter_htmlcorrector($text) . "\n";'

```

And for me the results are:

```
<ul><a href="http://goo
<ul><a href="http://goo</ul>

```

(The second line is the output of `_filter_htmlcorrector()`.)

It would be worth seeing if there's an issue for this already, and if not creating one. I find the built-in HTML corrector too limiting anyway (it always strips styles for example IIRC), and use htmLawed. With that you get:

```
drush php-eval '$text = "<ul><a href=\"http://goo"; print $text . "\n"; print htmLawed_filter('process', 0, -1, $text) . "\n";'

```

Results:

```
<ul><a href="http://goo
<ul> </ul>

```

(Again, second line is the cleaned output - it's simply stripped the incomplete tag.)

# Answer
> 0 votes
Got it! The lightweight solution is to remove malformed html tag from the very end of the string:

```
function YOUR_MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      // Cleanup teaser from the mallformed tag at the end of the string.
      $node->teaser = preg_replace('~<\w?[^>]*$~', '', $node->teaser);
      break;
  }
}

```

NOTE! Existing nodes should be updated to cleanup their teasers.

---
Tags: 6, input-formats
---


# Question
Title: Using a taxonomy select field as a contextual filter for an Entity Reference View powered select box
I've got a parent child relationship between two content types: Properties and Parks. They are organized into a taxonomy we'll call Market. When creating a Park you select the Market it belongs to. Then creating a Property (which is child to a Park) you also select the Market and then select the Park it should be a child of. I need the select list of Parks (which is an Entity Reference) to filter based on what Market is selected to only show Parks from that Market. I have created an Entity Reference View properly and am able to see it filtering properly in the preview. But how can I use the data from the first select box for Market (a Term reference select list) to power the contextual filter of the second select box for Parks (an Entity Reference select list with the Entity selection set to filter by Entity Reference View).

I'm not sure if this is even possible, but have been stuck on it for a while.

# Answer
I was able to find a workaround to this and display the market (taxonomy) and park (parent) in a select list from a view. Then wrote some javascript to disable the options that are irrelevant (parks from other markets) once the user selects the market of the property.
> 1 votes

# Answer
From what I understand you need the Views Dependent Filters module. Here is a quote about it (from the module's project page):

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.
>
> The module is compatible with both the Views basic and the Better Exposed Filters form plugins.
> 0 votes

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


# Question
Title: Node content in panels vs. configuration in code
I am trying to keep most of the configuration in code (and separating content and configuration). When I have a panel that is supposed to contain a content from for example a node, I would like to be able to export that setup somehow so that I can be sure it would work also on the other page. So it shouldnt be a node id, not either node title (so from my point of view, this help doesnt qualify).

The way I did it is somewhat complicated, but allows me to keep all config in code while happily creating the content separately. I am posting a writeup my colleague did to convince me i am doing it too much complicated. Yet, I cant think of a better way.

1. Create taxonomy vocabulary with terms: top, middle, bottom.
2. Create custom node-type called panel content to which you assign terms from vocabulary from pt 1
3. Create a view that takes term from vocab from pt 1 as an argument.
4. Place this view inside frontpage panel and hardcode the argument depending on region.

Am I missing some point here? Would there be a better way to it? Thanks.

# Answer
> 0 votes
One could

1. Use Fieldable panels panes, which can replace the custom entity you use, and put content directly into the pane.
2. Configure the view to find nodes with a certain tag. Tag the node that should show up. Require the tag to be uniquely applied if only a single node is allowed.

---
Tags: panels, features
---


# Question
Title: How to display user submitted nodes in the node detail view of the same user?
I'm aware of such modules as Relation and Entity reference but I can't figure out how I make automatic relation between nodes that depend on the user that submitted those nodes.

Site has users A, B, C ... Let's say user A submits 10 nodes. When any user clicks on any of his nodes you can see his other 9 submitted nodes in the detailed view. When you click on node submitted by user B you can see his other submitted nodes and so on. This should work automatically without manually building relations between nodes.

How do I achieve this?

Thanks a lot Ray

# Answer
> 1 votes
I tried the following and it seems to work:

1. Create a new block view
2. Add a Contextual filter of type `Content: Nid`
3. Add a relationship of type `Content: Author` (Required)
4. Add a relationship of type `User: Content authored` that uses the previous relationship and is required
5. Under Format you set `Show: Content | Full Content` \- You must also use the `User: Content authored` relationship for this one

You could also change the number of related nodes that will be shown and also you might wan't to add a filter of `Content: Type` to restrict what kind of nodes to display. Notice that you could create a template for a specific content-type ie `node--<YOUR_CONTENT_TYPE>.tpl` and load and execute the view from there.

In you `node.tpl` file you would load this view doing something similar to:

```
$view = views_get_view('YOUR_VIEW_NAME');
$view->set_display('YOUR_VIEW_BLOCK_NAME');
$view->set_arguments(array($node->nid));
$view->execute();
echo $view->render();

```

*Note* I think you should specify every field you wan't to use, in other words you shouldn't use `Show: Content | Full Content` \- because this will result in an infinite loop. I don't think this is a complete solution, but perhaps it will point you in the right direction.

If you are using fields in the view you could create a separate template named `views-view-fields--YOUR_VIEW_NAME--YOUR_VIEW_BLOCK_NAME.tpl` that will be used to output the actual fields.

To exclude the current node from the listing you need to modify your contextual filter.

* Click the `More` button for `Content: Nid` and choose `exclude` you should also make this filter use your relationship for `Content: Authored`

---
Tags: entities
---


# Question
Title: Changing exposed filter doesn't rebuild SQL query
I created 5 fields for filters. 3 of them are exposed to site visitor. Problem is that if I even change this exposed filter values while editing View it doesn't rebuild SQL query. Views version: 7.x-3.3 exposed\_filter\_problems Other 2 exposed to visitors filter have the same settings but different names.

# Answer
> 0 votes
After 4 hours of fight with exposed filter I found my problem. I used drupal administration in Opera. After moving to Chrome everything works great.

---
Tags: 7, views, database
---


# Question
Title: How do i deactivate "Your comment has been posted." after user posted a comment
How do I deactivate -Your comment has been posted- after user posted a comment.

Is it possible to deactivate the message above with out touching the core?

# Answer
you can add a custom submit handler to the comment form using hook\_form\_alter():

```
function yourmodule_form_alter(&$form, &$form_state, $form_id){
  if( $form_id == 'comment_form' ) { // find and use the actual form ID
    $form['#submit'][] = 'yourmodule_your_custom_comment_submit_function';
  }
}

```

Then in that submit function check to see if the message exists using drupal\_get\_messages():

```
function yourmodule_your_custom_comment_submit_function(){
  $message = drupal_get_messages('status', false);
  if( $message['status'] == 'Your comment has been posted' ) { // Or what is the actual message
    drupal_get_messages('status');
  }
}

```

This is for Drupal 7 but these functions exists in older drupal versions. Check api.drupal.org for details.
> 1 votes

# Answer
For a no-code solution that disables all messages with specific language, install the Disable Messages module, and under configuration you should enable filtering. Under "messages to be disabled" add

```
Your comment has been posted.

```

... or if your comment message differs, cut and paste your exact message into the field.

You can also use regular expressions or filter by user.
> 1 votes

---
Tags: hooks
---


# Question
Title: programmatically add body classes with template preprocessing
Is there a way to add body classes programmatically through template preprocessing without the use of a Javascript or a drupal module?

If so how would one do that? p.s. Using omega theme.

E.g.: I need to add a class to the body to change a particular background color.

# Answer
You can add your class to body element by adding `THEMENAME_preprocess_html()` to your `template.php` Like :

```
function MY_THEME_NAME_preprocess_html(&$variables) {
  // Compile a list of classes that are going to be applied to the body element.
  // This allows advanced theming based on context (home page, node of certain type, etc.).
  $variables["classes_array"][] = "blue-bg";
  $variables["attributes_array"]["class"][] = "blue-bg";// For Omega based themes
}

```

Refer this link for more details.
> 9 votes

# Answer
In the preprocess\_html function in your template\_php, you can add an item to the classes array which will render out the classes on your body. comme ca:

```
/**
 * Implements template_preprocess_html().
 */
function YOURTHEMENAME_preprocess_html(&$variables) {

  $variables['classes_array'][] = 'new-body-class';

}

```

This works on adaptive themes, and bartik based themes.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to hide comments below the node, but not close them?
Аctually I want to list comments for nodes myself (by Views, for example), so I need to hide standard comments list from core comment module. I can do it like that:

```
  unset($node['comments']['comments']);

```

But it will not prevent DB query for comments.
So I found some crazy ways to trick the comments module. For example, to set fake `$node->preview` property, or to create new view mode and overwrite standard `node/%node` callback.

Is it really so difficult to hide comments below the node but still allow to add new comment, or I missed something?

## Update about “Hidden” option

What about “Hidden” value for the content type:
I need close/open behaviour for my comments. But if I set “Hidden” for my content type, my new content pieces are set to “Comments closed” instead of hidden (here is the code). Another problem is that user with permission to “post comments” can't add a comment, if comments are hidden (here is the code).
So I can't get the idea.

## Answer

Solution found with `hook_module_implements_alter()`. Thanks a lot!

# Answer
In modules/comment/comment.module we can see that hook\_node\_view() (comment\_node\_view()) is running on line 614. This is where the functions are firing to load all comments and attach them to the node. The first 2 sets of if () { ... } appear to be handling the add comment form and action link. Then the final block of code is finally adding the comments, which I believe is what you're actually most concerned about hiding, and I assume you want this skipped for performance reasons:

```
// Only append comments when we are building a node on its own node detail
// page. We compare $node and $page_node to ensure that comments are not
// appended to other nodes shown on the page, for example a node_reference
// displayed in 'full' view mode within another node.
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

```

I think this code is silly, because comment module should not be dependent on any particular hardcoded view mode. Hopefully this will change and become a setting in the UI.

Regardless, I've found a similar post that might interest you: Is there a way to stop comment\_node\_view from firing?

Basically you're wanting to use hook\_module\_implements\_alter() to stop the comment module from being able to fire off hook\_node\_view(). Here is what you need to add to your custom module:

```
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    unset($implementations['comment']);
  }
}

```
> 9 votes

# Answer
Just try to use hide() in your template file, or hook\_preprocess\_node():

```
hide($content['comments']);

```
> 0 votes

---
Tags: 7, comments
---


# Question
Title: How to add two fields on one add another items?
I have 2 fields with unlimited values both fields show its own add another items button.
i am trying todo is add both fields add with one add another items button.

# Answer
> 3 votes
CCK version 6.x-3.0-alpha3 contains a module called Multigroup. It allows you to group multiple fields together and repeat that group of fields multiple times with a single add-another button. This is an alpha version though, so if you decide to use it, test well to make sure it doesn't break something else.

# Answer
> 1 votes
This post is a bit old, but I needed this info so someone else might as well.

For Drupal 7, install the Field Collection module.
Go to your form and add a field of type "Field Collection".
Give this field unlimited values.
This field is the container that all of your other fields will be in.

Then go to Structure \>\> Field Collections

and find the field that you just created. Add your inner fields into this form. That's it!

# Answer
> 0 votes
http://www.poplarware.com/articles/cck\_field\_module As an option, you can write own compound field. However, I'd suggest you to investigate why multigroup not working and fix this.

# Answer
> 0 votes
For this trick you can use follow modules:

I prefer **Field group multiple** module.

---
Tags: entities, 6, ajax
---


title: How to customize commerce order layout

text:
# Question
Title: How to customize commerce order layout
I'd like to modify the current order layout visible at user/\[uid\]/orders/\[order\_id\]

Specifically, I'd like to list the billing and shipping info *before* the line item detail:

1. billing and shipping
2. List item detail
3. subtotals

I know that the the line item detail is a View that can be edited, but I'm not sure how to control placement/sequence of items not in this view.

Thanks in advance for any tips or advice.

# Answer
> 6 votes
For reference there are a couple answers depending on the situation. The order of the field display can be controlled by going to store-\>configuration-\>order settings-\>Manage Display which I believe would solve the OP question.

If you are looking to setup a custom .tpl.php file I wasn't able to successfully use the template suggestions which are:

* commerce\_order
* commerce\_order\__commerce\_order
* commerce\_order\__commerce\_order\__customer
* commerce\_order\__OID (where OID is the order ID)

I found these in template\_preprocess\_entity in $variables\['theme\_hook\_suggestions'\]

However, since an order is an entity I was able to use http://drupal.org/node/1238606 (tutorial on theming custom entities) and use a template of my own choosing.

*template.php*

```
/**
* Process variables for MYTEMPLATE--order.tpl.php.
*/
function MYTHEME_preprocess_MYTEMPLATE(&$variables) {
  // This is the generic entity preprocessor
  template_preprocess_entity($variables);
}

/**
 * Implements hook_entity_view_alter to alter the entity theme used by
 * commerce_order.
 */
function MYTHEME_entity_view_alter(&$build, $type) {
  if('commerce_order' == $type){
    $build['#theme'] = 'MYTEMPLATE';
  }
}

```

From there you can use: sites/all/modules/entity/entity.tpl.php as a template for your template.

Hope this helps someone.

Cheers,

Rob

# Answer
> 0 votes
If you create a new .tpl that follows the orders path you will be able to expose whatever you want in whatever order you wish. Unless I'm misreading what you're asking.

---
Tags: commerce
---


title: Where to put custom modules?

text:
# Question
Title: Where to put custom modules?
If I create a custom module for a single site where should I put it? Previously I would put it in sites/all/modules, or possibly sites/all/modules/custom. However I just read this article, Creating Your First Module in Drupal 7 Module Development which say the best practice is to put them in sites/default/modules:

> However, as of this writing, /sites/all/modules is not the recommended place to put custom modules unless you are running a multi-site configuration and the custom module needs to be accessible on all sites.
>
> The current recommendation is to put custom modules in the /sites/default/modules directory, which does not exist by default. This has a few advantages. One is that standard add-on modules are stored elsewhere, and this separation makes it easier for us to find our own code without sorting through clutter. There are other benefits (such as the loading order of module directories), but none will have a direct impact on us.
>
> We will always be putting our custom modules in /sites/default/modules. This follows Drupal best practices, and also makes it easy to find our modules as opposed to all of the other add-on modules.

Is this really considered the current best practice? Is there some official reference to this?

# Answer
> 10 votes
Modules can live in many places. If you use Apple's OSX it's alot like where Applications and Fonts can live in OSX ...

Modules can live at:

* /profiles/PROFILENAME/modules/
* /sites/default/modules/
* /sites/all/modules/
* /sites/SITENAME/modules/

core drupal modules are found in DRUPAL\_INSTALL\_DIRECTORY/modules.

Where a module lives deems how drupal sees it.

* Modules in a profile directory can be seen by sites installed by that installation profile.
* modules in /sites/default can only be seen by the default drupal site.
* modules in /sites/all path can be seen by all drupal powered websites regardless how they were installed, or what subsite they are.
* modules in /sites/SUBSITE/modules can only be seen by that subsite.

In general it is best practice to place the module folder where it is needed for its scope of use in your Drupal installation.

Additionally, it is a best-practice to place subfolders such as:

* /sites/SUBSITE/modules/contrib
* /sites/SUBSITE/modules/custom

to distinguish within a modules directory what is standard 3rd party contributed modules used for a site, and what is custom built drupal modules by your company in /custom.

Yes, there is documentation on this in your drupal installation folder at /sites/all/README.txt

Note: alot of this changes slightly with drupal 8

**EDIT - references on /contrib and /custom directories.**

Basically at some point in drupal development you want to organize your modules more and more, per site, per drupal installation. Many developers use these types of conventions. Drush Make (bundled into core Drush as of 5.x) allows specification of a subdirectory within /modules to place a module.

# Answer
> 4 votes
Drupal looks for modules in the following directories, and in their sub-directories:

1. `profiles/$profile/modules`, where `$profile` is the name of the currently used installation profile
2. sites/all/modules
3. `$config/modules`, where `$config` is the directory containing the settings.php file currently used from the website

When you are using the default settings.php file, the last directory becomes sites/default/modules. Really, the last rule is thought to load the modules from, for example, sites/blog.example.com/modules, where sites/blog.example.com is the directory where Drupal looks for the settings.php file for http://blog.example.com.

If you are using the Update manager module, the modules should be copied in sites/all/modules, which is the directory where the module copies the modules when it updates them. If you are not using that module, and you have different teams that handle different sub-domains/domains for a multi-site Drupal installation (to which you give different access permissions to the directories containing the modules), then you could use `$config/modules` for the modules.

If you have a single domain, or you are not using a multi-site configuration, sites/all/modules is the directory I would use. Even in the case of a multi-site configuration, I would still put the modules in sites/all/modules, as it allows me to have a singe copy of the module for all the sub-domains/domains.

---
Tags: 7
---


# Question
Title: How do I add a custom style to node by its type?
I've tried following the instructions on http://drupal.org/node/1089656, but I somehow can't get it right.

How do I apply custom layout/style to a node based on its type?

# Answer
> 1 votes
If the content type of the node is Article, then the template file Drupal looks for is node--article.tpl.php.
If the content type name contains underscores, those are replaced with hyphens. If the content type machine name is snippet\_code, then the template filename is node--snippet-code.tpl.php.

---
Tags: theming
---


# Question
Title: Add/edit node auto share to social networks
Is there any way to add an option to share to social networks selecting with checkboxes and with predefined messages using token that a new node has been added or than an old one has been edited?

I had an idea about rules, and the Social Share module but I don't know how to implement it.

# Answer
I used the Janrain module for getting similar functionality. It allows you to integrate social networking logins, set up buttons for social sharing and a lot of other stuff. Its actually pretty easy to set up the module

Some other modules include - Socialmedia, social login If you are just looking for sharing - Sharethis
> 1 votes

---
Tags: nodes, rules
---


title: Contact recipient different than UID

text:
# Question
Title: Contact recipient different than UID
Is there any way to make that Drupal 7 built-in contact form sends the emails to a different address than the one of the UID 1?

# Answer
Under admin/structure/contact/edit/1 you can add or remove any e-mail address(es) you want from the "recipients" box.
> 5 votes

# Answer
Private Message allows you to send messages to users registers on the site. Its a very robust module which integrates pretty well with notifications and rules. It also has a bunch of related modules to extend the core module functionality.
> 0 votes

---
Tags: emails
---


title: Why is my patch failing a test?

text:
# Question
Title: Why is my patch failing a test?
When a patch fails testing because it doesn't apply, and the error reads "Ensure the patch applies to the tip of the chosen code-base." what does this mean?

# Answer
> 2 votes
Basically your patch have to be applyable with the command

```
patch -p1 < $filename.patch

```

http://drupal.org/node/707484 is a pretty good tutorial how to create patches so the testbot can use it.

---
Tags: testing, version-control
---


title: Module Block does not show up

text:
# Question
Title: Module Block does not show up
> **Possible Duplicate:**
> Block not showing up in drupal

For some odd reason, This very simple module block does not show up in structure under the list of viable blocks. Am I doing something wrong here?

```
[quick_links.info]

name= Quick Links
description = Simple block with links
package = Mpackage
core = 7.x
files[] = quick_links.module

[quick_links.module]

function quick_links_block_info() {
  $blocks['quick_links_staff'] = array(
    'info' => t('Quick Link'),
    'status' => 1,
  );
  return $blocks;
}//TODO add caching option

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'quick_links_staff' :
      $block['subject'] = t('Quick Link');
      $block['content'] = t('links go here');
      break;
  }
  return $block;
}

```

# Answer
I don't have a real explanation why my solution worked; I only replaced quick\_links\_staff with quick\_links in both places.

```
function quick_links_block_info() {
  $blocks['quick_links'] = array(
    'info' => t('Quick Link'),
    'status' => 1,
  );
  return $blocks;
}//TODO add caching option

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'quick_links':
    $block['subject'] = t('Quick Link');
    $block['content'] = t('links go here');
    break;
  }
  return $block;
}

```

Make sure to clear Drupal cache after you implement the change.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Content Type template override - Dash or Underscore?
I am looking for some clarification on whether to use and underscore ("\_") or a dash ("-") when creating a page template override for a content type. Some tutorials and articles say the format should use underscores such as ...

`page--content_type_name.tpl.php`

while others specify the format as dashes like ...

`page--content-type-name.tpl.php`

If my content type has a multi-word name how should the template override filename be formatted?

# Answer
If you look at `theme_get_suggestions()`, there is a comment:

```
// When we discover templates in @see drupal_find_theme_templates,
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.

```

If you look at a preprocess, like `template_preprocess_node()`, you will see things like:

```
$variables['theme_hook_suggestions'][] = 'node__' . $node->type;

```

This is using the machine name of the content type directly, which is underscored.

`--` is a delimiter between things, underscores are used within a thing.
> 4 votes

---
Tags: theming, nodes
---


# Question
Title: Customization of Facebook style Statues module
I am using Drupal 7 with Facebook-style Statues module.

While writing the status I would like to load the URL when user paste any URL, just like facebook.

Is there any way to customize this module or do i have to build entire new module.

# Answer
I think you want Facebook-style Micropublisher this allows you to have a image present if the URL your connecting to allows it.
> 1 votes

---
Tags: social-network
---


# Question
Title: Creating module with autocomplete and accepting multiple values in textfield
I am creating my own form in my module using the Form API.

How do I enter multiple values in the below textfield and have it autocompleted, and suggested (separated by commas, for example)?

Right now it takes whatever is in the textfield box as one single big string.

```
$form['keywords'] = array(
  '#type' => 'textfield',
  '#title' => t('Keywords'),
  '#size' => '40',
  '#multiple' => TRUE,
  '#autocomplete_path' => 'papers_pub_search/keywords_autocomplete'
);

function _autosearch($string) {
  $query = "SELECT name FROM users WHERE name LIKE :name";
  $result = db_query($query, array(':name'=> '%' . db_like($string) . '%'));
  foreach($result as $row) {
    $match[$row->name] = check_plain($row->name);
  }
  drupal_json_output($match);
}

```

# Answer
> 13 votes
You can use the following code.

```
function _autosearch($string) {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
      $matches[$value] = check_plain($value);
    }
  }

  drupal_json_output($matches);
}

```

This is the result.

If you want to avoid a username can be used more than once, then you can use the following code.

```
function _autosearch($string = '') {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      if (!in_array($user->name, $items)) {
        $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
        $matches[$value] = check_plain($value);
      }
    }
  }

  drupal_json_output($matches);
}

```

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


# Question
Title: How to make an "Add more logins" similar to Stackoverflow?
I am using OpenID Selector module to integrate OpenID logins to my website; the same service used by Stackoverflow for login/registration. However, how can I add an option to "Add more logins" like Stackoverflow? I am open to suggestions also.

The idea is to prevent duplicate users. I am using D7.

See attached image.

Also kind of tweaks are welcome.

# Answer
So the default assumption most Drupal modules make with authentication is that they will replace the current login setup with their own.

This approach is described well in http://drupal.org/node/114774#dist-auth and can be seen in how the current openid module provided in Drupal core works.

If I understand your question correctly you want to provide a way for people to authenticate from multiple different sources and have those enabled sources show up under their user profile. I don't think there is a module that does this yet, as most of the auth modules operate in their own little bubble as described above.

After a quick look at OpenID Selector you aren't going to get a lot of mileage from there, its mainly implementing and configuring the jquery library. You are going to need to write this from scratch.

The main pieces of your module will be:

1. A database table that maintains the logins associated to a given user.
2. Some kind of form\_alter scheme for the login page to show all of the available login options the site owner has specified (this will replace what the individual modules currently do)
3. An admin page for the site owner to select from available options.

Each one of those login options will probably be provided by a separate contrib module, so you might have to alter your logic for the specifics you find in the implementation from those modules.

To me its an ambitious undertaking for a configurable module that you plan to release, but if you go the quick and dirty highly customized / hard coded route for a single site it shouldn't take you too long.

Other places to look for inspiration on how auth modules operate in Drupal and possible sources you might want to include are FBOauth and Twitter.
> 9 votes

# Answer
Does the HybridAuth Social Sign-on not fit your requirements?

> This module integrates HybridAuth library into Drupal and allows your users to login and register using Google, Facebook, Twitter, Yahoo, MySpace, Windows Live, LinkedIn, Foursquare, AOL, OpenID and more. Additional providers include: Github, Gowalla, LastFM, Vimeo, Disqus, Instagram, Viadeo, Identica, Tumblr, Goodreads, QQ, Sina, Murmur, Pixnet, Plurk, Skyrock, 500px, Vkontakte, Mail.ru, Yandex, Odnoklassniki.

I have not used it myself, but reading the description and screenshots seems to suggest it does what you need.

Update: Looking at the *Usage statistics* it seems like the module got picked up only recently and might not have been usable when you posted this question.
> 8 votes

---
Tags: 7, users, authentication-authorization
---


# Question
Title: Creating nodes and interacting with drupal from the command line
I have a requirement where I will have to insert content (nodes) from the command line. I know that drupal bootstraping is needed to acces the environment, and this can be done using PHP.

Is there any tool that can create/modify/read content from the command line ? Are there any other programming language binds (besides PHP) ? What are the options ?

# Answer
> 1 votes
I think the best option would be to go with the Services module. About the module from the project page:

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

You can build the other application (like android app, Java app, and many more...) in any programming languages you like and make the application interact with Drupal using Services. There is an extensive documentation available which would help you through.
Take time to read through the project page (as it contains more resources to explore) and the documentation as it might take time to get accustomed with the module (as it happened with me).

For command line access to Drupal there is a "Command line shell and scripting interface" - Drush (Drupal Shell). List of the Drush commands could be found at this site. It is very powerful utility for Drupal developers (on Windows, Ubuntu Linux, Mac, etc.); but I'm not sure if one is able to create/modify/read content (nodes) with Drush though, I think one cannot do that (please correct me if I'm wrong).

# Answer
> 1 votes
You can check Drush and Drush Entity. Drush is a powerfull command line script for drupal and you can do a bundle of thing with it (install module, clear cache...). I have never worked with Drush Entity but it add interactions with entities for Drush.

---
Tags: bootstrapping
---


# Question
Title: form_comment_form_alter modify comment body
I am using `hook_form_comment_form_alter` to add values to the textboxes in the commenting form. But in the comment body I can seem to add a default value and can't seem to find a value that I can change. Does anyone have any ideas?

```
function mytheme_form_comment_form_alter(&$form, &$form_state, $form_id) {
  dpm(get_defined_vars());
  $form['author']['name']['#title'] = "";
  $form['author']['name']['#default_value'] = "Name";
  $form['author']['name']['#title'] = "";
  $form['author']['mail']['#default_value'] = "Email";
  $form['author']['mail']['#title'] = "";
  $form['author']['homepage']['#default_value'] = "Website";
  $form['author']['homepage']['#title'] = "";
  $form['author']['subject']['#default_value'] = "Subject";
  //$form['comment_body']['need default value']= 'I need to add a value';
}

```

# Answer
To add default value to your comment form body use the following snippet,

```
 $form['comment_body'][LANGUAGE_NONE][0]['#default_value'] = "Your default value";

```
> 2 votes

---
Tags: 7, comments, forms
---


# Question
Title: Ubercart: PHP message if a Product is in cart
I need help with a boolean function in PHP. It's simple (but I'm not PHP savvy enough to do it myself). I just need to create a block with a message (not a system message because I am using better messages and I don't want people to close the pop-out without even reading it) that will only show in the ubercart cart page, if two of the products are in the cart. Else it won't show.

Of course, if there is a better workaround tio this, I am open to suggestions.

Thanks in advance to whomever might wanna help.

# Answer
> 0 votes
Create a block with input format as php code. **uc\_cart\_get\_contents()** function will help you to get current cart products. So use it to check for your products.

eg:

```
$items = uc_cart_get_contents();
// print_r($items); you can see all items in cart
foreach ($items as $item){
  //check your condition if condition true print your message,
}

```

Assign the block to a specific region and give display in cart page only

---
Tags: blocks, ubercart
---


# Question
Title: Make content type available for anonymous to edit and use front end theme
I have a content type that I have made available for anonymous users to edit. I want that content type when it is in edit mode to use the front end theme. How would I achieve this? Thanks

# Answer
Just make sure your anonymous user role (and any other relevant roles) don't have the 'View the administration theme' permission...then they'll get the default front-end theme when accessing any page that's deemed to be an 'admin' page.
> 2 votes

---
Tags: nodes, theming
---


# Question
Title: How to retrieve a file via REST from the services module?
Which URL format should I use when retrieving a file via the services module? I figured that it would be formatted like this:

```
http://<domain>/<endpoint>/file/fid

```

I've tried several file ids but all I get is an empty result. Is this the correct url format for retrieving a file?

Services module version is 3.

# Answer
I managed to get this working in the end. I used the poster plugin to request the url and received a message saying that the file doesn't exist. I'd been using the wrong file ids! I had looked at the wrong drupal database to choose the file ids.
> 0 votes

---
Tags: 7, files, services
---


# Question
Title: Permission issue when displaying user list with authored content count
Following this tutorial https://drupal.stackexchange.com/questions/1709/using-views-how-to-list-users-and-have-the-number-of-nodes-created-by-them (the one of the most voted answer) I found an issue with the permissions of the view, I'm getting the list of users only when I'm logged in like super admin, any other role gets only the super admin listed.

I have reported it on the Views Issues Drupal page too ( http://drupal.org/node/1838796 ) because I think it's a bug on the Views coding. I have checked all the permissions and they are set to both anonymous and authenticated users to be allowed to view user profiles.

# Answer
Making a new view (master only) that receive the UID as contextual filter and the Views Field View module there is a good possibility of retrieving information about the contents of an specific user that using the normal relationships (the ones built-in Views) won't allow you to do or will give you issues with MySQL and sometimes Ajax request.

Example of embeddable view to retrieve count of authored content of an specific user:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'más';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Aplicar';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Reiniciar';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Ordenar por';
$handler->display->display_options['exposed_form']['options']['sort_asc_label'] = 'Ascendente';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
/* Campo: COUNT(Contenido: uid del autor) */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['group_type'] = 'count';
$handler->display->display_options['fields']['uid']['label'] = '';
$handler->display->display_options['fields']['uid']['alter']['trim_whitespace'] = TRUE;
$handler->display->display_options['fields']['uid']['alter']['strip_tags'] = TRUE;
$handler->display->display_options['fields']['uid']['element_label_colon'] = FALSE;
/* Filtro contextual: Contenido: uid del autor */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['exception']['title'] = 'Todo(s)';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Criterios de filtrado: Contenido: Publicado */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
$translatables['ctn'] = array(
  t('Master'),
  t('más'),
  t('Aplicar'),
  t('Reiniciar'),
  t('Ordenar por'),
  t('Ascendente'),
  t('Desc'),
  t('Todo(s)'),
);

```

Nota: remember to check the content types and the translated strings.
> 0 votes

# Answer
If you are using `D7` I think you will have to enable `aggregation` for you view, and then set the `group by` for you field (`Content:nid` for example) to `Count`.
> 0 votes

---
Tags: views, nodes
---