# Question
Title: add user profiles fields into comment fields
I'd like when a user comments, to display his information.

Let's assume I do have in my user profile 2 fields, Job title and Biography.

When a user comments, I would like to get those 2 fields and display them as comment fields.(same for existing comments) It will then display the comment + job title + bio

What the best solution for that ?

I was thinking about a preprocess to load the $user but maybe there is some configuration which could do it instead. In this example I added 2 fields in the comment section of my content type then I'm trying to get the user profile infos to the current fields.

```
function template_preprocess_comment(&$vars) {
      if($vars['comment']->uid !== 0){
        $user = user_load($vars['comment']->uid);
        $vars['field_job_title'] = $user->field_job_title;
        $vars['field_bio'] = $user->field_bio;
      }
}

```

Final approach was: For the existing one that what I came out with:

```
function hook_user_presave(&$edit, $account, $category){
    //get all node we need
    $results = db_select('node', 'n')
                  ->fields('n', array('nid'))
                  ->condition('type', 'my_content_type', 'LIKE')
                  ->execute();

    foreach ($results as $result) {
        $nids[] = $result->nid;
    }
    foreach ($nids as $key => $nid) {
        //get all comment ids
        $result = db_select('comment')
            ->fields('comment', array('cid'))
            ->condition('nid', $nid, '=')
            ->condition('uid', $account->uid, '=')
            ->execute();

        $cids = $result->fetchCol();
        $comments=comment_load_multiple($cids);
        foreach($comments as $comment) {
            //load comment
            // $user = user_load($comment->uid);
            if(isset($edit['field_job_title']) && isset($edit['field_bio']) && $account->uid !== 0){
                //change data of the comment
                $comment->field_job_title = $edit['field_job_title'];
                $comment->field_bio = $edit['field_bio'];
                //save it
                comment_save($comment);
            }
        }
    }
}

function hook_comment_presave($comment) {
    //if not user, otherwise it does it when you do the comment_save($comment) from the user_presave, then it won't work
    if(arg(0) !== 'user'){
        $user = user_load($comment->uid);
        if($user->uid != 0){
            $comment->field_job_title = isset($user->field_job_title) ? $user->field_job_title : NULL;
            $comment->field_bio = isset($user->field_bio) ? $user->field_bio : NULL;
        }
    }
}

```

and this one to hide the current fields when you comment:

```
function template_form_comment_form_alter(&$form, &$form_state) {
    $form['field_bio']['#access'] = FALSE;
    $form['field_job_title']['#access'] = FALSE;
}

```

# Answer
Here is my solution:

```
function hook_user_presave(&$edit, $account, $category){
    //get all node we need
    $results = db_select('node', 'n')
                  ->fields('n', array('nid'))
                  ->condition('type', 'my_content_type', 'LIKE')
                  ->execute();

    foreach ($results as $result) {
        $nids[] = $result->nid;
    }
    foreach ($nids as $key => $nid) {
        //get all comment ids
        $result = db_select('comment')
            ->fields('comment', array('cid'))
            ->condition('nid', $nid, '=')
            ->condition('uid', $account->uid, '=')
            ->execute();

        $cids = $result->fetchCol();
        $comments=comment_load_multiple($cids);
        foreach($comments as $comment) {
            //load comment
            // $user = user_load($comment->uid);
            if(isset($edit['field_job_title']) && isset($edit['field_bio']) && $account->uid !== 0){
                //change data of the comment
                $comment->field_job_title = $edit['field_job_title'];
                $comment->field_bio = $edit['field_bio'];
                //save it
                comment_save($comment);
            }
        }
    }
}

function hook_comment_presave($comment) {
    //if not user, otherwise it does it when you do the comment_save($comment) from the user_presave, then it won't work
    if(arg(0) !== 'user'){
        $user = user_load($comment->uid);
        if($user->uid != 0){
            $comment->field_job_title = isset($user->field_job_title) ? $user->field_job_title : NULL;
            $comment->field_bio = isset($user->field_bio) ? $user->field_bio : NULL;
        }
    }
}

```

and this one to hide the current fields when you comment:

```
function template_form_comment_form_alter(&$form, &$form_state) {
    $form['field_bio']['#access'] = FALSE;
    $form['field_job_title']['#access'] = FALSE;
}

```
> 0 votes

# Answer
Your solution is ok. But you could also

* Add a field on the comment fields of your content type that uses a reference to the user
* On hook\_comment\_presave fill out the user reference field with the uid of the logged in user
* On manage display of your comment fields, just render the user field as a rendered entity
* You could use a custom view mode on user that only shows the fields "job title" and "bio".
> 0 votes

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


title: Services for Products

text:
# Question
Title: Services for Products
I have a requirement where my website serves both products and services. I am using Drupal e-Commerce module for the same. It works perfectly fine for Products where we can set price for each product and user checks out from cart.

However, Services differ in their workflow. Each service product for ex: Electrician, will be associated with a service resource person, let's say Mr. XYZ. Now following are the requirements:

* Service Person is allocated to a service request product.
* The price of the service will be estimated after the service is provided.
* Rating & Reviews provided in case of service should be attributed to the Service resource as against that of the Product where rating is associated with a product.
* The price for a provided service has to be updated to the Order after the service is completed.

These differences are identified for starters, many more complex things might come in future. I have searched enough and I could not find a module which would satisfy the needs of both products and services. In fact, there is none for services. Is there a way to achieve what I want?

# Answer
> 1 votes
First up, I acknowledge that this is only half an answer - but as your question has received no attention as yet, I'll do my best.

The way I would structure a site to do this kind of thing is:

1. Create a content type for Service Person
2. Create a content type for Service Request that contains an Entity Reference field for allocating a Service Person
3. Don't create an order until *after* the Service Request has been completed, in this way the order can be crafted with the correct price

A couple of things to note:

* You'll probably need to write a custom module to handle permissions so that the Service Person allocated to a specific Service Request can create orders (effectively invoices)
* You may need to make your own ratings module that specifically targets the allocated Service Person rather than the Service Request.

# Answer
> 4 votes
Agree with the above and I would also add several suggestions: \- use Taxonomy and Taxonomy Access Control modules to control access to content and who can update which service node \- use Computed Field module that would take a value from related content to change a value (price) of the service/order depending on who did the work and what was the final price

Also, maybe this problem should be approached from a different angle? Maybe the service "product" should still be sold through e-commerce but instead of being "sold" would be "ordered" first, service performed and only then the final price updated, sold and ready for payment? Possibly that would require adding extra step in the checkout or allowing people to "order service" (Service would be a content type that people could assign to themselves as the "buyer") and only when performed and price was assigned, the Service would go through regular e-commerce checkout process with payment mechanism.

---
Tags: 7, ubercart, commerce
---


title: Drupal Node only with Title and Body?

text:
# Question
Title: Drupal Node only with Title and Body?
Using Drupal I need to recreated node that only display title and body.

Why ? I want to used my theme as e-mail template without re-creating a website manually. So I have to remove any menu, block, header, footer that is display it. Every time a new article is done they can export the page using their drupal theme but only showing the title and body to be send in an e-mail.

Any idea how to do this ?

# Answer
> 5 votes
Use the Print module that has an "email the content" functionality where you can control the look of that email including displaying only the page title and a body.

# Answer
> 0 votes
Path of least resistance: use a menu callback that accepts the node id as an argument.

Then you can just node\_load() and format it exactly as required for email.

# Answer
> 0 votes
You can use a different page template depending on the path.

If you had the following path:

```
/node/99/edit

```

PHPtemplate looks for the following templates, in descending order:

```
page-node-edit.tpl.php
page-node-99.tpl.php
page-node.tpl.php
page.tpl.php

```

**UPDATE: Regarding comment about original content type.**

To theme individual content types in different ways you would use the following convention:

```
page-node--page.tpl.php
page-node--forum.tpl.php
page-node--book.tpl.php

```

---
Tags: theming, emails
---


# Question
Title: How to ask drush to add timestamps to output?
Some of the steps in our drush-make process take a while and having timestamps in the build-log would be useful -- for every line.

Is there a way to do this already, perhaps? The `DRUSH_BACKEND` pieces of JSON contain timestamps (seconds since Unix epoch), but they aren't shown for *every* step. Perhaps, there is something like a `--timestamp` flag in drush already?

# Answer
> 0 votes
It doesn't look this is possible. There is a list of available commands for drush make here: http://www.drushcommands.com/drush-7x/make/make

---
Tags: drush
---


# Question
Title: How to display number of pageviews on articles and pages
I am looking to display the number of pageviews for articles and pages next to where it has tags for example.

Are there any modules that do this?

# Answer
> 0 votes
Have you tried with Node view count module ?

> Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

---
Tags: 7
---


# Question
Title: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'env_id' in 'field list': INSERT INTO {apachesolr_stats}
I get this error a lot in the drupal logs. Several times an hour. Anyone know why, what the impact is, and how to fix it?

My config:

* Acquia Drupal 7.36
* Running in IIS 7.5 / Windows Server 2008
* Solr 4.6
* PHP 5.3

Error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'env\_id' in 'field list': INSERT INTO {apachesolr\_stats} (timestamp, uid, sid, numfound, showed\_suggestions, total\_time, prepare\_time, process\_time, page, keywords, filters, sort, env\_id, page\_id) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13); Array ( \[:db\_insert\_placeholder\_0\] =\> 1423845337 \[:db\_insert\_placeholder\_1\] =\> 697523 \[:db\_insert\_placeholder\_2\] =\> XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \[:db\_insert\_placeholder\_3\] =\> 35 \[:db\_insert\_placeholder\_4\] =\> 1 \[:db\_insert\_placeholder\_5\] =\> 15 \[:db\_insert\_placeholder\_6\] =\> 15 \[:db\_insert\_placeholder\_7\] =\> 0 \[:db\_insert\_placeholder\_8\] =\> \[:db\_insert\_placeholder\_9\] =\> question about bill \[:db\_insert\_placeholder\_10\] =\> a:0:{} \[:db\_insert\_placeholder\_11\] =\> a:2:{s:5:"#name";s:5:"score";s:10:"#direction";s:4:"desc";} \[:db\_insert\_placeholder\_12\] =\> solr \[:db\_insert\_placeholder\_13\] =\> core\_search ) in apachesolr\_stats\_exit() (line 191 of D:\Inetpub\wwwroot\sites\all\modules\apachesolr\_stats\apachesolr\_stats.module).

**UPDATE**:

I am running apachesolr\_stats v. 7.x-1.0-beta1

Running update.php produces this error:

> Warning: Invalid argument supplied for foreach() in apachesolr\_stats\_block\_info() (line 961 of D:\inetpub\wwwroot\sites\all\modules\apachesolr\_stats\apachesolr\_stats.module)

# Answer
> 1 votes
Check your drupal database, table apachesolr\_stats if it has a field env\_id.

If not check installation of module apachesolr\_stats, maybe uninstall and reinstall. It should create that table apachesolr\_stats with the field env\_id.

---
Tags: database, search
---


title: Update hook batch stops halfway through

text:
# Question
Title: Update hook batch stops halfway through
I rarely ask questions on SE but now the teacher has become the student because this is driving me mad. I am doing a simple batch through an update hook and publishing some unpublished nodes. I am aware I could do this with a flat query, but I am preferring to use the batch system.

For whatever reason it arbitrarily stops at 50% no matter what I do. I have tried modifying the nodes per pass, etc. No errors. It just stop at the halfway point. When I debug the hook, I can see the counter variable increments right up to halfway and then stops. This is the hook. Am I crazy?

```
function mymodule_update_7200(&$sandbox) {
// Initialize the batch
  if (!isset($sandbox['total'])) {
    $result = db_query('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', array(':type' => 'event'));
    $sandbox['total'] = $result->rowCount();
    $sandbox['current'] = 0;

    // Disable Scheduler
    module_disable(array('scheduler'));
    drupal_set_message(t('The scheduler module was disabled'));
  }

  $nodes_per_pass = 20;

  // Get the nodes to process during this pass.
  $result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', $sandbox['current'], $nodes_per_pass, array(':type' => 'event'));
  foreach($result as $row){

    $node = node_load($row->nid);

    // Run a database update directly so we don't trigger any API calls through node_save
    db_query("UPDATE {node} n SET n.status = 1 WHERE n.nid = :nid", array(':nid' => $row->nid));

    // Log the event being published
    watchdog(
      'events',
      'Event was published: %title',
      array('%title' => $node->title),
      WATCHDOG_NOTICE,
      l('View', "node/$node->nid")
    );

    // Increment "current" by 1.
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('@nodes events were published. View the log for details.', array('@nodes' => $sandbox['total'])));
  }
}

```

# Answer
> 1 votes
The problem in this case is caused because results query differs between iterations.

You should replace:

`$result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', $sandbox['current'], $nodes_per_pass, array(':type' => 'event'));`

with

`$result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0 ORDER BY n.nid ASC', 0, $nodes_per_pass, array(':type' => 'event'));`

---
Tags: updating
---


# Question
Title: When to use a Webform vs. simply utilizing the Add Content page
Where is the line between using the Webform module vs. simply letting users create new content of a certain content type?

I am fuzzy on when each would be more appropriate. Especially after seeing the ambiguity of answers and comments to this question.

Use case: Users aren't entering data for a survey, they are actually entering content in to the site. They are entering data for a node that will be displayed as a normal content page. But it needs to be validated, have conditional fields, etc.

# Answer
> 3 votes
I think Webforms is usually more appropriate when the entered data is intended to be used by the organization behind the website and never shown to the public.

Webforms is also useful to send the entered data by email to who should receive it. You could also do this with a content type but you would require some kind of Workflow or trigger and action which might end up being "heavier" to the server

If you intend visitors / end users (authenticated or not) to see the data entered by others users then you just make a content type and use the add content form.

# Answer
> 0 votes
I think that the answer that says to use Webforms is there just because the OP asked to use Webforms.

It's way easier to use the Add Content page and create validations with a custom module, that way you will need to use the Drupal's hooks and not the Webforms custom hooks.

# Answer
> 0 votes
There are some discrepancies between how you understand Webform and what it actually does.

The docs actually clear this up pretty well.

It helps to think of Webform as a *node*, not a *content type*. Data submitted through the "node page" that is a Webform is not used to create a node, it is simply saved to the site.

If users are submitting data to create a node, simply style/customize the add content page for that content type. If users are submitting other data, use Webform.

---
Tags: 7, webforms, nodes
---


# Question
Title: Multiple Registration forms (with unique roles)?
I have a scenario where I want users to be able to register via the standard registration form and be assigned a role of "tenant". I also need the ability for site administrators to be able to create either "tenant" roles (with unique fields) or "landlord" roles (with their own unique fields and roles).

I've looked at profile2, user role field, and field permissions as possible modules, but I'm unable to see a way of getting this to work. How can I make certain fields required for one role, but hidden for another?

# Answer
> 2 votes
Sounds like profile2\_regpath will help you.

# Answer
> 0 votes
Multiple registration should help you.

---
Tags: entities, users
---


# Question
Title: TinyMCE editor does not show buttons in bar
I need a WYSIWYG editor so I installed drupal **wysiwyg module** in `sites/all/modules` folder. Further I downloaded **TinyMCE** and installed it in `sites/all/libraries/tinymce`.

The editor configuration is correctly displayed in `admin/settings/wysiwyg/profile/2/edit`. My interface language is German and TinyMCE has this language pack installed.

When I go to edit some text in the backend the editor itself is initialized but no buttons are displayed.

Any ideas why there are no buttons and how do I fix this?

# Answer
Did you enable some button /admin/config/content/wysiwyg/profile/yourprofile/edit ?

If yes, this can be caused by a javascript error. Do you see one in Firebug ?
> 4 votes

# Answer
Just to make this clearer since others may not read the comments...

Try to set the language to English and make sure that each filter configuration is set to English (in my case one was French and the other English)
> 0 votes

# Answer
**Installation:** **Step 1:** In Drupal 7, Download Tinymce (I've used TinyMCE 3.5.11 jQuery package) from here and save as like the actual library can be found at:

> \sites\all\libraries\tinymce\jscripts\tiny\_mce\jquery.tinymce.js

**Step 2:** Then reload the page and go to this location:

> /admin/config/content/wysiwyg

**Step 3:** Now choose tinymce from 'Editor' column for your appropriate 'Text Format' and click on the 'Save' button.

**Step 4:** Click on the 'Edit' button of tinymce enabled 'Text Format'.

**Step 5:** Make sure 'Language' is English in 'Basic Setup' tab.

**Step 6:** **By default all button and plugins are disabled**. So enable your required button or plugins from 'Buttons and plugins' tab,**strong text** otherwise you'll not see any button in 'rich text' input mode. *N.B.: Step 6 is the main answer of the question.*
> 0 votes

---
Tags: 7
---


# Question
Title: How to add new reference in entity reference field in node edit form keeping old references intact and hidden?
In my project, there is a content type 'song' containing an entity reference field to reference content type 'playlist'. More than one user can edit a 'song' to add it to their own 'playlist's.

Now, when one user updates a 'song' node creating his/her references in the node edit form, the previous references made by another user are deleted. In the node edit form, the field is formatted through an entity reference view showing a list of 'playlist's only created by the current user. The number of values for the entity reference field is set to unlimited.

What would be a good and server-friendly approach to solve this problem keeping in mind that there can be an unlimited number of previous references made by other users?

# Answer
Edit the field and set number of values to be unlimited. If you want more control and flexibility you could put the entity reference within a field collection.
> 0 votes

# Answer
In your current setup it's logical to only have entity reference to song from play list content type. Having the reference from song to playlist is redundant. You can always have view showing all the playlists that the song belongs to.
> 0 votes

---
Tags: entities, 7
---


title: How to skip route if not user access

text:
# Question
Title: How to skip route if not user access
I have two routes (from views module) with path "/test".

Route N1 required "role\_1" user role, route N2 required "role\_2" user role.

Rote N1:

```
class Symfony\Component\Routing\Route#9524 (9) {
  private $path =>
  string(5) "/test"

...

  private $defaults =>
  array(3) {
    '_controller' =>
    string(47) "Drupal\views\Routing\ViewPageController::handle"
    'view_id' =>
    string(4) "test"
    'display_id' =>
    string(6) "page_1"
  }
  private $requirements =>
  array(2) {
    '_role' =>
    string(6) "role_1"
    '_method' =>
    string(8) "GET|POST"
  }

...

```

Route N2:

```
class Symfony\Component\Routing\Route#9524 (9) {
  private $path =>
  string(5) "/test"

...

  private $defaults =>
  array(3) {
    '_controller' =>
    string(47) "Drupal\views\Routing\ViewPageController::handle"
    'view_id' =>
    string(4) "test"
    'display_id' =>
    string(6) "page_2"
  }
  private $requirements =>
  array(2) {
    '_role' =>
    string(6) "role_2"
    '_method' =>
    string(8) "GET|POST"
  }

...

```

How to skip route N1 if current user have "role\_2" but does not have "role\_1"?

# Answer
I'm created module for this feature.

See sandbox.
> 1 votes

# Answer
You can't have multiple routes on the same path with different access checks, it just doesn't work like that.

If you want something like this, then you need to create your own route, check permission/role of the user there and then display the right view based on that.
> 2 votes

---
Tags: 8, routes
---


# Question
Title: Commerce - Product and Total Price(s) on summary page not being updated by rule
I am creating an e-commerce website for a restaurant, there will be extra toppings available on pizzas. I have achieved this partially by using taxonomy to create the toppings and by giving this taxonomy term a field for price.

The rule then updates the price by adding the price of the topping on to the total price for that pizza. This is working when I view the cart page, but on the summary page it is not taking affect at all.

There is also an issue with the Ajax add to cart module in that if I add to cart a pizza of one kind with no extra toppings, and then add to cart the same pizza with an extra topping, the price in the cart for both pizzas is updated to be the price of the pizza WITH the additional topping.

However the total price is correct in this. I have checked the view for both the cart page and the summary page and they seem to be the same, which makes me think that the issue is with rules

This is my rule at present. I have used to commerce tutorial for a pizza shop using the customisable products module.

```
{ "rules_pizza_toppings" : {
    "LABEL" : "Pizza Toppings",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" :     "field_extra_toppings" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:field-extra-toppings" ] },
          "ITEM" : { "pizza_topping" : "Pizza Topping" },
          "DO" : [
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "commerce_line_item" ],
                "amount" : [ "pizza-topping:field-pizza-toppings-price:amount" ],
                "component_name" : "fee",
                "round_mode" : "1"
              }
            }
          ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
It's best to use separate questions for separate issues here. The one from the title is almost certainly due to a regression introduced in Rules 2.8 and documented in the Commerce 7.x-1.11 release notes: https://www.drupal.org/node/2408705

You can downgrade to Rules 2.7 until a fix is put into Rules.

---
Tags: commerce, rules
---


# Question
Title: How can I set values in the $conf array using the admin interface?
I am using the Journal module and in order to limit the forms its text box appears on the form ids have to go into a $conf variable. The docs say it has to go into settings.php but I don't watch that.

```
$conf['journal_form_ids'] = array(
    'fivestar_custom_widget' => 0,
    'guestbook_form_entry_form' => 0,
    'imagefield_js' => 0,
    'img_assist_header_form' => 0,
    'img_assist_properties_form' => 0,
    'link_widget_js' => 0,
    ...
);

```

Is there a module that can accomplish this from the admin interface? Can it be done through some kind of execute PHP form like with devel?

**It has to be done from the admin**

# Answer
> 2 votes
Sure, you can do this at `devel/php` if Devel module is enabled and you have access to Devel module's `Execute PHP code`.

The PHP to do what you want is

```
variable_set('journal_form_ids', array(
    'fivestar_custom_widget' => 0,
    'guestbook_form_entry_form' => 0,
    'imagefield_js' => 0,
    'img_assist_header_form' => 0,
    'img_assist_properties_form' => 0,
    'link_widget_js' => 0,
    // ...
  ));

```

---
Tags: configuration
---


# Question
Title: Strange problem with autocomplete field in forms in Drupal 7
I have an autocomplete field, which has been working perfectly for 1-2 days. Suddenly, it stoped working. I re-wrote the code, cleared the cache, and it works again. After comparing code, it is exactly the same code. I cannot trace the error. The problem is that it does not give back any results and the Firebug error is:

> TypeError: matches is null `if (typeof matches.status == 'undefined' || matches.status != 0)` ...

I cannot understand why it suddenly stopped working.

I have traced back the problem to a warning by Drupal:

> Warning: `call_user_func_array()` expects parameter 1 to be a valid callback, function '\_search\_idiomas\_autocomplete/list/confirm/' not found or invalid function name in `menu_execute_active_handler()`

Still not sure where the problem is. The code is standard autocomplete field from official documentation examples.

# Answer
> 1 votes
I have finally completely solved the issue. I copy the code which is working and below the code which was giving the error. Please some expert on Drupal to verify if I am right:

**Working code:**

```
$items['especialURL/autocomplete/%'] = array(

`'page callback' => '_mymodule_autocomplete' ,
 'page arguments' => array(2,3,4),`

```

**Wrong code:**

```
$items['especialURL/autocomplete'] = array(
   'page callback' => '_mymodule_autocomplete' . '/' . arg(2) .'/'.arg(3) . '/' . arg(4),
```

Explanation: the wrong code worked perfectly but once I cleared cache, it stopt working. Somehow the page callback was registered until the cache was emptied, and from that moment it would stop working. Maybe starting with page callback in the form of \_mymodule\_autocomplete and later adding the args() would work for a while. Interesting. These have been the worst 5 hours of my life working with Drupal due to using the wrong code while I had got it to work just by chance!!!

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


# Question
Title: Create categories with their own teasers and sliders
I'm new to Drupal. First look at my site's structure:

1. Homepage

* slideshow carousel - displays only selected nodes from the **whole** website
    * menu - displays links from a menu created for homepage
    * teaser - currently displays "promote to front page" items
    * footer - common to all pages (may be menu or site map)
2. Category

* slideshow carousel - displays selected nodes only from **current** category
    * menu - displays links from a menu or subcategories with their nodes
    * teaser - selected nodes only from current category
    * footer - common to all pages (may be menu or site map)
3. Article

* no slideshow
    * no menu
    * path to article (category breadcumb)
    * article title and body
    * footer - common to all pages (may be menu or site map)

How to divide website into categories as mentioned above?

Which modules to use? By default Drupal has Taxonomy module. Is it enough?

The simpliest way is to create custom templates like html--front.tpl.php, html--node--17.tpl.php, html--taxonomy--term--4.tpl.php, etc. but it's not flexible way. If you want to add more categories, you have to prepare another .tpl.php template.

What's the best and simple way to achieve this functionality?

More explanation:

Slideshow carousel is currently Slideshow:View module that displays all nodes with custom boolean field "promote to slider". Teaser on homepage works but I have no idea how to display it on category pages and even how to implement categories in Drupal. Any idea?

# Answer
I would recommend a content type for the slideshow and the article. For the categorization do you use taxonomy and Views for filtering and sorting. I can recommend https://www.drupal.org/node/394094
> 0 votes

---
Tags: 7, taxonomy-terms, breadcrumbs, nodes
---


title: How to use Drupal RSS Feeds with IFTTT

text:
# Question
Title: How to use Drupal RSS Feeds with IFTTT
I am trying to connect my Drupal RSS feed to If this, then That (IFTTT).

In IFTTT, it lists the following for RSS feed options:

* EntryTitle
* EntryUrl
* EntryAuthor
* EntryContent
* EntryImageUrl
* EntryPublished
* FeedTitle
* FeedUrl

How can I put these values in my Drupal RSS feed. I am creating a feed via Views, but it doesn't seem to have these options.

Ideally, I would like to map combinations of fields from nodes to these values.

For example, on my node, I have a "body\_text" and "into" field. I would like to store these in EntryContent.

# Answer
From what I can tell, these are not fields that IFTTT is actually looking for, they are rather the "ingredients" they provide for you to insert values they pull from a feed matching their criteria into your action part of the recipe.

When you create your recipe and enter your feed URL, they should prompt you if the RSS feed you entered doesn't meet their requirements. You can also see if your feed or XML validates at W3.org.

I created a basic RSS feed using views and copied the XML and it validated, and IFTTT accepted drupal.org/rss.xml which follows the same standards, so you should be good to go.
> 0 votes

---
Tags: views, feeds
---


title: WYSIWYG filter - Anchors get wiped out

text:
# Question
Title: WYSIWYG filter - Anchors get wiped out
I'm trying to allow anchors in my ckeditor but they always get wiped out by the WYSIWYG filter module.

For hyperlinks, my allowed attributes in WYSIWYG filter are "a\[!href|target\<\_blank|title|id|name\]". Then in the Rules for Element IDs section, I put "anchor\*".

So in my content, when I add an anchor named "anchor1", it adds `<p><a id="anchor1" name="anchor1"></a></p>` to the markup, which get replaced by `<p> </p>` once I save the content.

What am I missing to get this to work ?

Thanks !

# Answer
> 1 votes
According to the WYSIWYG Filter module page it follows TinyMCE valid elements syntax. From that page:

> ! Makes attributes required. If none of the required attributes are set, the element will be removed. For example, "!href".

It looks like your attribute string uses the exclamation mark to make the 'href' attribute required but the `<a>` tag you're putting in your content does not have that attribute so the element is being removed.

---
Tags: wysiwyg, navigation
---


title: Hide field when creating a node

text:
# Question
Title: Hide field when creating a node
How can I hide a field when creating a node, but displaying it when editing a node?

# Answer
If I understand your question, I think that you can use a custom module (in this example, the name of the module is `test_remove_field`) and include the following code:

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

    if (arg(0) == 'node' && arg(1) == 'add') {
    $form['field_test']['#access'] = 0;
    }

}

```

Note: remember that `field_test` must be your respective field name.
> 16 votes

# Answer
The **Field Permissions** module allows you to set field level permissions:

* Create field (edit on content creation)
* Edit field regardless of content author
* Edit own field on content created by the user
* View field regardless of content author
* View own field on content created by the user

You can use these options to enable role based permission for a field.

> When permissions are enabled, access to this field is denied by default and explicit permissions should be granted to the proper user roles from the permissions administration page. On the other hand, when these options are disabled, field permissions are inherited from the content view and/or edit permissions. In example, users allowed to view a particular node will also be able to view this field, and so on.

*Field permissions*
> 4 votes

# Answer
I'd use hook\_form\_alter() and set the `#access` property to `FALSE` just like the answer by @moon.watcher. In Drupal 7, you can call `hook_form_alter()` from your template.
> 3 votes

# Answer
This is a use case for the Rules Form Support Module - https://www.drupal.org/project/rules\_forms.

**Features include:**

> * Activate events for form creation, validation, and submission on a form-by-form basis.
> * Target individual form elements or the entire form in conditions and actions. Manipulate the attributes of a form element like title, description, weight, and more.
> * Validate the values of form elements during form validation.
> * Set form errors when rule-based validation fails.
> * Redirect users to a different page upon viewing or submitting a form.
> * Examine the attributes of elements in active forms with the element inspection tool.
> 2 votes

---
Tags: 7, nodes
---


title: Count values from field

text:
# Question
Title: Count values from field
i have a content-type "participants" with a field "number".

i want to calculate the total of all the values that are inserted in all the "participants"-node.

ie:

Node 1 -\> 200 participants Node 2 -\> 3 participants Node 3 -\> 15 participants

Total: 218

Only the result should be visible

I was thinking to do it with views, but i'm not succeeding.

Any suggestions?

# Answer
> 1 votes
Use views calc to achieve this behaviour, This module adds simple calculations to a views table: https://www.drupal.org/project/views\_calc

# Answer
> 0 votes
Also you can have a look at this module

https://www.drupal.org/project/nodeviewcount

Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

hope this helps :)

# Answer
> 0 votes
Views should be able to do this out of the box.

Create a block display showing fields and under your "Other" options, enable "Use Aggregation."

Add your field ("number"), select aggregation type "SUM" with your Group Column as "Value." In the next form set your label to Total. The key here is to not have a sort criteria. Filter by your content type "participants" and this should give you what you're looking for.

---
Tags: 7, views
---


# Question
Title: give permission of create new revision to specific roles
I need to give the permission of "create new revision" to a specific role. but nothing related to this issue appeares in permissions page! I've installed Revisioning module too. how can I set it?

# Answer
> 0 votes
**permissions (minimum):**

> **node:**
>
> View published content
>
> View own unpublished content
>
> View content revisions (optional)
>
> \[content type\]: create new content
>
> **revisioning:**
>
> \[content type\]: view revisions of own content

**For content types, in its edit UI:**

> Publishing options: Create new revision, New revision in draft, pending moderation (requires "Create new revision")

if you want to do it with Drupal core only, then this will suffice:

> **node:**
>
> View published content
>
> View content revisions (otional)
>
> \[content type\]: create new content

**For content types, in its edit UI:**

> Publishing options: Create new revision

---
Tags: users, nodes
---


# Question
Title: Drupal 8: How to properly add a settings widget to a node add/edit form and save the value?
So I reviewed the code in the core book, menu\_ui, and path modules, and they all seem to handle adding a settings widget in a vertical tab differently.

The book module uses a method called `addFormElement()`, which is called within a `hook_form_BASE_FORM_ID_alter()` hook.

The menu\_ui module is similar, but uses `hook_form_BASE_FORM_ID_alter()` directly.

Path seems to use a method called `formElement()`, and I'm not even sure where/how this method is used at the moment.

The real question I have is, how does one actually process the form setting and save it to the database? I have tried to find an example, but I'm at a loss.

Is there a help page with examples like the ones I found for adding an admin settings page?

If not, is there a recommended approach to displaying/saving a value in a vertical tab on a node add/edit form?

# Answer
I'm going to take a stab and show how I solved it, but I'm still curious to know if there's a better way.

In a nutshell, I used `hook_form_BASE_FORM_ID_alter()`, `hook_node_submit()`, and `hook_ENTITY_TYPE_insert()` or `hook_ENTITY_TYPE_update()` in the .module file.

Then I have a class called HierarchyManager that does all the heavy lifting that the D7 .module and .inc files used to do. It's listed as a service named "nodehierarchy.manager".

Lastly, I have a class called HierarchyOutlineStorage that handles the database inserts and updates. Quite a bit of that code was copied directly from D7.

In my .module file:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Adds the hierarchy form element to the node form.
 */
function nodehierarchy_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Load the node object associated with this form
  $node = $form_state->getFormObject()->getEntity();
  $account = \Drupal::currentUser();

  // Optional but keeps the .module code cleaner IMO
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');

  // Do your permission checks here
  $has_permission = ...;
  if($has_permission) {
    $form = $hierarchy_manager->addHierarchyFormElement($form, $form_state, $node, $account, $collapsed);
  }
}

/**
 * Implements hook_node_submit().
 */
function nodehierarchy_node_submit(NodeInterface $node, $form, FormStateInterface $form_state) {
  // Here the node object gets updated with the form value to be used later
  // If you aren't sure about the $form_state, download/enable devel and add
  // dsm($form_state->getValues()) to show all available values
  if (!$form_state->isValueEmpty('nodehierarchy_parents')) {
    $node->nodehierarchy_parents = $form_state->getValue('nodehierarchy_parents');
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for node entities.
 *
 * Save the form settings
 */
function nodehierarchy_node_insert(NodeInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $has_permission = ...
  if ($has_permisson) {
    $hierarchy_manager->hierarchySaveNode($node);
  }
}

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function nodehierarchy_node_update(EntityInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $hierarchy_manager->hierarchySaveNode($node);
}

```

In the HierarchyManager.php file:

```
public function addHierarchyFormElement(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
  // Insert $form array here
  $form['hierarchy'] = array(...);
}

public function hierarchySaveNode(&$node) {
  // Do all your processing here, then insert or update dB record
  $isNew = ...
  if ($isNew) {
    return $this->hierarchyOutlineStorage->insert($item);
  }
  else {
    return $this->hierarchyOutlineStorage->update($item->hid, $item);
  }
}

```
> 2 votes

---
Tags: 8, nodes
---


title: hook_menu not working with alias

text:
# Question
Title: hook_menu not working with alias
I have a hook\_menu:

```
$items['node/%/tokens/%api_token'] = array(
    'title' => 'View an API Call',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('api_token_edit', 1, 3),
    'access arguments' => array('edit own profile'),
    'type' => MENU_LOCAL_TASK,
);

```

When visiting url: `node/1229/tokens/1`, it works as expected.

When visiting the friendly alias: `mypage/tokens/1`, it gives me a 404.

Why is this? I thought `hook_menu` used the internal arguments?

# Answer
> 4 votes
That behavior is not inclued in core. You can try this two modules:

* Sub-pathauto (Sub-path URL Aliases): The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
* Extended Path Aliases: SImilar to previous module, but includes more functionlaity. The drawback is that it needs core patching (adding a line to nclude/path.inc) or installing PECL runkit library.

---
Tags: 7, hooks
---


# Question
Title: Theming the output of multiple image upload widget in node create/edit form
I need to theme the node create/edit page according to the user's specifications. To do so, I need to output of theme\_file\_widget\_multiple($variables), I suppose. It gives out table format which I need to convert into grid or divs. If there is some other easier hook or function for the same thing, please suggest me.

Can anyone help out?enter image description here

# Answer
> 2 votes
One option is to use MYTHEME\_image\_widget. This theme function allows you to adjust the output of the image widget.

In combination with MYMODULE\_field\_widget\_form\_alter and MYMODULE\_image\_field\_widget\_process you should be good to go.

---
Tags: nodes, theming
---


# Question
Title: Exposed proximity filter in geofield required, but still gives result
I've made a view with geofield proximity search. The user needs to fill in a location before I want to show result. So I made the exposed filter required:

But the view gives result, even when nothing is filled in. This is the query created:

```
SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language, 'node' AS field_data_field_adres_node_entity_type, 'node' AS field_data_field_location_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_location} field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = 'node' AND field_data_field_location.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('dealer')) ))
LIMIT 2 OFFSET 0

```

How can I make sure the query doesn't run if nothing is filled in?

# Answer
> 1 votes
Hope you are using Better exposed filter module and configured as this image.

---
Tags: views, location
---


# Question
Title: error 403 when trying to log in during checkout
It's the first time i'm posting on a forum but i've been really stuck with this problem for a few days. So thanks for your help.

I'm working on a site that's entirely https. The site uses the anonym checkout possibilities. I recently observed that when a user wants to connect during checkout (using the "/user" link, I don't use extra pannel to log in), after adding a product to cart or after a purchase, he gets an error 403. Whatever role he has, he is stuck with this error. The login and the password are correct. And this doesn't happen when we are on another page. It only appears from the moment a user adds a product in the cart. Then he has to empty the session and cache of the navigator to connect to his account.

I don't understand the problem because I don't have this problem on localhost, the only difference i see between the two server is that i don't use https on the localhost. That's why i think it's a session problem but i'm not sure. I tried all the solutions proposed for the settings.php, I don't use secure page (i used to but i uninstalled it because the site is entirely https now). The site is on a subdomain.

I have made a redirection to htacess to redirect possible entry by http to https with this code: RewriteCond %{HTTPS} off RewriteRule ^(.\*)$https://a.domain.com/$1\[R=301,L\]

I don't know what else to do, thanks for your help. Sorry if there's a lack of information, just tell me.

Thanks.

# Answer
> 0 votes
My problem was a session bug with my version of php (5.6.3) the code from here contains a workaround:

```
function mymodule_user_login(&$edit, $account) {
  $_SESSION['mymodule']['ulogged'] = 1;
}

```

---
Tags: commerce
---


# Question
Title: dpm breaks only if used in form custom submit on edit node
**Problem**

I have a case where the dpm printout is working fine in all cases except on a specific node type, in a very specific scenario.

If I edit the node type and place `dpm($form_state)` in the custom node submit called by `hook_form_alter`, no messages display on submitting the form.

If I create the node it works fine. If I put `dpm($form)` in the custom node submit it works fine. It's only that exact scenario which breaks.

I've read other questions where dpm breaks, but never for something so utterly and irritatingly specific.

I've cut down my code to:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'mycustom_node_form_id') {
    $form['#validate'][] = 'mymodule_form_validate';
    $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
  }
}

function mymodule_form_validate ($form, &$form_state) {
  dpm($form_state);
  dpm($form);
}

function mymodule_form_submit ($form, &$form_state) {
  dpm($form_state); <-- THE PROBLEM
}

```

The node type itself, contains a fairly complex field collection, a bunch of ordinary fields and a fivestar field.

Can anyone provide any guesses or places to begin debugging this? I'm completely stumped.

# Answer
Thumbson was spot on. MySQL was hitting it's the packet limit and increasing `maximum_allowed_packet` in `/etc/mysql/my.cnf` solved the problem. (ubuntu path)

The error won't show in Drupal, the only place I could find it was in my php-fpm log. See below:

```
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /srv/w$
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "Stack trace:"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#0 /srv/www/eslsearch.net/public/includes/database/database.inc(2171): PDOStatement->execute(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#1 /srv/www/eslsearch.net/public/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#2 /srv/www/eslsearch.net/public/includes/database/database.inc(2350): DatabaseConnection->query('SELECT expire, ...', Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#3 /srv/www/eslsearch.net/public/includes/lock.inc(167): db_query('SELECT expire, ...', Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#4 /srv/www/eslsearch.net/public/includes/lock.inc(146): lock_may_be_available('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#5 /srv/www/eslsearch.net/public/includes/bootstrap.inc(433): lock_acquire('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#6 /srv/www/eslsearch.net/public/includes/bootstrap.inc(455): DrupalCacheArray->set(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#7 [internal function]: DrupalCacheArray->__destruct()..."

```
> 2 votes

---
Tags: forms, debugging
---


# Question
Title: Change role of indirectly referenced users with Rules
I have two content types: Courses and Teachers (with a node reference field between them) and actual users are connected to Teachers with a user reference field. I'd like to assign users to a drupal role when they (the Teacher content they are refered to) refered to a Course. I can do it easly with a Rule if the node reference field has only one value but I can't cope with multi-value field. I have built this rule so far:

```
{ "rules_oktato_hozzaadas_oktato" : {
"LABEL" : "Oktat\u00f3 hozz\u00e1ad\u00e1sa - oktat\u00f3",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Oktat\u00f3" ],
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--course" : { "bundle" : "course" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_teacher" } },
  { "OR" : [
      { "entity_has_field" : { "entity" : [ "node:field-teacher:0" ], "field" : "field_related_user" } },
      { "entity_has_field" : { "entity" : [ "node:field-teacher:1" ], "field" : "field_related_user" } },
      { "entity_has_field" : { "entity" : [ "node:field-teacher:2" ], "field" : "field_related_user" } },
      { "entity_has_field" : { "entity" : [ "node:field-teacher:3" ], "field" : "field_related_user" } }
    ]
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-oktato" ] },
      "ITEM" : { "teacher_oktato" : "Tant\u00e1rgy oktat\u00f3i" },
      "DO" : [
        { "drupal_message" : { "message" : "Kurzus oktat\u00f3i: [teacher-oktato:field-related-user]" } }
      ]
    }
  }
]
  }
}

```

This setup works as I would like to but `[tantargy-oktato:field-csatolt-user]` is not available in 'change user's role' action. I can choose there only the individual field-teacher entries (:0, :1 etc.)

# Answer
Finally I managed to solve this issue. The Conditional Rules modul is the key:

```
{ "rules_oktato_hozzaadas_oktato" : {
"LABEL" : "Oktat\u00f3 hozz\u00e1ad\u00e1sa - oktat\u00f3",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Oktat\u00f3" ],
"REQUIRES" : [ "rules_conditional", "rules" ],
"ON" : { "node_update--course" : { "bundle" : "course" } },
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-teacher" ] },
      "ITEM" : { "list_teacher" : "List of teachers" },
      "DO" : [
        { "CONDITIONAL" : [
            {
              "IF" : { "entity_has_field" : { "entity" : [ "list-teacher" ], "field" : "field_related-user" } },
              "DO" : [
                { "user_add_role" : {
                    "account" : [ "list-oktato:field-related-user" ],
                    "roles" : { "value" : { "13" : "13" } }
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  }
]
 }
}

```
> 0 votes

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


# Question
Title: How to set only one save button for a page with Editable Fields by Views?
Using Views, I created a page that has editable fields(by Editable Fields Module) for Profile2 fields. Those editable fields have few kinds of type/widget of field such as Text, SHS(Simple Hierarchical Select) for Term reference, and Radio Button for List (text).

Now, I have a problem that few save buttons for each type/widget of fields are displayed in the page. The one is placed below SHS field and seems for saving only it, another is placed below the Radio Button field, and the other is for the Text one.

I want only one save button for all of fields in a page. Do anybody know how to unify those save buttons into one?

# Answer
You can use Editable views module. It uses one save button for all fields in a view.

**Editable Views:**

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
>
> Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
>
> Currently, the following Views fields can be edited:
>
> * All FieldAPI fields
> * Node title
> 2 votes

---
Tags: 7, views
---


# Question
Title: Views output into multiple columns based on variable of results
Scenario: I want to output a 3-column display, i.e. first 5 results on left column display, next 5 in middle column, last 5 on the final column.

I can do this with a fixed amount of results using different views + offest, but I want to do this with one view with a varied amount of results:

e.g. Col-1: 4 items Col-2: 3 items Col-3: 3 items

Example is iTunes website: `https://itunes.apple.com/au/genre/podcasts-technology-tech-news/id1448?mt=2&letter=X`

They even account for pagination `https://itunes.apple.com/au/genre/podcasts-technology-tech-news/id1448?mt=2&letter=T`

What would the best way to approach this? Would you need to get a count of results then set the offset for the 1st, maybe 2nd column if it's not a divisible number?

# Answer
> 0 votes
not sure what you're asking is really possible just through the Views UI.

However, this should is reasonably simple with a views template file and a bit of PHP knowledge.

http://webpartners.es/en/drupal-7-views-templates-and-preprocess provides some info about how to override the output of the view. you'll need to apply a bit of logic on how to begin/close your columns/lists but that's just a bit of arrays in PHP.

---
Tags: views
---


# Question
Title: how to get a field name by field label in Drupal 7
I have added a custom field with title 'play time'. How can I get the field name(internal value) using label value in my custom module. Is there any function to get the value?

# Answer
If you want to find specific content types based on field you can use:

```
field_info_instances($entity_type, $bundle_name);

```

If you want to find any field you can use:

```
field_info_field_map();

```

In both cases you will get an array of fields and you can get field name by filtering label value.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Virtual Directory for "sites" folder in IIS 7
I am running Drupal 7 on a Windows using IIS 7.5. This is not something I can change and is required by my company. Everything has been running great which is awesome.

I would like to setup the environment so that the "sites" folder is outside of Drupal Core so upgrading core will only require changing the application's Physical Path and not require copying the "sites" folder between versions. I have been doing some reading and this seems like a very easy thing to do using a Symlink for any Linux Machine.

So I have been trying a couple different configurations and have had no luck. I tried moving the "sites" folder out of the Drupal Folder and creating a Virtual Directory for the "sites" folder in IIS. This did not work, Drupal does not seem to respect the virtual directory and when Browsing the site I am asked to install. This should not be the case since I have sites that are running and working when the "sites" folder is placed inside the folder.

The second method was to use Windows and not the Web Server. I kept the "sites" folder outside of core where I had moved it and created a Shortcut. The same way you would create any shortcut on Windows OS. I took the shortcut which was named "sites" and put it in the Drupal Core folder. This will not work either and returns the same results by asking me to install.

If anyone has experience working with Drupal and IIS and has an answer it would be greatly appreciated.

# Answer
After some research and some help from a co-worker the answer has been discovered. It looks like Windows actually lets you create Symlinks, it is just not obvious.

http://technet.microsoft.com/en-us/library/cc753194(WS.10).aspx
> 1 votes

# Answer
A great explanation on symlinks in windows + a gui tool can be found here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

Be careful to test your backups after using this setup.
> 0 votes

---
Tags: 7, iis, files
---


title: get result count of a view in another

text:
# Question
Title: get result count of a view in another
I have 2 views. One view is displayed in the header of other view. Both views has its own block template. I need to get the sum of both views result count to display a no result message if sum is equal to zero. Is there any way to do it.

# Answer
Add a NO RESULTS BEHAVIOR Global: Text area to the inner view (the one in the header) and leave it empty.

Add this code to your theme's `template.php` file:

```
function THEME_views_pre_render(&$view){
  if (($view->name == 'outer' && $view->current_display == "default") || ($view->name == 'inner' && $view->current_display == "default")) {
    static $count = 0;
    $count += $view->total_rows;
    if (count($view->parent_views) && $count == 0){
      $view->empty['area']->options['content'] = "custom no result text";
    }
  }
}

```

Change the view names (outer and inner in my example) and display\_names (default in my example) to reflect your views.

Clear the cache.

Perhaps someone else can elaborate on how to add the global text for the no result in code instead of setting it to an empty value in the UI and then altering that value in code.

**EDIT**

If you intend to add any of these block multiple times on the same page then this answer will no longer be valid. Also, the no result text displays in the no result text for the inner view. You may want to consider altering the title of the block in that case. Unfortunately the outer view runs first, so it cannot be added to there as the result count of the second view is not yet available at that stage. count($view-\>parent\_views) is the bit of logic that checks for the inner view.You can change that to check for the $view-\>name if you want to.
> 2 votes

---
Tags: views
---


# Question
Title: Login fails due to loop on localhost. Any ideas why?
I have git cloned a site and used Backup and Migrate to bring the database over the the local host.

Working on the remote host the login works fine. Not locally. Well not anymore it worked for about an hour I'd say.

> Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

I've cleared all history, tried different browsers, and restarted apache a few times.

Any ideas?

EDIT:

I can install it and after installation I stay logged in for about 60 seconds after migrating the database. I'm then redirected in a loop.

The page isn't redirecting properly

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

This problem can sometimes be caused by disabling or refusing to accept cookies.

* I've cleared the browsers cookies and cache
* I've cleared drupals cache
* restarted apache
* tried different browsers

I'm beginning to think it may have something to do with how I'm setting up the site. I'm doing it in a very round-about way I think.

* backup database from dev site
* git clone site and point httpd.conf and hosts file at it
* create database with same name, user and password from settings.php file
* install site
* go in an enable backup and migrate
* import database from backup

site loads. drops after 60 seconds or so with the firefox message from above. I'm not 100% sure where to start troubleshooting.

# Answer
> 2 votes
`sudo a2enmod rewrite` fixed it. That is all.

# Answer
> 3 votes
You could find out for sure by adding some logging code in drupal\_goto() to backtrace what function fired the redirect. Then inspect why that function fired the redirect and work back from there.

Or, some more "guesswork" approaches -

* Check you don't have `$base_url` set in settings.php.
* Clear your cache tables after installing to copy (or don't back up the cache table contents).

`drush cc all`

* Disable modules which might be confused by relocation - securepages, canonical\_url, logintoboggan (guessing here).

`drush dis securepages canonical_url logintoboggan`

* Check your variables table for (and delete) any entries with values like '%http://your.old.domain%'.

`drush vget | grep your.old.domain`

`drush vdel some_variable_name`

# Answer
> 0 votes
You should also check your server error log and also install Firebug (if you don't have it already) and check the "Net" tab to see the HTTP requests. From these 2 sources you should normally have something to point you in the right direction.

# Answer
> 0 votes
Same issue happened to me, `infinite redirect loop`\- I could see all the pages within my website but when I try to login with my credentials, it gives me this error. So, I couldn't access my site as an admin. I found some solutions like adding a module, but I can't `add/disable` any modules. It took me around a day to resolve this,

Following steps worked for me in resolving this error:

1. Modified .htaccess file `RewriteBase /drupal`
2. uninstalled a module `Voting api` module, deleted the `voting api` folder.
3. cleared the `cache_* tables` in the database through `phpmyadmin`
4. Modified `my.ini/my.cnf` file - `max_allowed_packet = 32M.`

hope it would help someone.

REF:

https://www.drupal.org/node/706986

---
Tags: database, users, redirection
---


# Question
Title: Multisites with different database share rules
I create two sites with same code and different databases, but when I activate rules in the second site I can see the first site's rules.

I can disable the rules in second site and keep them active in the first, but rules with automatic name (ex. "Email on User Restriction") only appear one time.

Its a problem of my configuration? registry\_rebuild.php does not fix.

# Answer
> 0 votes
SOLVED: Problem appear when a sigle site (default) is moved to a multisite (sites/XXX). SOLUTION: erase rules in the other site don´t erase in the original site.

---
Tags: rules, multi-sites
---


# Question
Title: How do I dynamically change the title of a menu link?
I made a menu in administration, structures, menu. I want to change the title, as it appears on the menu, of one of the links based on the gender of the currently logged in user.

I have found several answers to similar questions but I can't figure out how to implement the solutions. Some of them suggest using hook\_menu\_alter(&$items) and a separate callback function, but I don't understand the structure of $items. I was hoping to just print out the value of $items, find the string I wanted to change, and change that value in $items in the hook. Apparently, though, you can't debug the $items variable because hook\_menu\_alter is rarely called. I tried to figure out the structure of $items from a bunch of other questions and answers and I found stuff like this:

```
$items['user/%user_category/edit']['title']

```

Why is 'title' a property of a path? Does this mean that every menu on your site that has a link to that path will display the title that you set the above variable to? What if you wanted a link to a specific path on one menu to have a different label than a link to that path on another menu? Isn't there somewhere I can access and change the title of a menu link like this

```
$allMenuData['My Custom Menu']['an item on my menu']['title']

```

# Answer
> 0 votes
You might try hook\_preprocess\_menu\_link()

```
function MYTHEME_preprocess_menu_link(&$variables) {
    global $user;

    if (isset($variables['element']['#original_link']['menu_name'])
        && $variables['element']['#original_link']['menu_name'] == 'my-menu-machine-name'
        && $variables['element']['#title'] == 'ORIGINAL LINK TITLE') {

        $new_title = (check for gender) ? 'New title 1' : 'New title 2';
        $variables['element']['#title'] = $new_title;
    }
}

```

Fill in your menu machine name, the title you want to change, the conditional for the gender and the new titles depending on the gender value.

---
Tags: routes
---


# Question
Title: Aggregated SUM from "Referencing entity" relationship, how to include nodes without relationship
I have two content types - `contact` and `payment`. Payment have `field_contact` that is an reference to `contact` and also `field_payment_amount` which is decimal.

In views I'm showing list of contacts (with filter by type = contact) but also would like to show SUM of payments for given contact. I added relationship: `Entity Reference: Referencing entity` to entities that are referencing my contact by field `field_contact`, turned on aggregation, and added to view `field_payment_amount` aggregated as SUM, and using my relationship. In this configuration all contacts are shown but field that should show my sum is empty.

Next I added another filter (by type), now using my relationship and for this relationship filtering by type = payment. In this configuration I can see my sums - great! But! If contact have no payments - it is excluded from table completely.

How can I show contacts without payments with "0" as sum of payments and calculate proper sums for contacts with payments? I feel like I'm missing something simple, or maybe not?

**Added:**

Ok, I reduced problem to most simple case, and analyzed query. Now interesting thing is that looks like the same query executed manually by me, and by view - gives different results O\_o .

Query:

```
SELECT node.nid AS nid, MIN(field_contact_node.nid) AS field_contact_node_nid, 'node' AS field_data_field_payment_amount_node_entity_type, SUM(field_contact_node__field_data_field_payment_amount.field_payment_amount_value) AS field_contact_node__field_data_field_payment_amount_field_pa
FROM
{node} node
LEFT JOIN {field_data_field_contact} field_data_field_contact ON node.nid = field_data_field_contact.field_contact_target_id AND (field_data_field_contact.entity_type = 'node' AND field_data_field_contact.deleted = '0')
LEFT JOIN {node} field_contact_node ON field_data_field_contact.entity_id = field_contact_node.nid
LEFT JOIN {field_data_field_payment_amount} field_contact_node__field_data_field_payment_amount ON field_contact_node.nid = field_contact_node__field_data_field_payment_amount.entity_id AND (field_contact_node__field_data_field_payment_amount.entity_type = 'node' AND field_contact_node__field_data_field_payment_amount.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('contact')) ))
GROUP BY nid, field_data_field_payment_amount_node_entity_type
LIMIT 12 OFFSET 0

```

Views output:

Query manual execution result:

Does anyone have possible explanation of this interesting behavior?

# Answer
> 0 votes
I just got this working by doing basically what you did:

**Relationship:** Content referencing Content from field\_contact, do not tick 'Require this relationship'

**Aggregation:** Yes

**Fields:**

1. Title: no relationship
2. payment amount: set relationship to Content referencing Content from field\_contact. Set no results behavior to '0'. Set aggregation to 'SUM', Group column to 'Value'

Works fine.

**Exported View**

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_contact_node']['id'] = 'reverse_field_contact_node';
$handler->display->display_options['relationships']['reverse_field_contact_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_contact_node']['field'] = 'reverse_field_contact_node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
/* Field: SUM(Content: payment_amount) */
$handler->display->display_options['fields']['field_payment_amount']['id'] = 'field_payment_amount';
$handler->display->display_options['fields']['field_payment_amount']['table'] = 'field_data_field_payment_amount';
$handler->display->display_options['fields']['field_payment_amount']['field'] = 'field_payment_amount';
$handler->display->display_options['fields']['field_payment_amount']['relationship'] = 'reverse_field_contact_node';
$handler->display->display_options['fields']['field_payment_amount']['group_type'] = 'sum';
$handler->display->display_options['fields']['field_payment_amount']['empty'] = '0';
$handler->display->display_options['fields']['field_payment_amount']['settings'] = array(
  'thousand_separator' => ' ',
  'decimal_separator' => '.',
  'scale' => '2',
  'prefix_suffix' => 1,
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'contact' => 'contact',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test';

```

# Answer
> 1 votes
I was debugging like crazy to figure this out and then after checking some values in views\_handler\_field\_field I realized what was wrong, and for sure it weren't Views! I forgot, or rather though of it as irrelevant, that there was third content type - a comment, that had a field "field\_contact". The problem occurred because Views when summing up, was also using existing "comment" nodes, but because they didn't have "field\_payment\_amount" at all - Views got confused. So the real answer is that we need to filter out any additional types that are using "field\_contact" field in our relationship.

I guess Views could act a bit better on this, and not get confused but use only available fields from proper nodes to create a sum, but it isn't much problem as long as we can filter out useless (for SUM) types that are using our reference field.

This explains why I got random/wrong results without type filtering on relationship, but when I added filter for "payment" - I didn't get "0" results, because then view assumed that relationship is required. The proper solution is then EXCLUDING wrong types that are in our relationship.

---
Tags: views
---


# Question
Title: Avoid drupal bootstrap for each image styles in private filesystem
Consider a scenario, where large number of images are attached to a node and they are displayed as thumbnail gallery when that node is displayed/rendered. The node has access control so it displayed accordingly. All images and corresponding image styles are stored on private file system.

Since every thumbnail is accessed from private filesystem it incurs a high latency due to permission check an every image.

Is it possible to avoid bootstrap/permission check for every image when they are displayed/rendered as a part of a specific node? So behave like public filesystem in this special case only. When any item is directly accessed via url, the permission checks kick in as they normally do for private filesystem.

# Answer
Haven't tried this before, but you could write an image field formatter that converts the thumbnail files to inline data URIs, eliminating the separate HTTP requests per image. That adds some overhead to the initial node render, but is probably more performant overall.

Here's a quick implementation. Encoding a thumbnail is almost trivially fast; the biggest performance hit is from generating image style derivatives if they don't exist yet.

```
/**
 * Implements hook_field_formatter_info().
 */
function image_datauri_field_formatter_info() {
  $formatters = array(
    'image_datauri' => array(
      'label' => t('Image Data URI'),
      'field types' => array('image'),
    ),
  );

  return $formatters;
}

/**
 * Implements hook_field_formatter_view().
 */
function image_datauri_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $style_name = 'thumbnail';
  $style = image_style_load($style_name);
  foreach ($items as $delta => $item) {
    $image_style_path = image_style_path($style_name, $item['uri']);
    if (!file_exists($image_style_path)) {
      if (!image_style_create_derivative($style, $item['uri'], $image_style_path)) {
        continue;
      }
    }
    $encoded_image = base64_encode(file_get_contents($image_style_path));
    $data_uri = 'data:' . file_get_mimetype($image_style_path) . ';base64,' . $encoded_image;
    $attributes = array(
      'src' => $data_uri,
      'alt' => (isset($item['alt'])) ? $item['alt'] : NULL,
      'title' => (isset($item['title'])) ? $item['title'] : NULL,
    );
    $element[$delta] = array(
      '#markup' => '<img ' . drupal_attributes($attributes) . ' />',
    );
  }
  return $element;
}

```
> 2 votes

# Answer
No because it are separate http(s) requests. Every requests needs to redo the check.
> 2 votes

---
Tags: bootstrapping, files
---


# Question
Title: How can I enter a custom maintenance mode message for a non-English D8 site?
I am playing around with a D8 site (8.0.0-beta6) and having trouble locating where some of the controls have gone. During the initial installation procedure I selected a non-English localization (Turkish). Subsequently putting the site into maintenance mode does indeed show the Turkish localized default maintenance message.

The trouble is I want a custom message. Entering one in the box on the maintenance page (I'm viewing the Administrator site using the same default locale) has no effect on the message displayed. Apparently this message changes the English only because if I add `/en` to by site URL I get the English maintenance mode page and header, but with my custom Turkish message below it.

Where does one change custom localized maintenance mode messages?

# Answer
> 2 votes
This function should have worked as expected. There is not some feature somewhere else or another way this should have been done. The result described is the consequence of this bug in the Drupal 8 core. As of this writing a patch has been proposed but not settled on. Such are the consequences of playing around with beta releases!

In the mean time the only way to may a D8 site behave is to hack it using one of the following methods:

1. Manually implement one of the patches described in that issue.
2. Manually override the core template file (`core\modules\system\templates\maintenance-page.html.twig`).
3. Use the Interface Translation module to access the internal localization strings. Override the default maintenance mode string for the target language.

Eventually when that issue is closed and another release cycle happens it should be fixed and providing a custom message from the Admin page will work again as expected.

---
Tags: 8, i18n-l10n, maintenance-mode
---


title: How do I reduce <div> elements?

text:
# Question
Title: How do I reduce <div> elements?
How can I reduce div elements Drupal creates in a view block?

for exmaple I have a block created by view and I see these many divs:

```
<div class="block block-views" id="block-views-shortcut-link-block">
<div class="content">
    <div class="view view-shortcut-link view-id-shortcut_link view-display-id-block shortcutlink-block view-dom-id-ad495e95183a1bbbe306bd1ec4f008e4">
        <div class="view-content">
        <div class="views-row views-row-1 views-row-odd views-row-first">
            <div class="views-field views-field-title">
                <h2 class="field-content"><a href="#">aaaaaa</a></h2>
            </div>
            <div>
                <div class="icon">
                    <img height="87" width="89" alt="" src="http://.....png" typeof="foaf:Image">
                </div>
            </div>
            <div class="views-field views-field-field-shortcut-slogan">
                <div class="field-content slogan">
                    bbbbbb
                </div>
            </div>
        </div>
    </div>
</div>

```

Are these two many div really needed? Can I reduce them by define a theme for this block?

# Answer
> 3 votes
I use Semantic Views to remove a lot of the cruft from views.

> This Views plugin makes unformatted styles, field row styles and other output more readily configurable without needing to override template files. Instead of overriding row style templates for views where you want to specify different HTML elements (tags) and class attributes, you can specify these inside the Views UI and avoid overriding templates for each view.

# Answer
> 1 votes
Additionally to "Semantic Views": **Fences** is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and **Views**. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

# Answer
> 0 votes
As Bryan say, Semantic views it's the best option for me.

But you have another 4 options.

1. Use Display suit to define a new display and use it to print the view. More or less you can also control the number of divs. It'll take more time than use semantic views.
2. In views, you can configure, also more or less, how the divs are printed, check the "Style settings".
3. You can create your own tpls to use in views, it will give you full controll of all the HTML.
4. You can crete your own formatters for fields,also here you can not controll all de divs, only the fields divs, like in the 2º option.
5. The last option is use the theme mothership, this theme have a configuration option that help you to clean all the drupal html, and leave only that it's required.

---
Tags: 7, views
---


title: how can I activate modules and themes?

text:
# Question
Title: how can I activate modules and themes?
I am very new to drupal, so, sorry for my basic question. I have tried to instal new modules and themes. The installation process went OK, I got a"successfully installed" message. But when I want to activate the new module, it does not show up on the HOME / ADMINISTRATION / MODULES list. The Update Manager module is activated, I am logged on as an administrator, I have all the rights set, but I still cannot see the newly installed modules or themes. Any ideas would be appreciated. Thanks. Greg

# Answer
> 2 votes
You can enable your installed modules here.

`/admin/modules`

and your theme here

`/admin/appearance`

You can double check to make sure the modules & theme are really there by navigating to your site modules & themes folder.

`/sites/all/modules` `/sites/all/themes`

---
Tags: 7, theming, installation
---


title: Confused about hook_update_n

text:
# Question
Title: Confused about hook_update_n
I am updating a module that I built for my site. When I originally built the module, I didn't know much about Drupal and I gave it a version of 0.0.1. Now I'm working on a completely different version that will be using 7.x-2.x as the version. I need to run an update for the module to work. I have this function

```
function contacts_blocks_update_7200() {
  // Update code.
}

```

When I go to update.php on my site, I get an error that there are no pending updates. I've also tried contacts\_blocks\_update\_7201. Neither is working. I do not understand how to make an update run this function. I've had a similar issue with another module and was never able to get the update function to run and ended up doing it manually.

I checked the schema\_version of the module in the system table and it says 0. I'd really like to learn how to do this. How do I determine the N for hook\_update\_N?

# Answer
> 2 votes
Provided your project's machine name is `contacts_blocks`, make sure that your implemenation of `hook_update_N` is located in a file named `contacts_blocks.install` that is inside your project directory. (Make sure you spell it exactly right `contacts_blocks.insall` will *not* work.)

The four digits should be `[major version][minor version][2 digits for sequence]`, so the correct name in your case (branch 7.x-2.x) should be `72XX`, where XX is some sequence number.

To figure out what number to use for the last two digits, run the following query:

```
SELECT schema_version FROM `system` WHERE name = 'contacts_blocks';

```

If it returns no result, then use `7200`.
If it returns something below 7200, then use `7200`.
If it returns a number above 7200, but below 7298, then increment with 1 and use that (e.g. if it returns 7202, use `7203`).

If there is a weird value for `schema_version` in the systems table, and you're just experimenting (i.e. nobody else have your module, so you're not going to distribute the `contacts_blocks.install` file with your update to anyone), you can get a fresh start by disabling and uninstalling the module (just disabling is not enough), the reinstalling it again.

API link: function hook\_update\_N

---
Tags: 7, updating
---


# Question
Title: Force View to be displayed only in a specific domain
I am using the Domain Access, Domain Access Views and Views modules.

I want to create a domain-specific view that will be displayed only in a specific subdomain of the website and if someone tries to access it from a different subdomain, he will be redirected to the proper domain.

So for example when a user navigates to:

http://www.example.com/myViewPath

or

http://customers.example.com/myViewPath

he should be redirected to:

http://blog.example.com/myViewPath.

Is there a way to do that?

# Answer
One solution would be to use hook\_preprocess\_html()

```
function MYTHEME_preprocess_html(&$variables) {
  global $_domain;
  if (arg(0) == 'myViewPath' && $_domain['subdomain'] != 'blog.example.com') {
    drupal_goto('http://blog.example.com/myViewPath', array(), 301);
  }
}

```

Note that the global $\_domain variable is provided by the Domain Access module.

Alternatively, in a custom module you could use hook\_boot()

```
function MYMODULE_boot() {
  if (arg(0) == 'myViewPath' && $_SERVER['HTTP_HOST'] != 'blog.example.com') {
    exit(header('Location: http://blog.example.com/myViewPath', TRUE, 301));
  }
}

```
> 0 votes

---
Tags: 7, views, domain-access
---


# Question
Title: Views: apply filter only if a condition matches
I've searched a lot the Views issue queue, searched for other modules, searched on stackexchange, but it seems that no one needs this functionality (or that there's another way to achieve it).

Use case: I have two content types: lecture and substitute teaching. A teacher uses the lecture content type when he has a normal lecture in a class where he has a chair. A teacher uses the substitute teaching when another teacher isn't at school (ill or in an excursion) and he has to replace the colleague.

In the lecture content type I have put an entity reference field named "chair", which filters the chairs so only the tearcher's ones are shown. For doing this I use the entity selection section of the field, and pass via token the teacher's uid to the view. But in the substitute teaching content type, I don't want to filter the chairs. Since a teacher could replace anyone, I need an unfiltered list of chairs.

Since the entity selection part of the field is applied everywhere this field is used, I had to create another entity reference field in the substitute teaching which references the chair content type, but without filtering. Having the same content type pointed, but using two different fields, is leading to maintenance nightmares (put both the content types and filter them based on chair field is nearly impossible), so I'm seeking for a different approach.

I think that a good one would be to pass to the view the uid and the content type. If the content type is "lecture", then apply filtering, otherwise don't. In this way I could use the same field in both the content types and everythig would work smothly. Well, it seems impossible to do such a simple thing.

The only solution that got me near the desired result was using conditional fields, but when filtering I got a bunch of empty option values where the view result was hidden, but it was selectable.

Any help or hint would be appreciated. Thanks!

# Answer
One possibility is hook\_views\_pre\_view()

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {

    if ($view->name == 'chairs' && $display_id == 'entityreference_1') {
        $node = menu_get_object();
        if ((is_object($node) && $node->type == 'substitute')
            || (arg(1) == 'add' && arg(2) == 'substitute')) {

            $args = array();
        }
    }
}

```

This solution is assuming the use of a contextual filter, with 'Display all results for the specified field' selected when the filter value is not available. This will remove the user id being passed as an argument when the content type is 'substitute.'

Another option might be a view with a relationship of 'Content: Author' and a filter (not contextual) for the current logged in user. The following could be used in that case to unset that filter if the content being added/edited is 'substitute.'

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {

    if ($view->name == 'chairs' && $display_id == 'entityreference_1') {
        $node = menu_get_object();
        if ((is_object($node) && $node->type == 'substitute')
            || (arg(1) == 'add' && arg(2) == 'substitute')) {

            unset($view->display_handler->default_display->options['filters']['uid_current']);
        }
    }
}

```

In this case it assumes the filter is a default for all displays for this view. If it is a filter an override for that display, the unset line will need to be:

```
unset($view->display_handler->options['filters']['uid_current']);

```

Fill in the machine names for your view name, display id and content type.
> 0 votes

# Answer
You will have to add a custom module for this. I usually have one monolithic module that I add to every project that I name the same as my project for project specific tweaks like this.

In that module's module file, add this code:

```
function MODULE_views_query_alter(&$view, &$query){
  // target the correct view
  if ($view->name == 'chair' && $view->current_display == 'entityreference_1') {
    // target the correct path
    $node = menu_get_object();
    if ($node && arg(0) == 'node' && arg(2) == 'edit' && $node->type == 'lecture') {
      // edit page on lecture type
      $view->query->add_where("entityreference_tweak", "node.uid", $node->uid, '=');
    }
    else if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'lecture')
    // create page on lecture type
    {
      global $user;
      $view->query->add_where("entityreference_tweak", "node.uid", $user->uid, '=');
    }
  }
}

```

I named the entityreference view 'chair', the entityreference display took the default name 'entityreference\_1', the lecture content type has the machine name 'lecture'. You need to substitute these name in the code above with your own machine names.

Then completely remove the contextual uid filter from your entity reference view and also do not pass anything to the view in the field settings of the content type. The code adds the filter dynamically. It checks if you are on a lecture edit/add page, then adds either the node author uid, or the uid of the currently logged in user.
> 0 votes

---
Tags: views, entities
---


title: Get all entities tagged with term

text:
# Question
Title: Get all entities tagged with term
`taxonomy_select_nodes` returns all the nodes tagged with a given tid. This function checks the taxonomy\_index table. That table stores the tid and the nids on which it is tagged.

Let's say I have some custom entities with terms on them AND a user entity with terms on it, how do I get all the entities tagged with a given tid? Can this be done in 1 query/function?

# Answer
I'm afraid not. The taxonomy index table is maintained specifically for nodes. There is no equivalent for other entities. It would be possible to maintain an index of your own though.

A workaround would be reusing the same field on different fieldable entities. Then you would only need to query the data field table to get all referenced entities.
> 2 votes

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


# Question
Title: How to hide user profile(edit current password, email, picture, everything) based on role?
When user logged in with common shared username and password, I wanted to hide user profile for some of the user based on the given role.

So, I want a feature where user can just logged in and logged out with the given shared user name and password and, I don't want to allow them to change their password or I don't want to allow them to edit in their profile.

I have created separate role for this users.

I came to know that we can hide edit user profile with CSS:

```
display: none;

```

Is there any other way to hide user profile based on some roles?

# Answer
Thanks for your help.

I found **User Protect module** very helpful. It gives the exact same functionality that what I wanted.

We can hide edit account, edit password, email from based on user roles and for specific users too.

Thanks!
> 0 votes

# Answer
You can set access for fields as FALSE as per user roles.

```
function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state) {
  global $user;
  if(in_array('your_role_name',$user->roles)) {
    $form['account']['pass']['#access'] = FALSE;
    // Similarly other fields, but fields can not be required fields on profile.
  }
}

```
> 2 votes

# Answer
a quick method would be to theme the user profile template file and do a quick check for the role there. seeing as you're okay with that css approach, I'm guessing this is more of a nice to have rather than some mission critical thing, so I think this would work nicely for you.

https://api.drupal.org/api/drupal/modules!user!user-profile.tpl.php/7
> 1 votes

# Answer
User role field module allows you to specify role-specific fields. When creating a new field, you specify what roles this field is enabled for.

Fields are only visible and editable if a user has a specific role.

This role does not determine access controls for visible fields. You could use the Field Permissions module for setting access controls.

More then 120 sites currently use this module.
> 0 votes

---
Tags: 7, users
---


title: Function breaks chart.js

text:
# Question
Title: Function breaks chart.js
I am trying to insert my chart.js into a Drupal page.
Here is the fully functional fiddle:
http://jsfiddle.net/vy0yhd6m/80/

When I enter that into a basic page content item in Drupal, the chart will not display. However, if I remove `scaleLabel()`, it works and displays perfectly on the Drupal page. For some reason, adding that function in the Full HTML content item makes the chart disappear, even though it works perfectly in the above JS Fiddle.

```
scaleLabel: function(label){return  ' $' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}

```

Does anyone have any idea on why this is happening?

# Answer
So I realized I was using an outdated version of Chart.js (from an old production site). I just updated to the latest version, and now all is well with the world.

Thanks.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How can I bypass the Minimum cache lifetime when programmatically clearing the cache?
Is it possible to clear the cache of individual node without regard to the minimum cache lifetime in the cache settings Drupal 7?

It seems like `node_save` clears the cache:

```
entity_get_controller('node')->resetCache(array($node->nid));

```

However, that respects the minimum cache lifetime.

This is an issue when unpublished saved nodes go from an unpublished to a published state. Users served from the cache can't see the page until it expires, and it's immediately shared on Facebook or Twitter, those who click get a page not found 404.

I'm stuck using the `Clear all caches` button on /admin/config/development/performance. That seems like a heavy-handed approach.

Is there a better way?

Is `cache_clear_all();` (called with no-params) the programmatic equivalent of the `Clear all caches` button?

Thanks in advance for any help!

# Answer
> 2 votes
First, a couple contextual comments on all this:

1. You are probably getting a 403 (Access Denied) message instead of a 404 (Not Found) message when visiting a previously unpublished page that was cached.
2. The method call that you referenced (`entity_get_controller('node')->resetCache(array($node->nid))`) within `node_save()` does not have anything to do with the page cache, and is instead related to the static entity cache, which only has an impact on the current request. However, you are certainly correct that Drupal makes an effort to clear the page cache upon a node save, but that happens in node\_form\_sumbit() when it calls `cache_clear_all()` at the end.
3. The cache clearing methods in Drupal are very strange and non-intuitive. I've seen entire threads erupt in passionate arguments and misunderstandings over the workings of `cache_clear_all()` and `DrupalDatabaseCache::clear()`.

If `cache_clear_all()` is called without any arguments, as is the case on a node update, only the page and block cache bins will be targeted for clearing. That's fine as it's presumably the page cache that matters in your case, but as you noted the "Minimal Cache Lifetime" will be respected. The exact logic used to respect this "Minimal Cache Lifetime" (in `DrupalDatabaseCache::clear()`) might make your mind melt... but that's an aside.

As indirectly noted in another answer, you can call `cache_clear_all()` *with a specific* node URL to force the needed page\_cache entry to be cleared. This will do the job independent of the "Minimal Cache Lifetime" which, IMHO, is quite non-intuitive. Thankfully there are tools that account for all this non-intuitive logic for us, like the Expire module. Not only does it have the ability to target certain actions in Drupal (such as a node update), and clear the cache when they happen, but it will do it in such a way that the "Minimal Cache Lifetime" is factored-in and bypassed as needed. There is an old issue thread here that seems to talk about this a little more.

Also, if you have another page cache active (Varnish, Boost, etc.) they may be suspect too, and may be returning a previously cached version of the request independent of the local Drupal page cache. If you have an external cache like this in place you should check its own settings along with the the core "Expiration of cached pages" setting (just below the "Minimal Cache Lifetime" setting). Once again, the Expire module can help here as it also integrates with external caches to sync their expirations with Drupal updates.

# Answer
> 0 votes
This is the simple way to clear cache For example:

```
function YOUR_MYMODULE_node_insert($node) {
  drupal_flush_all_caches();
}

```

or to clear only the static page cache after a node has been updated:

```
function YOUR_MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid);
  cache_clear_all($nodeurl, 'cache_page');
}

```

refer this for more info

How to delete cache after updating/deleting/adding new content using hooks?

---
Tags: 7, caching
---