# Question
Title: What is the difference between hook_preprocess_page and hook_preprocess_html?
I see that both `hook_preprocess_page()` and `hook_preprocess_html()` are implementations of `hook_preprocess_HOOK()`, but I don't understand when to use which.

`hook_preprocess_page` is called first, but that doesn't really help me understand who is calling it.

Looking at the `debug_print_backtrace()` output, it's getting called by `theme()`, but that doesn't really get me to the answer.

Is it simply defined by the array that is passed into `drupal_render()`?

# Answer
`hook_preprocess_page` is the preprocess hook invoked when the page.tpl.php template file is used, and `hook_preprocess_html` is the preprocess hook invoked when the html.tpl.php template file is used.

Both the preprocess hooks are invoked when a page is rendered with `theme('page')`, since the page element defined from system\_element\_info() defines html as theme wrapper.

```
  $types['page'] = array(
    '#show_messages' => TRUE,
    '#theme' => 'page',
    '#theme_wrappers' => array('html'),
  );

```

system\_theme() then defines html as follows.

```
'html' => array(
  'render element' => 'page',
  'template' => 'html',
),

```

As for when to implement `hook_preprocess_html()`, you implement it to alter the variables used in the html.tpl.php file, which by default has the following content.

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

As you can see, it contains just the HTML tags that wrap a page content, available in `$page`. With that, you can change the content of the `<head>` tag, the page title (the one that goes in the `<title>` tag in the `<head>` tag), the CSS styles and the JavaScript files added to a page, the classes and the attributes for the `<body>` tag.
With the page.tpl.php template file, you can change more of the page being rendered, including the site name, the site slogan, the page title, and the feeds associated with the page. For most of them, there is a specific Drupal function/hook you should instead use.

`hook_preprocess_HOOK` is the generic hook name used for all the preprocess hooks, in the same way `hook_form_FORM_ID_alter()` is the hook name used for a class of alteration hooks.
> 21 votes

# Answer
`hook_preprocess_page` and `hook_preprocess_html` are theme layer hooks you can use to add variables that can be used in your templates (`page.tpl.php` & `html.tpl.php`).

`hook_preprocess_hook` is the big theme layer hook that page and html use, and the custom ones you've made in `hook_theme()` as well.

For example, here is the declaration of `hook_theme()`:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'custom_theme_function' => array(
      'variables' => NULL
      'template' => 'custom-theme-template', // available as custom-theme-template.tpl.php
    ),
  );
}

```

and here are your preprocess functions:

```
mytheme_preprocess_page(&$vars) {
    $vars['variable'] = 'string'; // $variable will be available in page.tpl.php
}

mytheme_preprocess_html(&$vars) {
    $vars['variable'] = 'string'; // $variable will be available in html.tpl.php
}

mytheme_preprocess_custom_theme_function(&$vars) {
    $vars['variable'] = 'string';  // $variable will be available in the template you specified in mymodule_theme() (custom-theme-template.tpl.php)
}

```

additionally `hook_preprocess()` allows you to capture multiple theme hooks, and add variables in it as well

```
mymodule_preprocess(&$vars, $hook) {
  if ($hook == 'custom_theme_function') {
    $vars['variable'] = 'string'; // $variable will be available in them template you specified in mymodule_theme() (custom-theme-template.tpl.php)
  }
  if ($hook == 'page') {
    $vars['variable'] = 'string'; // $variable will be available in page.tpl.php
  }
  if ($hook == 'html') {
    $vars['variable'] = 'string'; // $variable will be available in html.tpl.php
  }
}

```
> 8 votes

---
Tags: 7, theming
---


# Question
Title: Looking for a good Mini - Panels tutorial
There are lots of good to tutorials for view and panels, but I'm having trouble finding specific information on how to properly use mini panels. Does anyone know of a good tutorial or explanation of how it works? again I've seen to referenced a bunch of times as a possible solution to certain problems, but never really understood how to use it.

(D7 panels 3 would be ideal)

# Answer
> 6 votes
I have not found a tutorial specifically for mini-panels, but it works similarly to page panels. nodeone.se has an excellent tutorial on using Page Panels (Page Manager & Panels modules enabled).

Mini Panels are closely related , but behave more like blocks. When you define a mini-panel it will be available in the panels UI for placement as well as in the admin/structures/blocks form. The major difference from blocks is that mini-panels are smart. They can take context from the node, user and other sources and display accordingly. They also connect to a View.

There is one thing to observe when defining a mini-panel. The UI is slightly different from Page Panels and the first time I used them, I could not figure out how to add content to one. To access the "content" and other setting forms select the Panels breadcrumb menu at the top.

# Answer
> 2 votes
Although for panels2, here is a basic tutorial for minipanels. Current panels adds some stuff, but the idea is illustrated well.

---
Tags: panels, 7, views
---


title: Can't add taxonomy term to node?

text:
# Question
Title: Can't add taxonomy term to node?
This code saves the taxonomy term, but it doesn't add it to the node. What is the problem?

```
             $node = new stdClass(); // Create a new node object
            $node->type = "article"; // Or page, or whatever content type you like
            node_object_prepare($node); // Set some default values
            $node->language = en; // Or e.g. 'en' if locale is enabled
            $node->title = $title;
            $node->field_image['und'][0] = (array)$file;
            $node->uid = '1'; // UID of the author of the node; or use $node->name

            $tags = explode(",",$sended_tags);
            $vid = 1;

            $term = new stdClass();
            $term->name = $tags[0];
            $term->vid = $vid;
            taxonomy_term_save($term);

            $node->taxonomy[] = $term;

            node_save($node);

```

# Answer
> 4 votes
You can do it like this:

```

if ($foo = taxonomy_get_term_by_name($term_name)) {
      $foo_keys = array_keys($foo);
      $node->your_taxonomy_field_name[LANGUAGE_NONE][]['tid'] = $foo_keys[0];
    }
    else {
      $node->your_taxonomy_field_name[LANGUAGE_NONE][] = array (
        'vid' => 1,
        'tid' => 'autocreate',
        'name' => $term_name,
        'vocabulary_machine_name' => 'machine_name'
      );

```

---
Tags: taxonomy-terms
---


title: show nodereferenced nodes in view

text:
# Question
Title: show nodereferenced nodes in view
I have 2 node types: Authors and books. Authors has node reference to book node type. Created view:

Relationships - i have used reference field, in arguments i have used Node: nid (content id from node URL).

In fields i have used my noderef relationship.

in a node.tpl.php:

```
print views_embed_view('video', 'block_4', $node->nid);

```

But it shows nothing. (i have created 1 node author, and 2 nodes book)

Views 2, Drupal 6. What i am doing wrong? Thanks

# Answer
> 0 votes
The function views\_embed\_view is meant to be used to embed the view in a page or a block during the processing of a page. After the page processing is done, the results are passed to the theme engine. It is not meant to be used in the theming stage.

What you can do is create a region in your template where you want the view to appear, then create your view as a block and place it in that region on the Blocks admin page, following the insructions here;

---
Tags: 6
---


# Question
Title: How can 'programatically' configure my site?
I often find myself re-creating the same site: a 'clean' instance of what I have developed so far. It takes me several hours to do. So, I have created a .install file to create all of my content types and fields when I install the first of my custom modules. I also need to:

* Create two menus
* Configure some blocks
* Configure the user permissions
* Alter some of the default theme settings

What is the best approach to achieving the above 'programatically'? At the moment I do all of these tasks through the various user interfaces, but like I say it's time cosuming to keep doing it every time I want to start afresh.

Thanks

# Answer
> 9 votes
So You Want to Build a Drupal Distro

Take a look at Packaging a distribution on Drupal.org

**Here are the steps:**

1. Assemble the pre-requisites
2. Create a Drush Make file
3. Convert to a Drupal.org-specific Drush Make file
4. Build and verify it works
5. Commit your code to Git
6. Release your code on Drupal.org
7. Maintain your distribution

Another great tutorial How to Write a Drupal 7 Installation Profile

Also there is Profiler Builder module.

> Profiler Builder is a module for automating the creation of installation profiles and distributions. It has support for the Profiler installation profile simplifier library but is able to run independent of it (1.0-RC4+). This module creates a downloadable tar package that gives you a well made installation profile and associated drush make file based on the site its installed on.

# Answer
> 0 votes
Features module enables you to export many configured variables, such as content types, in code. It is considered the current standard.

Many other modules, such as Rules and Views, are compatible with Features and allow you to export the configuration you create with them.

There are also modules to enable export of extra config as needed (i.e. Features Extra and Role Export) enable you to export more things, such as Nodequeue settings and Roles/permissions.

Using Features and Role Export, plus a clone of your site's theme, would likely enable you to export all of the configuration variables you want.

# Answer
> 0 votes
I think both @beth's and @Nikhil's answers here supply part of the picture. Create an install profile that enables Features modules and you are most of the way to a rounded solution. There will often be other things you want to do but generally they can be scripted using drush, then the whole process can be wrapped up into a shell script.

---
Tags: installation
---


title: Can I control Input Type by Field?

text:
# Question
Title: Can I control Input Type by Field?
I have a node type with multiple text fields. The majority of these are designed to fit very specific templates, and have fixed height and width, and are generally quite small. The full CKE interface is too much of a good thing for these fields, so I made a different "Text Format," and tied it to a distinct Wysiwyg profile, "Full HTML (Simple)"

All of this is super, except that the default is still the default, and unless the user CHOOSES the other profile... it serves no purpose whatsoever. These same users have access to multiple filters, so the obvious option is out.

I understand limiting the profiles by roles... and I half understand Filtering by Node Type... but I don't understand not limiting them by field.

I checked modules and it looks like Better Formats is on the way to doing it for 7, but I can't see any modules out there that ready for prime time.

I can't be the first person who has desired this. Is there a hiccup in my logic, or a methodology I should be considering?

# Answer
> 0 votes
@Clive was spot on... Better Formats does exactly what I wanted.

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


# Question
Title: Send mail once content approval of custom content types
I am creating one Like job posting custom content type.The permission for only posting the job for recruiter.After Post the job I need the approval for publishing permission from admin. My thought when recruiter post the job i want to send the mail like recruiter post the new job for admin and once admin approved the content. How can i do this

# Answer
> 0 votes
It's kind of hard to understand what you want but I think you should use the "Rules" module, which allows you to "to define conditionally executed actions based on occurring events": https://drupal.org/project/rules

# Answer
> 0 votes
Actually it sounds like you need to use the Modr8 module.

With the module activated, you can set the publishing options for the Job Posting content type to *In moderation queue* and let your admin approve the post.

You can configure the modr8 module to send email notifications to the author when the posting is approved, or if it is held in moderation with a note to author by the admin.

The author can still view and edit the post, but it is not available for general viewing untill it has been approved and removed from the moderation queue.

---
Tags: 7
---


# Question
Title: How should I store a simple, time dependent, repetitive data type in drupal
Im interested in collecting simple data series over time with Drupal. for instance, lets say a user wants to input a monetary amount the spend on a given item each day, and then track that over time. It seams like overkill to log the information as a node, or even an entity for that matter. What is a good way to store data of this nature?

# Answer
> 0 votes
Since I last looked webform submissions were not 1st class drupal citizens. This may have changed by now ...

I recommend using ECK; or using a custom Content Type and RabbitHole (to hide the raw submissions if you dont want direct access to a single silly datum entry) to leverage Drupals core Field and Entity concepts for your data.

Then as an example I would recommend using the Google Chart API along with Views for Drupal 7 to provide reports about your data over time -- depending on the complexity of your reports you may have to write a custom drupal module ...

But, this will be much more flexible than working with webform submission results in the long run.

# Answer
> 0 votes
I think Webform is what you are looking for. You make a form that user(s) can fill in and submit.

You can track the submissions over time, export them etc. There are lots of features you can do with webforms.

This is not a complete how-to for your question but you can take it as a start point. This way you don't create a node for each submission, but the form itself will be a node of type Webform.

---
Tags: entities
---


title: Views vs. EntityFieldQuery

text:
# Question
Title: Views vs. EntityFieldQuery
Why would one use entityfieldquery over views? Is there any benefit to using EntityFieldQuery over using views? Is it the performance benefit? Is it the ease of use of a API? Does it provide you more granularity?

# Answer
It was recently written that there are several benefits over EFQ, entityfieldquery over other methods:

1. OOP - EntityFieldQuery provides an object oriented programming approach that allows you to create abstract classes to extend.
2. Flexibility - An advantaged arised from #1, creating your own objects allows you to modify the entitycontroller to do more things: Store field data via mongo DB, return data into blocks only, etc.

Source: http://chris-on-the-web.blogspot.com/2012/03/drupal-7-views-vs-entityfieldquery-pt1.html
> 1 votes

---
Tags: views, database
---


# Question
Title: Why Drupal does not see permission from custom module?
I tried disable and reinstall module, but with no luck, clearing cache does not work too. Module name is bip\_menu\_perm:

```
/**
 * Implements hook_perm()
 */
function bip_menu_perm_perm() {
    drupal_set_message('test');
    return array(
        'administer menu permissions' => array(
            'title' => t('Administer menu publishing permissions per user'),
            'description' => t('Users with this roles can edit menu publishing permissions'),
        ),
    );
}

```

What I am doing wrong here? This function does not invoke on permissions page.

# Answer
The hook is called `hook_permission()` in Drupal 7, it changed names from `hook_perm()` (Drupal 6)

> This hook can supply permissions that the module defines, so that they can be selected on the user permissions page and used to grant or restrict access to actions the module performs.

Make sure you clear Drupal's caches once you've made the change so it gets picked up.
> 7 votes

# Answer
As rightly mentioned by Clive, it is `hook_permission()` in drupal 7.
Following is the example:

```
/**
 * Implementation of hook_permission().
 *
 * @return array An array of valid permissions for the mymodule module
 */
function mymodule_permission() {
 return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: URL paths taxonomyterm/pagename instead of content/pagename
I've set up a vocabulary with some terms. I've created some new pages and tagged with the newly created terms. However, the node urls are in the form of content/pagename and I would like them to be taxonomyterm/pagename instead.

What do I need to do in order to get the urls to display in the taxonomyterm/pagename format?

Drupal 7

# Answer
Under */admin/config/search/path/patterns* you can change the default pattern for the content type from `content/[node:title]` and set the pattern to `[node:field-tag]/[node:title]`. It is probably a good idea to restrict field\_tag to a single value, and to make it required if you are going to use a pattern like this.
> 0 votes

---
Tags: taxonomy-terms
---


title: Add class to one SPECIFIC menu item

text:
# Question
Title: Add class to one SPECIFIC menu item
I'm looking for a way to add an extra class to a specific menu item in my main menu. I see ways to add classes to the entire menu, but not one specfic item. Can someone point me in the correct direction.

This is for Drupal 7.

# Answer
> 4 votes
You probably want to install Menu Attributes.

> The module currently allows you to set the following attributes for each menu item: Id, Name, Target, Rel, Class, Style, Accesskey

---
Tags: 7, javascript
---


# Question
Title: How to override/enhance file_save_upload() function of file.inc?
For a specific requirement, wherein whenever an image is uploaded to a particular field of a node, a watermark should be added to it, I made changes in file\_save\_upload() function of file.inc

```
if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
    form_set_error($source, t('File upload error. Could not move uploaded file.'));
    watchdog('file', 'Upload error. Could not move uploaded file %file to destination    %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
   return FALSE;
}
else{
    process_image(drupal_realpath($file->uri));
}

```

But these changes will be lost whenever Drupal core will be upgraded. So what is the best way to override/enhance file\_save\_upload() function of file.inc or any function in the core drupal?

# Answer
> 2 votes
Drupal runs on a Never hack core policy.

The Drupal way to add a watermark to image is to use hook\_form\_alter to modify the form submit and do your things with `$form_state['values']['YOUR_FIELD']`

Eg:

```
function mymodule_form_alter(&$form, $form_state, $form_id)  {
  switch ($form_id)  {
   case 'YOURFORMID':
     $form['#submit'][] = 'yourModule_yourform_submit';
     break;
   }
 }

function yourModule_yourform_submit($form, &$form_state) {
    // do what you want to do
    // use $form_state['values']
}

```

Or Try ImageCache Actions module.

> Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency

---
Tags: 7, media
---


# Question
Title: How to display fields from different entities in views
In my project, i need to create a view that displays fields created in the profile 2 module and a field from the core registration form (Username) in the same table. Please how can this be done? I plan to filter users using the username field. and other values provided via the profile 2 fields.

Thank you.

# Answer
Start with either the base table of user entity or profile 2 entity, then just add a relationship in views to the other. It is found under the "advanced tab" in views.
> 3 votes

---
Tags: views
---


# Question
Title: How to manually create links to change focus on horizontal tab items?
I have a horizontal tab group with a few horizontal tab items. I want to create a text link that allows users to move through the tabs instead of clicking on the horizontal tabs themselves.

I found this other question: How can I activate a horizontal tab?

Unfortunately the answers do not work. I see that my horizontal tab items have a unique ID. For example, id="node\_contenttype\_form\_group\_stuff". Simply creating a link like the below does not work:

```
<a href="http://www.example.org/node/add/contenttype#node_contenttype_form_group_stuff">CLICK HERE FOR NEXT TAB ITEM</a>

```

By clicking on that link, it takes you back to the very top of the horizontal tab groups, but it does not put the horizontal tab item specifically into focus. It just pulls you back to the top of the page where you can see the horizontal tab group.

EDIT: Looking at the source code, it appears that all the tab items are like the below in the HTML source:

```
<li class="horizontal-tab-button horizontal-tab-button-1" tabindex="-1">
  <a href="#">
    <strong>
      II. Text of horizontal item #2
    </strong>
  <span class="summary"></span>
  </a>
</li>

```

# Answer
> 1 votes
There is a css trick that can achieve this.

Firstly, reset the default positioning on the `a` element:

```
.horizontal-tabs > ul.horizontal-tabs-list li a {
  position: static;
}

```

Secondly, apply an `::after` pseudo-element to the link for the horizontal tab AFTER the selected/active one:

```
.horizontal-tabs > ul.horizontal-tabs-list li.horizontal-tab-button.selected + li a::after {
  content: "next";
  display: block;
}

```

Given we reset the positioning on the parent `li` (and the `ul` is relatively positioned by default) we can now position our pseudo-element relative to the `ul`, which spans the whole content block. So if you wanted to put your "next" link top right, do something like this.

```
.horizontal-tabs > ul.horizontal-tabs-list li.horizontal-tab-button.selected + li a::after {
  content: "next";
  display: block;
  position: absolute;
  right: 0;
  top: 30px;
}

```

This example assumes that our `ul` has a height of 30px. Given that the last `li` element (ie the final tab) does not have an immediate sibling, the "+" selector does not match on the last `li`, which automatically excludes the "next" link on the final tab.

---
Tags: 7, javascript
---


title: Drupal user points and commerce

text:
# Question
Title: Drupal user points and commerce
I have 3 products: A, B and C. After the user buy the product A, I want to give the user 5 points, for B 10 points and C 20 points.

How do I do this with rules?

# Answer
* Add a new rule with some name, e.g - Award Userpoint for Product A.
* In event select "Completing the checkout process".
* If you want to award userpoint only if payment has been done in full, then after going forward delete the "Completing the checkout process" & add another action "When an order is first paid in full".
* Add condition "Order contains a particular product", put the SKU of the product A. User operator & quantity as per your requirement.
* Add a action named "Grant points to a user", in data selector choose "commerce-order:owner" & set the points which you want to award.

Done...this is how I am doing.
> 0 votes

---
Tags: commerce, rules, userpoints
---


# Question
Title: How do I allow both kg and lbs units for a field
I want the user to be able to submit weight as either kg or lbs and do any necessary conversion on the fly. I took a look at Unit Conversion Formatters but it seems that this is designed to convert for display only (not for storage).

# Answer
Create two fields, one for number, second for unit. Optionally put them in a field collection.

Then, add Computed field that will use both values for computation and store the result the way you need it. For best flexibility, you might want to create two of them, ie `field_real_kg` and `field_real_lbs`.

> computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields
> 3 votes

---
Tags: entities
---


# Question
Title: Commerce Hook Function To Checkout Button
I am a Drupal Commerce novice. I have a basic cart system working fine, but I now need to get into some custom code. I don't think I can use Rules because the code is a bit too complicated.

I have a Shopping Cart page with a Checkout button. I want to hook into that Checkout button.

I need to add a php function (which I already have) which will execute when that button is clicked but -before- the checkout page is rendered.

And I need this to do so without disabling the default actions that the Checkout button performs.

SO: How do I hook into this button without disabling the default behaviour?

Due to my noobness--I'd appreciate as complete an example as possible. I'm not lazy, just can't take for granted that I'll catch everything I need to if the answer is 'shorthand'.

TIA,

---JC

# Answer
> 2 votes
The checkout form is a form like any other, so you can just alter it (using `hook_form_alter()`) and add a submit handler:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_commerce_cart_form_default') {
    $form['#submit'][] = 'MYMODULE_some_function';
  }
}

function MYMODULE_some_function($form, &$form_state) {
  drupal_set_message('This was run after the cart form was submitted, before the checkout page was rendered.');
}

```

Addressing the comments...

As you have a custom shopping cart form, with a link instead of submit button, no extra processing will be done so you can just hook into the page build of the linked page (/checkout/%) and perform your operation there; it will have the same effect.

There are a couple of places you could do this (neither really 'better' than the other), `hook_page_alter()` and `hook_init()`. There are other places too (theme preprocess functions) but for processing logic something a bit earlier is probably more appropriate. Basic example (will probably need tweaking for your needs):

```
function MYMODULE_init() {
  if (arg(0) == 'checkout' && $some_other_pertinent_condition) {
    // Do some processing.
  }
}

```

As for learning Commerce - that's a tricky one. Commerce is heavily integrated with Drupal and uses a lot of its functions/hooks/integrations just like any other module would. So really you need to know Drupal's workflow, and then overlay Commerce's workflow on top of that. The best advise I can give is to grab a Drupal book (Pro Drupal Development is excellent), and after you're happy with the workflow there, hit the Drupal Commerce support pages and read, read, read.

Drupal has a notoriously steep learning curve, and there isn't really a shortcut to understanding how it works as a whole. You just have to get stuck in. But it's well worth it, Drupal's awesome.

# Answer
> 1 votes
Yikes. As far as I can tell, there isn't a direct hook for clicking the checkout button. The provided hooks for the Drupal Commerce checkout module are over here, there's a general hooks list here, and the actual checkout form output is generated here which can be overridden.

This is a tricky request, and I'm at a loss. The test site I set up doesn't even show the checkout button in a form, it's just a link - so I guess you can't use hook\_form\_alter() on it.

My thoughts for chasing this down are:

* Add some custom JS and make an ajax call on button click that initiates a condition for the next page
* Start logging the previous page in a session variable and do a comparison when you land on the checkout page - if you came from a page that has a checkout button, execute action. (Might be able to adapt Previous Pages for use)
* Use Rules to trigger on a "Product is viewed" action with a path condition of the checkout page
* Hook into the checkout\_page\_info\_alter function to determine whether you're on the correct page
* Redirect users to a staging page of sorts before they hit the actual checkout page - change the cart page to something of your own choosing, collect some data, append a ?destination parameter to the URL and roll through with your new info

I'm at a loss. Since this isn't really an answer, I can't give a great example of how to do any of this without great detail. I did figure out the Commerce hooks for you though:

`hook_commerce_cart_order_is_cart_alter` becomes `YOURTHEME_commerce_cart_order_is_cart_alter`

Lol. Sorry for not being more useful... good luck.

---
Tags: 7, hooks, commerce
---


# Question
Title: Job board: Faceted Search with "OR" operator, but sort results by most matching facet criterias/term count
I'm quite stuck with searching for a solution for my problem and I hope that you can maybe help me.

In general I want to build a small job platform. It includes an "Explore"-Section, which is just like a Search-Page with Facets. The actual job-nodes can be tagged with terms of the two vocabulary "skills" and "interests". The facets on the search page allow the user to filter jobs exactly along these skills and interests. However, I want to use the "OR"-Operator for the Facets, so that the user gets a list with jobs, that nearly perfect match their skills & interest but also jobs that match only some of these terms.

So, here you can see the default listing page. On the left are the Facets for interest and type (Operator "OR"). On the right, you can see the result set with title, and the node's skills & interest terms: Jobsearch Default page

Now, I'm applying "Musik" and "Kultur" as interest-filters: Jobsearch with applied filters

As you can see in the result-set, the OR-operator delivers all the results. However, I would like to sort these results according to their "relevance" resp. according to the count of matched criterias. The 4. and 5. results match both terms, that are selected in the facet, but they should be listed in front of all other terms.

So, I hope you understand what I want to achieve. I started at first with Views to accomplish the goal, but I then switched to search\_api and SOLR as I think, that this approach is more enhanceable in the future.

The second aim is, that a user can store his/her individual interests & skills (the filters mentioned before) in his user profile. Here, the user should see individual job recommendations based on his profile on his account-page.

So, any hints, tips, tricks, links are very welcome as I have no idea if I'm on the right track to solve my problem(s). :)

Robert

# Answer
> 0 votes
Maybe this approach could be an alternative: Instead of using the tags as facets/filters, I could use them just as search input. when i'm typing my terms/tags within the search field of an apache-sold-search-page, i'm getting exactly the results sorted by their relevance:

Searching for filters/term instead of using them as real filters

So, maybe I have just to do a small piece of code, that automatically creates a search query based on the clicked term/tags…

---
Tags: search
---


# Question
Title: I am using node_save() to alter a node field, but HTML code is showing escaped
This is the code I execute with "Execute PHP" with the Devel module.

```
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'my_writings'; // Machine name of the content type

$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $node_type)
  ->execute();

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));

  foreach($nodes as $node) {

    $str=<<<END
 <h3> TITLE</h3>
<p>
Hello world.
</p>
END;
    // Replace field_foo with the machine name of the field to update.
    // - 0 refers to specific within the field array, for when the field contains
    //    multiple values. If the field only has one value, it should be 0.
    $node->field_author_box[$lang][0]['value'] = $str;
    node_save($node);
  }
}

```

The output I get is this HTML code like this.

```
<h3> TITLE</h3>
 <p>
    Hello world.
</p>

```

The input format is set to *Full HTML*, but the HTML tags are shown escaped, even if in the database they appear normal.

I tried to re-save the node; then, it is normal. I tried also to use `html_entity_decode()` without luck, if I do the same with body field then it works fine, but with a new field its showing escaped characters.

What could the problem be?

# Answer
Drupal core does not modify the data you save in the database \[\*\]. All filters are applied only when displaying the data - this ensures that you never loose any data.

Assuming that you are using Drupal 7, and that the field in question has filtered text enabled, then what is happening is that when you save your new field, you are not setting what the filter format should be - so it defaults to plain text. You need to set the format of the field when saving it. In your code, you would do this as follows:

```
$node->field_author_box[$lang][0]['value'] = $str;
$node->field_author_box[$lang][0]['format'] = 'full_html';
node_save($node);

```

\[\*\] Though some contrib modules may do this. For instance WYSIWYG editors such as CKEditor do modify your data (though in that case only when using the UI).
> 4 votes

---
Tags: nodes
---


title: Adding group of fields in custom module

text:
# Question
Title: Adding group of fields in custom module
I am trying to programmatically create a content type with 2 fieldsets, where the second one have an "Add more" option to create multiple set of fields. I looked for a working example to create multiple sets of fields, save, and edit them. Unfortunately, I couldn't find any. My module is creating, editing and saving the content type without 'add more' option.

Can anybody help?

# Answer
> 1 votes
I hate to say that there is an only way that I know to have multi-value field groups in Drupal 7 is Field Collection module. It is based on Entity API. It creates a new entity of which you can add any number of fields, and attaches that to the content type or any other entity you create.

---
Tags: 7
---


# Question
Title: Drupal 7, Default value php snippet missing?
Im using drupal 7 and created a content type abc. In abc there is a CCK field called seller. When a logged in user create a new item for content type abc, the value of the seller field would be the name of the person who is logged in. So what I want is a default value for the sellers fiels or you can say that a small piece of php code. But I am not able to find the place for the php code to enter in drupal 7. In drupal 6 there is text area for the php code to enter. But how can this be done with the drupal 7. Any ideas?

# Answer
This functionality is not part of the Field UI in Drupal 7. You'll need to install the CCK module.
> 5 votes

# Answer
Enable PHP filter module, that's core module of drupal 7.
> 0 votes

# Answer
(I assume Drupal 7)
May be a bit late answer ...
As @Nikit said, you have to enable the PHP filter module.
But also, beware of a trap that cost me some time : you will have to set *permissions* to *admin* for this module as default permissions are empty (may be because this module is rather on the dev side, so even admin should not have this permission by default ?).
Then, in the visibility settings for pages, you will have a third options (radio button) that allows you to add PHP for :

> Pages on which this PHP code returns TRUE (experts only)

PS : i don't get the answer from Dylan as CCK was mostly incorporated to D7 core...
> 0 votes

# Answer
I'm using Drupal 7. I had also same issue.

Even though most of CCK has moved to core in the Drupal 7 version, we cant see the option to include PHP code / PHP function until you install cck module.

After installing this module only, we can see the options to include PHP function.

I have created select list to display city data. For this i have used one function to fetch all city data from my custom table.

For more details see this image : (city\_list\_from\_maxmind - PHP function)
> 0 votes

---
Tags: 7, entities
---


title: Using Ubercart with https protocol

text:
# Question
Title: Using Ubercart with https protocol
I just installed rapidssl certificate and I want to serve my cart pages using https protocol. I put all files inside apache2/ssl folder, edited default-ssl inside apache2/sites-available. The certificate is installed, but after visiting https://www.mysite.com or any link using https protocol, the browser gives me either the "It works page" or a not found page. It is probably due to path pointing to default directory.

I am assuming that I if put the correct path in the default-ssl file it should work. However, I read that having both http and https pages serving the same content is not good for SEO.

What would be the correct way of enabling cart\* pages to automatically use https protocol?

# Answer
> 0 votes
If you care for SEO, consider using Metatag module:

> Meta tags have additional uses like the Open Graph Protocol used by Facebook, **specifying the canonical location** of content across multiple URLs or domains.

For Drupal 6 there is Nodewords module, that was inspiration for Metatag as far as I know.

To force https where you need it, use Secure Pages. You can check "Switch back to http pages when there are no matches" to make sure pages not *required* to use SSL will never actually use it - that way you save both server's CPU load (as encoding isn't free) and problems with duplicated content. It's pretty convenient, and a good first step, but it should not stop you from setting canonical, of course.

---
Tags: 6, ubercart, ssl
---


title: Issues with upgrading

text:
# Question
Title: Issues with upgrading
I am trying to upgrade from Drupal 6.28 to Drupal 7.22. By following the steps that were available on Drupal community doc, I succeeded in upgrading it to Drupal 7 successfully. I upgraded core, migrated CCK fields as well, but there are issues with the Views module: Various fields are not working. It is showing an error for a missing or broken handler.

The issue is that Drupal 6 had an embedded video field which was not included in Drupal 7. In Drupal 6, the widget type was embedded video, while in Drupal 7 the widget that we get by embedded media selector is media file selector.

How can I resolve this issue?

# Answer
If you followed all the steps, I assume you have (or can get) a working copy of original 6.x page.

The question is - are your *nodes* OK?

* If they work properly, it means you have data in good enough state. Delete views that include problematic fields and recreate them from the ground. Optionally export them, remove fields that cause problems from exported file, delete from server, import and add fields. That's the easy case
* Sadly, if there was changes in the fields you were using in the very nodes, that renders nodes unusable, it will be worse. You will need to export data from 6.x site to some more or less universal format, like csv or xml, and import it anew to 7.x

+ Delete migrated data and it's content type
    + Create new content type with new-style fields, that maps 1:1 to old node structure. If possible, keep names
    + Export node data, using Node Export, Views data export or similar tool
    + Secure all the files referenced by nodes
    + If needed, manually upload secured files to new version; see next step
    + Import nodes using tool like Node Export or Feeds \- it may be required for files to be already uploaded, read the manual of your importing tool
> 1 votes

---
Tags: 7, upgrading
---


# Question
Title: Validating a Webform with CAPTCHA locally before submitting to an external URL
**I have the following setup**

* Drupal 6.x
* Webform 6.x - 3.17
* reCAPTCHA 6.x - 1.17

**I also have the following custom module**

```
function webform_to_data_repo_form_alter(&$form, &$form_state, $form_id)
{
if ($form_id == 'webform_client_form_765')
    {
        $form['#action'] = url('some-external-site.com', array('external' => true));
        $form['#method'] = 'post';
    }
}

```

As it is now, the form is able to communicate with the external website. It cannot however validate entered values before it submits.

This lack of validation is a problem for several reasons because

1. The CAPTCHA field can be left blank, which defeats its purpose.
2. Any field that I specifically made mandatory can now be left blank, again defeating its purpose.

I've also read on multiple occasions that once you use `$form['#action']`, any attempts on validation will cease to work.

I was wondering if there was a way I could prioritize the validation of forms over `$form['#action']` and if so, how?

If you could just point me to the right direction, in terms of what my custom module is missing, I'd appreciate it.

Thanks in advance.

# Answer
If you want to validate form, you need to leave action intact. Then, you can send it's content to external server in it's save handler using it's api or drupal\_http\_request().

The point is - `action` tells the **browser** where to send the data. If you make it send data to external server, your Drupal will never get it, so it will have no opportunity to interact with it. Of course you might try to implement validation in browser too, using JavaScript, but that's unreliable and shouldn't be used as an only way of validation.
> 0 votes

---
Tags: webforms, forms, captcha
---


# Question
Title: Force using specific filter text on a content type
How can I limit the text filter type upon a textarea field.

Example (the needed result would be like this) :

* Authuser is a role that can change the value of textarea\_1 and textarea\_2 on contentTypeA
* Authuser can't change the 'text filter' value of textarea\_1 (it's on filtered HTML)
* Authuser can change the 'text filter' value of textarea\_2 with only (Plain text or ckEditor(WYSIWYG))

Is that possible? if yes, how?

Thanks in advance.

# Answer
Using format permissions in combination with the Better Formats module should allow you to do what you are trying to do.

The Better Formats module allows you to set allowed and default text formats per field - so you can set different allowed formats for both of your fields.
> 6 votes

---
Tags: 7, entities
---


# Question
Title: exporting/importing nodes without losing disqus comments / social media stats
I've been working on a website and the live version there is still content being created while i develop the local site.

Whats the best way for me to import the new nodes that have been created on the live site into the local site without losing the disqus comments or social media stats (fb likes etc.) it has?

# Answer
To export single nodes you can use the Node Export module. This one allows you to export a node, it's fields and contents to a text file which can be imported on another site with the *Node Export* module.

Assuming you are using the Disqus module: To export comments and social media stats you will have to use the *Disqus Migrate* submodule. To use either Import/Export, you have to register an Application with Disqus and fill in both your public and private keys in the main Disqus settings page. Make sure your authentication method is set to the deprecated legacy method. Download the PHP API implementation here and upload the `disqusapi` folder to your `sites/all/libraries` folder.

**Export**:

* Export your comments using the XML method until the API method is fixed, and save the file to your computer.
* Upload the XML file to your Disqus site in the Tools section (generic WXR method), and wait for the import to complete.
* Check for errors after importing, but most comments should have been imported successfully. They will appear automatically on any Disqus-enabled nodes on your website.

**Import/Sync**:

* You can do a one-time import at Comments-\>Disqus Import. Specify the timestamp you want to import from.
* You can have comments automatically import from Disqus on an interval basis. Turn this on in the import settings at Site Config -\> Disqus -\> Import. Turning on syncing will query Disqus for any comments that came in since the last import.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to make the Webform submit button use an uploaded submit-image?
I am building a D7 website and I want the following feature for the site admin, regarding the Webform module:

When the admin creates a webform, the admin uploads a submit-image and this image is used as the submit button for the webform. so if he uploads a "click-me.png" I want the path to this image to be used in the `input[type=image] class="form-submit" src="/path to uploaded image"`

Is there a simple way to achieve this, or do I have to seperately hardcode the behaviour I want for each webform?

P.S. By default webform's submit button is of type "text" and not "image", but I easily managed to change this using this excellent solution.

# Answer
> 1 votes
The easiest way to do this would be to write your own module. The place to start looking would be here: http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/function/hook\_webform\_component\_info\_alter/7

---
Tags: webforms, forms
---


# Question
Title: SelectQuery::fields and Drupal's naming conventions - how to make it all match?
Convention for database column names is `underscore_notation`. Convention for class properties is `camelCaseNotation`. But when I'm using `SelectQuery::fields('t')` and then `fetchObject()`, fetched object's properties are in `underscore_notation`.

I know I can use code like:

```
foreach($fields as $field)
    $query->addField($table_name, $field, to_camel_case($field));

```

That's a solution when I know fields I'm supposed to get. What if I don't? If all I want is good old `SELECT * FROM {table}`? Is there a simple way to fetch object compatible with Drupal's naming convention?

I know that formally, as written, convention does not apply to objects generated dynamically and returned from PDO. I want to avoid mixed namings none the less. It feels wrong to make user input `$object->camelCase` and give him `$output->underscored_answer` back. Bad as in causing errors and confusion.

# Answer
What the naming conventions actually say is that "Methods and **class** properties should use lowerCamel naming." (my emphasis).

The properties added to the *object* returned by a query are not class properties. This is confirmed by the PHP documentation which defines "properties" (or "class member variables") as "defined by using one of the keywords public, protected, or private, followed by a normal variable declaration". There is no such declaration that applies here.

The object you are looking at is of type StdClass. There isn't much about the concept behind StdClass in the PHP documentation (unless I missed it), but the concept of a class-less object with dynamic fields is sometimes known as "anonymous object". You can create one in PHP by doing:

```
$obj = (object)(array('field' => 'value'));
echo $obj->field; // Outputs 'value'

```

In the case of the object returned by the query, it doesn't even have methods - it could just be an array (which it would be if you fetched your data using DatabaseStatementInterface::fetchAssoc). So we can think of anonymous objects as containers, rather than instantiations of classes to which the coding style should apply.

Since this object is a container of fields from the database, I think it makes sense for the database convention to apply. It is an object wrapper around a database row.

As a Drupal programmer, if I get a result that is essentially a database row, I will actually *expect* it to be in underscore notation. While it may feel wrong, it is what people are used to expect. Every time I use `[node_load][4]`, the result I get is an object in underscore notation. Even when you use the entity meta data wrappers, which essentially are there to provide an object interface around Drupal entities, you still use the underscore notation. Changing this approach would potentially confuse other Drupal programmers.

I understand that if you are writing, say, an API which returns your own data, you may want to abstract the fact the result is a database row and present it as an object like any other (as suggested by your param vs. result example). One option, though one that has some overheads, would be to create a class to hold such result, and casting the database result object to it. This would at least make it clear that what you are returning is a proper object, not just a container around a database row. You could do something like this:

```
Class MyApiResult {
  function __construct($row) {
    $vars = get_object_vars($row);
    foreach ($vars as $name => $value) {
      $cc_name = to_camel_case($field);
      $this->{$cc_name} = $value;
    }
  }
}

```

Then your API would return:

```
return new MyApiResult($row);

```

However this has some overheads, it depends whether those will be acceptable in your particular case.
> 1 votes

# Answer
I've mucked to much with PDO and Drupal -- try this it out and let us know :).

The database layer in Drupal uses PDO. You can fetch results to a custom class typically by setting the `FETCH_MODE` .... welllll I was gonna link you here Fetching into a custom class

But, it looks the answer is more simple but probably doesn't buy you much. But maybe you'll find this helpful. Read on ...

You just need to tell PDO to respect the case semantics of your SQL statement for **your** queries (trying to do this on all queries in drupal, see below, will probably blow chunks).

Relevent Additional Documentation is here:

I think you'd have to write your queries similar to:

```
// This gets the default drupal database connection, you can pass parameters to
// select alternate dbs defined in settings.php
$db = Database::getConnection();
// This tells PDO to use the case of the raw SQL statement allowing you to write:
// SELECT foo_bar AS fooBar, some_other_property AS someOtherProperty ...
// and they will return in your fetchObject object as camelCased (natual, whatever you AS'd as case) ...
$db->setAttribute( PDO::ATTR_CASE, PDO::CASE_NATURAL );
// This is the long route of writing db_select('table')->fields() ...
// caveat the db_select->fields() method doesnt allow aliasing, you have to
// add fields to your query via addField()
$query = $db->select('some_table', 'some_table_alias');
// Then add to your select query as needed.
$query->addField('some_table_alias', 'foo_bar', 'fooBar');

```

Some other notes:

* Without getting reallllly creative I dont think you can do this using db\_query(). db\_query() is a simple helper method to the default database connection (not any db) and I'm not sure you can Database::getConnection()-\>query("...");
* You could try to set this globally in drupal in your settings.php by using a patch https://drupal.org/node/726192 to allow abritrary PDO attributes to be set on the database connection defined in settings.php. I dont recommend this.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Use Privatemsg admin form in theme (Missing functions!)
I've exposed the privatemsg\_list\_view() form in my site theme with a bit of work and it's displaying well. However, updating message statuses or trying to delete bulk messages results in a sad error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText: Fatal error: Call to undefined function privatemsg_list_submit() in [...]/includes/form.inc on line 1464

```

Now I know that privatemsg\_list\_submit() is indeed set as the form #submit handler and I know that it *does* exist, over in `modules/privatemsg/privatemsg.pages.inc`. Obviously there is a disjoint between /system/ajax and my template.

What needs to happen to make this work? Do I just have to attach the .inc file to the form handler somehow? I've tried playing with module\_load\_include() to no avail.

Suggestions?

**Update**: The only place I have tried adding the `module_load_include()` function is directly before the function call in /includes/form.inc - that would have been somewhere just before line 1464. Obviously that was just a hack for troubleshooting purposes... should the `module_load_include()` function be placed somewhere else?

For reference: Call to undefined function privatemsg\_list\_submit()

**Update 2**: I have also tried inserting `module_load_include()` in a custom module\_init() function as well as inside the theme `hook_form_alter()` \- no luck.

**Update 3**: Manually including the file within a `module_init()` hook makes it work. Here's what it looks like:

```
function MYMODULE_init(){
    if($_GET['q'] == 'system/ajax'){
        if ( preg_match('/privatemsg_list/', $_POST['form_id'])) {
            include('/great/big/system/path/web/sites/all/modules/privatemsg/privatemsg.pages.inc');
        }
    }
}

```

While this appears to work on the surface, I'm sure it's not the right method. Is there a better function hook to use to include this file?

# Answer
> 0 votes
Though I suspect that this is an improper workaround, the solution was to hook a custom module's hook\_init() function, watch for a system/ajax path and include the file if needed:

```
function MYMODULE_init(){
    if($_GET['q'] == 'system/ajax'){
        if ( preg_match('/privatemsg_list/', $_POST['form_id'])) {
            include('/great/big/system/path/web/sites/all/modules/privatemsg/privatemsg.pages.inc');
        }
    }
}

```

**UPDATE**: Answer is available at https://drupal.org/node/1961776! In short: use `form_load_include()` instead of `module_load_include()`.

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


# Question
Title: How to inspect a variable when testing with `drush test-run`.
When testing with my SimpleTests, I want to inspect a variable. `var_dump()` and the likes are not being rendered in the output of Drush, Xdebug interactive debugger does not work due to the simulated browser being ran in `DrupalWebTest`.

How can I render, export, inspect or otherwise dump the contents of a variable in my code? I.e. the `DrupalWebTest` of `dpm()`, `var_export()` and such.

# Answer
The documentation for Troubleshooting Tests has a number of insights:

1. Use `debug()` in Drupal 7. This will work during testing, and display the output right in your test results.
2. Print them with a test that always passes (using something like `$this->pass(var_export($var, TRUE));`). It's a bit of a kludge, but it'll work in the absence of anything else.
> 2 votes

# Answer
Call DrupalTestCase::assert() passing the message to show.

```
$this->assert(TRUE,
  t('Variable content: @variable', array('@variable' => var_export($variable, TRUE))
);

```

This is similar to the code used by DrupalTestCase::assertIdentical(). The difference is that in your case the first argument is `TRUE` because you are just outputting the content of a variable, which never fails.

```
protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
  return $this->assert($first === $second, $message ? $message : t('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
}

```
> 2 votes

# Answer
Have you tried `print_r($variable)`? For a human friendly output you could try

```
print '<pre>';
print_r($variable);
print '</pre>';

```
> 0 votes

# Answer
I can suggest 2 solutions

1) you can use watchdog.

`watchdog($type, $message);` Just put your variables with custom type name like:

```
watchdog('drush_test_run', print_r($message));

```

2) you can create some file `log.txt` and write variables into it with php file functions.
> 0 votes

# Answer
Any of these answers would be OK under most circumstances except that the problem I was having with a specific test case was do to the fact that I implemented an `exec` call and that function captures all output.

In my case I replaced the `exec` call with `passthru` and that fixed the issue for me.
> 0 votes

---
Tags: debugging, testing, drush
---


# Question
Title: Usernames in git commit messages on Drupal.org
I recently changed my username on drupal.org, and as a result is now different from my git username.

When you attribute a patch someone else using the commit author, you use the anonymous email address, which is based off of the git username (which also shows up in that user's profile page.

When you can commit directly to a project, there is a standard format for commit messages:

> Issue #\[issue number\] by \[comma-separated usernames\]: \[Short summary of the change\].

Are these supposed to be the git username or the drupal.org username?

# Answer
The usernames are the usernames for the Drupal.org accounts, not the git usernames.

The reason is simple: Everybody can provide a patch, even the users who don't have a git account. As far as I recall, everybody can have read access user to a Drupal.org git repository. You can create a patch that solves an issue; once the issue has been resolved, or the feature request implemented, the git commit will report the usernames of those who contributed with a patch.

The other reason for using the Drupal.org usernames is that not every users see somebody else's git username, and it is more practical to use what is visible in the issue where the patch is being discussed.
> 4 votes

---
Tags: version-control, community-official-site
---


title: Convert Uploaded Files To .pdf

text:
# Question
Title: Convert Uploaded Files To .pdf
I'm reviewing a spec. that calls for all files uploaded via a file field to be automatically converted to PDF format. I have two questions:

1. Is this wise? Files would be uploaded by anonymous customers. Allowed file extensions (.doc, .xls, .png, .jpg, etc) would be provided as per normal file field use.

(Edited to clarify my main concern is security)

1. Are there any conversion tools you would recommend? Paid or free is fine. Remote service is fine, local server-based is preferable. I can't find anything in the Drupal-verse, but have uncovered tools such as `unoconv` and `JODConverter` that look promising.

# Answer
Personally, I would store the file as it was uploaded, and then render it as a PDF for users when they download it. Your spec may say PDF *now*, but you want to have the flexibility should things change *in the future*.

Is this a good idea? That is a tough question, and really depends on the exact scenario. Personally, I would push back on this requirement. Format conversion can tax system resources, and I don't think you can really constrain the .doc and .xls formats enough, like you can with images, to be something reasonable.

Tools? The Printer, email and PDF versions module has a list of of the PHP-based PDF modules:

I am unaware if any of these will support .doc or .xls formats. I have used Ghostscript to convert images to PDF, and I am pretty sure it has some support for .doc. I am unaware of any Drupal-ready solution for this, though.

As for security implications, the scenario "makes my spidey sense tingle", but I can't point to anything in particular. I don't think you would have any problems with any of the malicious payloads in .doc and .xls files that normally affect Windows machines. However, if you go with a solution like GS, you will have to use a `popen()` or something similar, so you run the risk of an exploit there.
> 3 votes

# Answer
See if https://github.com/delphian/drupal-convert-file/wiki fits your needs. It will make a backup of the original file, and uses remote providers (currently google drive) to do the actual file conversion. The google drive provider will convert .doc .xls and .txt to .pdf.
> 1 votes

---
Tags: 7, files
---


# Question
Title: theme_table drupal 7 issue - operator not supported for strings in theme.inc
Although i have found the fix of this problem, but i thought of sharing with others.

Problem is if you mention $rows & theme\_table like following:

```
$row[] = array('data' => drupal_render($form[$key]['alt_name']), 'class' => 'alt-ing-name-td');

$output = theme_table(array('header' => $header, 'rows' => $rows,'attributes' => array('id' => 'recipe-id')));

```

then you will get following error:

```
Fatal error: [] operator not supported for strings in theme.inc

```

# Answer
> 3 votes
To fix this problem you need to mention class & id values in array. PFB, the corrections:

```
$row[] = array('data' => drupal_render($form[$key]['alt_name']), 'class' => array('alt-ing-name-td'));

$output = theme_table(array('header' => $header, 'rows' => $rows,'attributes' => array('id' => array('recipe-id'))));

```

Hope this will help.

---
Tags: 7, theming
---


title: Certain roles creating users

text:
# Question
Title: Certain roles creating users
I am spinning up a site that will have 18 different organizations interacting together. Each organization has a president with access to specific forms and parts of the site. I would like them to be able to create/add users from their own organization.

Where I am stuck is that each president should only be able to edit/remove users from his own organization (aka that he created). Do I need to create 18 different roles for each president and 18 different roles for members from their organizations, or is there a more convenient way of managing this.

I have reviewed the following modules without success: Protect\_critical\_users, role\_delegation, administerusersbyrole

Thanks.

# Answer
> 1 votes
You need not to create different roles for each user but one user role will serve the purpose with help of SUBUSER module. Though it's in alpha stage for D7 but it has served me well for a project where I am handling organization as users. You will need to give proper permission though, I hope you can play with that.

---
Tags: users
---


title: Draggable view with sections

text:
# Question
Title: Draggable view with sections
I need a draggable view that includes draggable sections, where both sections and rows are draggable (see image for reference). The sections are not entities on their own. Ideally, the sections would map to a field attached to the entities being output in the view so that they would be available in views, theming, etc. See attached image for reference.

Is there anything in the drupal world that does this today? Looking for ideas or examples on how best to approach this requirement.

Edit Jan 7, 2013 - this is what I have so far, using entity reference, field collection , and field collection table modules, per user user5950's answer below. It's not exactly what I want, and it becomes slow as you add a lot of items (a lot slower to edit a node with 50+ items), but it is functional.

# Answer
I am using the module Entity reference in conjunction with Field collection to achieve that goal. That means you

1. add a node with an Entity reference field, where you save the rows (if they actually are entities in your case),
2. attach that Entity reference field to a Field collection.
3. Now you can use the delta value of the Entity reference field to sort the row and the delta value of the Field collection field to sort the sections.

Note! You can use core's node edit form as sorting interface. If you would like to have more than one sort you could do that adding a node for each sort. Draggable view becomes useless that way.

Here is an example:

If you want to have an interface, which does not allow to alter other data than the order you could replace the autocomplete field with text an remove the buttons with hook\_form\_alter().
> 3 votes

---
Tags: views
---


# Question
Title: How do you disable modules in bulk via Drush matching a specific pattern?
Currently I have to disable all of the ubercart modules in bulk, but there are too many of them to do it one at a time via the modules page. And doing it via drush doesn't disable every module related to ubercart sometimes. Is there a quick way to disable these modules via Drush in bulk matching a specific pattern?

# Answer
> 6 votes
Here's the drush recipe combined with a few other commands to disable modules in bulk:

```
drush pm-list | ack uc_ | ack Enabled | grep "\((.*)\)" | awk -F'(' '{print $2}' | awk -F')' '{print $1}' | xargs -i drush dis '{}' -y

```

**Broken down:**

1. `drush pm-list` lists out all of your modules
2. `ack uc_` returns only the lines matching "uc\_"
3. `ack Enabled` returns only the enabled modules
4. `grep "\((.*)\)"` matches the words in parentheses
5. `awk -F'(' '{print $2}'` breaks up the line starting with the `(` character
6. `awk -F')' '{print $1}'` breaks up the line starting with the `)` character
7. `xargs -i drush dis '{}' -y` runs the returned result into drush disable command with the `-y` parameter for yes to all.

---

Thanks to greg\_1\_anderson, I updated it to be a bit shorter.

```
drush pm-list --status=enabled --pipe | grep 'uc_' | xargs -i drush pm-disable '{}' -y

```

---
Tags: 7, drush
---


# Question
Title: get the permission must the user have to access to the 'Access denied ' page
i'm working on a drupal 7 online payment module ,

and i need to know if there is a Drupal 7 function that can track (each time and for all the users) if 'the logging online user' is requesting an 'Access denied ' page , and then get the permission must the user have to access to that page

> PS: i'm creating a drupal payment module , the payment will be by roles , for exemple ( user1 can create 'Blog content type' just if he has the permission on that, if not i i need to know which 'Access denied ' page he is in and it's role so i can show him a message to buy this role depending on the price in the database) all what i need is the string permission of the page

thanks in advance ^\_^

# Answer
The only answer I can think of is to roll this functionality yourself with some coding in a custom module.

You probably want to use Chain Menu Access and the drupal API function user\_role\_permissions.

You can use the chain menu access api to put a fired-last menu access check that does some comparisons over previous access checks and Roles:

```
<?php
  chain_menu_access_chain($menu, 'an/existing/path', '_mymodule_new_access_callback_check_permissions_to_roles');
?>

```

Then use the drupal api user\_role\_permissions to see what Role has X permission that was failed in a parent-chained access callback. You could store that for example in the users `$_SESSION` data. Then write a custom 404 page that shows them purchase options.
> 0 votes

---
Tags: 7, users
---


title: Intermittent silent login failure

text:
# Question
Title: Intermittent silent login failure
A knowledgeable user had a strange login problem today. Our site is using LoginToboggan.

1. User went to directly to a URL requiring login (clicked on a link a in an email), but was not logged in.
2. User got 403 page, Access Denied, as expected. I have 403 pages set to go to `/toboggan/denied`.
3. User typed in name and password (or browser had it memorized) and clicked "Log in"
4. User went to a 403 page again. This happened repeatedly.

The user tried two other browsers, cleared cookies, etc. Eventually he tried our usual login page, which has a regular login block. That worked fine.

I tried this myself several times, and was able to reproduce it exactly once. I noticed at some point during multiple failures that the URL on the 403 page was *not* the original URL, but was `/user/logout`. It was as if I was sort of half-logged-in or half-logged-out.

Since then I've tried numerous variations on this and haven't been able to duplicate it. For the user, it happens consistently. I went over the user's browser settings and they don't seem to be unusual (he accepts third-party cookies, etc.).

Suggestions welcome as to what else to check for.

# Answer
I believe this was due to the user logging in as http://example.com and then trying to access a link (from an email) to http://www.example.com/page-that-requires-a-login. In addition the user had a bad browser-memorized password for http://www.example.com, though his password for http://example.com was good. This apparently caused an odd loop of login failures.

I have uncommented the Drupal-supplied redirects in `.htaccess` that force all http://www.example.com URL's to redirect to http://example.com versions, and have told all my users they may need to re-memorize their passwords in the browser.
> 0 votes

---
Tags: 7, users
---


# Question
Title: In Drupal Commerce, what Rules need to be set to go directly to checkout after Add to Cart button is clicked?
On a fresh drupal commerce install, clicking on add to cart brings your back to the same page. What is needed in Rules to have it go straight to checkout after clicking on the **Add to Cart** button?

# Answer
Since this isn't built into Drupal commerce itself, you have to create a new custom rule (admin/config/workflow/rules). The event would be called:

**After adding a product to the cart**

and then the action would be:

**System \> Redirect Page**

**URL should be:** checkout
> 6 votes

---
Tags: 7, commerce
---


title: Testing the values of Views fields

text:
# Question
Title: Testing the values of Views fields
I have a View that displays four types of field (`field_ba_before`, `field_photo_gallery`, `field_body_image`, `field_image_position`).

In my `views-view-fields.tpl.php` file, I have created a variable called `$class`. I want the variable of `$class` to change according to the values of the four fields.

Not every Views row result will use all of the fields, so in my code, I have used IF statements to check if the field exists.

This is my code:

```
<?php if(($fields['field_ba_before']-> content || $fields['field_photo_gallery']-> content)): ?>
<?php $class = "content-aside-layered"; ?>
<?php else: ?>
<?php if (($fields['field_body_image']-> content)): ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_right'): ?>
    <?php $class = "content-aside"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_left'): ?>
    <?php $class = "aside-content"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_bottom'): ?>
    <?php $class = "content-aside-layered"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_default'): ?>
    <?php $class = theme_get_setting('body_image_position'); ?>
    <?php endif; ?>

<?php endif; ?>
<?php endif; ?>

<div class="<?php print $class; ?>"> </div>

```

I am not sure why it is not working. Is there a special way of testing the values of Views fields? Thanks for any help that can be offered!

# Answer
Views provide to the template the html output of the field and not the actual value or a means to detect if it is empty or not. You will thus need to compare the field-\>content value with the expected html output. Assuming that you use Drupal 7 and you haven't overriden the field output or you haven't set the field as hidden ("exclude from display" option), the default field output is:

```
opendiv class="field-content"> ... html output here ... closediv>
```

Steps to achieve what you're trying to:

1) Add a function like the following: (replace "opendiv" and "closediv" with html open and close div tags, I couldn't get the editor not to filter them)

```

function mymodule_views_field_compare_value($field, $expected_value) {
      if ($field->content == 'opendiv class="field-content">'.$extected_value.'closediv>') {
          return true;
      }
      return false;
  }

```

2) To check if a field is not empty do:

```

if (!mymodule_views_field_compare_value($fields['field_ba_before'], '')) {
}

```

3) To check the value of the image positioning:

```

if (mymodule_views_field_compare_value($fields['field_image_position'], 'image_position_default')) {
}

```

This should help. You can use dpm($fields\['field\_image\_position'\]) (if you're using the devel module) or var\_dump($fields\['field\_image\_position'\]) to check the actual output of the field, in case it is different than just 'image\_position\_default', I don't know what type of field it is.
> 2 votes

---
Tags: views, theming
---


# Question
Title: Reducing redundancy (code duplication) in templates
The front page of my site needs a very different layout to every other page on the site, so I want to use `page--front.tpl`. However, the front page still has many of the standard regions, and shares the same `main_menu` as the rest of the site.

I have just tried moving the shared "outer" parts of my `page.tpl` (including `main_menu` and `page_bottom`) into the `html.tpl` because I want to use `page--front.tpl` without duplicating code if possible.

Unfortunately, many of these variables, notably `main_menu` are defined only for `page.tpl`, so I've had to hack it into `X_preprocess_html`. This makes me nervous because I don't know what other variables I might be missing: I basically want to refactor it to avoid code duplication.

Am I going about this the wrong way? Or if not, how can I be sure I still have all the variables and regions I need pushed up to `html.tpl`?

# Answer
> 0 votes
Yep, you can do it in a simple manner, just follow this

It simply states you can (for example) use `<?php include 'page.header.inc'; ?>` on a template and include the code for that header. In this .inc file you just enter the code you want to reuse

---
Tags: theming
---


# Question
Title: is it possible to add a permission to only one user , without creating role for him?
i'm trying to create drupal 7 module for online payment , it will be by roles , for exemple ( user1 can create 'Blog content type' just if he has the permission on that) so after the payment i want to add that role to that user so i can avoid the each time creating roles for the users

thanks ^\_^

# Answer
> 0 votes
Assuming you're using Ubercart this would be super easy by using hook\_order through your own module: http://www.ubercart.org/docs/api/hook\_order. I do this exact same thing with one of my other sites.

I can't go into it all, but essentially it flows like:

```
//make sure the order is complete and payment is received:

function sitetheme_order($op, &$arg1, $arg2) {
{
 // on the final update check this order
 if ($op == 'update' &&
     $arg1->order_status == "payment_received" &&
     $arg2 == "completed")
 {

```

In order to keep this short I can't include everything, but I have short loop written that loops through the order until it meets a condition like "Tickets". Then, I'll assign a role and do some other stuff. Like:

```
//If they bought tickets, assign them the role "TicketHolder"
if ($node->type == 'tickets') {
  //I assign some vars, for example the ID of the user role:
   $ticketUser = $node->uid;
   $customerRole = 16;
   //Assign this user the "TickHolder" role after the sale is complete
       $data = array(
       'uid' => $ticketUser,
       'rid' => $customerRole,
        );
   drupal_write_record('users_roles', $data);

```

That would be it. In your case you check to see if they purchased rights to create blog content, then assign the role.

---
Tags: 7, users
---


# Question
Title: hook_path_update (and insert and delete) not getting called
I've added the following methods to my module, saved, and flushed all caches on my site. I have double checked that my module is enabled and working properly in all other respects.

```
function xxxxxxx_path_insert($path) {
  kpr($path);
  var_dump($path);
}

function xxxxxxx_path_update($path) {
  kpr($path);
  var_dump($path);
}

function xxxxxxx_path_delete($path) {
  kpr($path);
  var_dump($path);
}

```

I want to receive notifications when content path aliases are updated so that I can store some info about them for my custom module. I just put these shell methods in place to ensure I was getting the hook calls and to double check the structure of the $path variable.

Then I edited an existing piece of content. I changed the title and saved the node. Since I'm also using pathauto, that module updated the content path alias to point to a new url based on the new title. I did not receive any of the calls.

Ok, so I figured maybe the auto generation of the alias was the problem, so I edited the piece of content, disabled the auto generation of the path alias and changed the path alias to something by hand. Then saved the node. I did not receive any of the calls to the above hooks.

What am I doing wrong? Why aren't these hooks getting called?

The hook documentation for your reference: path.api.php

# Answer
*sigh* I flushed all caches a TON of times and it would never call my hooks. I had to completely disable my module, flush all caches, and then re-enable my module.

Then the system saw my hooks.

*sigh*
> 0 votes

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


title: Create a slideshow from external links

text:
# Question
Title: Create a slideshow from external links
Is it possible to create a slideshow using( slideshow module or views slideshow module or anything else) external image url's instead of downloading the images, then uploading in the image field?

Also I'm looking for a functionality where there are some image fields( containing uploaded images) and some external image links but all need to be shown in single slideshow.

I've googled this but could not find anything useful ..

# Answer
> 1 votes
The Embedded Image Field module supports third party image content and also you can integrate with views.

Also look into below module

Remote stream wrapper Provides the ability to use external files with file fields without saving the files to your local files directory. Also provides a 'Remote URL' browser plugin for Media. see DEMO

---
Tags: 7, javascript, views
---


# Question
Title: Cannot change CSS after CSS/JS aggregation
I'm using D7, recently I checked all the bandwidth optimization option in **admin/config/development/performance**, I wanted some change-back in CSS afterwards, which now I can't with the bandwidth optimization being checked. I tried unchecking that bandwidth optimization, then it accepts the new change. But when I check the bandwidth optimization again, it takes me to an older version of CSS, Please let me know how to update the CSS as well as checking all the optimized radio buttons.

# Answer
CSS/JS aggregation's purpose is to bundle all your non-external css/js files into a single file. This way instead of requesting multiple files and requiring multiple connections with the server, the client only has to download the unified css/js file once. However, this specific file is not re-created every time you make a change to your css or javascript. You will have to manually do it. Here is how:

In Drupal 7 go to: **Administration \> Configuration \> Development \> Performance (admin/config/development/performance)**

and click the "Clear all caches" button. Notice that this will clear all caches of your site.

The method that I use more often though is to clear all the caches through Drush (if you do not know what Drush is, you should really check it out since it's a real life saver). Instead of navigating to the URL and clicking the button, you can just write the simple command:

```
drush cc all

```

in your command line and all caches will be cleared.

Keep in mind, that if you are still theming/developing your site, you should disable CSS/JS aggregation. If you don't, you are adding more workload to the server that is rebuilding the unified css/js files every time that you press the "Clear All Caches" button. The specific option should only be turned on on production sites where css/js files have been finalized.
> 2 votes

---
Tags: 7, theming, css-js-aggregation
---


# Question
Title: Identifying drupal installation on windows
I don't want a google custom search to be shown on my development system which is on windows but it should be visible when on production system which is on Linux.

How do I check it?

This isn't working out. I've placed this code in the block "Pages on which this PHP code returns TRUE (experts only) " but it does not work in my Windows installation:

```
<?php
if(  file_exists("C:"))
{
return false;
}
return true
?>

```

# Answer
> 2 votes
You can achieve this by implementing the php\_uname() function:

```
$os_name = php_uname("s");
if($os_name == 'Linux') {
  return TRUE;
}
//can apply additional checks for other OS
else {
  return FALSE;
}

```

---
Tags: 7, blocks
---


title: Loading a form by ajax

text:
# Question
Title: Loading a form by ajax
I've been stucked on problem since two weeks. Basically, what i'am trying to do is: 1) Create a page, in which there is an link ("Click me"), When i click on it, a form is fetched from another page and added to the current page. The form is correctly fetched, but it seems any javascript/ajax related to the form is lost. I have a custom Ajax submit callback for this form, on the page of the form(submit button has class ajax-processed), it is working correctly but when fetched by Ajax(submit button does not has the class ajax-processed), it doesn't.

Below is my code:

```
<?php

function custom_preprocess_page(&$vars){

  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'drupal.form');
    drupal_add_js(drupal_get_path('module','custom').'/custom.js', 'file');
}

/**
 * Implements hook_menu
 * @return string
 */
function custom_menu() {

    $items['my-test/my_form'] = array(
        'title' => 'Ajax test',
        'description' => 'Page containing form',
        'page callback' => '_custom_retrieve_webform',
        'access callback' => TRUE,
    );

    $items['my-test/retrieve_form'] = array(
        'title' => 'Ajax test',
        'description' => 'Page where form should be loaded by ajax',
        'page callback' => '_custom_retrieve_html',
        'access callback' => TRUE,
    );
    return $items;
}
function _custom_retrieve_html(){
    return '<div id="justadiv"><a class="clickme">'. t('click me'). '</a></div>';
}
function _custom_retrieve_webform(){

   $node = node_load(12);
   $submission = (object) array();
   $enabled = TRUE;
   $preview = FALSE;
   $form= drupal_get_form('webform_client_form_12', $node, $submission, $enabled, $preview);
  return '<div id="myform">'.drupal_render($form).'<div>';
}

function custom_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_12') {
        $nid = $form['#node']->nid;
        $form['submitted']['gender']['#default_value'] = 'M';
        $form['actions']['submit']['#ajax'] = array(
            'callback' => 'mymodule_webform_js_submit',
            'wrapper' => 'webform-client-form-' . $nid,
            'method' => 'replace',
            'effect' => 'fade',
        );

       //$form['#theme']=array('custom_web_form');

       array_unshift($form['#theme'], 'custom_web_form');
    }
}

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {

        dsm($sid);

        $confirmation = array(
          '#type' => 'markup',
          '#markup' => 'sucess',
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }

```

My js:

```
(function($){

    Drupal.behaviors.my_custom= {

        attach:function(context,settings){
            $('a.clickme').click(function(e){
                $('#justadiv').load('/d7/my-test/ajax_loaded #webform-client-form-12', function(response, status, xhr) {

                    Drupal.attachBehaviors('#webform-client-form-12');

                });
                Drupal.attachBehaviors($('#webform-client-form-12')[0]);
            });

        }

    }

})(jQuery)

```

CAn anyone tell me what is wrong ?

# Answer
> 2 votes
Solution posted here:

basically:

> You need to generate the javascript settings for the form, and send them to the browser to be merged with the existing settings. Without doing this, any AJAX on your form will not work.

https://drupal.org/node/2009252

---
Tags: forms, ajax, nodes
---


title: Creating Views based on html source

text:
# Question
Title: Creating Views based on html source
Is it possible to create a view from third-party source that includes html, js and css?

Example: http://www.addyosmani.com/resources/shinetime/

I want to create a view of the example shown in the link and display it as a block on my site. Is there an automated process for doing this or I would have to do it manually? If manually then how? Thank you

# Answer
If all you want to do is display that in/on your website, include it in an iframe, eg, create a block that just has:

```
<iframe src="http://www.addyosmani.com/resources/shinetime/"></iframe>

```

in it.

Now, if you are wanting to create a View, eg http://drupal.org/project/views, then you need to give some more specifics of what you are wanting to do.
> 0 votes

# Answer
If i didn't get you wrong, you want to have this kind of block with your fields with the help of views. There are no automated process for this.

You got to copy or download the source of this stuff (the markup, js, css). In my humble opinion the easiest way to do this with views is just having your needed fields (title, images) and then overriding the html output of these fields to fit your css and js selectors. Also you can set classes and markup in the format and fields settings in the view created.

There is also different method: hide all of your fields and leave the lowest one. Check to override the output of it and put the markup you need, replacing titles and images, description and other with your fields which would be listed below in the patterns examples.
> 0 votes

# Answer
In my opinion, you can create a basic page and code the PHP + HTML code. (You must enable PHP filter in module page)

For the php code, you create a SQL statement to get the data that you want, for example, db\_query in Drupal
> -2 votes

---
Tags: views, blocks, javascript
---


# Question
Title: How to migrate drupal6 ubercart to D7 commerce
I have a website in D6, and ubercart is used now i want to upgrade the site to D7 but with commerce. How can it be done?

# Answer
You probably want to look at Commerce Migrate together with Commerce Migrate Übercart that respectively understand how to create Commerce content and read Übercart content.

Commerce Guys already wrote two blogposts, Part 1, and Part 2, on the difference between the two.
> 1 votes

---
Tags: commerce, ubercart
---


# Question
Title: How to make DrupalChat more stable, to have it recognise online users?
Never had any luck with the DrupalChat module. It is always flickering on and off, saying other users are currently offline when they are on.

Does anyone have any tips or tricks for making DrupalChat stable?

# Answer
In the module config page `admin/config/drupalchat/configuration` see **Chat List Latency** says

> The delay, in seconds, after which the user will be shown offline in the chat list(i.e. removed from the chat list) from the time he/she goes offline. Increase this value if you find the chat list is unstable and keeps on changing a lot (for example - when a user navigates from one page to another he/she goes offline and then comes back online again). Decrease it if you find that the users are shown in the chat list for too long after they have left your website.
> 2 votes

---
Tags: 7
---


title: Node edit layout based on Role

text:
# Question
Title: Node edit layout based on Role
I want Authenticated users to be able to add content (a custom content type). However, they should not see all the fields.

Users with a Role of "manager", should be able add/edit this content type, and see all the fields.

I've created a custom module, using hook\_theme and hook\_form\_alter to hide the display of fields, but i don't know how to do this based on user or role. With the module active, even the admin user is blocked from seeing all the fields.

What is the best way to setup a custom node edit form based on Role, or at minumum, bypass for the Admin user?

For example, I have hide the form fields in erp\_reco--node-form.tpl.php, and hide the revision, author, comments etc in hook\_form\_alter.

How do i hide fields then based on Role?

```
 function cct_erp_reco_theme($existing, $type, $theme, $path) {
return array(
    'erp_reco_node_form' => array(
        'arguments' => array('form' => null),
        'path' => drupal_get_path('theme', 'ERP').'/templates/forms',
        'template' => 'erp_reco--node-form', 'render element' => 'form',
    ),
); }

function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'erp_reco_node_form') {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

```

# Answer
as @Human love mentioned there is a module out there to accomplish this Field Permissions. There is usually a module to do just about anything in Drupal -- but therein lies the problem; 80+ modules later you may regret installing so many modules.

There are plenty of examples of leveraging Drupal Core and not just using 3rd party contrib modules to meet your needs to keep a lean(er) codebase. Here's an example with EFQ from Phase2 in place of using Views.

That being said you just need to check for a UID or Role in your `hook_form_alter`. See the next 2 examples:

```
function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
  global $user;
// Allow admin.
if($form_id == 'erp_reco_node_form' && $user->uid !== 1) {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

```

Or:

```
function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
  global $user;
// Dont show items for SOME_USER_ROLE.
if($form_id == 'erp_reco_node_form' && in_array('SOME_USER_ROLE', $user->roles)) {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

```

Ideally the contrib module will be more flexible in the long run for many many content types etc. But, if you understand your own requirements then this is perfectly fine.
> 3 votes

---
Tags: forms
---


# Question
Title: What is an alternative and easy way to test if Webform is in fact sending mail?
I'm not sure if its the webform module or my server, but a few days ago i was receiving webform submissions via email, but today its not working when I did a test on the same webform. Is there a easy way to test if its webform that's the issue or my server?

# Answer
> 1 votes
Try one of the Mail Logger or Maillog modules. That will enable you to see whether there is an email actually being created. I personally used to use the second, with D6 though.

---
Tags: 7, webforms, emails
---


# Question
Title: How to convert an HTML website to Drupal 7 nodes?
I have a website that I want to move to Drupal 7. It is in HTML. I want the content to be in nodes. I don't know much about Drupal and so I need help doing this. I don't want to create a new theme because I want the design to change. I just want the content in nodes. How can I do this in Drupal? Is there a module that can help?

# Answer
> 1 votes
You don't necessarily need a module to add a content to drupal. Just simply create a content of type page and add your content. To help you with formatting, you may want to install the WYSIWYG module to help you with formatting.

# Answer
> 1 votes
The module I used (several years ago) was the Import HTML module. I imported a site into Drupal 5 and it worked well. There is a Drupal 7 dev version, but I have no experience with it.

If you use it, plan and prepare well, and you can expect a considerable amount of manual editing after the fact. You may have to try a few times before you get it right, but for a bulk import, it saved me a lot of work.

---
Tags: nodes, theming
---


# Question
Title: Trying to display a views list with order based upon current node being viewed
I have a view block which shows lists of content type "news" which displays in a sidebar showing only the node title for users to peruse.

There are about 150 such "news" nodes and so I use pagitation.

These "news" nodes are completely linear. You always want to read them in order. So if you read node/20, you must read node/21 next, then node/22 etc.

I would like the view block in the sidebar to display the titles of 2 nodes BEFORE and AFTER the current node. So, if I went to node/20, I would like the view block to display:

* Title of node/18
* Title of node/19
* Title of node/20 (current node being viewed)
* Title of node/21
* Title of node/22

I was hoping for some pointers as to how I might achieve this. All things that I've tried thus far have proved futile.

Thanks.

# Answer
> 1 votes
In your View, under Block Display, go to:

**Advanced-\> Contextual filters (Add)-\>Content: NID**

In the "When the filter value is NOT available" option select:

**Provide default value-\> PHP Code**

and add the following code:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nodeid = arg(1);
  $result = strval($nodeid-2) . "+" . strval($nodeid-1) . "+" . strval($nodeid) . "+" . strval($nodeid+1) . "+" . strval($nodeid+2);
  return $result;
}

```

Last but not least, under "More", select the option: **"Allow multiple values"**

# Answer
> 1 votes
In relation to your comment:

**Limit the output of this view to a particular content type**

```
$nid = $handler->argument;  // the node id from url
$nodes = array();           // an array for node id's
$type = "news";             // content type (mashine name)

// get two previous node id's and the present one
$result = db_query("SELECT nid FROM {node}
                    WHERE nid <= :nid
                    AND status = :status
                    AND type = :type
                    ORDER BY nid DESC
                    Limit 3",
                    array(  ":nid" => $nid,
                            ":status" => 1,
                            ":type" => $type
                            )
                    );
foreach ($result as $row){
    $nodes[] = $row->nid;
}

// get next two node id's
$result = db_query("SELECT nid FROM {node}
                    WHERE nid > :nid
                    AND status = :status
                    AND type = :type
                    ORDER BY nid ASC
                    Limit 2",
                    array(  ":nid" => $nid,
                            ":status" => 1,
                            ":type" => $type
                            )
                    );
foreach ($result as $row){
    $nodes[] = $row->nid;
}

// compose and return the filter argument
$handler->argument = implode('+',$nodes);
return $argument;

```

***"Allow multiple values" has to be selected***

This solution should suit your needs if your are going to show this block only on particular content type ("news" in this case).

---
Tags: views
---