# Question
Title: Month Year granularity on views exposed filter for a custom table exposed to view
I have a custom table exposed to view with a column of type int where I am storing current time stamp. while exposing the custom table I have kept views filter handler as "views\_handler\_filter\_date", but this is not allowing to create expose filter with month and year granularity.How can I get month and year granularity for my date\_of\_purcahse

Here is the snippet exposing the field to views.

```
  $data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

```

# Answer
> 0 votes
In order to get month, year granularity we can use date handler as defined by date module so while exposing field to use it will be all about choosing the right filter handler so I used "date\_views\_filter\_handler\_simple" handler.

Code while exposing the custom table field with proper filter handler.

```
$data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'date_views_filter_handler_simple',
    ),
  );

```

---
Tags: views
---


title: Drupal 7 - Module with form and view

text:
# Question
Title: Drupal 7 - Module with form and view
I'm trying to develop a module that creates a form and a view that displays that page.

In my module I used `hook_menu()` and `hook_form()`.
Also I saw some tutorials  &

What I cannot understand where & how to add my form to the view?

# Answer
I have never used it in that way, but some thoughts:

The second link doesn't seem relevant, as I suppose that you use Views 3.

If you use the approach described in the first link, than you don't need to implement `hook_form()` in your module, instead you need to create a views field handler and there you need to define the methods `views_form()`and `views_form_submit()`, optionally also `views_form_validate()`. You would then "add the form to the view" using the Views UI where you can add the field (the one that you have written a handler for) to the display. That's how your handler get's called and is responsible for the rendering of the element, which usually renders a value wrapped in some markup, but in your case it would render a form.

The first link explains that all very well. Just go through it again and try to follow it in detail.
> 1 votes

---
Tags: 7, views, forms
---


# Question
Title: How to create internal and external links
In drupal 4.x, in contents, links are created like this
\[url=1\]Some text\[/url\]
So when "Some text" click it open node 1.

Sometime it may link to external url also. like below:
\[url=http://www.abc.com/somepage.html\] external link \[/url\]

same thing how can i do it in drupal 7.x

# Answer
To be honest, I don't know anything about Drupal 4. I don't regard it as a platform to build on in 2014.

In Drupal 7, out of he box, you create links using plain HTML:

```
<a href="/node/42" title="internal link">internal link</a>
<a href="http://example.com/somepage.html" title="external link">external link</a>

```

There are a bunch of modules for Drupal 7 you can install that gives you other syntaxes for adding links to content. To mimic the square brackets around tags syntax you cite as example. Install the Bbcode module. It uses markup based upon BBCode. For a more modern style, similar to StackExchange, install the Markdown filter module. It let content authors use markup based upon John Gruber's Markdown.
> 2 votes

# Answer
If I understand your question correctly, then you need way to differentiate internal URL with External URL and there is way out.

If you want to give internal link just give like 'node/' in href where if you want to connect link with external URL, give full URL like 'http://www.google.com'.

Now, if you have question how drupal will recognize it, we have module extlink (https://drupal.org/project/extlink) which does that job.

hope this answers give you what you seeking for.
> 0 votes

---
Tags: nodes
---


# Question
Title: How can i filter taxonomy by another taxonomy term with views (term)?
I explain my question : i have a main content -\> travel, Then i have taxonomy term -\> country.

On my taxonomy term country, i put a taxonomy term : "tagcountry" (with words like "dangerous", "safe",...)

My question is simple, how can i create a block with related taxonomy "tagcountry"?

For instance, i would like to have in my taxonomy page country "Syria" tagged by "dangerous", a block with the first 10 countries that are tagged "dangerous". It's quiet easy to achieve this with "content", but i fail with "taxonomy".

Thanks in advance for your answers !

---

Edit : I already tried with all contextual filters : nothing worked. Except when i provide a manual value like this (but it's not dynamic) :

But when i want to use "taxonomy ID from url" with specified vocabulary ("Load default filter from node page, that's good for related taxonomy blocks"). It doesn't work...

# Answer
Finally i found a solution with references module :

https://drupal.org/project/references

If some of you want to use custom taxonomy, may be it's better to use nodes with "node reference" than taxonomy...
> 0 votes

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


title: comment form doesn't send comments!

text:
# Question
Title: comment form doesn't send comments!
This is the code of my `page.tpl.php`

```
<div id="mainWrapper">
    <div id="left_column"><?php include 'left_column.php'; ?></div>

    <div id="right_column_wrapper">
            <div class="section">
                <a id="main-content"></a>
               <?php print $messages; ?>
                <?php print render($title_prefix); ?>
                <?php if ($title): ?><h1 class="title" id="page-title"><?php print $title; ?></h1><?php endif; ?>
                <?php print render($title_suffix); ?>
                <?php if ($tabs): ?><div class="tabs"><?php print render($tabs); ?></div><?php endif; ?>
                <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>
                <?php print render($page['content']);?>
                <?php print $feed_icons; ?>
             </div>
    </div>
</div>
<div class="footer_div">
    <?php include 'footer.php'; ?>
</div>

```

There are two content types in my website called CT1 and CT2. comment sending is open for both of them. This is template.php

```
function MyTHEME_preprocess_page(&$variables)
{
    if (isset($variables['node']))
        {
        switch ($variables['node']->type)
        {
        case "CT1":
            $suggest = "page__node__CT";
            $variables['theme_hook_suggestions'][] = $suggest;
        //I added the fields of CT1 here using entity_metadata_wrapper

            $comment = new stdClass;
        $comment->nid = $variables['node']->nid;
        $variables['form'] = drupal_render(drupal_get_form('comment_form', $comment));
            break;
    }
    }
}

```

and in `page--node--CT.tpl.php` I wrote this code:

```
<div id="DIV_FOR_CONTENTS">
    <?php //Contents are displayed here with some css&html format ?>
</div>
<?php
    print $form;
?>

```

it displays the form but doesn't send comments. For CT2, I created a file renamed it to `node--CT2.tpl.php` and this is its code

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>
  </div>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>
<?php
    $comment = new stdClass;
    $comment->nid = $nid;
    $form = drupal_render(drupal_get_form('comment_form', $comment));
    print $form;
?>
    </div>

```

it works and sends the comments. from what I see, they both follow the same way to display the comment form but why CT1 form doesn't work?

# Answer
> 0 votes
I found it. I must suggest the theme hook in `MyTHEME_preprocess_node` not the `MyTHEME_preprocess_page`

---
Tags: nodes, forms, comments
---


# Question
Title: Is there any way to change home page on small screen?
I want to change the home page for small screen. Is there any way to set the front page according to the screen size by using `hook_preprocess_page()` or any other?

# Answer
> -1 votes
I used Mobile\_Detect API and redirect the page using hook\_preprocess\_page in template.php.

# Answer
> 0 votes
To actually answer your question (*Is there any way to set the front page according to the screen size*). No. Especially as you mentioned that you don't want to use JavaScript in a comment to Inizio.

The server by itself has NO idea of the screen size of the client, so the only way to get that info back would be using JavaScript (either implementing `drupal.settings` or some kind of custom AJAX callback). Any module that you use would alos have to utilise JavaScript.

If you want to change the frontpage based on DEVICE, then that's more realistic, with something like Mobile Detect, Browscap, WURFL (or something similar) but again - not foolproof.

---
Tags: 7
---


# Question
Title: update node field without node be updated
I want to update a field of node programmically,I did it with below code

```
$node = node_load($nid);
        $node->field_share_counter['und'][0]['value'] = intval($node->field_share_counter['und'][0]['value']) + 1;
        node_save($node);

```

but after update with this method the node will be update,I mean in content show that this node recently update, I want update custom field without the node updated.also I know db\_update is suitable for update a field of table in db but in here I dont know how achieve this job.

tnx

# Answer
I found this http://timonweb.com/how-insert-and-update-only-specific-fields-your-entity-drupal-7 and it is useful and final solution is :

```
$node->field_share_counter['und'][0]['value'] = intval($node->field_share_counter['und'][0]['value']) + 1;
        //$node->field_product_description[$node->language][0]['value'] = 'This is a very nice and useful product. Buy it now! We want your money!';

            // Get the numeric id of your field by passing field name
            $info = field_info_field('field_share_counter');
            $fields = array($info['id']);

            // Execute the storage function
            field_sql_storage_field_storage_write('node', $node, 'update', $fields);

            // Clear field cache
            cache_clear_all("field:node:$node->nid", 'cache_field');

```
> 4 votes

# Answer
I prefer using `field_attach_presave('node', $node);` and `field_attach_update('node', $node);` field API. Here is an example http://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself. But it seems this API is not issued for this reason and has some consequences, fortunately it worked well every time for me.
> 2 votes

# Answer
Completely untested code, but it should work around these lines:

```
// Load the field information.
$field_info = field_info_field('field_share_counter');
// Get the storage information, this assumes that the fields data is saved using a database backend.
$storage_info = $field_info['storage']['details']['sql'][FIELD_LOAD_CURRENT];
$tables = array_keys($storage_info);
// This is the table where the field data is stored.
$table = reset($tables);
$value_field = $storage_info[$table]['value'];
db_update($table)
  ->fields(array(
    $value_field => intval($node->field_share_counter[LANGUAGE_NONE][0]['value']) + 1,
  ))
  ->condition('entity_type', 'node')
  ->condition('bundle', $node->type)
  ->condition('entity_id', $node->nid)
  ->condition('language', LANGUAGE_NONE)
  ->condition('delta', 0)
  ->execute();

```

This code does not respect revisions and it will come with possible side effects because other modules can not hook into this process. Also I'm in doubt about your motivation here. In general this is an error prone approach. Whenever possible you should let the Field API do the work for you. If you simply do not want users to know that the node has been updated, then should suppress this information from the user instead of circumventing default behavior by Drupal.

You can also have a look at this thread which describes how to do what you want using the Entity module.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: Changing CCK field value(s) by clicking URL - possible? Advisable?
I'm trying to figure out if it's possible/advisable to create URLs that get sent out in user notification emails which, when clicked, carry out actions like changing a CCK field value.

So for example - say you have an issue tracking system. There's no activity on one issue for a week, so the system sends an email to the person who posted the issue asking if they consider the issue closed. And if so, please click here to close the issue.

They click on the "close the issue" link in their email, the CCK status field for the issue is changed to "closed," and they're taken to some arbitrary page on the site.

Is something like that doable?

In Drupal 6?

# Answer
I found a module that does more or less what I want -

http://drupal.org/project/node\_update\_from\_url

It lets you create URLs that a user can click to update any CCK field, provided the user has permission to edit their own content. Takes the user to a confirmation page where they have to click on "update"... and then the action is carried out.

I'm just testing it. Seems to work. Should probably suit my requirements for now. But! - the other answers are pretty interesting & I'll probably explore them as well.
> 0 votes

# Answer
It's feasible but not advisable. Drupal's standard for changing data via URLs: 1) Use \_GET variables (or simple URL paths) to \_access\_data 2) Use \_POST variables to change data

Along with using \_POST, you would want to use Drupal's Form API so that tokens and fields are generated and validated.

Options you could do to change the data via URL (e.g. link) is to: 1) Add a token to URL to validate it's only used once (or other validation necessary) 2) Ensure user is logged in (and maybe ensure he is owner of that ticket, etc.) Hope this helps.
> 1 votes

# Answer
You will have to install and setup rules to email 1 week after inactivity.

For the menu link, create a custom module

```
/**
 * Implements hook_menu()
 */
function MYMODULE_menu()  {
  $items['issue/close/%'] = array(
    'page callback' => '_MYMODULE_close_issue',
    'page arguement' => array(2),
    'access callback' => TRUE,
  );
}

function _MYMODULE_close_issue($nid = NULL) {
  if ($nid) {
    $node = node_load($nid);
    $node['field_issue_closed'][0][value] = TRUE;
    node_save($node);
  }
}

```

Problems:

* This gives access to anyone
* No control to get users to login
* No validation on array(3). User could pass anything

The way you really want to do this is how Drupal does user password resets, where it emails the user a hashed link that is good for a one time login. Except you have a predefine action to this link, which is to close the issue.

I know someone from my Local Community Drupal Meetup that is creating a module that creates these hash links. I believe its still in a sandbox. I'll try to track him down to see where his project is at.
> 1 votes

# Answer
For Drupal 7, there is another module which allows to change values from anchor link. It's called Rules Link and it's much more popular. It's connection with rules allows to do more - activate any rule you want.
> 0 votes

---
Tags: entities, uri, emails
---


# Question
Title: Hook for when a new content type is created?
Does a hook exist for when a new content type is created? If so what is it? I've looked through the API and nothing has jumped out at me.

# Answer
`hook_node_type_insert()` is invoked from `node_type_save()` after the node type is added to the database.

See: hook\_node\_type\_insert()
> 2 votes

---
Tags: 7, hooks, entities
---


# Question
Title: How do I send http authorization header in GET request in drupal?
How do I send http Authorization header in http GET request in drupal ?

Every things else works except the authorization part.

My custom module code:

```
/*
 *Implements hook_menu
 */
function mymodule_menu() {

$items['demo'] = array(
    'title' => 'Demo API integration with Drupal 7',
    'page callback' => 'demo_page',
    'access callback' => TRUE,
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );
return $items;
}

//page callback
function demo_page() {

$options = array(
  'method' => 'GET',
  'data' => '',
  'timeout' => 15,
  'headers' => array('Accept' => 'application/json',
                    'Authorization' => 'Basic SomeKey23412lkjdfadjfadfasd'),
);

$result = drupal_http_request('https://api.examlesite.com/test/', $options);
var_dump($result);
drupal_set_message("Result is processing");
return "hello world";
}

```

# Answer
> 1 votes
You can add basic authorization to url to access http basic protected address.

```
  // http auth
  $remote_url = 'http://uname:pw1234@example.com/service/node';

```

---
Tags: routes, users
---


title: db_query for a specific titles

text:
# Question
Title: db_query for a specific titles
I'm building a custom module for webform and I want to get only a title for a specific content type.

In phpMyAdmin with sql query I've managed to sort what titles I need. This is the SQL query:

```
SELECT title FROM `node` WHERE TYPE = 'outlets' AND uid

```

How can I wrap this into db\_query() ?

# Answer
You can read more about db\_query() here.

```
$result = db_query("
  SELECT title
  FROM {node} n
  WHERE n.type = :type
    AND n.uid =:uid
", array(':type' => 'outlets', ':uid' => $uid));

foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}

```
> 3 votes

---
Tags: database
---


# Question
Title: Theme is not working when files are uploaded from localhost to the web server
I have finally made it to point where i think it's ok to upload my work from localhost to a web server of mine.

I tried to upload my work from localhost to my web space (on hostgator).

My problem is that Drupal seems not to recognize the theme that is supposed to be used, including not identifying some custom template files I have written for views and nodes.

Same things work ok on localhost and page source code is generated ok (i.e. the correct path img src="http://localhost:8888/drupal/sites/all/themes/simpler/logo.png" is generated for my logo (custom)) but the same thing when uploaded on web server is not working and the path for img src is not generated at all in the page source.

I have several other problems, like custom tpl.php files (for nodes or views) are not used at all, i guess because the system for some reason does not reach (?) the /sites/all/themes/simpler .

I have tried flushing caches with no luck. Also, found some posts suggesting go clicking the 'Save changes' button in theme admin screens but no luck with this too.

If this means something, i have uploaded the whole 'drupal' folder from my localhost to my web server and switched the settings.php to point to my web servers db, which was created by importing .sql file (exported from my localhost).

Hope this whole thing makes sense and someone could help or point me to a direction.

# Answer
> 2 votes
Have you tried putting another theme as default, them uploading the database again ? If you then try to set your theme as default on the live site, it might work...

# Answer
> 2 votes
I know this is an old question, but there is very little guidance out there, and I thought I'd share what I just found out. Try putting the site into maintenance mode, and THEN flushing the caches. D7 (maybe D6, I don't know) has a weird bug/feature where the registry builder does not check the file system for new themes when the cache is flushed unless the site is in maintenance mode. See this thread for discussion: https://drupal.org/node/808030

# Answer
> 1 votes
Have you checked the permissions of the folders/files that you uploaded. It is one of the steps you should check in trying to find out why your theme is not working. I don't know hostgator or what level of access you have to your root directory (Drupal root) i.e. are you using shared hosting or a VPS? If on shared hosting you could use Filezilla to set permissions (remember to protect critical files such as settings.php). In my experience a lot of problems arise from file permissions being incorrect following uploads.

If you're sure the permissions are correct, you could try removing the old theme (or switching it off if it's Garland/Minelli) and setting the new one as your default and admin theme. Check the status report for errors.

Also, check the ownership and group of the folders/files that you have uploaded for example **root:www-data** for owner and group. Check the owner and group of the /sites directory and set your uploaded folders to the same.

If you think permissions are the problem, here is a useful guide on Drupal.org relating to this topic: http://drupal.org/node/244924

Regards,

---
Tags: 7, views
---


# Question
Title: How do I grab a list of all fields in a content type?
How would I grab a list of all the fields in a content type? Currently, I'm using entity\_metadata\_wrapper() to grab each field individually, but I feel that there's probably a more efficient way to get all of the values for a given content type.

# Answer
You can use the field\_info\_instances to get a list of all fields for a specific entity / bundle. In your case the entity would be 'node' and the bundle will be your content type.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: How can I reference two field without nid or uid?
I have two content types: 1.- Equipment and 2.- Configuration

The First CT has the following fields:

* Title : is equipment id with autocomplete module serial and hide for not capture.
* model : Text
* Serial : Text

The Second CT has the following fields:

* Title : is conf id with autocomplete module serial and hide for not capture.
* installed os : Check box (Yes|No)
* App Installed : Check box (Yes|No)
* Network Access : Check box (Yes|No)
* Serial : Text

I need make a relationship with field serial and then create a view that shows all properties of CT two.

Regards Advanced.

# Answer
1. enable entity reference module.
2. In the second CT , add an entity reference field.
3. In the field settings of the entity reference field select the first CT from a list of CT .
4. Create a view of second CT with all its related field.
5. Add relationship under the advanced options , add an entity reference relationship referencing first CT.
6. Then add all the fields of first CT.
7. use the module link - https://drupal.org/project/views\_dependent\_filters for equating the serial text field.
> 1 votes

---
Tags: views, entities
---


# Question
Title: How to hide published content to anonymous user programmatically?
I have created a new content type programmatically and I would like to set permission so that **anonymous users** do not see this content when it is published.

How can I do this?

# Answer
> 3 votes
By default, Drupals permission system does not support specific view permissions by content types. You will need a module for that. Have a look at Controlling Access to Content Overview. In Drupal 6 projects I have used Taxonomy access control lite quite offen.

# Answer
> 1 votes
Assuming Drupal 7, you can look into hook\_node\_access(), eg, something along these lines:

```
function YOURMODULE_node_access($node, $op, $account) {

  // If $node is a string, the node has not yet been created and we don't care about that case.

  if (is_string($node)) {
    return NODE_ACCESS_IGNORE;
  }

  $type =  $node->type;

  if ($op == 'view' && $type == 'YOUR_CONTENT_TYPE' && !$account->uid) {
    return NODE_ACCESS_DENY;
  }

  return NODE_ACCESS_IGNORE;

}

```

A good place to look for more information on this would be the `node_access_example` module inside the Examples Module.

# Answer
> -1 votes
You could use a custom module that:

* add a permission for every content type
* modify permissions to node/nid with hook\_menu\_alter

Obviously you can create a permission only for your custom content type.

Here is an example:

```
<?php
/**
 * Implements hook_permission.
 */
function mymodule_permission() {
  $permissions = array();
  foreach (node_type_get_types() as $type) {
    $permissions['view ' . $type->name . ' contents'] = array (
      'title' => t('View published contents for ' . $type->name . ' nodes'),
      'description' => t('Let users to see nodes of type ' . $type->name),
    );
  }
  return $permissions;
}

/**
 * Implements hook_menu_alter.
 */
function mymodule_menu_alter(&$items) {
  $items['node/%node']['access arguments'] = array(1);
  $items['node/%node']['access callback'] = 'mymodule_check_permission';
}

/**
 * Check permission
 */
function mymodule_check_permission() {
  global $user;
  if ($node->status == 1) {
    if (user_access('view ' . $node->type . ' contents', $user) || user_access('administer nodes', $user))) {
      return TRUE;
    }
  else {
    return user_access('access content', $user);
  }
}
?>

```

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


title: Expand views visible fields with ajax

text:
# Question
Title: Expand views visible fields with ajax
I'm searching for a module that can expand the number of visible fields in a particular view result with a mouse click. I'm probably not searching with the good words because I only thing I found is thing like "infinite scroll" or "view load more" module and that's not what I nead.

Example of what I nead : You have 10 view nodes showing the title and the image of a content type. And when the user pays "Read more..." the node is reloaded with Ajax adding the description to the result of this result.

Did somebody know a module that can do a thing like this?

Thanks a lot and sorry for my bad English, English isn't my first language.

# Answer
> 0 votes
The screen cast from Sean Buscay : How to use Drupal 7's built-in Ajax framework almost do that. The only difference is that the loaded nobe is always display on the same div base is id.

```
<?php

function ajax_reader_init() {
  drupal_add_js('misc/jquery.form.js');
  drupal_add_library('system', 'drupal.ajax');
}

/**
 * Implements hook_menu().
 */

function ajax_reader_menu() {
  // A menu callback is required when using ajax outside of the Form API.
  $items['ajax-reader'] = array(
 'page callback' => 'ajax_link_response',
 'access callback' => 'user_access',
 'access arguments' => array('access content'),
 'type' => MENU_CALLBACK,
  );
 return $items;
}

function ajax_link_response($type = 'ajax', $nid = 0) {
  $output = _ajax_reader_load_noder($nid);
  if ($type == 'ajax') {
    $commands = array();
    $commands[] = ajax_command_replace('#block-block-6', '<div id="block-block-6">' . $output . '</div>');
    $page = array(
      '#type' => 'ajax',
      '#commands' => $commands
    );
    ajax_deliver($page);
  }
  else {
    $output = '<div id="content">' . $output . '</div>';
    return $output;
  }
}

function _ajax_reader_load_noder($nid = 0) {
 return views_embed_view ('front','block', $nid);
}

```

Now the problem is I don't wan to send the result always to the same div. I wan to replace the view row by the new ajax loaded view. But I don't know how to pass the result to the good div.

```
    $commands[] = ajax_command_replace('#block-block-6', '<div id="block-block-6">'

```

Lets say I click the title of the third view row the nid of this third element is process in the module but I nead a way to pass the parent div class (view-row-3) to the function ajax\_reader\_menu()

Did anybody can guide me on that, thanks I know that I'm not super clear, but all this still vary obscure for the moment, sorry.

# Answer
> 0 votes
Ok passing the variable to the module is easy. I change the line : function ajax\_link\_response($type = 'ajax', $nid = 0) { by this line : function ajax\_link\_response($type = 'ajax', $nid = 0, $row\_number) { and edit the link to add this variable to adding the row\_number:

but now I don't know how to add the\_row\_number to the link. I'll study view theming and comeback with the result.

---
Tags: views, ajax, database
---


# Question
Title: change where Authoring information and Publishing options Checkbox is displayed
Currently Authoring information and Publishing options have options within their own how do you call it "tab/page". Example: When you edit a page you have to click Publishing options in order to see the **checkbox Published**.

I want that checkbox Published + it's functionality when checked somewhere else within the edit content page.

So there is no step where you have to click Publishing options. Should I do this with a custom block?

Can anyone assist because I really don't know how to do this :)

# Answer
In the admin/content page 1. at the top there is filters provided to sort content by number of options like for e.g filter by content type, published or unpublished. 2. then below that there is drop down containing list of actions like "publish selected content", "delete selected content", etc 3.You can select the check box corresponding to the content you want the action to perform and submit.
> 0 votes

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


# Question
Title: How to remove extra white spaces and line breaks from HTML in drupal 7
I am using drupal 7 and created my custom theme. Now I am facing problem that page is containing extra line breaks and while spaces when I open view source.

Can some one suggest any module/code snippet which minimize my html so that page render fast.

Else tell me where I can minimize it in my template.php file or any .tpl file.

# Answer
Agree with rooby, whitespace in html does not slow down the site performance.

You can use the Minify module to remove extra line breaks and whitespace before and after HTML tag.

Minify also minimize the JavaScript files. Minimized JavaScript files are smaller in size as compare to regular JavaScript files. Smaller size will helps you to load site faster.

To use Minify

* Download and install minify module
* Go to performace
* Select minify HTML
* To minify JavaScript files select Minify JavaScript files in upper right corner
> 3 votes

# Answer
I agree with all the suggestions so far. One other way I handle the injection of p tags and
conversions is through the content authoring settings. If you're using Full HTML settings on the node, you can edit how Drupal handles line breaks by visiting the config page at Configuration \> Content Authoring \> Text Formats \> Full HTML. Under the Cleanup and Output you could check the box to remove linebreaks.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Migrate addressfield: Call to a member function import() on a non-object in migrate/includes/migration.inc on line 696
also posted to Migrate issue queue as a support request

I am importing users and data from csv with a Migrate Group. The initial user creation and some additional data in other tables in working fine.

I have read everything I can find on Google about Migrate and Addressfield, and some of it is 2 years old and confusing. For example, Migrate has deprecated $arguments for field mappings, sub-fields are mapped with colon notation. Also, I am adding the Addressfield migration to a group so it gets the correct uid from the completed user migration, so posts about direct csv imports are not helpful.

I am getting a message when I migrate (with drush)

PHP Fatal error: Call to a member function import() on a non-object in /var/www/\[site\]/sites/all/modules/contrib/migrate/includes/migration.inc on line 696

I put a drush\_print\_r on that line

drush\_print\_r($this-\>destinationValues);drush\_print\_r($this-\>sourceValues);

the output of drush\_print\_r just before the error is

```
stdClass Object
(
    [entity_id] => 483
    [field_user_address] => Array
        (
            [0] => US
            [arguments] => Array
                (
                    [administrative_area] => NY
                    [first_name] => [actual first name]
                    [last_name] => [actual last name]
                    [locality] => New York
                    [postal_code] => 10028
                    [premise] =>
                    [thoroughfare] => [actual address]
                )

        )

    [revision_id] => 483
)

stdClass Object
(
    [Row] => 1
    [Type] => M
    [Prefix] => Miss
    [FirstName] => [actual last name]
    [MiddleName] =>
    [LastName] => [actual first name]
    [StaffNotes] =>
    [ColumbiaAffiliation] => Alumna/nus
    [ProfessionalAffiliation] =>
    [AddressLine1] => [actual address]
    [AddressLine2] =>
    [City] => New York
    [State] => NY
    [ZipCode] => 10028
    [Country] => Array
        (
            [0] => US
        )

    [TelephoneNumber] => [actual phone number]
    [Email] => [actual email]
    [Birthday] =>
    [ID] => [actual ID]
    [Descriptor] => [A] A: EN07
    [GraduationYear] => 2007
    [SchoolAffiliation] => EN
    [csvrownum] => 1
    [migrate_map_hash] =>
)

```

my field mappings:

```
$this->addFieldMapping('field_user_address', 'Country');
$this->addFieldMapping('field_user_address:administrative_area', 'State');
$this->addFieldMapping('field_user_address:locality', 'City');
$this->addFieldMapping('field_user_address:postal_code', 'ZipCode');
$this->addFieldMapping('field_user_address:thoroughfare', 'AddressLine1');
$this->addFieldMapping('field_user_address:premise', 'AddressLine2');
$this->addFieldMapping('field_user_address:first_name', 'FirstName');
$this->addFieldMapping('field_user_address:last_name', 'LastName');

```

and in prepareRow():

```
$row->Country = array($row->Country);

```

# Answer
I gave up with the Addressfield Migration Class and decided to do a db\_insert -- and it worked!

Not only works, but because I register the insert in the prepare() function of class SchoolMigration (where I was already using db queries) it also rolls back!

```
<?php
/**
 * @file migrate_users.migrate.inc
 * Our own hook implementation.
 */

/**
 * Migration classes for migrating users and user fields
 *
 * see Migrate handbook: https://drupal.org/migrate
 * and http://www.verbosity.ca/working-drupals-migrate-module
*/

/* useful functions for debugging using drush migrate commands:
drush_print_r($row);
drush_print_r($this->destinationValues);
*/

/**
 * Implements hook_migrate_api()
 *
 * Returns 'api' => 2 for the 7.x-2.x branch of Migrate.
 * Registers the migration classes for the 7.x-2.6 branch of Migrate (including
 * 7.x-2.6+xx-dev).
 */

function migrate_users_migrate_api() {
  $api = array(
    'api' => 2,

    // Migrations can be organized into groups. The key used here will be the
    // machine name of the group, which can be used in Drush:
    //  drush migrate-import --group=MigrateMembers
    // The title is a required argument which is displayed for the group in the
    // UI. You may also have additional arguments for any other data which is
    // common to all migrations in the group.
    'groups' => array(
      'MigrateMembersGroup' => array(
        'title' => t('Import Member Users'),
      ),
    ),

    // Here we register the individual migrations. The keys (MigrateMembers_Step1,
    // etc.) are the machine names of the migrations, and the class_name
    // argument is required. The group_name is optional (defaulting to 'default')
    // but specifying it is a best practice.
    'migrations' => array(
      'MigrateMembers' => array(
        'class_name' => 'MigrateMembers',
        'group_name' => 'MigrateMembersGroup',
      ),
      'GraduationYear' => array(
        'class_name' => 'GraduationYearMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
      'School' => array(
        'class_name' => 'SchoolMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
      'SchoolID' => array(
        'class_name' => 'SchoolIDMigration',
        'group_name' => 'MigrateMembersGroup',
      ),
    ),
  );
  return $api;
}

/**
* Abstract class as a base for all our migration classes
*/

abstract class MigrateMembers_Basic_Migration extends Migration {
  public function __construct($arguments) {
    // Always call the parent constructor first for basic setup
    parent::__construct($arguments);
    // Avoid known line ending issue: drupal.org/node/1705850
    ini_set('auto_detect_line_endings', TRUE);
  }
}

/**
* User-only migration
* (and creates $row (Row) with user id to key other tables in subsequent migration classes)
*
* The data file is assumed to be in
* sites/all/modules/migrate_users/data_sources/
* the columns in the csv must be in the same order left-to-right as the $columns array below
* every row in csv must have a unique id in the first column (can be ascending numbers, for example)
*/
class MigrateMembers extends MigrateMembers_Basic_Migration {

public function __construct($arguments) {
  parent::__construct($arguments);
  $this->description = t('Import an CSV-file (only "User Account"-fields)');
  $columns = array(
  // Format: ('Fieldname', t('Description'))
      0 => array('Row', t('Row number (must be unique)')),
      1 => array('Type', t('S = Student M = Member')),
      2 => array('Prefix', t('Mr. Mrs. etc')),
      3 => array('FirstName', t('First Name')),
      4 => array('MiddleName', t('MiddleName')),
      5 => array('LastName', t('Last Name')),
      6 => array('StaffNotes', t('Staff Notes')),
      7 => array('SchoolNameAffiliation', t('SchoolName Affiliation')),
      8 => array('ProfessionalAffiliation', t('Professional Affiliation ')),
      9 => array('AddressLine1', t('Address Line 1')),
      10 => array('AddressLine2', t('Address Line 2')),
      11 => array('City', t('City')),
      12 => array('State', t('State')),
      13 => array('ZipCode', t('Zip Code')),
      14 => array('Country', t('Country')),
      15 => array('TelephoneNumber', t('Telephone Number')),
      16 => array('EMAIL', t('Email')),
      17 => array('Birthday', t('Birthday')),
      18 => array('SchoolID', t('SchoolID')),
      19 => array('Descriptor', t('Descriptor')),
      20 => array('GraduationYear', t('Graduation Year')),
      21 => array('SchoolAffiliation', t('SchoolAffiliation')),
  );

  // TIP: delete ", array('header_rows' => 1)" in the next line, if the CSV-file has NO header-line
  $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
  $this->destination = new MigrateDestinationUser();
  $this->map = new MigrateSQLMap($this->machineName,
  array('Row' => array( // this field is used to connect user to other tables
          'type' => 'varchar',
          'length' => 6,
          'not null' => TRUE,
          'description' => t('User\'s Member-ID') // description never used
        )
       ),
  MigrateDestinationUser::getKeySchema()
  );

  // Mapped fields

  $this->addFieldMapping('name', 'EMAIL')
    ->defaultValue('')
    ->description(t('Name (User Account)'));
  $this->addFieldMapping('mail', 'EMAIL')
    ->defaultValue('')
    ->description(t('Email address'));
  $this->addFieldMapping('init')
    ->defaultValue('')
    ->description(t('Email address used for initial user-account creation'));
  $this->addFieldMapping('pass', 'PASSWORD')
    ->defaultValue('asdf')
    ->description(t("User's password (plain text)"));
  $this->addFieldMapping('is_new')
    ->defaultValue(TRUE)
    ->description(t('Build the new user (0|1)'));
  $this->addFieldMapping('roles')
    ->defaultValue(6)
    ->description(6 . t(' = "member"'));
  $this->addFieldMapping('theme')
    ->defaultValue('')
    ->description(t("User's default theme"));
  $this->addFieldMapping('signature')
    ->defaultValue('')
    ->description(t("User's signature"));
  $this->addFieldMapping('signature_format')
    ->defaultValue('filtered_html')
    ->description(t('Which filter applies to this signature'));
  $this->addFieldMapping('created')
    ->defaultValue(time())
    ->description(t('unique timestamp of user creation date'));
  $this->addFieldMapping('access')
    ->defaultValue(0)
    ->description(t('unique timestamp for previous time user accessed the site'));
  $this->addFieldMapping('login')
    ->defaultValue(0)
    ->description(t('unique timestamp for user\'s last login'));
  $this->addFieldMapping('status')
    ->defaultValue(1)
    ->description(t('Whether the user is active(1) or blocked(0)'));
  $this->addFieldMapping('timezone')
    ->defaultValue(t('Europe/London')) // 'America/Los_Angeles', 'Europe/Berlin', 'UTC', ... from drupal.org/node/714214
    ->description(t("User's time zone"));
  $this->addFieldMapping('language')
    ->defaultValue(t('en')) // e.g.: 'en', 'fr', 'de', ...
    ->description(t("User's default language"));
  $this->addFieldMapping('picture')
    ->defaultValue(0)
    ->description(t('Avatar of the user'));

  // Other handlers
  if (module_exists('path')) {
    $this->addFieldMapping('path')
       ->defaultValue(NULL)
       ->description(t('Path alias'));
  }
  if (module_exists('pathauto')) {
    $this->addFieldMapping('pathauto')
    ->defaultValue(1)
    ->description(t('Perform aliasing (set to 0 to prevent alias generation during migration)'));
  }
  // Unmapped destination fields
  $this->addUnmigratedDestinations(array('role_names', 'data'));
  }
}

class GraduationYearMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
  parent::__construct($arguments);
  $this->description = 'Add data to field_data_field_graduation_year';
  $this->dependencies = array('MigrateMembers');
  $table_name = 'field_data_field_graduation_year';

  $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
  $this->destination = new MigrateDestinationTable($table_name);
  $this->map = new MigrateSQLMap($this->machineName,
    array('Row' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
       )
     ),
    MigrateDestinationTable::getKeySchema($table_name)
    );

  // Mapped fields
  // add uid from completed MigrateMembers migration
  $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
  $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');

  // Insert Graduation Year value
  $this->addFieldMapping('field_graduation_year_value', 'SchoolAffiliation')->sourceMigration('MigrateMembers')
    ->defaultValue(date("Y"));

  // set some defaults from the schema
  $this->addFieldMapping('delta')
    ->defaultValue("0");
  $this->addFieldMapping('entity_type')
    ->defaultValue("user");
  $this->addFieldMapping('bundle')
    ->defaultValue("user");
  $this->addFieldMapping('language')
    ->defaultValue("und");

  $this->removeFieldMapping('path');
  $this->removeFieldMapping('pathauto');
  }
}

class SchoolMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = 'Add data to field_data_field_member_school';

    $this->dependencies = array('MigrateMembers');
    $table_name = 'field_data_field_member_school';
    $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationTable($table_name);
    $this->map = new MigrateSQLMap($this->machineName,
      array('Row' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
         )
       ),
      MigrateDestinationTable::getKeySchema($table_name)
      );

    $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('field_member_school_tid', 'SchoolAffiliation')->sourceMigration('MigrateMembers');

    // set some defaults from the schema
    $this->addFieldMapping('delta')
      ->defaultValue("0");
    $this->addFieldMapping('entity_type')
      ->defaultValue("user");
    $this->addFieldMapping('bundle')
      ->defaultValue("user");
    $this->addFieldMapping('language')
      ->defaultValue("und");

    $this->removeFieldMapping('path');
    $this->removeFieldMapping('pathauto');

  }

  public function prepareRow($row){
    // convert 3 letter codes to ISO 3166-1 standard 2 letter codes http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Current_codes
    // TODO:
    // 1 - check for full list of country codes in old data
    // 2 - many records with US addresses do not have a foreing country code, not the USA country code
    // 3 - What are INO SAF SWD?
    switch ($row->Country)
      {
        case 'AUS': // Austria
        $row->Country = "AT";
        break;
        case 'BEL': // Belgium
        $row->Country = "BE";
        break;
        [more mappings]
        default :
        $row->Country = "US";
        break;
      }

  }

  function prepare($entity, stdClass $row){

    // delete rows added by MigrateMembers
    $num_deleted1 = db_delete('field_data_field_member_school')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();
    $num_deleted2 = db_delete('field_data_field_user_address')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();

      switch ($row->SchoolAffiliation)
      {
        case 'AR': // Arts
        $row->SchoolAffiliation = "91";
        break;
        [more mappings]
        default :
        $row->SchoolAffiliation = "NULL";
        break;
      }

    $this->destinationValues->field_member_school_tid = $row->SchoolAffiliation;

    $fields = array('entity_type' => 'user', 'bundle' => 'user', 'deleted' => 0, 'entity_id' => $this->destinationValues->entity_id, 'revision_id' => $this->destinationValues->entity_id, 'language' => 'und', 'delta' => 0, 'field_user_address_country' => $row->Country, 'field_user_address_administrative_area' => $row->State, 'field_user_address_sub_administrative_area' => '', 'field_user_address_locality' => $row->City, 'field_user_address_dependent_locality' => '', 'field_user_address_postal_code' => $row->ZipCode, 'field_user_address_thoroughfare' => $row->AddressLine1, 'field_user_address_premise' => $row->AddressLine2, 'field_user_address_sub_premise' => '', 'field_user_address_organisation_name' => '', 'field_user_address_name_line' => '', 'field_user_address_first_name' => $row->FirstName, 'field_user_address_last_name' => $row->LastName, 'field_user_address_data' => '');
    db_insert('field_data_field_user_address')->fields($fields)->execute();
  }
}

class SchoolIDMigration extends MigrateMembers_Basic_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = 'Add data to field_data_field_SchoolID';
    $this->dependencies = array('MigrateMembers');
    $table_name = 'field_data_field_SchoolID';

    $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'migrate_users') . '/data_sources/drupaluser_import.csv', $columns, array('header_rows' => 1));
    $this->destination = new MigrateDestinationTable($table_name);
    $this->map = new MigrateSQLMap($this->machineName,
      array('Row' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
           )
         ),
        MigrateDestinationTable::getKeySchema($table_name)
      );

    // add uid from completed MigrateMembers migration
    $this->addFieldMapping('entity_id', 'Row')->sourceMigration('MigrateMembers');
    $this->addFieldMapping('revision_id', 'Row')->sourceMigration('MigrateMembers');

    //this assignment does not find the SchoolID; it is set in prepare()
    //$this->addFieldMapping('field_SchoolID_value', 'SchoolID')->sourceMigration('MigrateMembers');

    // set some defaults from the schema
    $this->addFieldMapping('delta')
      ->defaultValue("0");
    $this->addFieldMapping('entity_type')
      ->defaultValue("user");
    $this->addFieldMapping('bundle')
      ->defaultValue("user");
    $this->addFieldMapping('language')
      ->defaultValue("und");
    $this->addFieldMapping('field_SchoolID_format')
      ->defaultValue("plain_text");

    $this->removeFieldMapping('path');
    $this->removeFieldMapping('pathauto');
  }

  function prepare($entity, stdClass $row){
    // delete rows in table added by MigrateMembers
    $num_deleted = db_delete('field_data_field_SchoolID')
      ->condition('entity_id', $this->destinationValues->entity_id)
      ->execute();

    //
    if ($row->SchoolID) $this->destinationValues->field_SchoolID_value = $row->SchoolID;
    else $this->destinationValues->field_SchoolID_value = "NULL";
  }
}

```
> 0 votes

---
Tags: entities, migrations
---


title: apply a discount to product in Commerce

text:
# Question
Title: apply a discount to product in Commerce
I have a Drupal Commerce site and I'd like to apply a discount to the price where it is calculated. I have a table in the profile user with SKU | discount pairs and I'd like some way (maybe Rules?) to search the product on the table and apply the discount to the price.

Is there any way to do this in Drupal Commerce?

# Answer
> 1 votes
I use the Commerce Sale Price module with great success on my website. It is easy to configure. Just install and enable then you can set the discounts on the product pages.

Update: I think you could use Commerce Coupon to achieve your results. The coupons can be automatically applied based on a role. Sorry I did not understand your question fully before. Also, I have not used this module but the description appears to do what you want.

# Answer
> 0 votes
I can't give solution for your the values which you saved in the user profile as I have never had that situation but I can give simple solution based on the requirement which I understood from your comment.

You can set several rules for discount based on no. of items in cart & user type.

Rules work on 3 things - `Event`, `Condition` & `Action`.

So your **event** will be - `Completing the checkout process`.

**Condition** \- `Total product quantity comparison` & `User has role(s)`.

**Action** \- `Multiple the unit price by some amount` (Which you can set as per your discount model e.g. 0.95 for 5%, 0.92 for 8% etc).

---
Tags: entities, commerce, rules
---


# Question
Title: Node's cache isn't automatically cleared on update (intermittent problem)
Occasionally, about 1 out of 5 times, a node's cache isn't cleared when it is updated. Even going to view the revision that the update created or editing the node doesn't show the changes. Minimum cache lifetime is set to 1 minute but even after waiting for a minute and running cron it isn't automatically cleared.

It seems that this problem happens more during the site's busier times and we haven't been able to reproduce the issue in our development environment (which typically only has 1 user on it at a time). The cache tables are all InnoDB so I'm told this means we shouldn't need to worry about locking.

A similar problem with the chosen answer saying that this is just an issue of properly setting the minimum cache lifetime. But, I found this Drupal bug that implies that on node updates the cache should be cleared regardless of that setting. Though, its status is still "needs work" which maybe means a solution was never implemented and this is still the case.

## Update

Building off a patch in the bug and using `hook_node_update` I tried the following

```
function MYMODULE_node_update($node)
{
   // Forcibly wipe this node's page view from the cache because, if a
   // minimum cache lifetime is in effect, cache_clear_all() will not
   // clear any page cache entries younger than that minimum.
   //
   // Page cache cids are absolute URLs.  url() in absolute-mode will
   // get the aliased path if there is one, and we also wipe the
   // absolute version of the node/nid URL just in case.
   // Copied from http://drupal.org/node/256416#comment-838118
   global $base_url;
   cache_clear_all( url('node/'.$node->nid, array('absolute' => true))
                  , 'cache_page' );
   cache_clear_all($base_url .'/node/'. $node->nid, 'cache_page');
}

```

This should work around the minimum cache limit and only clear the cache for that node. Unfortunately, **this did not work**.

## Update 2

After digging further I discovered that running `cache_clear_all('field:node:<nid>', 'cache_field')` (where `<nid>` is replaced with the relevant node ID) cleared the correct cache when the problem cropped up. I tried putting this in a `MYMODULE_node_update()` hook but it did not resolve the issue.

In discovering this and following the path of the code I also discovered that the APC module is taking care of the caching and none of this is being stored in the database as I originally thought.

Knowing that the caching is being handled by APC and considering the intermittent nature of the issue it brings me back to a possible locking issue with APC. Would that even make sense? Preliminary searches have not revealed anything.

# Answer
> 0 votes
Ended up having more issues after upgrading the APC module. Talked to some others offline about their experience with Drupal and APC and confirmed that others experienced locking issues with APC. Switched to using memcached and the Memcache module and all our problems were solved. Haven't had an issue since switching, over a year ago.

# Answer
> 1 votes
I updated the APC module to 7.X-1.0-beta4 from beta3 and it seems to have fixed the problem. At least the client has not reported any further issues for several days now and we have not been able to reproduce the issue in our somewhat limited testing.

I noticed nothing in the change lot between beta3 and beta4 that would suggest a fix to this issue. I'm not convinced that this is what fixed it, but I have no other clues.

---
Tags: 7, nodes, caching
---


# Question
Title: Is it possible to request multiple nodes in one request using Services?
I would like to be able to make one request to the Services module node resource and have it return more than one node in the response. Is this possible?

# Answer
Enable the index crud operation on resources tab. After that you should get all the entities that are accessible to your authenticated request. I had to use hook\_entity\_info\_alter and custom access callback to provide everyones entities of specific type for my api role user.
> 0 votes

---
Tags: 7, services, entities
---


# Question
Title: Views exposed filters set per content type in same view
Sorry for my fuzzy title. The problem I have is that I have a view that lists 2 different content types. Now I want to use a filter that will only filter on ONE of the content types that is listed.

Say I have one content type named "Album", and one content type named "Songs" that gets listed in the same view. Now I still need to have them both listed in the same view, but I want to add the filter "First letter is A" to the songs ONLY. So the Albums gets listed as before, but the songs that doesn't start with the letter A is removed.

Is there any way to accomplish this?

# Answer
> 0 votes
1. Create a filter that filters on content type for **Album**
2. Create a filter that filters on content type for **Songs**
3. Create a filter that filters on title (set it to exposed and set the operator to "Starts with"
4. Under Filter Criteria instead of add, click on the arrow and choose "And/Or, Rearrange"
5. Click "Create new filter group"
6. Now drag the filter created in step 2 and 3 to the new group (Songs and Title)
7. Make sure the operator between the filter groups is OR and the operators between the filters in a group are set to AND

Your filters should look like

---
Tags: views
---


# Question
Title: Custom content type and views field rendering
I have a template views-view-fields--services.tpl.php

I don't want to iterate over the array of fields as I know which each of them are in this case.

I want to simply:

```
<div>
  <?php echo $row->title; ?>
</div>
<div>
  <?php echo $row->image; ?>
</div>

```

Doesn't appear to be a higher level template which might have this context of data???

UPDATED CODE SAMPLE:

**views-view--services.tpl.php:**

```
<!-- Services -->
<section class="site-section section-details">
  <?php print $rows; ?>
</section>

```

**views-view-unformatted--services.tpl.php:**

```
<?php foreach ($rows as $id => $row): ?>
  <alex>
    <?php print $row; ?>
  </alex>
<?php endforeach; ?>

```

**views-view-fields--services.tpl.php:**

```
<?php foreach ($fields as $id => $field): ?>

  <?php /*print $field->class;*/ ?>
  <?php print $field->content; ?>

<?php endforeach; ?>

```

Results in:

```
<section class="site-section section-details">
    <alex>

    <span>Entry #1</span>

    <div><img src="http://temp.local/sites/foo/test.png" width="280" height="280" alt=""></div>

    <div><p>Briefly describe which problems we can help with.</p>
</div>
  </alex>
  <alex>

    <span>Entry #2</span>

    <div><img src="http://temp.local/sites/foo/test2.png" width="280" height="280" alt=""></div>

    <div><p>Quickly describe the services we offer or how our services can help?</p>
</div>
  </alex>
</section>

```

# Answer
> 0 votes
Have a look at views-view-field.tpl.php. It' not used by default views, but available as a template override.

**Edit:** In views-view-fields.tpl.php you can also use `$fields['my_field_name']->content;` to access individual fields, but this will give you the fields default markup as well. The raw values can be accessed with `$fields['my_field_name']->raw` but those values must be proper sanitized before printing.

---
Tags: views, theming
---


# Question
Title: Is this the proper way to alter a path defined in code by another module?
I have installed the FAQ module on my site, and it defines the path to the FAQ page in code as 'faq-page'. I would like to make the path be 'mypath/faq' instead. I think I need to create a little module that implements `hook_menu_alter()`, so that if I upgrade the FAQ module, my custom path won't be overwritten. I think it should go something like the following:

```
/**
* Implements hook_menu_alter.
* Override FAQ page path defined by the FAQ module.
*/
function MYMODULE_menu_alter(&$items) {
  $items['mypath/faq'] = $items['faq-page'];
  unset($items['faq-page']);
}

```

Is this the proper way for me to override the path defined by another module?

# Answer
> 2 votes
No, that's not the right way. You are actually looking for aliases. They are provided by the Path module that is integrated in core.

It's possible to do it the way you propose, but it comes with possible side effects and is a little to much for what you want.

# Answer
> -1 votes
Yes,
with `$items['mypath/faq'] = $items['faq-page'];` you basically create an alias for '/faq-page', so you are not overriding anything.
For what you want to achieve is all you have to do.

The `unset($items['faq-page']);` instruction is unnecessary, use it only if you don't want that the original path will be a valid one and prefer a "page not found" error if some link still happen to point there.

---
Tags: 7, uri, routes
---


# Question
Title: Commenting option for each paragraph of a node body
I want to provide this option that users be able to put comment on each paragraph of an article that a user has posted in Drupal.

I have applied some changes to node.tpl.php file, like

```
$paragraphs = explode("<p>",render($content));

```

so I can render each paragraph with a for loop, like:

```
 $number=count($paragraphs);
 for ($i=1;$i<$number;$i++)
 print render($paragraphs[$i]);

```

Now, I want to write a module to provide the commenting option for each paragraph. I will use hook\_node\_view function to define a new field like:

```
 $node->content['paragraphcomment']

```

which is similar to

```
   $node->content['comments']

```

but the new one I am defining is a 2 dimensional array. so after

```
   print render($paragraphs[$i]);  // in node.tpl.php

```

I can write

```
   print render($content['paragraphcommnet'].

```

But I need to know in which file `$node->content['comments']` is defined. If anybody can help me with I would really appreciate it. Also if you think my solution is wrong, please let me know.

Thank you

# Answer
Have you looked at modules that may provide similar functionality like:

1. https://drupal.org/project/annotator
2. https://drupal.org/project/annotate

Other links:

1. https://groups.drupal.org/node/72748
2. https://github.com/patrickmj/Open-Review
3. https://groups.drupal.org/node/10875

They may not solve the problem you have but they may have code solutions that can help you go down the correct track
> 1 votes

---
Tags: nodes
---


# Question
Title: What is difference in the referencing entity options while adding a relationship in a views?
I have entity reference field field\_patient\_reference. While adding a relationship in views I get two options : What is the difference between the two options below:

> **Entity Reference: Referencing entity** A bridge to the Content entity that is referencing Content via field\_patient\_reference
>
> and
>
> **Entity Reference: Referenced Entity** A bridge to the Content entity that is referenced via field\_patient\_reference

# Answer
> 3 votes
Lets say that Content A references Content B via an entity reference.

Content B is the **Referenced Entity**, while Content A is the **Referencing Entity**.

It really depends on what you are trying to see. Say for example you pull a view of all content type B but want data from content A. In that case you would use **Entity Reference: Referencing entity**. If you have Content A and want data about Content B you would then use **Entity Reference: Referenced Entity**.

---
Tags: 7, entities
---


# Question
Title: How to create custom bundle of "User" entity using GUI?
Is it possible to create custom bundle from "user" entity without programming? Only using drupal administration? Are there any modules that could help to create such bundles?

I would like to achieve, that some user roles would have custom fields. I have found this module for creating fields per user role, but maybe it would be better to create custom user bundle.

# Answer
> 2 votes
I had the same requirement recently and was able to achieve this using the Profile2 module. Basically you set up profiles and add custom fields to that particular profile. Then you create a user using that profile. Works great but if you are pulling a view of these you must reference the profile in a relationship.

Profile2 https://drupal.org/project/profile2

# Answer
> 1 votes
If you are trying to restrict certain fields to particular user roles then Field Permission module is the perfect one.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you want to group certain fields under user entity then you might be looking for Profile2 module.

> The module is aimed to provide a simple, but extensible solution providing a similar end user interface like the core profile module by default. Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those.

---
Tags: 7, users, entities
---


# Question
Title: TB Megamenu - How can I reuse a menu with different megamenu configuration?
I have a Drupal core menu setup for my main menu that has \> 50 links setup. I've also got TB Megamenu configured for that menu to show the menus with pictures, etc.

Now I have a case in which I want to show the same menu content, but configured differently (to shown only standard flyouts with no images) on all pages but the home page.

I haven't been able to find a way to do this without duplicating the main menu link by link (which I obviously don't find sustainable).

Can anyone think of a way I could accomplish this?

(Note that I did try the Context module, which is great, but is not really suited for this purpose).

Thanks.

# Answer
> 1 votes
You can use Superfish module and reuse same main menu . All you need to do is configure super fish menu block with main menu.

Project page says

"Multi-column sub-menus. (Megamenus) Easing effects with the jQuery Easing plug-in, and many more...."

# Answer
> 0 votes
While the project page states this is an upcoming feature:

> Multi instances of one Drupal core menu for different styles/appearance

Meanwhile you can hide (css) or better, unset (custom module) the images for particular pages.

---
Tags: routes
---


title: How to run <script> code in a block

text:
# Question
Title: How to run
 To get the BRENT oil price, please enable Javascript.
`

# Answer
1. Create a block (navigate to **Structure** -\> **Blocks** -\> **Add block** or **http://example.com/admin/structure/block/add**)
2. Make sure you set the **Text format** of the block to "Full Html"
3. Paste in your embed code

Please be aware of the security risks involved http://example.com/admin/help/filter, https://drupal.org/node/213156
> 3 votes

---
Tags: blocks
---


title: What is the purpose of caches?

text:
# Question
Title: What is the purpose of caches?
I was wondering why caches exist. As a Drupal newbie, I often read solutions for all kind of problems that mention "you have to clear caches". Therefore, it appears to me that they only have disadvantages. This may sound a bit naive, but I would like to know what their purpose is.

# Answer
Caching decrease your page load time and speed up your site. It is used especially when you have images, maps, videos and audio on your page. We can use drupal internal cache or integrate other caching tools like APC, Mem Cache, Varnish with our drupal site.

**Why we clear cache?** When we made some new changes in our theme or code, so to test them we clear old cache so that old data will be removed from cache and new data will be loaded to be displayed changes.
> 2 votes

# Answer
For a very beginner guide to caching and why it's helpful try this link

and if you still wanna get a little (just a little) more into it try this Lullabot article
> 0 votes

---
Tags: caching
---


# Question
Title: Website is getting very high load due to "UPDATE cache SET data..."
It's a high traffic website, but I guess high load is not because of traffic because many times it runs smooth on same traffic. I researched a lot and optimized Apache, switched off logging modules to save resources and done whatever may be cause of load. Then finally I installed devel on site and check using "Collect query info", "Display query log" and I found that this particular query taking too much time (more than 2000 ms)

```
UPDATE cache SET data = 'a:2:{s:7:\"profile\";a:36545:{s:32:\"c21f969b5f03d33d43e04f8f136e7682\";a:17:{s:6:\"layout\";s:7:\"default\";s:14:\"layout_desktop\";s:7:\"default\";s:15:\"layout_handheld\";s:2:\"-1\";s:13:\"layout_iphone\";s:2:\"-1\";s:4:\"menu\";s:13:\"primary-links\";s:10:\"menu_style\";s:4:\"mega\";s:11:\"option_font\";s:1:\"0\";s:14:\"option_layouts\";s:1:\"0\";s:11:\"option_menu\";s:1:\"0\";s:13:\"option_screen\";s:1:\"1\";s:13:\"option_t3logo\";s:1:\"1\";s..........................................................

```

and page getting loaded and loaded to infinite time, it never completes. I am sure this is the only reason for high load on server.

APC is already installed on my seerver.

# Answer
> 1 votes
Given your server already has APC installed, you do not need to keep cache in database at all. And probably shouldn't.

Install APC module (for older Drupal versions see Cacherouter or Cache Backport) to move your cache from MySQL to RAM. Without it, APC only caches opcode, not Drupal's cache data. Also, APC Status or APC Admin module helps with monitoring.

It might be wise to exclude form cache from APC and keep it in database, but that's material for another question.

For APC optimization, see this question.

---
Tags: database
---


title: Private Files and corrupted files

text:
# Question
Title: Private Files and corrupted files
Hello fellow Drupal expert,

I'm in search of wisdom. Some said i can find it in here :)

Okay so here's my issue. We got an intranet and we'd like to have some privacy (if you know what i mean). We're using IMCE and a module called private\_file\_download\_permission (so we can map our existing roles to folders). But nothing is working, we can set private folders (and control their access) but every file we upload (through IMCE)is being corrupted.

Let me explain cause i've found some interesting things. First, if i download my file through FTP it work well. But if i go through the website it is corrupted. So I looked around and find that when i open my file with a text editor there's 2 empty lines added to it and if i delete them the file goes back to normal. But remember this happen only when the file is put on a private folder (works fine on public ones).

Have you some idea of what kind of sorcery is going on ?

Sorry for my english, and thank you for your answer; Rémi

# Answer
> 2 votes
Ok my colleague found the solution !!

There was 2 lines added at the start of our settings.php :

This thing added lines at our downloaded files and corrupted them !!

Ok so thank you for your time :)

---
Tags: files
---


title: Calling web service on page load

text:
# Question
Title: Calling web service on page load
Until now I'm calling a web service with using specific function like hook\_user\_logout, \_validate, \_submit..., but now I need to create a page that will display details that I'll receive results from the web service, but I don't know how to call when I enter lets say user/%/reports.

Also on that page there will be a link that will display more details that will come from the webservice.

Is there a function for page load, url open or something similar in Drupal 7?

Here's my part of the code when a user logouts.

```
<?php

function mymodyle_user_logout($account) {

    global $user;

    $username = $user -> name;
    $ip_address = $_SERVER["REMOTE_ADDR"];
    $session_id = session_id();

    $xml_string = '<some_method>
       <username>' . $username . '</username>
       <ip_address>' . $ip_address . '</ip_address>
       <session_id>' . $session_id . '</session_id>
       <language>en</language>
       </some_method>';

    $client = new nusoap_client('http://10.10.60.80:8090/CardHolderAuthentication.asmx?wsdl',  array('soap_version' => SOAP_1_1, 'trace' => 1, 'exeptions' => true));
    $client -> soap_defencoding = 'UTF-8';
    $client -> decode_utf8 = FALSE;

    $result = $client -> call('Logout', array('_xml' => $xml_string));

    //$response = simplexml_load_string($result['LogoutResult']);

    //$status = $response -> error->descr_bg;

}

```

# Answer
> 1 votes
If the page content needs to be fetched via an API request, you can use

`hook_menu`

to define a URL path to function callback to generate the page content.

Basically your own path to the content.

The page callback will fetch the API response from cache or perform the request, cache the response and display it.

---
Tags: services
---


# Question
Title: Using References module, is it possible to only show nodes created by the logged in user in select list?
I made a node reference field and it gives me a select list of all the nodes of a specific content type. However I only want the select list to show the nodes made by the logged in user. Is there any way to set conditions some way?

# Answer
> 0 votes
You can try making a views which return the list of all node title created by the user & then use View reference module to have field calling that.

---
Tags: 7, nodes
---


title: Add custom URL to Image on a node

text:
# Question
Title: Add custom URL to Image on a node
I'm using Drupal 7, and my nodes have an image and a weblink in seperate fields, The weblink is using the link module so not sure if that will complicate things here. (if so I could downgrade the link field to a text field)

anyway I'd like to create an `<A>` tag around my image whilst its being themed and I want the `href` or that `<a>` tag to point to the weblink url. Sounds like an easy thing to do hey... well I can't figure it out at all! so any help would be awesome :)

# Answer
If I understand well your question, an alternative can be edit your image field ("Configure field" options) and select `Rewrite results > Rewrite the output of this field`. Here you can make lots of things with your image, for example add a link from other **previous** view field, over your image.

here one example to string included in the rewrite field:

```
<a href="[field_link_test]">[field_image_test]</a>

```

in this example \[field\_test\_link\] is a text field with the respective web address, and \[field\_image\_test\] is the field that comes with the image.

this image comes from Drupal 7, but this steps also are possible in Drupal 6
> 4 votes

# Answer
As far as I know there is a module called Link Image Field

> LinkImageField is a CCK module that allows you to specify the hyperlink for images with a custom URL. The CCK ImageField allows links from the image to the node or to the image itself, but not to a user supplied link.
>
> Features Upload Image Title for the Image Alternative Text for the Image URL to hyperlink the image Example Use: Your site supplies a product image and description, but you want the image to link off-site to an affiliated web store.

You can find a port to D7 here.
> 0 votes

# Answer
Drawnword,

This is what worked for me:

Under Rewrite Results, scroll down until you see "Replacement Patterns".

Here is where you will see which tokens are available to include in the field.

Simply copy the tokens and paste them in the field above using the string provided by moon.watcher.

If you don't see your tokens, go back to the view, and rearrange the fields. In my case, I moved "Company Link" above "Company Logo".

I hope this helps!
> 0 votes

# Answer
This works fine on Drupal 6 just ensure to put the alias in the link to page field you create in your content type, not the absolute path.
> 0 votes

# Answer
LinkImageField is a CCK module that allows you to specify the hyperlink for images with a custom URL. The CCK ImageField allows links from the image to the node or to the image itself, but not to a user supplied link : http://drupal.org/project/image\_link\_formatter
> -1 votes

---
Tags: entities, media, uri
---


title: Which template used for adding nodes

text:
# Question
Title: Which template used for adding nodes
I want to add some custom checks to all of my Drupal pages (except the administration pages).

I am using **Bartik** theme that comes with **Drupal 7.26**

**I added the custom check in node.tpl.php and the check worked for all urls of type /node/% <br>However, I also want to add this check for node add, edit and delete pages. I cannot do this.**

What I have already tried:
-\> Creating a node--add.tpl.php in bartik folder and adding check there.
-\> Creating a custom module, and using hook\_menu to route /node/%/id to a custom page.
-\> Adding this function

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

```

in my bartik template.php file. After adding this function I created node-add-product.tpl.php file and added check there.

For all the methods I have tried, the node creation page does not change at all.

I also tried creating page--node--add.tpl.php. Then the custom check works. But the header, footer, and sidebars disappears. (Only node creation template is rendered)

# Answer
I think you are using the wrong tpl file to edit the node/add/\[content-type\] form.

You need to create (if I remember correctly) a \[content-type\]-node-form.tpl.php and add the required elements you wish from there. See here for more details:

https://drupal.org/node/1092122
> 0 votes

---
Tags: theming
---


title: Prevent node from being saved

text:
# Question
Title: Prevent node from being saved
So, this seems like a rather simple task but I've been stuck on it for a while.

I need either in `hook_node_presave` or in `hook_node_submit` (but NOT in `hook_node_validate`) to check for a field value in a node and according to that value choose whether or not to cancel the node saving procedure.

How do I do that? (The canceling part, not the checking part ;) )

# Answer
Implement drupal\_goto()

I believe this function obliterates any followup processing other than saving session data and forwards the user immediately on to a new page.

> Excerpt from Drupal.org: drupal\_goto();
>
> This function ends the request; use it instead of a return in your menu callback.

To define where the users will be sent to, simply pass the same data you would to the url() function.

For example:

```
drupal_goto('node/44');  // Sends users to yoursite.com/node/44

```

An update regarding the drupal\_goto() function from a submit handler (See https://drupal.stackexchange.com/a/33281):

```
//Note from https://drupal.stackexchange.com/a/33281
//When using drupal_goto() from a submit function you may need to be more aggressive.
$url = url("node/$nid");
header("Location:$url");
drupal_set_message(t('Message to be displayed in the next page'));
drupal_exit();

```
> 2 votes

# Answer
I've found that the best way is to just thrown an error during presave. Here's a simple example:

```
function mymodule_node_presave($node){
  if(empty($node->title)){
    throw new Exception('Error saving node: Title cannot be empty');
  }
}

```

The node\_save() function has a try...catch block wrapping the presave step that will catch the exception.

The advantage of this over drupal\_goto() is that, if you're importing multiple nodes, it will skip the current node and proceeed to the next one. This is great if you're using something like the Feeds module. In contrast drupal\_goto() will exit immediately and may interfere with other steps in the request or cron, which will break importing multiple nodes.
> 9 votes

---
Tags: 7, nodes
---


# Question
Title: How can I export shortcut sets and shortcut links in Drupal 7?
I am using Drupal 7 and I have some **shortcut sets** (per role using the shortcut per role module) **and shortcut links** in them and I would like to **export** them either using the **features** functionality or with any other exporting mechanism.

But I do not find any relevant exportables in the features exporting options not even in the **Strongarm** section. Is there a way yo do this or should I manually recreate them in the other site installations?

I have also seen a relevant question but it does not have any answers regarding the shortcuts part.

# Answer
Finally, managed to **programmatically** create the shortcut sets and links with the following php script:

```
<?php
echo 'populating shortcuts...';
$shortcut_set = new stdClass();
$shortcut_set->title = 'Default';
$shortcut_set->set_name = 'shortcut-set-1';
$shortcut_set->links = array(
    array('link_path' => 'admin', 'link_title' => 'Admin',),
);
shortcut_set_save($shortcut_set);
echo ' shortcuts population finished';
?>

```

as mentioned in this drupal post.

A also had to apply this patch in shortcut module, which fixes the shortcut\_set\_save function called by the script.
> 2 votes

---
Tags: 7, navigation, users, features, importing-exporting
---


# Question
Title: limit access to some configuration pages (manage display and manage fields)
I have editor and administrator role in my website, the editor role must have `"Administer vocabularies and terms"` permission (in `admin/people/permissions` page),

How can I restrict editors from "manage display" and "manage fields" **without uncheck** `"Administer vocabularies and terms"` , so they can't access to this page : `admin/structure/taxonomy/VOCABULARY_NAME/display/`?

# Answer
I would probably go into one of my custom modules and:

invoke a hook\_permission() with my new needed permission (administer display and fields) that will be granted only to admin.

Then invoke hook\_menu\_alter() to alter the access control on the menu path the taxonomy module creates.

This way on install admin will be granted automatically the permission and only the roles granted this permission will be able to access that page.
> 1 votes

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


# Question
Title: What is the URL for configuring OAuth2 services?
If this is the code in `oauth2_servers.services_auth.inc` module, what is the url to enable the "require authentication" checkbox?

```
/**
 * Services authentication "controller_settings" callback.
 */
function oauth2_server_services_controller_settings($settings, $controller, $endpoint, $class, $name) {
  $form = array();
  $form['require_authentication'] = array(
    '#type' => 'checkbox',
    '#title' => t('Require authentication'),
    '#default_value' => isset($settings['require_authentication']) ? $settings['require_authentication'] : FALSE,
  );
  $form['scope'] = array(
    '#type' => 'textfield',
    '#title' => t('Scope'),
    '#default_value' => isset($settings['scope']) ? $settings['scope'] : '',
    '#description' => t('A space-separated list of required scopes. Leave empty to ignore the check.'),
  );

  return $form;

```

# Answer
> 1 votes
You enable OAuth2 authentication in admin/structure/services/list/$yourserver, then on the Authentication tab (admin/structure/services/list/$yourserver/authentication) you select the OAuth2 server. After that, once you go to the Resources tab (admin/structure/services/list/$yourserver/resources) you will see the mentioned settings in the Settings column for each resource.

Make sure that you have the latest -dev release of Services, or the patch mentioned on the OAuth2 Server project page applied, otherwise it won't work.

---
Tags: authentication-authorization
---


title: Role based menu redirect

text:
# Question
Title: Role based menu redirect
## Setup:

I have a main module (called public) and several sub-modules that extend the support offered by the public module.
A sub-module (let's call it sub) functions can be accesed only by users with the role that that sub-module creates (guess what, called sub).

Some of the pages defined in public\_menu() are extended by the pages defined by sub\_menu().

For example, if the public module declares:

```
$pages["public/asl/info"] = array('page callback'=>'public_asl_info', ...);

```

the sub module declares:

```
$pages["sub/asl/info"] = array('page callback'=>'sub_asl_info', ...);

```

also, consider that sub\_asl\_info() extend public\_asl\_info() like this:

```
function sub_asl_info( $id)
{
    $public_page = public_asl_info( $id);
    $dip_page = sub_asl_dip_info( $id);

    $page = $public_page.$dip_page;

    return $page;
}

```

there are more complex cases, but this is enough to explain the setup :)

## How i solved it (**wrongly**) so far:

```
function sub_menu_alter( &$item)
{
    if( !has_role( 'sub'))
        return;

    $item['public/asl/info']        = $item['sub/asl/info'];
    $item["public/operatori/info"] = $item["sub/operatori/info"];
    $item["public/ospiti/info"]     = $item["sub/schedario"];
    $item["public/query"]           = $item["sub/query"];
    $item["public/tassonomia"]  = $item["sub/tassonomia"];
    $item["public/comunicazioni"]   = $item["sub/comunicazioni"];
}

```

The redirects are hard saved inside the menu\_router table, so with more than one user logged it doesn't work.
I came to this solution based on how i solved the same problem but for blocks, however, using \_block\_view\_alter() doesn't hit the same wall.

## How do i solve this (programmatically)?

Possibly without using yet-another-module, unless really neccessary.

# Answer
> 0 votes
The final solution was much easier than i could possibly hope for.

I ended defining my own hooks and allow the sub-modules to implements the changes using said hook,s after checking the role of the user. Using the example above, it became:

```
function sub_asl_info_alter( $page, $id)
{
  if( has_role('sub'))
    $page->content .= sub_asl_dip_info( $id);
 }

```

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


# Question
Title: Displaying taxonomy terms and its contents with views
I am quite new to Drupal and I'm having troubles in some tasks.

I need to show food categories and food products as its contents. In order to do that, To begin with, I created a content type with the field of taxonomy term reference for products and taxonomy vocabulary for categories.

Secondly, I added categories as taxonomy terms and products as content by choosing its related category. Everything is fine up to now.

For the categories page output, I created a view to show categories (taxonomy terms) and set details as below:

Fields Taxonomy term: Name

Filter criteria Taxonomy vocabulary: Machine name (= Food Categories)

path: /categories

This page help me to show categories.

For the other page that needs me show each product(content) for the selected category I created another view and set details as below:

Fields Content: Food Category Content: Title

Filter Criteria Content: Type =(Food Product)

Contextual Fiter Content: Food Category (filed\_food\_category)

Contextual filter settings are:

When the filter value IS in the URL or a default is provided Option: Override title is checked and value is %1

Specify validation criteria Option: Validator is checked and set taxonomy terms where vocabuary is food categories Filter value type set to Term name converted to term ID

Option: Transform dashes in URL to spaces in term name filter values is checked

path: /categories/%

This view is able to show me each content related category. For example when I tried to type /categories/category-1 I can see output through this view properly.

And I needed category titles from the first taxonomy terms page redirect me second view which shows each product under the related category. To achieve this I set url each alias of taxonomy terms as categories/category-name and checked the option of the filed Taxonomy Term:Name as Link this field to its taxonomy term page.

But here is the problem. When I attempt to click link on each food category (taxonomy term) provided by first view redirect me another page while it is supposed to redirect to second view page. After some research I figured out that links on the first taxonomy terms view redirect me default taxonomy page. And I read that it's possible to override default taxonomy page by using some extra module called Taxonomy Display and Display Suite. After installation modules and I follow the insturctions, I found out the option taxonomy terms page display under the related taxonomy vocabulary. I set Associated content display as views and picked related view(second view I created) but I can't get output of second view. I get all content listed(not filtered).

Please help me, I feel very desperate. Thanks in advance.

# Answer
Open a view you have create

1) set the path: /categories

2) add a **CONTEXTUAL FILTERS** as

3) OR add a **RELATIONSHIPS** as

after save a view
> 2 votes

---
Tags: taxonomy-terms, views, display-suite
---


# Question
Title: webform "Load a pre-built option list" not shown
I use the webform module to build a form. I'd like to fill a select with values coming from a database. I use the hook

Here is some sample code:

```
    /**
     * Implementation of hook_webform_select_options_info().
     * See webform/webform_hooks.php for further information on this hook in the Webform API.
     */
    function custom_webform_pre_build_list_webform_select_options_info() {
        $items = array();
        $items['user_roles'] = array(
            'title' => t('Roles'),
            'options callback' => 'custom_webform_pre_build_list_user_roles'
        );

       return $items;
    }

    /**
     * Build an options list to be used with webforms select list based in drupal roles
     */
    function custom_webform_pre_build_list_user_roles() {
        $roles = user_roles();

        $contentarray = array();

        $contentarray[0] = t("Select user role");

            #$new_taxonomies = array();
            foreach ($roles as $role) {
                $contentarray[$role] = t($role);
            }

        return $contentarray;
    }

```

I activated the module. Now my problem is to select this list of entries for my select. I cannot see the "Load a pre-built option list" when I click "Add" under "options" for the select box in the form builder. What am I doing wrong?

I'm using version 3.x of webform and the "Options element" module.

Thx, Sven

# Answer
> 1 votes
I had the formbuilder module activated. There is no possibility to "Load a pre-built option list"! I deactivated it then it works. The problem is, there is not a nice builder ui anymore ;-(

---
Tags: hooks, webforms
---


# Question
Title: Webform Submission not Working with .tpl.php file
I have a webform that i needed to style a little differently. So I did this creating a `webform-form-3.tpl.php` file (the node of my form is 3). Inside that I have this code:

```
<?php // Contact Us form ?>
<div id="left-column">
    <?php print drupal_render($form['submitted']['event']);?>
</div>
<div id="right-column">
    <div class="form-actions">
        <?php print drupal_render($form['actions']['submit']);?>
    </div>
</div>

```

Unfortunately, by doing this, it stops the submitting functionality of the form. I am assuming that I messed up on missing some of the submitting options. Does anyone have any ideas where i may have gone wrong? Any help would me much appreciated! Thank you!

# Answer
> 5 votes
Stick this at the bottom:

```
<?php echo drupal_render_children($form); ?>

```

---
Tags: 7, theming, webforms
---


title: Wrong path with drupal.add.js

text:
# Question
Title: Wrong path with drupal.add.js
The problem occurs when a node alias consists of a backslash.

My example:

```
drupal_add_js(path_to_theme() . '/js/script.js', array(
    'type' => 'external',
    'scope' => 'footer',
    'weight' => 5
));

```

Now I have a node with the alias EXAMPLE/example.html

The path to the script.js is now **`domain.com/EXAMPLE/sites/all/themes/example/js/script.js`** and not **`domain.com/sites/all/themes/example/js/script.js`**

What do I do to make the path right?

# Answer
> 0 votes
Try making it absolute:

```
$options = array(
  'type' => 'external',
  'scope' => 'footer',
  'weight' => 5,
  'absolute' => TRUE
);
drupal_add_js(path_to_theme() . '/js/script.js', $options);

```

# Answer
> 0 votes
You can avoid that by making the path absolute starting from the base path of your Drupal install. You can use the `base_path()` function get the base path (which really just returns the GLOBAL `$base_path` with a slash (`/`) added to the beginning and end, or just a slash if there is no base path.

```
$options = array(
  'type' => 'file',
  'scope' => 'footer',
  'weight' => 5,
);
drupal_add_js(base_path() . path_to_theme() . '/js/script.js', $options);

```

Also, "type" should be set to "file" unless you're loading an external file with a full path.

---
Tags: javascript, uri
---


# Question
Title: Drupal Commerce: How to perform a complex calculation of order's final cost (VATs & discounts)?
Here's is what I want to accomplish:

* There are 2 taxes in my country: 6.5% & 23%. Every product has to be matched with 1 of these 2 VATs (I'm currently using a taxonomy vocabulary holding these 2 VAT values instead of using commerce tax module)
* A discount should always be available, **based on total order's amount, excluding tax** e.g. an order's total (with no tax included in base prices) of €0,01-€50,00 awards the customer with a discount to the order's total (including tax) of -5%, from €50,01 to €80,00 gives a discount of -8% etc etc

What I want to accomplish: \- Customer adds products to cart (product prices are displayed excluding tax, ie w/o components) and heads to checkout. According to order's total (addition of products' base prices w/o tax), the appropriate discount will be applied. \- Final Price = (Products' base prices + their appropriate taxes)\*Pre-calculated Discount + Shipping Cost

**Example**: Shopping cart includes: \- Product 1: €20 base price (6.5% VAT) \- Product 2: €25 base price (23% VAT) Checkout Process:

1. Discount pre-calculation: Total base price is €20 + €25 = €45. As a result, the customer should be awarded with a -5% discount (see available discount rates above).
2. Order's total including products' VATs = (€20 + €20\*0.065) + (€25 + €25\*0.23) = €21.30 + €30.75 = €52.05
3. The pre-calculated -5% discount from step 1 is applied: €52.05 - €52.05\*0.05 = €49.45 and that's what the customer has to pay for the products in his/her cart.
4. Order's weight is calculated and a shipping flat rate is applied (I have this functionality already working). As a result, the shipping cost is added to €49.45 and we finally get the sum that the customer will have to pay using one of available payment methods.\*

I would appreciate your suggestions on how to make this happen.

Tricky parts:

* different products can have different VAT (23% or 6.5%).
* The discount has to be calculated by adding all products' base prices (NOT including tax) and THEN applied to line item (including tax) prices.
* It would also be nice if VATs & discount were displayed to customer in order's review.

# Answer
> 2 votes
You can achieve what you're looking for using some module and disabling others. This explanation is based on Drupal Commerce (7.x).

1. Uninstall standard Commerce Tax module since it leads to weird results with different VAT if you aren't a Rules master as exposed in this issue on drupal.org.
2. Install Commerce European Union VAT (commerce\_eu\_vat) choosing the right country: the module has a good written API and you can adapt it for extra-EU countries easily. Now you can assign product by product the right VAT and even assign a default VAT by product type via "manage fields" on product variations administration.
3. Install Discount (commerce\_discount) module. You can set discount per product and per order (your case). Create a new discount, e.g. "My funny discount".
4. Now you can create your per-order discount. Every time you create a new discount it appears on both Discount page and on Pricing rules. Since VAT is sometimes applied before Discount (in my case it was) then you have to change the Rule weight for your new discount. Go to the Pricing rules administration page, search for "My funny discount" \> edit \> Settings \> Weight and give it a negative weight to apply the discount before the VAT. Note: when you override the discount you cannot save it anymore since you've changed the parent Rule. Just revert the rule to make it editable again and then reapply the weight trick.
5. Now you have to hide unwanted components from your price on display: to do this install Commerce price by components (commerce\_price\_components). On your product type \> Manage display you can change your price field widget from "Formatted amount" to "Price by components" and check only Discount and Base price, excluding VAT and other components.

Here the result on checkout:

Hope this helps.

---
Tags: commerce, rules
---


# Question
Title: Retrieve node information in VIEWS template(s)
I have figured out I need to override two templates:

1. views-view-fields.tpl.php
2. views-view-unformatted.tpl.php

Basically my node has an "align" property which I need to access in both templates to properly generate the expected markup.

```
<?php echo '<pre>'; print_r(get_defined_vars()); exit; ?>

```

Using this I can see I have a monster of a structure at my disposal but the I am nervous about traversing such a structure as the slightest change to it's arrangment means my template(s) would break!!!

Ideally I would like to implement a preprocessor such as:

How can I add variables from a preprocessor function to be used in an unformatted view template?

Basically add the "align" value from the node to a simple variable which I can then access and check inside both templates listed above...

Suggestions???

# Answer
> 0 votes
You can use `hook_preprocess(&$variables, $hook)`to find out which hook you have to react on, in your case it should be `hook_preprocess_views_view_fields()` and `hook_preprocess_views_view_unformatted()`.

Next you have to find a way to access the node object. If your view is node based, then there should be an nid somewhere in the variables array. Don't be afraid to dif into the `$variables` array. You can use dpm (devel module) or `print_r`or whatever you're comfortable with. You can't really break anything without manipulating the array.

---
Tags: views, theming
---


# Question
Title: Multiple sites, each is either one page (with multiple editable content) or has multiple pages
I tried researching into this on google for a while, but I'm stuck.

Basically what I'm trying to do is this: I have a "big" main website. Then, on the same drupal installation I want to have a "mini" site that will have a completely different theme, and only one page (but the page will have multiple editable content). I also will have another site that will have a completely different theme, completely different navigation, and multiple pages. Final piece that has me puzzled is that this will be on a subfolder basis. By that I mean / will have the main site, /sitea will have the single page site, and /siteb will have the multipage site.

Any suggestions on how to handle this?

# Answer
> 0 votes
If you don't need multiple domains (or sub-domains for that matter) you could probably get away with using a custom module to simply switch themes under a given criteria (URI path, user role, etc).

How do I change a theme based on the URL?

---
Tags: multi-sites, subsites
---