# Question
Title: What are the key differences with Pressflow?
I am currently using Drupal 7. I heard Pressflow is another solution for high performance sites.

If you have experience with both systems, what is the benefit of migrating from Drupal 7 to PressFlow 7? What are the major differences between Drupal 7 and Pressflow 7?

# Answer
The differences with standard Drupal 7 are scattered about the Pressflow wiki though not documented very well, perhaps because Pressflow 7 is relatively new. (There is a comparison chart that has not been updated for Pressflow 7.)

Although it is sometimes said that Pressflow is a drag-and-drop replacement for Drupal because you usually don't have to make many changes to your modules' configuration, to get the most out of it you'll want to set up Varnish, APC, Memcached, etc. This will probably be impossible to do on a shared host; you'll need some sort of dedicated server and SSH access to go this route, and it's unnecessary to do so unless you actually have a high performance site.

If, however, like me you just like trying out new things, you could sign up for a free account with Pantheon (disclaimer: I'm a member), and try out Drupal on their servers. Pressflow, Varnish, etc. all come pre-configured. Pantheon was founded by David Strauss, who also co-founded Four Kitchens, the company behind Pressflow.
> 4 votes

# Answer
I dug in to find all of the differences and looked them up on GitHub and this is what I found:

Here's a full diff as of October 2013: https://gist.github.com/alanthing/6064500
> 13 votes

---
Tags: 7
---


title: CURDATE() return wrong result

text:
# Question
Title: CURDATE() return wrong result
I have write sql query in drupal looks like this.

Let's assume **today's date is 2013-07-24 and total of node is 4**.

```
    $query = "SELECT COUNT(*) amount FROM {node} n
              LEFT JOIN {flagging} f ON n.nid = f.entity_id AND f.fid = '1'
              LEFT JOIN {field_data_field_tarikh_tamat_passport} ttp ON n.nid = ttp.entity_id AND (ttp.entity_type = 'node' AND ttp.deleted = '0')
              WHERE (( (n.status = '1') AND (n.type IN  ('data_pekerja')) AND (ttp.field_tarikh_tamat_passport_value > CURDATE()) AND (f.uid IS NULL ) ))";
$result = db_query($query)->fetch();
print $result->amount;

```

The output of code **above is 3** but with this code **below is 1**

```
 $query = "SELECT COUNT(*) amount FROM {node} n
                  LEFT JOIN {flagging} f ON n.nid = f.entity_id AND f.fid = '1'
                  LEFT JOIN {field_data_field_tarikh_tamat_passport} ttp ON n.nid = ttp.entity_id AND (ttp.entity_type = 'node' AND ttp.deleted = '0')
                  WHERE (( (n.status = '1') AND (n.type IN  ('data_pekerja')) AND (ttp.field_tarikh_tamat_passport_value > '2013-07-24') AND (f.uid IS NULL ) ))";
    $result = db_query($query)->fetch();
    print $result->amount;

```

The different of this sql query is only the value of **CURDATE() and '2013-07-24'**

Can you please explain why the output is different? I need the query to displaying total of node that has date field value greater than today.

# Answer
> 0 votes
Drupal usually stores dates as Unix timestamps, not regular date strings. Have a look at your field\_data\_field\_tarikh\_tamat\_passport table to confirm which data format you're working with. If it's a timestamp, update your query to use UNIX\_TIMESTAMP() instead of CURDATE().

---
Tags: 7, datetime, database
---


# Question
Title: Creating a view from multiple content types where one is optional
Is it possible to display multiple content types within a view that may or may not have a related secondary content type?

I have two content types (A - which contains a title and body field, and B - which contains a title and body field). In this view, content type A will always exist - and I would like to have any related B content types display underneath the appropriate object. It is possible that no content B types will exist for that title, so if that's the case it can move on and display the next content A type info:

(A) Title = New York, body = "Something"
(A) Title = Ohio, body = "Something"
(B) Title = Ohio, body = "An interesting tidbit about Ohio"
(A) Title = Virginia, body = "Something"
...etc...

Any idea how I may go about accomplishing this? I have heard about a References module to explore, but it seems like that would only pull data where that relationship exists, right? And that in my above example, although I would be anticipating three states in my view, references would only show me the Ohio one because that's the only one that also contains a content B type.

Is that correct? Or is my understanding incorrect?

# Answer
> 1 votes
Install the Entity Reference module, and create an entity reference field on your Content Type B. Configure the field to reference Target Type *Content* and Target bundle *Type A*. Lets call the field ref\_to\_a.

Set up a view of Content Type A as a table of fields. Add the *Title* and *Body* fields. Then under *Advanced* add a Relationship. Use *Entity Reference: Referencing Entity* and choose **Content referencing Content from field\_ref\_to\_a** Do not set the relationship as required, as you do not want to exclude the Type A records which do not have a Type B referencing them.

Now add a *Content:Body* field to your view, and configure it to use the relationship you have just created.

This should give you a view which will look like:

```
New York    Something
Ohio        Something   Interesting tidbit
Virginia    Something

```

Adjust your formatting as required, and good luck.

---
Tags: views
---


# Question
Title: what is the difference between "Commerce Product Attributes" and "Commerce Customizable Products"
Commerce Product Attributes

Commerce Customizable Products

What is the difference between these 2 modules.?

I'm creating orders from a view table, without a product display for each product. I've added a text field to a custom line item with "Commerce Customizable Products" module. The line item display shows the fields but I cant find how to edit it. (working on panels btw.)

# Answer
i'm bad in english, but still try to explain.

Product attributes are always set by the administrator, and customer can not change it. For example, if you set a colour as product attribute, you also have to define all possible variants of colors. There is no difference whether you are using conversion rates depending on the color value of the attribute or not.

Customizable products, however, allow the customer to select an attribute value depending on the preference. For example, if you sell T-shorts, you are able to allow customers choose an inscription on a T-shirt, without price changing. Customer may order T-short with any inscription that he wants to.

To be more precise, trying to explain the difference in terms of data structures. Product attributes add fields to commerce product entity, and customizable products add fields to line item entity. So there is the main difference with all the consequences.

Based on my experience:

I use a Customizable products to sell tea sold by weight. Customer allowed to enter any amount of tea in grams, and then i recalculate sell price using rules.
> 1 votes

---
Tags: commerce
---


# Question
Title: How can I programmatically get a list nodes that a user can update?
I'd like to build a list of nodes which the current user is able to update. This is to be used in a site using Organic Groups.

My first hope was that there would be a Views filter that can check that the content is editable. Alas, no.

My second attempt was to use EFQ:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'suggested_listing')
    ->addMetaData('account', $account)
    ->addMetaData('op', 'update')
    ->addTag('node_access')
    ->pager(20);

```

would work, but it seems as though OG isn't setting the update column in `node_access`?

# Answer
> 1 votes
Following may be an inefficient way to do it as compared to EFQ - you first retrieve the nodes using db\_select and check each node using node\_access function, but it works the way you want it.

```
//build db query
$result = db_select('node', 'n')
        ->fields('n')->condition('status', 1)
        ->condition("type","suggested_listing", '=')
        ->execute();

        //fetch each node from database
         foreach ($result as $record) {

                $node = node_load($record->nid);
                //check if current logged in user has an update permission on the node being checked
                if(node_access('update', $node)){
                    //user has update permission to this node
                    var_dump($node->title);
                 }

    }

```

You can do similar thing using Views. Install the Views PHP module - https://drupal.org/project/views\_php. It gives you a PHP filter. After you add a PHP filter, write following code.

```
 $node = node_load($data->nid);

  if(!node_access('update', $node)){
    return TRUE;
   }

```

# Answer
> 2 votes
There should be a view filter like that, but you'll need to use a relationship (Access log: User should do it) then add the filter called User: Permission.

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


title: Node Reference retrieve Field

text:
# Question
Title: Node Reference retrieve Field
I'm using Views RSS to generate custom RSS feed which includes georss

I have to content types `Shops` and `Events` I can get the location fine from `Shops` because it has dedicated location field, but `Events` uses `Node Reference` to generate drop down menu of all `Shops` and has no location field.

How can I access the location of the referenced `Shop` from the `View`? I understand I have to create a relationship, but I'm not really sure where to start.

I'd appreciate any advice.

# Answer
View of nodes where content type = Event.

Add a relationship to nodes referenced via the Shops field.

Add a field for Location using the Shops relationship.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Help with Geocoding and Openlayers missing markers
I have followed this tutorial exactly http://drupal.org/node/1002852 to create a node type with geocoding. I have a default install of openlayers, openlayers\_geocoder. Geocoding appears to be working when editing/saving the node, however the marker (or polygons) do not appear on the node's map.

# Answer
> 4 votes
I have gone through this same problem.

I believe this is happening to you, because you did not set the Openlayers Data Overlay on Views.

And if you did, you did not selected/activated it on your Openlayers preset:

And if you did, you did not map the fields on the openlayers data overlay display settings:

# Answer
> 0 votes
I ran into this problem as well, but in my case it was that I didn't have the proj4JS library downloaded. I ran drush dl-proj4js, cleared caches, and all worked as expected.

---
Tags: 6, javascript, location
---


title: import content types from sql dump

text:
# Question
Title: import content types from sql dump
I recently had a db crash on the site I am currently working on. I was running sqlite, and the crash locked the db. No matter what I tried, I couldn't get drupal to access the database again (killed the process, exported into a new db, reinstalled drupal). So I decided to just migrate it to MySQL. I converted the sql dump from the old database to MySQL syntax without too many problems. I can import my nodes just fine, I cannot however get my content types, panels and views to import.

I have tried dbtng migrate, it recognizes both databases, however it keeps giving me schema errors that I can't get around. ie. destination database does not contain table variable\_store -\> import variable store from sql dump -\> destination database contains table varaible\_store dbtng migrate cannot overwrite table. That is an issue in and of itself, but I digress.

The original site is completely dead, there is no way I can backup from the Drupal UI.

TLDR cannot import content types, panels or views from sql dump.

# Answer
Assuming your SQLite dump is complete, your best bet is probably to try and properly convert it to MySQL format and then restore to an empty database.

There's a good thread over at stackoverflow with information on SQLite to MySQL conversion: https://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql

I would paste a solution from there here, but as it's a sibling site, probably ok to just pop over and try some of those solutions.

Good luck
> 1 votes

---
Tags: 7, database
---


# Question
Title: My subtheme css is overriden by the parent theme. How to I reverse this?
I have created a subtheme and for some reason the css I add in there to override the parent theme doesn't work. THe parent theme's css seems to be prioritized over my new stuff. Is there any way of weighting themes or ordering loading of themes?

# Answer
> 1 votes
I'm encountering the same issue. If I disable the css aggregation I can see that the reason is that my sub-theme's css stylesheet is being `@import`ed before the one(s) from the base theme, which means, of course, that the base theme's styles are overriding mine anywhere where I use the same selectors. Which is crazy. How is this not a problem for more people? Is there something we're missing here?

**Edit:** sure, I can use `!important`, which is what I'm doing as a workaround (and presumably the OP @Nigel Waters could do the same?), but doesn't this rather defeat the purpose to some degree?

# Answer
> 0 votes
Maybe your selectors are off, make sure specificity is good. Use this:

# Answer
> 0 votes
It most likely has to do with the order the styles are loaded- the css loaded last overrides styles that come before.

To correct this, you could add a higher weight to your css if it's called through drupal\_add\_css.

```
drupal_add_css(
      '/path/to/css.css',
      array(
        'weight' => '9999',
      )
);

```

Another option is to override the parent theme's style by identically naming your stylesheet.

/parenttheme/css/style.css will not be used if /childtheme/css/style.css exists.

---
Tags: theming
---


# Question
Title: How to control resource usage of my website?
I'm using drupal 6 website and i don't know to check which module or script uses high resource. Below is the graph for my website Resource Usage from my hosting provider. They intimate me to control the usage. Really i don't know how i am going to solve this. And i am in shared hosting.

Any idea ?

# Answer
> 0 votes
I solved the issue by **upgrading to VPS** and also blocked the **unwanted bots** and limit the bot access.

# Answer
> 2 votes
* Use the Devel module It should show you a list of queries run when the page is loaded and the time taken to run the query. From there you can check which query is coming from which module.
* You can also try a PHP profiler which gives you a lot of metrics.
* Or try disabling your modules one at a time to decide when the load time gets really high
* Another option lies in smarter caching

---
Tags: 6
---


# Question
Title: Is there any way to use a jQuery overlay to confirm/reject node deletion?
When I delete a node (any type of node, presumably), I'd like to have the confirmation happen through a jQuery-like yes/no dialog popping up over the page, rather than being redirected to a separate page with the "This action cannot be undone" message. This being the 21st century and all...

http://bootboxjs.com/ would seem to be a good candidate for handling the dialogs, but the question is how to tie it into the form and node deletion processes, ideally without hacking core and/or patching everything in site. Has anybody thought this through?

# Answer
> 2 votes
You might be able to do that with:

https://drupal.org/project/ctools\_automodal\_admin

> Provides automatic modal support for any hook\_menu() paths that have 'modal' =\> TRUE defined. This makes it easy to add optional modal support in any contrib module and helps reduce the burden on module developers to support modals.

If you added the node delete path, perhaps `node/%node/delete` to the modal paths, it may just work.

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


# Question
Title: Drupal feeds module causing high cpu usage when pulling feeds
I am using the Drupal Feeds module to download the feeds from an external site. I have setup a dedicated content type to pull the feeds and then created nodes of another content type for the individual feed items.

After updating the site recently I noticed that the site was using the CPU continuously so much so that the hosting tech support notified me about it.

I proceeded to limit the frequency with which the feeds were being pulled but the CPU usage remained constant and I was finally forced to disable cron.php.

This never happened before the update.

Checking the dblog I noticed that the JobScheduler initiated the feed pull (I had set the watchdog to print the title of each node being created) and was repeating this scenario every minute 24x7.

I have not figured out what is causing this issue or from where to start?

Any possible solutions guys?

Site runs on Drupal 6.

# Answer
If you are in shared hosting, then it is the right time to upgrade to VPS or Dedicated Server.

I had a same issue How to control resource usage of my website? , better you can remove the unwanted bots. You need to see the **Access Log** in your hosting control panel.

try disabling your modules one at a time to decide when the load time gets really high and remove the unwanted modules and also it delete from modules folder.
> 0 votes

---
Tags: 6, feeds, cron
---


title: Why isn't my view title displaying?

text:
# Question
Title: Why isn't my view title displaying?
I have a view, displaying in a block, with a views-view--VIEWNAME--block-1.tpl.php:

```
<div class="X">
    <h2>
    <?php
        print render($title_prefix);
        if ($title): print $title; endif;
        print render($title_suffix);
    ?>
    </h2>
    ...some view content...
</div>

```

Most of the content in this template has been copied straight from the template given by theme =\> information =\> display template in the view settings.

This displays (with some whitespace differences):

```
<section id="block-views-VIEWNAME-block-1" class="block block-views">
    <h2>BLOCK TITLE</h2>
    <div class="content">
        <div class="X">
        <h2></h2>
        </div>
    </div>
    ...some view content...
</section>

```

Why is the view not displaying the view title inside the `<h2>`? The title is definitely set for the view.

I've put the following code in the view template:

```
print print_r(array_keys(get_defined_vars()), 1);

```

And the result (including "title" at index 30) is:

```
Array
(
    [0] => template_file
    [1] => variables
    [2] => view
    [3] => view_array
    [4] => theme_hook_suggestion
    [5] => theme_hook_suggestions
    [6] => zebra
    [7] => id
    [8] => directory
    [9] => classes_array
    [10] => attributes_array
    [11] => title_attributes_array
    [12] => content_attributes_array
    [13] => title_prefix
    [14] => title_suffix
    [15] => user
    [16] => db_is_active
    [17] => is_admin
    [18] => logged_in
    [19] => is_front
    [20] => rows
    [21] => css_name
    [22] => name
    [23] => display_id
    [24] => header
    [25] => footer
    [26] => exposed
    [27] => more
    [28] => feed_icon
    [29] => pager
    [30] => title
    [31] => attachment_before
    [32] => attachment_after
    [33] => dom_id
    [34] => classes
    [35] => attributes
    [36] => title_attributes
    [37] => content_attributes
)

```

# Answer
Just had the same problem on another site: for some reason the view title (`$handler->display->display_options['title'] = 'Blogs';`) was coming out in the page.tpl.php template `$title`, but not in the views-view.tpl.php `$title` (despite the default template for that page suggesting that it should). Possibly the variable gets undefined after it's used in an "earlier" template? Or maybe the title variable is only set for the view template if the view is being rendered as a block, on the assumption that the page template has already printed the title for the page?

Anyway, the solution is just to do the printing in the page.tpl.php right before rendering the page content (which will likely come from either the node template or a view depending on the page):

```
<h1><?php print $title; ?></h1> <!-- either our view title or our node title -->
<?php print render($page['content']); ?>

```

Of course if you're doing this you need to make sure *not* to print the $title variable out in the node template because if you do that you'll have the title printing twice.
> 6 votes

# Answer
Based on:

```
if ($title): print $title; endif;

```

and that you say that

##

is empty suggest that $title does not have a value.

Take a look at the handbook page "Views 2 theming". There's a section called "Step 4: Identifying Your Template Variables" which outlines how to get a listing of the variables currently defined. You'll need to confirm that $title is defined.

```
print print_r(array_keys(get_defined_vars()), 1);
  // If you have devel.module installed, comment the line above and uncomment the line below
  // dsm(array_keys(get_defined_vars()));

```

Each array key is the name of a variable, so an array key named "foo" could be inserted into the template as:

```
print $foo;

```

If $title is not defined you'll have to dig deeper. Please check back and let us know what you find. We'll help go further in finding $title if you don't have any luck.
> 2 votes

---
Tags: 7, views
---


title: How to customize a form with php?

text:
# Question
Title: How to customize a form with php?
I want to put my form in a table. After some searches I've found this code.

```
 $form['city'] = array(
    '#type' => 'select',
    '#title' => $list_titles['city'],
    '#options' => $list_cities,
    '#prefix' => '<table height= \'30\' width=\'80%\'><tr><td width=\'100\'>',
    '#suffix' => '</td>', '#required' => TRUE,
    '#default_value'=> $node->city
    );
  $form['adr'] = array('#type' => 'textfield', '#title' => $list_titles['adr'], '#required' => TRUE,
    '#prefix' => '<td>',
    '#suffix' => '</td></tr></table>',
    '#default_value'=> $node->adr
    );

```

Where do I put this code?

# Answer
You can use #prefix and #suffix to wrap the form elements in a table. Here's an example:

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

        $form['field1'] = array(
                '#type' => 'textfield',
                '#title' => t('My Field'),
                '#prefix' => '<table><tr><td>',
                '#suffix' => '</td>',
        );

        $form['submit'] = array (
                '#type' => 'submit',
                '#value' => t('Submit'),
                '#prefix' => '<td>',
                '#suffix' => '</td></tr></table>',
        );

return $form;

}

```
> 0 votes

---
Tags: forms
---


title: ajaxifying simplenews subscribe

text:
# Question
Title: ajaxifying simplenews subscribe
is there a way to ajaxify simplenews subscribe to newsletter block? I was thinking of hook\_form\_alter ing it and adding my ajax callback, But its not working.

```
my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'simplenews_block_form_7182') {
    $ajax = array(
          'callback' => 'simplenews_block_form_validate',
          'wrapper' => 'simplenews_wrapper_block',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array('message' => '')
        );
    $form['submit']['#executes_submit_callback'] = TRUE;
    $form['submit']['#ajax'] = $ajax;

```

but now when I trigger the submit button i get `Fatal error: Call to undefined function simplenews_block_form_validate() in /includes/form.inc on line 1460`

# Answer
> 3 votes
Hope this will help you,

In Drupal 7, you can achieve this using **form\_load\_include** OR **require\_once**

Try **form\_load\_include()** OR **require\_once()** in your form alter.

```
function test_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
    case 'simplenews_block_form_ID'://add your form_id
        require_once(DRUPAL_ROOT . "/modules/contrib/simplenews/includes/simplenews.subscription");
        //OR
        form_load_include($form_state, 'inc', 'simplenews', 'includes/simplenews.subscription');
    break;
   }
}

```

Reference

---
Tags: ajax, emails
---


# Question
Title: How to disable error messages to screen while mysql service is down
Our production environment got a problem and the mysql service was down. The all our drupal based sites show the error messages below which expose to many information.

> PDOException: SQLSTATE\[HY000\] \[2002\] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in lock\_may\_be\_available() (line 164 of /home/workspace/drupal7/includes/lock.inc).

I find this page (via) about how to disable drupal errors, but have no effect when mysql is down.

Any one can give me a hand?

# Answer
> 3 votes
Removing `<?php print $messages; ?>` in maintenance-page.tpl.php could fix this, see http://drupal.org/node/332413#comment-2887676

# Answer
> 8 votes
Having just run across the same issue, to avoid hacking the core files you can set the default error reporting level in your site's `settings.php` by adding the following line:

```
$conf['error_level'] = ERROR_REPORTING_HIDE;

```

Since the `error_level` variable is normally set from the database the setting otherwise defaults to DISPLAY\_ALL if MySQL is down.

Note: this means the error level can no longer be configured through the admin interface (admin/config/development/logging).

---
Tags: database
---


title: restric view row by the URL in block

text:
# Question
Title: restric view row by the URL in block
I have a view block disply that contains a list of nodes. i want to restrict Nid's by my url in one field in node.(Similarly, system block visibility) for example i have a field with name `field_visibility` and save node by fill that `gallery`

so, my list in block is:

> view-row-1 =\> \[nid\]-1 =\> field\_visibility ='gallery'
> view-row-2 =\> \[nid\]-2 =\> field\_visibility ='contact'
> view-row-3 =\> \[nid\]-3 =\> field\_visibility ='blog'
> .
> .
> .

so in page **www.example.com/gallery**, in block should be

```
1. [nid]-2
2. [nid]-3

```

and in page **www.example.com/contact**, in block should be

```
1. [nid]-1
2. [nid]-3

```

# Answer
> 0 votes
No need to use `field_visibility`

try this if using Views 3

* Click on the "advanced" tab.
* Click on add under "contextual filters".
* Choose Content:nid.
* Under "when the filter variable is not available, choose "provide default value".
* From the drop down menu select "content id from url".
* Scroll all the way down to the bottom of the window and click on the "More" link.
* Click "Exclude"

---
Tags: views, blocks
---


title: Custom block for contact form

text:
# Question
Title: Custom block for contact form
I have created contact us block ,inside that i have add the html form with form action action="/foldername/contact/". on submit its redirecting to contact page . how to submit the form with out redirecting to contact us page

# Answer
That's how the `action` attribute works, it submits the data in the form (via POST or GET) to the location you specify. You should, as Molot says, use the Form API. Or even easier, the Webform module (in Drupal 7), which allows you to create a webform as a block. Install the module and then

1. Create your webform in a node.
2. Edit the node.
3. Select the Webform tab.
4. Select the Forms settings tab.
5. Select Advanced settings.
6. Switch on Available as block.
7. Save configuration.

If you have a Drupal 6 site, you can use Webform Block.
> 0 votes

---
Tags: hooks
---


# Question
Title: Can you filter views user list result based on the current users role
Is it possible to have the result of a views user list only contain users with a specific role that the current user also has?

I'm not familiar with Views, but it seems to fit the bill for making a better looking and more usable user list than the one that comes standard with Drupal. However, I need to have the user list filtered.

I setup multiple user groups that are identified by a specific role (like groupmember - group A). Admin users of that group have an additional admin role (like group manager), but they should only see users in their own group when using the view.

Can something like this be done? I'm writing modules so I could use the api if that is the way to go. I'm using Drupal 7.

# Answer
> 1 votes
As I understand, you want to create a view which list users which lists only those users who has a specific role or roles that the current user also has. The below approach can be a solution :

1. Add a field 'User: Uid' in your view (Let the view is of type 'Users').
2. Make the field as 'Exclude from display'.
3. Add a 'global php' field and add some code as below under 'VALUE CODE' :

```

$user_load = user_load($data->uid);
$data->user_role = $user_load->roles;
return ($data->user_role);

```

Here, we are getting the roles of each user being rendered.

Here used '$data-\>uid' instead of '$row-\>uid' to avoide issue of returning NID with $row in D7. Although in this case '$row-\>uid' returns correct information.
4. Make the field as 'Exclude from display' as well.
5. Under Filter Criteria add a 'global php' field and add the below codes :

i) Under 'Setup Code' :

```

 global $user;
 $roles = array();
 $view->roles = $user->roles;

```

Here we are getting all the roles of the current user.

ii) User 'Filter Code' :

```

 // Suppose you have five roles in the instance with the 'rid's as saved in
 // 'role' table as : 1 (anonymous user), 2(authenticated user), 3(administrator), 4(hr), 5(web admin)
 // Suppose ROLE you want be matched has RID = 4
 if (isset($view->roles[4])) {// Checking if the current user has the role that you want to be matched with
   if (!isset($data->user_role[4])) {// If the user getting rendered doesn't have that role
     return TRUE;// If TRUE is returned, then that row is NOT shown
   }
 }

```

Note : Considering, 'views\_php' module is installed.

Note : If the current user doesn't have the role that you want be filtered for, then the view will list the default list of users based on other conditions.

Note : Instead of writing the 'rid' in the filter code directly, we can provide an admin menu which will render a custom form with a text field and, admin or user with required access permission, can set any role(s) through that form and save it in a drupal variable, and we can render the role information we want be matched from the variable inside our filter code.

Hope it helps

# Answer
> 0 votes
In `Views`, you can add a block showing those users which have the same roles as current user has:

**An example of view block configuration:**

*The current user has to be autencitaded, so we'll be able to get his roles:*

BLOCK SETTINGS -\> Access: Role | authenticated user

*Now, add contextual filters:*

**User: Roles**

When the filter value is NOT available -\> Provide default value -\> PHP code:

```
global $user;
if ($user->uid) {
  $roles = $user->roles;

  // unset 'authenticated user' ( related users doesn't have to be logged in )
  $roles = array_diff($roles, array('authenticated user'));

  // get roles keys
  $roles = array_keys($roles);

  // compose the arguments
  // in order to displaying only users with exactly the same roles as current user has
  // the arguments will be separated by commas.
  $arguments = implode(",", $roles);
  return $arguments;
}
else {
  return false;
}

```

*Users might have multiple roles, so multiple values have to be allowed:*

More -\> check: Allow multiple values

*That's all for this contextual filter. Save it.*

*Probably, you would need to remove the current user from the view, because he don't need his name on the list. To do that, add next contextual filter:*

**User: Uid**

When the filter value is NOT available -\> Provide default value -\> User ID from logged in user

MORE -\> check: exclude

---
Tags: 7, views
---


# Question
Title: How to implement view with nodes grouped per taxonomy term
I have a content type 'Event' which has a 'Category' content taxonomy field (single selection against respective 'Category' vocabulary). If vocabulary has 3 terms, I want to implement a listing where all 3 terms will always be displayed, along with the newest event for each category (sort by publication date in descending order). Something like this:

**Category 1**

Title of newest event for category 1

**Category 2**

Title of newest event for category 2

**Category 3**

Title of newest event for category 3

What is the best way to implement this with views in Drupal 6?

# Answer
> 1 votes
Desired solution implemented using the Views Grouping Row Limit module. Here is a quote about it (from the module's project page):

> This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field ...
>
> To use this module, simply change the style plugin for your view to the "Grouping Field (with Limit)" option. You will then be presented with options to choose your limit and offset (the offset just controls what row to start on, e.g. an offset of 1 would omit the first row from each grouping field). Please note that in order for this to take effect, you must set your row limit on the actual view to Unlimited.

# Answer
> 1 votes
You must use the group option in the style display. In group option you must select the field taxonomy term. And then you must Exclude from display the field taxonomy term.

# Answer
> 0 votes
https://drupal.org/project/views\_field\_view might be the solution to your issue. Granted it must be used with caution as it adds some extra overhead but ultimately it grants the SELECT FROM SELECT query that solves your problem.

---
Tags: views, 6
---


# Question
Title: Same module for different Drupal versions
I've just started developing Drupal module and have completed the simple "Hello "World" module. The module is working fine on both Drupal 6 and 7.

How can I use the same module on both Drupal 6 and 7, instead of packaging it as 2 separate modules?

# Answer
Sorry, you can't without hacking Drupal's core. By the documentation for Drupal 7 you need to set:

```
core = 7.x

```

in module's info file. At the same time documentation for Drupal 6 requires you to set:

```
core = 6.x

```

Values without `[]` may appear only once, so you cannot write:

```
core = 6.x
core = 7.x

```

And you cannot make a value to be an array, so following also would not be recognized and accepted:

```
core[] = 6.x
core[] = 7.x

```

Safest way to solve it is to keep modules separate, and move common PHP code to a PHP library. With Libraries API it should be pretty easy to do.
> 3 votes

---
Tags: hooks
---


# Question
Title: User profile form make custom form required
I'm trying to use a hook to make a user field (company name) required based on assigned roles so:

```
if($form['#id'] == 'user-profile-form') {
  dsm($form);
  if (!in_array('BPSA user', array_values($user->roles))) {
    $form['field_dealership']['#type'] = 'hidden';
    $form['field_company_name']['und']['#required'] = 1;
    $form['field_company_name']['und'][0]['#required'] = TRUE;
  } else {
    $form['field_company_name']['#type'] = 'hidden';
  }
}

```

It's not working and I can't find any other 'required' form elements?

Ps I know this would only rewrite if the user was not a BPSA user.

Thanks,

Steve

# Answer
Try the following code to set a field to required.

```
$form['field_company_name']['und']['0']['value']['#required'] = TRUE;

```
> 1 votes

---
Tags: 7, hooks, forms
---


# Question
Title: Show all nodes in the Getlocations map with diffrent marker colors per Content Type?
I have three content types with Getlocations Fields and try to get a map with views (type: Getlocations) showing all nodes as marker in the map with different marker colors with "Content Type Markers" activated in admin/config/services/getlocations. I get only blue markers, this is the "Default Content Map marker". What is the trick?

Thanks for help.

# Answer
> 1 votes
There is a bug in getlocations.views.inc line 96 & 97:

```
if (isset($options['node_marker__' . $location['type'] . '__' . $location['field_name']])) {
              $marker = $options['node_marker__' . $location['type'] . '__' . $location['field_name']];

```

You need to strtolower $location\['type'\], then it works:

```
if (isset($options['node_marker__' . strtolower($location['type']) . '__' . $location['field_name']])) {
              $marker = $options['node_marker__' . strtolower($location['type']) . '__' . $location['field_name']];

```

# Answer
> 0 votes
1) Create a views. Inside this views create 3 different **Overlay Layers** (views display name is 'OpenLayers Data Overlay'), one for each content type. You should do this on the same view by overriding each display (recommended).

2) Add a new Openalyers map (admin/structure/openlayers/maps/add). In the *Layers & Styles \> Overlay Layers* section add the 3 layers with the marker types you prefer.

3) On the views described on 1 create a page display with format "Openlayers Map" and select the Map you have created on step 2.

---
Tags: views
---


title: Add nofollow to quicktabs

text:
# Question
Title: Add nofollow to quicktabs
I have set up quicktabs programmatically - all working fine. Code is as follows:

```
    $tabs['overview'] = array(
        'title' => 'Title of tab',
        'contents' => $content,
        'weight' => 2,
    );

```

.. etc

```
    $qt_options = array(
        'style' => 'nostyle',
        'ajax' => FALSE,
        'default_tab'=> 'overview',
    );

    $qt_name = 'project-tabs';
    $qt_project = quicktabs_build_quicktabs($qt_name,$qt_options,$tabs_project);

```

Issue: I need to add a rel='nofollow' to the quicktabs. Are there any attributes option I can pass to the `$tabs` array? Similar to using the `l()` function? I've looked and tried a few things, but nothing seems to work.

# Answer
Unless you want or can modify `$qt_project` and add in the rel to the attributes array of the links, the only way I see is to add in a custom renderer in your module.

This would entail some ctools integration implementing hook\_ctools\_plugin\_type(), some quicktabs integration implementing hook\_quicktabs\_renderers() and then basically copying `QuickQuicktabs.inc` from the quicktabs module to your module's directory structure, changing the name to something appropriate, and then inside, also changing the name of the QuickQuicktabs class to something similar, and then in the guts of that, changing

```
/**
 * Helper function to construct link options for tab links.
 */
protected function construct_link_options($tabkey) {
  $qt_name = $this->quickset->getName();
  $id = 'quicktabs-tab-' . implode('-', array($qt_name, $tabkey));

  // Need to construct the correct querystring for the tab links.
  $query = drupal_get_query_parameters(NULL, array("qt-$qt_name", 'q', 'page'));
  $query["qt-{$qt_name}"] = $tabkey;

  $link_options = array(
    'attributes' => array(
      'id' => $id,
    ),
    'query' => $query,
    'fragment' => 'qt-' . $qt_name,
  );
  return $link_options;
}

```

to most probably just

```
/**
 * Helper function to construct link options for tab links.
 */
protected function construct_link_options($tabkey) {
  $qt_name = $this->quickset->getName();
  $id = 'quicktabs-tab-' . implode('-', array($qt_name, $tabkey));

  // Need to construct the correct querystring for the tab links.
  $query = drupal_get_query_parameters(NULL, array("qt-$qt_name", 'q', 'page'));
  $query["qt-{$qt_name}"] = $tabkey;

  $link_options = array(
    'attributes' => array(
      'id' => $id,
      'rel' => 'nofollow',  // just this one little addition :)
    ),
    'query' => $query,
    'fragment' => 'qt-' . $qt_name,
  );
  return $link_options;
}

```

and then calling `quicktabs_build_quicktabs()` with `'render'` pointing to your custom renderer in the `$qt_options` array.
> 2 votes

---
Tags: blocks
---


# Question
Title: Connecting to multiple databases of different type for form submission
I'm developing a GIS mapping system and for that I am using pgSQL, however I am bounded to using mysql for the drupal install because we use Drupal 6 mulitsites using mysql already. I know I can get around this problem by hard coding using php, html to create my forms that submit to this. I know from Drupal Community Documentation this is not possible as standard. **Is it possible via any other method to utilise the Form API and submit to an external DB in a different structure such as pgsql?** or do i continue coding my forms by hand for each node?

The example below is exactly what I would like to do however it is clearly shown in the link above that this will not work.

```
// ... header of the settings.php file

$db_url = array (
"default" => "mysql://user:pass@host/db",
"second" => "pgsql://user:pass@host/db"
);

```

**The code below is from the Form API getting started doc, however it doesnt specify the databse it is actually connecting to?**

```
function test_myform_submit($form, &$form_state) {
 db_query("INSERT INTO {table} (name, log, hidden) VALUES ('%s', %d, '%s')",
   $form_state['values']['name'],
   $form_state['values']['access']['log'],
   $form_state['values']['hidden']);
drupal_set_message(t('Your form has been saved.'));
}

```

# Answer
In Drupal 6 you cannot use more than one database engine with Drupal's functions. If you are using MySQL as Drupal storage, to connect to PostgreSQL you need to directly call PDO:

```
try {
  $dbh = new PDO('pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass');
} catch (PDOException $e) {
  watchdog("your module name",
           "PDO error: %error",
           array("%error" => $e->getMessage() ),
           WATCHDOG_ERROR);
}

```

Then use your handler just as you would in any non-Drupal PHP code, preferably with prepared statements.
> 2 votes

---
Tags: 6, forms, database
---


title: Looking for a gallery on drupal 7

text:
# Question
Title: Looking for a gallery on drupal 7
this is my site on blogger mysite

I decide to do it again on drupal as my first website. I cannot find any way (module or view) to make the content look like my site. I don't want exactly the same. I want only the image and if I hover the mouse, then with effect I can see the title or other fields.

Do you know anything like this?

Update. Describe the gallery:

The gallery in my previous site was a grid like that one on views, but when you hover the image on the grid, the image sliding down and title and description show. I have try to do it with views's grid, but I cannot find a way to add an effect.

The last option for me is to take the css from my previous site and modifying in for the new one, but I prefer a easier way like a module.

# Answer
> 0 votes
I recently did a similar site to that css effect, http://www.chinafile.com

This was my process, but this is just a general idea of how i did it:

1. create new View and display in the following order in the format of a Grid: image, title, body (truncated). now all your fields will be stacked on top of another.
2. CSS absolute position the image so everything below it will float up into the image.
3. set the title and body to display:none
4. create a css :hover event to change the title and body to display:block once you hover.

Thats the general idea behind how to do that type of effect. Now if you wanted it to animate you will need to use the CSS property transition:

Its mainly going to be CSS and creating a View. No need to modify any HTML or any extra coding.

# Answer
> 0 votes
If the main purpose of this gallery is displaying the products, I think first you need to do is to create a content type "**Product**" and add fields like: **image, link, category** (term reference).

Then you can create a view page showing fields in grid format.

The most important settings:

**Fields** (title, body, image)

**Filter** (Content type: Product)

**Path** (e.g: /product/category/%)

**Contextual filter** ( Content: Has taxonomy term ID ) - in order to filter the results according to the category you need to provide raw value from URL and validate as a taxonomy term converted to term ID (I can clarify this step if you'll need to)

Rest of work is based on CSS

I think it should be the base of your gallery, just add some work and you'll get the same result as this one on your site.

---
Tags: views, media
---


# Question
Title: For logged in user, let them view a list of content they have created (front-end user)
I have a user called a creator who can create a 'skill' content type. When they are logged in, I want them to be able to view a list of the skills they have created. I am a beginner with drupal when it comes to users. What kind of settings would I need on my view so that the view showed only content by the logged in user. I know how to do this with custom code, but would be more convenient to do with views.

# Answer
In your Views UI, at the right, expand "Advanced". Next to "Relationships" click "Add" and select "Content: Author". Apply that and make sure the relationship is listed. Next, on the lower left is "Filter Criteria". Click "Add" and way down that list, select "User: Current". Click "yes" for "Logged in user" and you should only see your authored content.
> 1 votes

# Answer
Add the fields you want from your skill content type to fields and then simply add a relationship of **User: Author** and then create a filter using field **User:current** and make sure you use setting logged on user
> 1 votes

---
Tags: views, users
---


title: Creating node forms

text:
# Question
Title: Creating node forms
Does anyone know how to create a node form for specific Content Types? Instead of clicking *Content \> Add Content \> Content Type* they can just, I don't know, go to the sidebar and fill out the info there.

This would be great for Content Types which allow Anonymous access like a *Testimonials* Content Type. There's a short something over at http://goo.gl/LMpSS but it doesn't really explain anything and leaves you wanting for more.

# Answer
I'd recommend using the Form Block module.
This module simply exposes node forms in blocks. You'll get an extra set of options for each content type, which enables/disables the block.

If you need to do it programmatically, `node_add()` is the best way to go, as suggested by @kiamlaluno.
> 7 votes

# Answer
You can use the code for node\_add() as a guideline.

```
function mymodule_node_form($type) {
  global $user;

  $output = array();
  $types = node_type_get_types();

  if (isset($types[$type])) {
    $node = (object) array(
      'uid' => $user->uid,
      'name' => (isset($user->name) ? $user->name : ''),
      'type' => $type,
      'language' => LANGUAGE_NONE,
    );

    $output = drupal_get_form($type . '_node_form', $node);
  }

  return $output;
}

```
> 8 votes

# Answer
Shamelessly lifted from SO:

https://stackoverflow.com/questions/5344754/drupal-7-how-to-display-node-add-sometype-form-on-another-page#answer-7740337

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('node_type');

```

Kudos to @"Marius Ilie"
> 1 votes

# Answer
I didn't try, but I think that you have to create a display (block, content panel, view, etc) and put the `drupal_get_form()` call in this display.

You can create a display programmatically (`hook_block_view()` for example), or you can use the Views module. With this module you create a new view (at admin/structure/views), add a display ('block' for example), then you add 'a global text area' (in header or footer) where you past his PHP Code (don't forget to change the formater of the global text, 'Filtered HTML' to 'PHP Code'.

To finish, if you created a block, you can place it where you want (with the admin UI at admin/structure/block).
> 0 votes

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


# Question
Title: How do I include linked data to a Page in Page manager?
Given two pieces of data, for example two entities, two nodes; when viewing one of them, how do I pull in data for the other one into Page manager/Panels?

# Answer
In the image below, one can see the `Context` settings for a particular `Page variant`. Under `Contexts`, one can also see `Relationships`.

`Relationships` are what one uses to tell Page manager to pull in more, related, data, based on the `arguments` that the `page` is built around.

With two nodes related to each other with a reference field, and the base node being supplied through the URI on `node/%nid`, we can add `Node from reference` as seen in the screenshot below.

Further content types (and other options) will now be available in Panels for display.
> 5 votes

---
Tags: panels, chaos-tool-suite
---


# Question
Title: How secure are variable_get and variable_set?
I have a custom module that saves variables with FTP usernames and passwords. Is variable\_get secure? Ie. Can it be accessed outside of the module.

Is variable\_set equally secure?

Obviously they are being saved to the database and are only as secure as the DB but I'm assuming the DB is secure.

# Answer
All variables set using `variabe_set()` will be stored in DB, then retreived and assigned to global variable `$conf`.

```
function variable_get($name, $default = NULL) {
  global $conf;
  return isset($conf[$name]) ? $conf[$name] : $default;
}

```

Unless you have a content type that allows users to add PHP scripts this is secure enough.

> I'm assuming the DB is secure.

What if entire DB is exposed by a SQL injection attack ? Always store sensitive data in encrypted format so that even if it gets hacked it will be of no use to the attacker. You should not store the password as a plain text in database. Use any encryption algorithm to store them.
> 0 votes

# Answer
I suggest not storing this information with a variable\_set or system\_settings\_form which will put it in the variable store (which is the database by default, and can be cached wherever caching is happening such as memcache).

Instead, I suggest using the `$conf` array in `settings.php` for the information. The benefit is that `settings.php` is a file you are already using to store credentials for the database and already protecting from prying eyes.

The beauty of this system is you can still use `variable_get` to load the value from `$conf` which is easy, handy, etc.

For more details read the `settings.php` file itself which has a lot of commented out code examples and documentation.
> 7 votes

# Answer
Don't save FTP password in database as is - encrypt it using mcrypt (http://www.php.net/manual/en/mcrypt.examples.php) or other library and store encryption cipher in code.

Examples.

Save FTP password

```
$encrypted_password = mcrypt_ecb(MCRYPT_3DES, $cipher, $form_state['values']['password'], MCRYPT_ENCRYPT);
variable_set('ftp_password', $encrypted_password);

```

Load FTP password

```
$decrypted_password = mcrypt_ecb(MCRYPT_3DES, $cipher, variable_get('ftp_password', ''), MCRYPT_DECRYPT);

```

Note: $cipher must be somewhere defined in module code.
> 5 votes

# Answer
All of these variables that you get via variable\_get are stored in variable table, and loads everytime Drupal starts. Site Name, main email address, and other module configurations are stored in this table but NOT encrypted.

variable\_get works anywhere in the site - in page templates, custom php blocks, etc.

The best way to protect your password is to not retrieve the password anywhere other than the FTP implementation. For an example, in admin forms, we use `variable_get('form-element-key-here', '')` as the default value. So forms look like it stored configuration. Do not do this for the password field. You can see the same technique used in SMTP authentication module and PHPMailer module. http://drupalcode.org/project/phpmailer.git/blob/refs/heads/7.x-3.x:/phpmailer.admin.inc

Unless you leave Devel module enabled and insecure, nobody with php or database access can see your password.
> 1 votes

# Answer
In short, it's just a function to store/retrieve info from a specific table in your database. Your whole database is accessible from every module/template/... within your Drupal instance.

Some advice might be to keep in mind what do you want to store in your db. You mentioned that you're assuming the db is secure, and that is the biggest part of all.

As already mentioned, better to encrypt that kind of data before storeing it.
> 0 votes

---
Tags: 7, security
---


# Question
Title: Convert an exported rule to a programmatic rule
I created a Rule through the GUI and it works fine. I would like to convert this into a programmatic rule that I can include with my custom module. This way I dont have to re import my rule every time I set up a site. Is there any way to do this (other than manually)?

# Answer
You can implement `hook_default_rules_configuration()`

> This hook is invoked when rules configurations are loaded. The implementation should be placed into the file MODULENAME.rules\_defaults.inc, which gets automatically included when the hook is invoked.

and use `entity_import()` to convert the export string into something Rules will understand. e.g.

```
function MYMODULE_default_rules_configuration() {
  $items['my_rule'] = entity_import('rules_config', 'EXPORT STRING HERE');

  return $items;
}

```
> 5 votes

---
Tags: rules
---


title: Multisite override modules

text:
# Question
Title: Multisite override modules
If I have a module in sites/all/modules named dc\_front and then I have a module in sites/default/modules named dc\_front, which one gets used when it is enabled?

It appears the module in default gets used.

Is this expected and reliable behavior?

# Answer
`drupal_system_listing()` is the function that handles this.

According to its inline documentation:

```
// Duplicate files found in later search directories take precedence over
// earlier ones, so we want them to overwrite keys in our resulting
// $files array.
// The exception to this is if the later file is from a module or theme not
// compatible with Drupal core. This may occur during upgrades of Drupal
// core when new modules exist in core while older contrib modules with the
// same name exist in a directory such as sites/all/modules/.

```

And as far as I can tell from the function, it searches directories in the following order:

1. /profiles
2. /sites/all
3. /sites/\[domain\]

So each directory in the list above would override matches from previous directories.

Having modules in the `/sites/default` directory is not normal, so I'm not sure what the expected behavior would be. My guess is that it depends alphabetically on your `[domain]` directory name.
> 1 votes

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


# Question
Title: How to implement a Views 3 exposed filter in block as a list of links, and update the view via ajax?
I need to create a views exposed filter that is displayed as a list of links, and updates the view via Ajax. I've tried using Better Exposed Filters and it will display the filter as links, but without ajax. I've tried to figure out how to theme the default views select element (which is ajaxified) as a list of links, but haven't found a good way to go about this yet. Any suggestions would be much appreciated. Thanks!

# Answer
Try this patch: https://drupal.org/node/1268150#comment-7393486, it's for better exposed filters and it's to make it work with AJAX.

As for the default views select element, try using an argument.
> 1 votes

---
Tags: 7, ajax, views, navigation
---


title: How to use Form API

text:
# Question
Title: How to use Form API
I'm new to drupal, and especially new to drupal form API. I see all the documentation which seems to make sense. They miss one key instruction that you need to create .module / .info files. I have created those, and copied the code from into my module Form example code drupal 6 However, I don't know how to view the module.

I know that if I can get a working example, I will be fine, but I can't. I am lost, and no matter how far I search all the guides miss the early steps, or make too much of an assumption.

### test\_form.info

```
name = Form example
description = My form example form API.
core = 6.x
package = Example form

```

### test\_form.module

```
function MYMODULE_menu() {
  $items['some/form'] = array(
    'title' => 'Some Form',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_some_form'),
  );

  return $items;
}

function MYMODULE_some_form($form_state) {
  $form['item'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#default_value' => 'Default...',
  );

  return $form;
}

```

# Answer
Rather than keep this going in the comments, here's a very basic form/menu example (un-tested but it should work).

```
function MYMODULE_menu() {
  $items['some/form'] = array(
    'title' => 'Some Form',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_some_form'),
  );

  return $items;
}

function MYMODULE_some_form($form_state) {
  $form['item'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#default_value' => 'Default...',
  );

  return $form;
}

```

All of the above goes in a single module file. Once you install the new module (or clear the caches if it's already installed), you should see a basic form at `/some/form`.
> 1 votes

# Answer
I learnt by studying the Examples Module. Install the examples module (https://drupal.org/project/examples), enable form api example sub module in it. Follow the code.

API Documentation: https://api.drupal.org/api/examples/form\_example%21form\_example.module/group/form\_example/7

A simple way to follow would be - look at the hook\_menu function.

Look at the code here: http://drupalcode.org/project/examples.git/blob/HEAD:/form\_example/form\_example.module

The following code snippet builds the page at http://baseurl.com/examples/form\_example \- you can now follow along.

```
$items['examples/form_example'] = array(
   'title' => 'Form Example',
   'page callback' => 'form_example_intro',
   'access callback' => TRUE,
   'expanded' => TRUE,
);

```

Another useful piece of information is the form api examples at: https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/6

For Drupal 7, look at: https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7

Hope this helps.
> 1 votes

# Answer
I was totally new to drupal, drupal modules (creating) and the form API.

Here is the basics to getting a simple form loaded with the menu link. Note the credits go to @Clive.

First of all I have a module in the module folder as follows.

**formpractice - folder**

--**MYMODULE.info**

name = My Test Form

description = A very simple Test Form to get you up and running.

core = 7.x

--**MYMODULE.module** (It is important that the MYMODULE\_menu = the module name. So in this case at the module is called MYMODULE thats what is here replacing the hook\_menu. This was my main reason for my module not loading the simple form. I had called my module something different to what the hook\_menu was utilising.Then from here the form is the 2nd function, that can be further developed using the API instructions. I hope this helps any new users to getting started with the FORM API.

```
<?php function MYMODULE_menu() {
$items['some/form'] = array(
'title' => 'Some Form',
'access arguments' => array('access content'),
'page callback' => 'drupal_get_form',
'page arguments' => array('MYMODULE_some_form'),
);

 return $items;
}

function MYMODULE_some_form($form_state) {
 $form['item'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#required' => TRUE,
'#default_value' => 'Default...',
 );

 return $form;
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: How to set one variable for each link on a views un-formatted list
I'm trying to create a variable to put in a l() function. It's the $rellink below.

```
<?php print l('<span class="link-spanner"></span>', "$rellink", array ('html' => TRUE)); ?>

```

I have a list of content nodes I'm displaying in an un-formatted view. I want $rellink to be the link for each of them. So on item 1, it's the link to item 1. On item 2 it's the link to item 2 and so forth.

In the unformatted.tpl.php file I can print out

```
<?php print $view->style_plugin->row_tokens[$id]['[view_node]']; ?>

```

Which will print the correct link. But I need this inside the link part of the l() function and when I copy and past it in, it doesn't work.

So the question is, what have I done wrong there or if that's not possible/bad practice how do I set-up a variable in my preprocess function that I can use instead?

I've tried this in the preprocess funtion:

```
$view = $variables['view'];
$rellink = $view->style_plugin->row_tokens['$id']['[view_node]'];

```

But it doesn't recognise the global $id variable and I get an un-defined variable rellink variable warning anyway.

# Answer
> 0 votes
I accidentally left the quotes in when entering the variable path so it didn't work. I was entering:

```
<?php print l('<span class="link-spanner"> a</span>', "$view->style_plugin->row_tokens[$id]['[path]']", array ('html' => TRUE)); ?>

```

And the I should've been putting in:

```
<?php print l('<span class="link-spanner"> a</span>', $view->style_plugin->row_tokens[$id]['[path]'], array ('html' => TRUE)); ?>

```

When you're calling a value in an array, it won't work if you put the path in quotes.

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


# Question
Title: Assign previous migration destination id in prepareRow
Working on migration of 6 to 7 where 2 websites are being merged into one. This is being done using migrate module.

There are duplicate users in 2 source sites and intended result is that the user that exists from the 1st migration should be linked as destination id on the second without being updated.

We already have migrations set up for 2 sites and site #1 is imported. When importing users from site #2 we want to essentially keep the same user from site #1 and link all content from site #2 to be owned by user from #1.

Can this be done in prepareRow and how ?

# Answer
In your site 2 content (Node) migration you probably want to use the prepare() function.

> function prepare($entity, stdClass $row)
>
> The Migration class prepare() method is called by the destination class prepare() method, after it has called all field-level prepare() methods and immediately before the destination object is saved. The $entity argument is the destination object as populated by the initial field mappings and manipulated by the field-level methods; the $row argument is an object containing the data after prepareRow() and any callbacks have been applied. The prepare() method is the last chance to manipulate the destination object before it is saved to the Drupal database. It is important to remember that, since it is called after the field handlers, fields will be in their fully-expanded forms (i.e., in Drupal 7 a text field value will be at $entity-\>field\_textual\_data\['und'\]\[0\]\['value'\] rather than simply $entity-\>field\_textual\_data).

Within your Migration prepare function you want to set the `UID` of the content to whoever you want to be the creator of that piece of data.

As an example:

```
public function prepare($entity, stdClass $row) {
  $query = /* Query to figure out UID from site 1, from a UID in site 2 ... for current node NID*/;
  $desired_uid = db_query($query);
  $entity->uid = $desired_uid;
}

```
> 0 votes

---
Tags: users, migrations
---


title: Multilingual Themes

text:
# Question
Title: Multilingual Themes
I am trying to switch themes when the site language is switched. Is it possible to have separate themes for each language in a Drupal 7 multilingual site?

# Answer
> 4 votes
Yes - you can create different themes for just about any condition you like as long as you have a way of switching between them. There are several theme switcher modules available but one of the better ones is 'ThemeKey' which does what you are looking for:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.

---
Tags: theming, i18n-l10n
---


title: Show and hide certain markers

text:
# Question
Title: Show and hide certain markers
I am using GMAP module on Drupal7 for Google Maps. I am using it with Views module. Have created map view with markers from content type. Everything works fine.

Now I want to be able to show and hide some markers (not all) based on for example some category or any node field. How can I manipulate (just show and hide some of them) markers outside the view? Or maybe there is a possibility to do it within view?

# Answer
> 1 votes
I was able to show and hide specific markers on my full map under Administration » Structure » Views » Full Map View. I added a filter that showed markers based the Content: Author uid. Then I set the pages I wanted to show to have one author and the other locations that I didn't want to display to a different author. This article helped me figure it out: https://groups.drupal.org/node/19614

Hope that helps you.

---
Tags: views, google-maps
---


title: Without access on a taxonomy term page

text:
# Question
Title: Without access on a taxonomy term page
I have created a taxonomy term "tags". If I use the url to access the content with that term I have the following error.

403 Forbidden You don't have permission to access /drupal/tag/sport on this server.

"sport" is a taxonomy term and tag is the taxonomy.

Even if I am admin or anonymous user.

# Answer
> 0 votes
around the top of your .htaccess file you have

```
# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(|~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

```

just remove 'Tag', new code should look like this

```
# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(|~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

```

you can replace this lines with new one that I provided above...

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


# Question
Title: need to replace default drupal user picture with an image field from user profile
Need to replace the user\_picture with my own field\_profile\_picture(since i've provided a nice crop with imagefield crop).

I've succeeded in getting the file path using template\_preprocess\_user\_picture and the code

```
 function theme_preprocess_user_picture(&$variables) {
    $account = user_load($variables['account']->uid);
    if(isset($account->field_profile_picture['und'][0]['uri'])) {
        $variables['user_picture'] = $account->field_profile_picture['und'][0]['uri'];

```

the user\_picture is getting replaced by the file path.... how to render the image???

Anyone Please....

# Answer
> how to render the image???

Sounds like you're probably looking for `image_style_url()`. Assuming you have an image preset called `thumbnail`, try something like this:

```
$picture_style = 'thumbnail';
$picture_uri = $account->field_profile_picture['und'][0]['uri'];
$variables['user_picture'] = image_style_url($picture_style, $picture_uri);

```
> 1 votes

---
Tags: theming, users
---


# Question
Title: How do you provide conditional checkout options depending on whats in the cart?
Is it possible to provide different payment options depending on what is in the cart? Say someone wanted to purchase a service vs a physical product. For service related items, I want to be able to provide a payment option of Bitcoins and if its physical products, provide paypal. if they have a service and product in their cart it would only provide paypal as an option. Can this be done via rules and which rules would i need to edit?

# Answer
> 0 votes
I believe you have already set different product types to handle different kind of product.

So what you have to do is, by default disable payment methods and set them one by one in rules to make a payment option available if certain product type in in cart.

* Add Event "Select available payment methods for an order"
* Add Condition "Order contains products of particular product type"
* Add Action "Enable payment method: `(Your Payment Method)`"

I have done something like this for COD(Cash on Delivery) for certain product type in certain postal codes.

---
Tags: 7, commerce
---


# Question
Title: Can not find the price of products in ubercart tables
I need to export products from Ubercart, the problem I am facing is the price of products is shown 0.000 in uc\_products in all related fields (list\_price, cost, sell\_price) for almost every product but on admin side and front end every product has price more than 0.000.

my question is **Where else the price could be store in ubercart tables other than uc\_products?**

Any where in cache tables, attribute wise or somewhere else?

# Answer
> 0 votes
I dont know what modules are installed on the site. But prices were in different tables for different currencies, found them finally

```
content_field_price_usd
content_field_price_eur

```

---
Tags: 6, ubercart
---


# Question
Title: Given a block_id, what would be the most reliable method to decide if the block was generated by Views?
I would like to use `hook_form_block_admin_configure_alter` to add configuration options to the blocks admin, but only if the block is for a View. It's important to add the settings here rather than in the view settings itself, since it will grouped with other additional block settings that are not Views specific.

Thanks!

# Answer
> 4 votes
As Clive said, each block will contain the module name from which it was created in the block configuration. For views blocks, it's views module.

This module information will be available in the form structure itself, like below:

```
$form['module']['#value']

```

So you don't need to query the database to retrieve it.

Pseudo code:

```
function my_module_form_block_admin_configure_alter(&$form, &$form_state) {
  if ($form['module']['#value'] == 'views') {
    // ...
  }
}

```

# Answer
> 2 votes
The module responsible for a block is listed as a column in the `block` table, so you can just do something like

```
$module = db_query('SELECT module FROM {block} WHERE bid = :bid', array(':bid' => $bid))->fetchField();
if ($module === 'views') {
  // ...
}

```

---
Tags: views, blocks, forms
---


# Question
Title: Alter the "My Account" link in installation profile
Well i've tried the following code to insert an attribute to the user-account link on installation profile.It works for all other menu items (Home\[\]), except the user-account link, probably due to the reason it is rebuilt again.

```
<?php
   $path = 'user';
   // Check for user (My account) menu item.
   $existing_item = db_select('menu_links')
    ->fields('menu_links')
    ->condition('link_path', $path)
    //->condition('module', 'system')
    ->execute()->fetchAssoc();

  $item = array(
   'mlid' => $existing['mlid'],
   'link_path' => $existing['link_path'],
   'link_title' => $existing['link_title'],
 //'menu_name' => $existing['menu_name'],
   'router_path' => $existing['router_path'],
 //'module' => $existing['module'],
 //'plid' => $existing['plid'],
   'options' => array(
    'attributes' => array(
    'target' => '_blank',
    ),
   ),
 );
 // $item['options'] = serialize($item['options']);
 // $item = _menu_link_build($item);

 // $link['options'] = serialize($link['options']);
 if (menu_link_save($item, $existing) == $existing['mlid']) {

   drupal_set_message(t('User menu target attribute updated'));
 }

```

The above code :

1. selects form the database the {menu\_links} record for 'user' menu item.
2. Alter the options in the $item\['options'\] array
3. Performs menu\_link\_save() on the existing item since we have given an existing $mlid

Well, i've tried menu\_cache\_clear, rebuilds, straight altering the database values.. everything! but the "My account" link is rebuilded after my profile installation routines, even though is the last one.

How this will work? How can i achieve this kind of alteration in installation profile?

In general, is it possible to override module-defined menu items options/properties in profile, or hook\_menu() will run always after my code and revoke all my changes?

# Answer
> 0 votes
The solution?

```
variable_set('user_target_attr', '_blank');

```

in the profile installation and

```
hook_menu_link_alter()

```

normally afterwards in the module like :

```
/**
 * Implements hook_menu_link_alter().
 */
function module_menu_link_alter(&$item) {
  $destination = drupal_get_destination();
    if ($item['link_path'] == 'user') {
    // Allow to be overriden!!
    $default_target = variable_get('user_target_attr', '_blank');
     if ($default_target != $item['options']['attributes']['target']) {
        variable_set('user_target_attr',
          $item['options']['attributes']['target']);
     }
    // Alter all the links to user page to open via the configured or default attribute.
    $item['options']['attributes']['target'] = variable_get('user_target_attr', '_blank');
    }
}

```

If we don't make the check for the default target , it will always get the default one and we could never update the defaults from amdin UI

# Answer
> 0 votes
Perhaps you could use:

`hook_menu_alter`

Not sure if it'll work with option attributes, but worth a try.

e.g

```
/**
 * Implements hook_menu_alter
 */
PROFILE_menu_alter(&$items){
  $items['user']['options'] = array('attributes' => array('target' => '_blank'));
}

```

Alternatively, it would be easy enough to add the \_blank attr with jQuery.

e.g:

```
$('body.some-class #user-menu-link a').attr('target', '_blank');

```

Update: added example PROFILE\_ option for menu\_alter hook

---
Tags: 7, routes, distributions, users
---


title: Printing nice menus using template file

text:
# Question
Title: Printing nice menus using template file
I am having a custom menu created in admin/structure/menu configured to nice-menus. and now I am trying to print that menu using my section.tpl.php file like

```
$nice_menu = block_load('nice_menus',"1");
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($nice_menu ))));

```

What I see is only the menu title displaying on the page, when I inspect the html source in firebug I see the html needed for the menus are generated. This is frustrating me for the last couple of hours, is there is another way to print my nice menu using the template file?

# Answer
> 2 votes
Try This

```
$nice_menus_block =_block_get_renderable_array(_block_render_blocks(array(block_load('nice_menus', '1' /*1,2,3 more,  this is get nice_menus_2 block*/))));
print render($nice_menus_block);

```

---
Tags: 7, routes, navigation
---


title: Dynamic block on the side suggestion

text:
# Question
Title: Dynamic block on the side suggestion
Googling didn't help a lot in this issue. I was wondering if there is a drupal module that inserts sort of a dynamic content in the side of the page the can be expanded and shrinked while pressing a button/arrow?

# Answer
> 1 votes
This is more like a Javascript question, no i don't think you will find that kind of module.

You can always write your own Javascript/jQuery slideToggle() behavior (my suggestion) in a .js file in your theme, control any DOM element (like a block title) and assign this behavior to it.

---
Tags: 7
---


# Question
Title: Unable to use a hyphen in a Drupal 7 text field
I've got a simple field of type "text", widget = "text field" (Drupal 7).

I am able to use special characters like &(%, but when I try to type a hyphen, there is no result. I can use a rich text field, but I only want plain text.

I **am** able to use the ASCII code like `S-26` where I really just want `S-26`.

This was not an issue in Drupal 6.

Thanks very much!

# Answer
> 1 votes
The zoom behavior of the map is responsible for this unwanted behavior. You need to disable keyboard controls on the map in your node edit form. This could be the default map or the default map installed by geofield.

# Answer
> 0 votes
I finally found the solution after spending a lot of time in OpenLayers library. Basically the solution is to create a new behavior which will override the function OpenLayers.Control.KeyboardDefaults, after that you will have to comment the lines which use the - and + code keys, and in the end force to render the behavior.

This Solution works for Drupal 7

Create a new module and don't forget to add these 2 lines in the info file:

```
dependencies[] = openlayers
dependencies[] = geofield

```

The new behavior

```
function mymodule_openlayers_behaviors(){
  return array(
    'openlayers_behavior_OKC' => array(
      'title' => t('Override key control'),
      'description' => t('Remove the - and + zoom key'),
      'type' => 'behaviors',
      'behavior' => array(
        'class' => 'openlayers_behavior_OKC',
        'parent' => 'openlayers_behavior',
        'path' => drupal_get_path('module', 'mymodule') . '/includes',
        'file' => 'openlayers_behavior_OKC.inc',

      ),
    ),
  );
}

```

the file includes/openlayers\_behavior\_OKC.inc will call the js to override the function.

```
class openlayers_behavior_OKC extends openlayers_behavior {
  /**
   * Provide initial values for options.
   */
  function options_init() {
    return array(
      'keyboarddefaults' => '',
    );
  }

  // /**
  //  * Render.
  //  */

  function render(&$map) {
      drupal_add_js(drupal_get_path('module', 'mymodule').'/js/openlayers_behavior_OKC.js');
      return $this->options;
    }

}

```

after that you just need to rewrite the function OpenLayers.Control.KeyboardDefaults (I've comment the lines related to the + and - but you can choose or add new keys if you want to) Here is the file js/openlayers\_behavior\_OKC.js

```
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * Keyboard Defaults Behavior.  Implements the KeyboardDefaults OpenLayers
 * Control.
 */
OpenLayers.Control.KeyboardDefaults = OpenLayers.Class(OpenLayers.Control, {

    /**
     * APIProperty: autoActivate
     * {Boolean} Activate the control when it is added to a map.  Default is
     *     true.
     */
    autoActivate: true,

    /**
     * APIProperty: slideFactor
     * Pixels to slide by.
     */
    slideFactor: 75,

    /**
     * APIProperty: observeElement
     * {DOMelement|String} The DOM element to handle keys for. You
     *     can use the map div here, to have the navigation keys
     *     work when the map div has the focus. If undefined the
     *     document is used.
     */
    observeElement: null,

    /**
     * Constructor: OpenLayers.Control.KeyboardDefaults
     */

    /**
     * Method: draw
     * Create handler.
     */
    draw: function() {
        var observeElement = this.observeElement || document;
        this.handler = new OpenLayers.Handler.Keyboard( this,
                {"keydown": this.defaultKeyPress},
                {observeElement: observeElement}
        );
    },

    /**
     * Method: defaultKeyPress
     * When handling the key event, we only use evt.keyCode. This holds
     * some drawbacks, though we get around them below. When interpretting
     * the keycodes below (including the comments associated with them),
     * consult the URL below. For instance, the Safari browser returns
     * "IE keycodes", and so is supported by any keycode labeled "IE".
     *
     * Very informative URL:
     *    http://unixpapa.com/js/key.html
     *
     * Parameters:
     * evt - {Event}
     */
    defaultKeyPress: function (evt) {
        var size, handled = true;
        switch(evt.keyCode) {
            case OpenLayers.Event.KEY_LEFT:
                this.map.pan(-this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_RIGHT:
                this.map.pan(this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_UP:
                this.map.pan(0, -this.slideFactor);
                break;
            case OpenLayers.Event.KEY_DOWN:
                this.map.pan(0, this.slideFactor);
                break;

            case 33: // Page Up. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0, -0.75*size.h);
                break;
            case 34: // Page Down. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0, 0.75*size.h);
                break;
            case 35: // End. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0.75*size.w, 0);
                break;
            case 36: // Home. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(-0.75*size.w, 0);
                break;

/*            case 43:  // +/= (ASCII), keypad + (ASCII, Opera)
            case 61:  // +/= (Mozilla, Opera, some ASCII)
            case 187: // +/= (IE)
            case 107: // keypad + (IE, Mozilla)
                this.map.zoomIn();
                break;
            case 45:  // -/_ (ASCII, Opera), keypad - (ASCII, Opera)
            case 109: // -/_ (Mozilla), keypad - (Mozilla, IE)
            case 189: // -/_ (IE)
            case 95:  // -/_ (some ASCII)
                this.map.zoomOut();
                break; */
            default:
                handled = false;
        }
        if (handled) {
            // prevent browser default not to move the page
            // when moving the page with the keyboard
            OpenLayers.Event.stop(evt);
        }
    },

    CLASS_NAME: "OpenLayers.Control.KeyboardDefaults"
});

```

---
Tags: input-formats, javascript
---


# Question
Title: How do I disable the default user system or view pages without login?
I apologize in advance if I haven't used the proper terminology, but I am very new to working with any CMS, let alone Drupal.

Now... On to the question...

On the page, I have a block that explains the purpose of the site, and everything looks fine when I'm signed in, however, once I sign out, I get "Access Denied" on all of my pages & subpages.

For the website I'm building, I have absolutely no need for a user/authentication system at this time.

How can I disable the user framework, or how can I make all pages visible without having people log in?

Again, sorry for the likely improper terminology... Thanks in advance for your time & help.

# Answer
It depends on the type of page really, what module provides it, how permissions are implemented by that module - the short answer is by setting correct permissions at /admin/people/permissions.

You can't disable the user module, it's a required part of Drupal. Conceptually, if you were to disable it you'd have no authentication control over the admin section, and any user could make whatever changes they wanted - obviously that's not a situation that can be allowed to exist for 99.99% of users. And if you *do* want that, you just need to set up permissions to allow it.

But you can stop users from registering, which avoids that problem. And by setting appropriate permissions you can decide exactly what users (or even groups of users, using the Roles system) can see/do.
> 1 votes

---
Tags: users
---


# Question
Title: Dynamic footer link based on current url
I've got a link to the mobile version of my site in the footer, but I need this link to be dynamic based off the page that the user is currently on.

Shown below are the options I have for the link.

Under the path there is this help text

`The path for this menu link. This can be an internal Drupal path such as node/add or an external URL such as http://drupal.org. Enter <front> to link to the front page.`

What I need is similar to the ability to use `<front>` to signify the homepage. I'd like to be able to use something like `http://m.example.com/<node>` so that this link will always go to the mobile version of the page that I'm currently on.

Is this possible? Or is what I want to do more complex than just using a keyword for the path?

# Answer
The default menu system won't let you do that...but if you install the Menu Token module you should be able to use a path similar to the following to get what you need:

```
http://m.example.com/[current-page:url]

```
> 2 votes

---
Tags: routes, uri, path-aliases
---


title: Email Validation php

text:
# Question
Title: Email Validation php
When validating an email address using the code below I get this error when i run the same code from within a drupal node, where I coded a form using php/html

```
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
$errors[] = 'Please enter valid email';
}

```

I get this error:

```
Fatal error: Call to undefined function filter_var() in /var/www/html/drupal1/includes/common.inc(1743) : eval()'d code on line 53

```

# Answer
A better option might be to use `valid_email_address()` to keep it all Drupal friendly :)

> Verifies the syntax of the given e-mail address.

See RFC 5322 for details.

Example:

```
if (valid_email_address($email) != TRUE) {
  $errors[] = 'Please enter valid email';
}

```
> 1 votes

---
Tags: emails, forms
---


# Question
Title: Slider via uploaded Image on each node + Fallback
I want to create a slider block shown on every page filled with the images uploaded to the active Basic Page, Article, ... On these pages just the Uploaded Images of the active page should be shown and if there are no images uploaded (e.g. on View pages, Taxonomy pages, ...) a fallback Slider should be shown.

I've added a Imagefield called Sliderimage to the Basic Page (and the others), created some pages and uploaded individual images to them.

Then I've created a view block with the following settings: Format: Slideshow (default values from views\_slideshow) Show: Fields Field: Content:Sliderimage - Rendered File, Original, Display all values in the same row (no seperator) Filter Criteria: Published Contextual filter: Content: Nid

But somehow the node id seems not to be delivered to the filters (or I misunderstood it) because at the contextual filter I choose "Display all results for the specified field" at WHEN THE FILTER VALUE IS NOT AVAILABLE I get all at the different pages and with "Hide view" I get nothing would would be right.

If the above issue is solved I want to add the fallback at "WHEN THE FILTER VALUE IS NOT AVAILABLE" as fixed value or php code. Would that be the right way?

# Answer
> 0 votes
Solved because I've found out that block views don't retrieve node-ids by default.

You have to set at "When the filter value is NOT available": \- Provide default value: with type "Content ID from URL"

Now the block view recognizes the ID as well.

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


# Question
Title: Count results in Views using aggregation
Is it possible to count results (e.g. count the nodes of the content type x) in a view, using aggregation (not programmatically)?

# Answer
Yes, it is possible in Views 3 out of the box.
The idea is the same as in SQL aggregations. Lets see an example:

1. Edit your view and enable Views aggregations:
2. Remove default sort criteria.
3. Add fields “Content: Type” and “Content: Nid”:
Select COUNT function for Content: Nid:

To see what happens just turn on checkbox “Show the SQL query” at global Views settings page.

```
SELECT node.type AS node_type, COUNT(node.nid) AS nid
FROM
{node} node
WHERE (( (node.status = '1') ))
GROUP BY node_type
LIMIT 10 OFFSET 0

```

So, we are grouping nodes by node\_type and calculating count for this groups.
> 52 votes

# Answer
Great answers here though your original question does not state what you are going to *do* with the count value. Presumably you want to display it?

If so, here's another solution:

Assuming that your View is already set up to filter by items of content type, then you can also add a header in the View and choose the "Global: Result summary" option and use the token variables provided in the text area.
> 12 votes

# Answer
Just in case someone comes across this.

I used the Views Date Format SQL to format the date to the granularity.

> The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date.
>
> This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.

Worked right out of the box - easy as!
> -2 votes

---
Tags: 7, views
---


title: Drupal how create alias

text:
# Question
Title: Drupal how create alias
I am looking to create aliases.

My url is `user/uid/edit` and I want `panel/your-edit` or `panel/uid/your-edit` How can i do that? How create alias?

When i try create alias in admin panel I have an error: Path user/\[user:uid\]/edit is incorrect or user do not have access.

# Answer
> 2 votes
Hope this will help you,

In Drupal 7 you can use these modules for your requirement

# Answer
> 0 votes
In permission, check user access control and make sure that all users can "access content"

---
Tags: path-aliases
---


title: Form without <form> tag

text:
# Question
Title: Form without <form> tag
I've got a moderation form in the admin section, where a moderator can edit the text, the user has written.

Here is my form:

```
function phase2_moderation_form($admin, $moderation, $phase2, $edit, $sdid) {

    $sql = 'SELECT * FROM {phase2_submitted_data} WHERE sdid = :sdid';
    $results = db_query($sql, array(':sdid' => $sdid));
    foreach ($results as $result) {
        $submission[] = $result;
    }

    $form = array();

    $form['status'] = array(
    '#type' => 'select',
    '#title' => t('Status'),
    '#options' => array(
            '0' => t('not enabled'),
            '1' => t('enabled')
            ),
    '#required' => TRUE,
    '#value' => $submission[0]->status,
    );

    $form['question'] = array(
            '#type' => 'textarea',
            '#title' => t('question'),
            '#required' => TRUE,
            '#value' => $submission[0]->question,
    );

    $form['topic'] = array(
            '#type' => 'select',
            '#title' => t('topic'),
            '#options' => array(
                    'social' => t('Social'),
                    'culture' => t('Culture'),
                    'government' => t('Government'),
                    'environment' => t('Environment'),
                    'traffic' => t('Traffic'),
                    'other' => t('Other')
                    ),
            '#default_value' => 'other',
            '#required' => TRUE,
            '#attributes' => array('id' => array('topic'), 'name' => array('topic')),
            '#title_display' => 'before',
            '#value' => $submission[0]->topic,
            );
    $form['answer'] = array(
            '#type' => 'textarea',
            '#title' => t('Our Answer'),
            '#required' => FALSE,
            '#value' => $submission[0]->answer,
            '#title_display' => 'before',
            );
    $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            );
    $form['#submit'][0] = 'phase2_moderation_edit_form_submit';
    $form['cancel'] = array(
            '#type' => 'button',
            '#value' => t('Cancel'),
    );
    return $form;
}

```

Actually nothing special, but there is no form-tag rendered.

In Firebug, I see that there are the form-element-divs, but there is no around that divs. I already tried to comment out the Cancel-Button, but that doesn't help.

Could you please help me?

Here is the hook\_menu:

```
function phase2_menu() {
    $items = array();
    $items['admin/moderation/phase2/edit/%'] = array(
        'title' => t('Moderation Phase 2'),
        'page callback' => 'phase2_moderation_form',
        'page arguments' => array(0,1,2,3,4),
        'access arguments' => array('moderation phase 2'),
        'file' => 'phase2.moderation.form.inc',
    );
 return $items;
}

```

I do not call anything extra (no preprocess-function or tpl.php) or anything else. I thought Drupal render it itself by a function deep inside.

Bye Tom

# Answer
> 4 votes
I think you need to use `'drupal_get_form'` as a `page callback` and use `array('phase2_moderation_form', 0, 1, 2, 3, 4)` as `page arguments`

Or you can change the `page callback` to another function, like for example `'phase2_get_my_form'` and in that function call `return drupal_get_form('phase2_moderation_form', $arg0, $arg1, $arg2, $arg3, $arg4);` (obviously change the `$argX` to your proper argument names.)

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


# Question
Title: When reimplementing Drupal.tableDrag.prototype.dropRow(), how do I access classes of would-be parent?
Using code below, I can access classes of a row that's being dropped:

```
Drupal.tableDrag.prototype._dropRow = Drupal.tableDrag.prototype.dropRow;
Drupal.tableDrag.prototype.dropRow = function(event, self) {
  console.log('dropRow');
  console.log("feature-group: " + $(self.rowObject.element).hasClass('feature-group'));
  console.log("feature: " + $(self.rowObject.element).hasClass('feature'));
  if ( /* use classes here */ ) {
    /* return custom result here */
  }
  /* fallback to default here */
  return self._dropRow(event, self);
};

```

But now I don't want to test classes of a dragged row, but ones of a row that would be a parent. How do I do that?

To clarify: I need tabledrag parent, not DOM parent. All tabledrag rows are DOM siblings, and I need the row with ID field value equal to the would-be Parent ID field value (`class="parent"`) of a dragged row.

Something in JavaScript sets the parent ID properly, during either drag or drop (can't tell), so I'm sure there is a way. I just don't know how to find it.

# Answer
Get a reference to some parent DOM element ... the jquery parents() or parent function(s) comes to mind. Then use `hasClass` on those parents as needed.

some parent would be something like the following based on your example:

```
var parents = $(self.rowObject.element).parents(/* a selector to limit the type of parent, td, tr, whatever */);

```

**EDIT:**

dragged rows get a class of like `.dragged-previous`. The file `tabledrag.js` doesnt care about the current row, nor about IDs of anything during drag -- its just doing a DOM swap of rows and inserting the dragged row before another row; and assigning a Drupal `weight` to the hidden weight column. So cant you use like jquery prev() function to get the immediate previous element:

```
var parent = $('#menu-overview tr.drag-previous').prev();

```

I'm taking these values from a Main Menu tabledrag example of a vanilla D7 site:
> 0 votes

---
Tags: javascript, theming
---


# Question
Title: Displaying Ubercart order history for customers in their "my account" page
I currently have a small store set up with Ubercart where customers can purchase the items I have listed. They go through the process of purchasing and then receive an order confirmation email. On this email their is a link to "Check Order Status". That is what I want however, when the link is clicked they are taken to their "My Account" page and nothing is displayed.

**Question:** Because Ubercart gives this link I assume their is some sort of information that can be displayed (ie order history/status). Is their an area in the configuration that I can insert the information or is it even possible.

# Answer
So after long last, by accident, I found the option. In Drupal 7 go to Home » Administration » People and select the permissions tab. Once there navigate down the "Orders section" within that section you will be given the option to allow users to view certain order information. Select the relevant information and you are good to go. Be careful not to give them access to things they should not be able to see (these options are also available there as well).
> 2 votes

# Answer
Log into Drupal7. From there goto Home \>\> Administration \>\> People \>\> select the permissions tab.

In that Order title, if u want to give particular role like(buyer) then u need to provide "View own orders" permission alone for that role(buyer). That will display his orders alone. It will displayed in the my account(user) link, there will be a tab called as orders.

There is also other thing which is "View all orders" which will display all orders of all buyers(role) in the site.It should be enabled only for administrator.
> 2 votes

---
Tags: views, ubercart
---


# Question
Title: Have the server interpret www.example.com/directory as a directory rather than a Drupal path
I've got a Drupal 6 site running at webroot, and a MediaWiki wiki running at webroot/wiki. I can access the wiki fine by going to wiki.webroot, but when I try to access it using the path webroot/wiki the server interprets this as a Drupal 6 path: how do I get the server to interpret this as a directory? I'm guessing this is something to do with htaccess?

# Answer
So, your drupal site lives at webroot, and your wiki lives at webroot/wiki? First thing i would suggest is to put your wiki outside your drupal root and creating a separate virtual host. You're asking for trouble with your current setup.

The .htaccess file that ships with Drupal *should* properly be treating webroot/wiki as a directory, if it exists. See https://stackoverflow.com/questions/15879029/dont-understand-rewritecond-request-filename-f-and-d

If it just won't work for you, update Drupal's .htaccess to explicitly add your wiki path:

```
RewriteCond %{REQUEST_URI} ^/wiki

```

Put this right before:

```
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

Your rewrite section will look like this (comments elided):

```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wiki
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```
> 0 votes

---
Tags: 6, path-aliases
---