# Question
Title: What to do when translation imported using Locale has an inappropriate translation?
I used Locale module to translate Drupal to my national language. But some words' translation is not appropriate. How can I change the translation of some words?

# Answer
Go to Administer -\> Site building -\> Translate interface -\> Search (d6) or Configuration -\> Regional and language -\> Translate interface -\> Translate (d7). You will see a search box. Simply search and edit string you think should be edited.
> 2 votes

# Answer
One quick fix is to use the String Overrides module to override the translation of the specific words whose translation you disagree with.

A more community spirited solution would be to join the the translation team for your national language at https://localize.drupal.org/, and improve the translation by participating in the translation effort and discussions within the team about what is the *best* translation of a particular word or string. If you get consensus about a change, the "official" translation of the word or string will be changed and you no longer need to override it.
> 1 votes

---
Tags: 7, i18n-l10n
---


title: How to make relationships between users

text:
# Question
Title: How to make relationships between users
I have the quiz module installed on my website. I have setup two user roles on my site, Student and Parents.

I want to make a view that shows the results of a parents children.

Now I have made two fields in the registration using the profile module.

```
The number of student
The number of parent

```

These two fields are now available both for parents and their children. How can I fetch the results of a parents children using this relationship?

I'm thinking I should I say:Show the result of the users were the field "profile\_no" is the same?

Is there a better way to make relation between two users?

Thanks everyone!

# Answer
> 0 votes
Using the Entity reference module you can reference all entities (nodes, users, terms etc).

When you use the Entity Reference module you get a field where you can choose one ore many entities to reference. In this case it will be other users you choose (children).

This is the way it could look when you choose children in your user profile.

I suggest you read up on the Module Monday blog post by Jeff Eaton about Entity Reference. to get up to speed on relationships.

---
Tags: users, quiz
---


# Question
Title: how to define entity preprocess function
My custom module defines a custom entity, which extends the EntityAPIController class. I managed to make it basically working, i.e. displaying fields etc via my custom tpl.php file. But I would like to create a `mymodule_preprocess_entity` function (as suggested here) to add custom variables to the tpl.php file. But such function is not running (is not called).

Also, when I display this entity, I noticed that the function `template_preprocess_entity(&$variables)` from entity.module is not running, either.

What else needs to be defined to make the preprocess function for custom entity being called?

# Answer
I created a general `mymodule_preprocess(&$variables, $hook)` function and it showed that the specific function name should be `mymodule_preprocess_myentity`. Where `myentity` is the proper name of the entity.

So, this code is working for me:

```
function mymodule_preprocess(&$variables, $hook) {
  if (isset($variables['elements']['#entity_type'])) { // or maybe check for $hook name
    $function = __FUNCTION__ . '_' . $variables['elements']['#entity_type'];
    if (function_exists($function)) {
      $function($variables, $hook);
    }
  }
}

function mymodule_preprocess_myentity(&$vars) {
  ...
}

```
> 10 votes

# Answer
A more generic approach:

```
/**
 * Implements hook_preprocess().
 */
function mymodule_preprocess(&$variables, $hook) {
  if (isset($variables['elements']['#entity_type'])) {
    $myhook = "preprocess_{$variables['elements']['#entity_type']}_{$variables['elements']['#bundle']}_{$variables['elements']['#view_mode']}";
    $modules = module_implements($myhook);

    foreach ($modules as $module) {
      $function = "{$module}_{$myhook}";
      $function($variables);
    }
  }
}

```

Unfortunately `module_implements()` doesn't check if the active theme implements the preprocess hook.
> 2 votes

---
Tags: 7, theming, entities
---


# Question
Title: Create user permission with specific role?
How do I give the "create user profile" permission to a role? I have the *manager* role and I want to give permission to to it to create an *editor* or *manager* user. I don't want to show all the roles on the user create or edit page.

Is there any module for achieving this?

# Answer
Use the role delegation module

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.

**UPDATE:**

Simply create two roles Manager and Editor role. When you create this roles, two permissions will appear on the permissions page. Assign Manager role and Editor role. Give the manager the two roles to assign. And also give the user permission to create new users.

And if you login as that user, that user will only be able to create the roles you have assigned to them.

**UPDATE 2:**

Use the module administer user by role. To stop the manager role from canceling or editing the adminstrator role or any other role you don't want them touching

> This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Pager Gone when I edit query in "views_pre_execute"
Today I faced a strange problem.

Indeed I tried to manipulate SQL QUERY of a view in "views\_pre\_execute" event.

I made a module with name **"modify\_view\_query"** and created related function in my module.

```
function modify_view_query_views_pre_execute(&$view) {
}

```

the view name is **"view\_products"** so I added this condition to the function.

```
function modify_view_query_views_pre_execute(&$view) {
    if($view->name=="view_products") {

    }
}

```

Then I retrieved the SQL query and tried to inject.

```
function modify_view_query_views_pre_execute(&$view) {
    if($view->name=="view_products") {
        $sqlStr = $view->build_info['query'];
    }
}

```

The original Query is

```
SELECT DISTINCT(node.nid) AS nid, node.type AS node_type, node.vid AS node_vid,
    node.title AS node_title, node.language AS node_language,
    node_data_field_product_brand.field_product_brand_value
        AS node_data_field_product_brand_field_product_brand_value,
    node_data_field_product_brand.field_product_dosage_value
        AS node_data_field_product_brand_field_product_dosage_value,
    node_data_field_product_brand.field_product_package_value
        AS node_data_field_product_brand_field_product_package_value,
    node_data_field_product_brand.field_product_drug_category_value
        AS node_data_field_product_brand_field_product_drug_category_value,
    node_data_field_product_brand.field_product_indication_value
        AS node_data_field_product_brand_field_product_indication_value,
    node_data_field_product_brand.field_product_type_value
        AS node_data_field_product_brand_field_product_type_value,
    node_data_field_product_brand.field_product_patient_advisor_nid
        AS node_data_field_product_brand_field_product_patient_advisor_nid

    FROM {node} node LEFT JOIN {content_type_product} node_data_field_product_brand
    ON node.vid = node_data_field_product_brand.vid

    WHERE
        (node.status = 1)
        AND (node.type in ('%s'))
        AND (node.language in ('%s'))
        AND (SUBSTR(node.title, 1, 1) = '%s')
        GROUP BY nid ORDER BY node_title ASC

```

I want to inject an OR condition to my code. indeed I want to replace **SUBSTR(node.title, 1, 1) = '%s'** with **SUBSTR(node.title, 1, 1) = '%s' OR SUBSTR(node.title, 1, 1) = '%s'**

So I used string replacement function as follow.

```
$sqlStr = str_replace("SUBSTR(node.title, 1, 1) = '%s'","SUBSTR(node.title, 1, 1) = '%s' OR SUBSTR(node.title, 1, 1) = '%s'",$sqlStr);

```

Finally I set the parameter and new SQL string for the view.

```
    $view->build_info['query_args'][2] = 'A';
    $view->build_info['query_args'][3] = 'B';
    $view->build_info['query'] = $sqlStr;

```

The Final Function is

```
function modify_view_query_views_pre_execute(&$view) {
   if($view->name=="view_products") {
    $sqlStr = $view->build_info['query'];
    if($view->build_info['query_args'][2] == "A" || $view->build_info['query_args'][2] == "B")
    {
        $sqlStr = str_replace("SUBSTR(node.title, 1, 1) = '%s'","SUBSTR(node.title, 1, 1) = '%s' OR SUBSTR(node.title, 1, 1) = '%s'",$sqlStr);
        $view->build_info['query_args'][2] = 'A';
        $view->build_info['query_args'][3] = 'B';
        $view->build_info['query'] = $sqlStr;
    }
   }
}

```

every thing works fine. But the problem is when I use this code to manipulate the query **the PAGER is disappeared**. I am sure that this code causes the problem because when I disable the module or comment the function Pager appears but again when I active the module or un-comment the codes Pager disappears !!!

Please help me. What is my mistake ??

# Answer
> 1 votes
I found the solution of the problem.

Indeed I manipulate the code in wrong function.

I switched to hook\_views\_query\_alter and modify my codes in that function.

now everything works fine with no problem.

my function is

```
function modify_view_query_views_query_alter(&$view, &$query){ }

```

and I modify the query parts by changing the array values.

```
$query->where[0]["clauses"] and $query->where[0]["args"]

```

---
Tags: views, paging
---


# Question
Title: Show all content related to child taxonomy terms in parent
I don't think I could explain it any better here then I have in the title.

Basically if I have a taxonomy term call `Parent` and it has sub terms called `Child 1` and `Child 2`. I'd like to be able to see any content related to `Parent`'s sub terms (`Child 1` & `Child 2`) appear on the `Parent` taxonomy page.

Thanks in advanced!

# Answer
Looking around I have found the solution that helps me. It's a module called Hierarchical Select.
> 1 votes

# Answer
Use Hierarchical Select module and in manage display filed setting for that.

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
> -1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to combine views exposed filter with search?
My client asked me for a single field, that would work 2 ways:

* Autocomplete filter based on taxonomy.
* If site visitor inputs something that's not in taxonomy, full text search should be performed on content's body, and appropriate info message shown.

That way if user enters category name, he will get hand picked nodes listed, and if anything else, he will at least get some content.

Separately, it's easy. But how to combine these behaviours in one field?

# Answer
Finder module will do your requirement exactly, You can select taxonomy term as well as node title, body, fields, ..etc to perform the search.

> There are many ways to put together finder's functionality to get the sort of search form you need. There are also many hooks and theme functions allowing full customization of finder's output.

It is used for these purposes:

```
As a search tool to find a group of nodes or users.
As a way to navigate to a specific node or user page that matches criteria.
As an alternative to exposed filters for a Views module display.

```

See the below screen shot, In the **finder field** you can choose taxonomy terms as well as node body to perform the search in auto-complete exposed field, even you can perform multiple keyword search separated by comma. Read the Finder documentation for more information..

Once you added the element you can select the **finder fields** from the list, hold the

Ctrl key to select the **taxonomy term** as well as **Node: Body**
> 17 votes

# Answer
I am writing without testing but I have a feeling that you can use it at least as a starting point.

Using the Views Field View module, you can embed a view into another view, and it also allows you to pass a contextual filter to the embedded view.

In your case, I would create just another view that has a contextual filter that searches the given filter. I am not sure on that point, if you can make a search through contextual filters, but I have seen some options like 'Search: Term' etc.

Having said that, if you can achieve this first step anyhow, the rest is relatively simple.

In your original view, you add a 'No results behavior' under the advanced options section, and add a 'Global: View (Views field view)' and select the view you previously created, and pass the token for the exposed filter as a contextual filter to the embedded view (you can find the tokens in the list for the replacement patterns).
> 3 votes

# Answer
I have gone through the above discussions and possibly the below scenario can address the post 'How to combine views exposed filter with search?'. The implementation will require some custom coding.

1. Consider the url http://www.seedandspark.com/studio.
2. Here, on Left hand side, you have a search form. This is a custom form (`form_id = 'sns_studio_form_filter'`).
3. On the content region we have around 7-8 view blocks & all generating dynamic information (for anonymous users 3 blocks only)
4. Now, we have exposed filters enabled with each view block.
5. We have kept those exposed filters hidden from view
6. We have kept a note of the url structures when we use view exposed filters
7. In our custom form submit handler, we take information from the fields of the custom form and generate the similar url as we have noted in step 6. And, finally we redirect to that url. It will be like this in the submit handler ::

```
$form_state ['redirect'] = array(
  $path,
  array(
    'query' => $params // $params is the url
  )
);
drupal_redirect_form( $form_state );

```

So, now once step 7 is executed, all the view blocks will get filtered based on the filter criteria you have set.

Hope it helps.
> 3 votes

# Answer
There's also another way of doing it: You could try out Concat Field module. You basically add the field to content types, and then you can use filter by this field as search.

It's quite similar to Finder, I agree, but I think it's still worth mentioning.
> 3 votes

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


# Question
Title: how can i add billing information in invoice email
I have been using commerce Invoice 7x-10-alfa3 commerce Email 7x-2x-dev Variable email 7x-10-alpha -1x Variable 7x-22,4-dev HTML 7.x-2.65 modules

I want to sent an invoice email, which will include except of the order information (included in the token \[commerce-order:commerce-email-order-items\] ) , also the billing information address (I need all the information as it is appearing in the order view).

However, even though i try two different tokens \[commerce-invoice:order:commerce-customer-billing:commerce\_customer\_address\] and \[commerce-order:commerce-customer-billing\] none of the them renders any data but they just appear as simple strings!. Also other tokens i added in the body of the email, are just displayed as simple strings. I trying to modify the "default" value of the email through the store-\>configuration-\>emails

From what i have seen there is an issue with commerce email ,which have not been yet resolved https://drupal.org/node/1818380 . I was wondering whether someone has found a workround solution i can use.

Failing that is there any other way i could achieve the same result ? (To be able to sent an invoice email with order details and complete billing information). Maybe a combination of tokens in rules with different modules (or different versions of modules).

As i am pretty desperate any suggestions would be more than welcome. Thanks in advance

# Answer
I've implemented similar functionality for a Drupal Commerce site I built using Commerce Kickstart 2. It's actually a Rule created by the **commerce\_email** module which I'll break down for you below:

* **Rule is called "Send an order notification e-mail (Customers)"**
* **Event: Completing the checkout process**
* **Action: Send mail with variable (contains all default commerce\_email variable settings)**

Then if you navigate to the Commerce Email admin section: **(/admin/commerce/config/email)**

The token I use to display the customer address is:

**\[commerce-order:commerce-customer-shipping:commerce\_customer\_address\]**

Using that token everything prints out in my email template correctly as expected.

Hope this helps!
> 2 votes

---
Tags: rules, emails, tokens, commerce
---


# Question
Title: How to effectively remove module created fields?
During the installation procedure of a module one may create some fields and corresponding instances and attach them to a content type. What is the best practice to clear up what we have created after module uninstallation?

It seems that removing fields created by a module is not yet implemented in D7 (see `field_modules_uninstalled` docs.). What would be the best approach then to remove module fields?

**OR**

*NOTE:* the `comment` module removes the field upon uninstallation (see here).

# Answer
> 2 votes
This is the code snippet I usually use to remove fields created by a custom module:

```
if (field_info_field('my_field_name')) {
    field_delete_field('my_field_name');
    field_purge_batch(100);
}

```

Hope this helps

---
Tags: 7, entities
---


# Question
Title: Change the way results are shown when using the Quiz module
I have installed the Quiz module. Using the quiz module you can see the results of all the persons who have taken the quiz under `node/*/results`. Right now it shows shows the username of person in the table.

In the database I have a table that is called "`profile_value`" and there are some columns in it, "`fid`", "`uid`", "`value`".

Now I want to show the "`value`" of this where "`fid`" is equal to "`1`" and the user id is equal to "`uid`" instead of user-name in the result of the quizes.

I think I should be able to do this by changing the file `theme/quiz-results-browser-body.tpl.php`.

Am I right? How should I change it?

# Answer
Generally speaking when you need to alter the output of a module, you need to override the theme function which is responsible for formatting the data you'd like to alter.

You can do this either by overriding the theme function within template.php within your theme (can get messy quite quickly with a lot of overrides), or by overriding the theme function within a custom module (I would rather recommend doing it this way).

There's plenty of reading material on the subject out there to get you started. Just remember never to hack away at the core or contrib module's theme functions!! :)

Good luck!
> 1 votes

---
Tags: theming, quiz
---


# Question
Title: "Configure Block" region highlight missing in Drupal 7
The usual region highlight (a dashed-line border around the region) with a little gear icon that opens up a drop down saying "Configure Block" is missing on my custom Drupal 7 site. Which or What admin option is responsible for this?

* I am logged in an an administrator.
* I have actual regions.
* Those regions have data.
* "Demonstrate Block Regions" shows where the regions are correctly.

How do I bring this highlighting back?

Contextual Links module is enabled.

This is my block.tpl-

```
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>
<div class="block-inner clearfix">
<?php print render($title_prefix); ?>

<?php print render($title_suffix); ?>

<div<?php print $content_attributes; ?>>
<?php print $content; ?>
</div>
</div>
</div>

```

# Answer
1. Make sure you have the Contextual Links module enabled.
2. If you're overriding the default block template in your theme, make sure you're printing the `$title_prefix` and `$title_suffix` vars; I forget which one, but one of those contains the markup for the contextual links javascript.
> 2 votes

---
Tags: blocks, theming
---


# Question
Title: How to set a different theme when the site is on maintenaince mode?
Hi i am searching for a way to change the active theme when the site is on maintenaince mode (Drupal 7), can you help me? thanks in advice

# Answer
I think there is no way to set active theme while on maintenance mode, but you can change the way site looks.

For that to happen in your local site there is `/modules/system/maintenance-page.tpl.php` available.

You can overwrite as you need by pasting this into your theme directory.

Then in settings.php you need to set

```
$conf['maintenance_theme'] = 'ThemeName'

```
> 3 votes

---
Tags: theming
---


# Question
Title: Editing own content for content type giving me access denied
For content type "XYZ" for a user that has "Edit own XYZ" content I get an access denied message when attempting to edit content that was created by user. Do I need any further access permissions? I can delete and view my own content, just not edit.

# Answer
The "input format" on the body field might be set to one that you don't have access to, example "Full HTML", "PHP", etc.

Check that you (your role) has that access. Look here: "admin/settings/filters"

If you don't have access to the "input format" used on the body field then you can't edit that content.

I recently ran in to something close to this, I was surprised to find this as the solution. Hope this works for you.
> 4 votes

# Answer
Try rebuilding permissions @ admin/reports/status/rebuild

Verify user is the author of the node.

Verify user has role that has Edit Own XYZ permissions.
> 2 votes

# Answer
I solved the problem (after DAYS of work) by disabling the “Domain content type” module.

To diagnose the issue, I had to enable the possibility to view the callback functions (which often bear the name of the module) in the trace the PHP code in `/var/www/synthesys/public_web/include/menu.inc` in the `function menu_executive_active_handler($path=NULL) (line 336):`

1) I replaced

```
if($router_item=menu_get_item($path)) {

```

with

```
if($router_item=menu_get_item($path)) {
  print_r($router_item)

```

...and...

2) replaced

```
else {
  return MENU_ACCESS_DENIED;
}

```

with

```
else {
  return call_user_func_array($router_item['page_callback'], $router_item['page_argument']);
  //return MENU_ACCESS_DENIED;
}

```
> 0 votes

---
Tags: users
---


title: Menu not updated after role purchase

text:
# Question
Title: Menu not updated after role purchase
after a user purchases a certain role (i use UC and a rule to do so) the main menu is not updated automatically. The user had access to everything that belongs to the new role, but the menu only gets updated when i manually clear the cache on the site. In searching for a solution i found this has to do with menu caching. I don't use drush or devel and need a solution that suits a production site. Is it best to completely disable menu caching? And how do i do that? Is there a module for that? Thanx, Cas

# Answer
> 0 votes
You cannot disable menu cache - if you could, Drupal would need to scan all modules on every request and it would kill your site. You can use Cache Actions:

> It currently provides actions for:
>
> * Clearing Drupal cache bins
> * Clearing CSS/JS cache
> * Clearing The cache of specific views
> * Clearing The cache of specific panel pages
> * Clearing The cache of specific mini panels

Just clear menu cache in the same rule you use to add a role to your user. After adding that role, of course.

---
Tags: routes, ubercart, caching, users
---


# Question
Title: custom module js loaded before the module which it depends, Drupal.behaviors
The "Drupal.behaviors" doesn't behave as "document.ready", if I use a document.ready I will have the correct map but if I do a Drupal.behaviors, there will be an error related to the openlayers library function which is not found :(

After check, the OpenLayers.js is loaded after my module js. Is it possible to make it load after another one ? I though adding a dependency on another module would make him load before the other one.

If I use a setTimeout it's working but it's not the best solution !

Do you have any idea how I can do that ?

Thank you guys

```
(function ($) {
Drupal.OL_lat_long = Drupal.OL_lat_long || {};
    Drupal.behaviors.OL_lat_long = {
         attach: function (context, settings) {
                setTimeout(function(){
                    var map = $('#openlayers-map').data('openlayers').openlayers;
                    var pointLayer= map.layers[1];
                    console.log(pointLayer);
                    proj4326 = new OpenLayers.Projection("EPSG:4326");
                    proj900913 = new OpenLayers.Projection("EPSG:900913");
                    Drupal.OL_lat_long.dragPoint();
                    Drupal.OL_lat_long.actualizeLatLong();
                    Drupal.OL_lat_long.clickMap();
                    $('#redrawPoint').click(function(){
                        Drupal.OL_lat_long.redrawPointOnMap();
                        Drupal.OL_lat_long.actualizeLatLong();

                    });
            },200);
        //  });
        }
    }
}(jQuery));

```

# Answer
> 2 votes
Maybe you could try altering the weight of the script you add in your module?

```
drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/myscript.js', array(
    'weight' => '999',
  )
);

```

# Answer
> 0 votes
I had a similar scenario where I needed to track site wide events through mixpanel on events like submitting a form (which will reload the page and in some times will redirect to some other page and so the minimum 300 ms time needed for mixpanel tracking was failing).

I followed this approach :

I added a cookie inside a Drupal behavior while some required event occurs using -

```

set_cookie('cookie_name', SOME_VALUE);

```

Then in the module file under proper hook like say 'hook\_node\_view', 'hook\_user\_view', 'hook\_user\_login', 'hook\_preprocess\_page', 'hook\_user\_insert' or so, I added code like below :

```

if (isset($_COOKIE['cookie_name'])) {// Validation
  $value = 0;// Variable Declaration
  $value = drupal_json_decode( $_COOKIE ['cookie_name'] );// Get value From Cookie

  if (isset($value ['via_btn'])) {// Validation
    if (!empty($value ['via_btn'])) {// Validation
      drupal_add_js(array('YOUR_MODULE_NAME' => array('SOME_NAME' => 1)), 'setting');
    }
  }

  // Delete Cookie
  setcookie("cookie_name", '', time() - 3600);
  if (isset($_COOKIE["cookie_name"])) {
    setcookie("cookie_name", '', 1, '/');
  }
}

```

Kept the below code in theme.js (so that it's available in all pages) :

```

function set_cookie(cookie_name, cookie_val) {
  var expires = "";
  if(cookie_name && cookie_val){
    document.cookie = cookie_name + "=" + JSON.stringify({
      via_btn:cookie_val
    })+ expires + "; path=/";
  }else{
    document.cookie = cookie_name + "=" + "" + expires + "; path=/";
  }
  return 1;
}

```

Now added the below code in the js file :

```

Drupal.behaviors.SOME_SUITABLE_NAME = {
  attach: function (context, settings) {
    if(typeof Drupal.settings.YOUR_MODULE_NAME !== 'undefined' && typeof msg === 'undefined') {
      msg = Drupal.settings.YOUR_MODULE_NAME.SOME_NAME;
      if (msg !== undefined && msg === 1) {
    // Do Something
      }
    }
  }
};

```

So, here, what I am doing is trying to track an event after going through some proper hook so that I can skip using 'setTimeout'.

Note : In my case, I have used

```
$(document).ready(function(){});
```
if it worked. I went through the above approach only when default drupal behavior approach or 'document.ready' didn't work.

Hope it helps

---
Tags: javascript
---


title: Pagination for Views RSS

text:
# Question
Title: Pagination for Views RSS
I'm using Views RSS module to generate a custom RSS feed. I want to be able to limit the results by adding `?offset=50&limit=50` . How could I achieve that? Is there any Views plugin I could use?

Thanks

# Answer
> 0 votes
Not sure if there is a dead simple solution. I know that by using Services and Services Views you can use offset and limit as arguments when calling the service.

So that the URL could look like: http://example.com/rest/views/articles?limit=5&offset=2

---
Tags: views, feeds, paging
---


# Question
Title: Performance issues with Migrate Cron update
I am running Migrate updates with cron every couple of minutes. I don't have many nodes (less than 100) but certain of them are data-heavy. Because of the wonky way my XML is written, I am forced to update all data every couple minutes. My site is now taking a real performance hit. Is this because I am running Migrate with cron? Or is there a way to force Migrate to update via hashes or something? I can't use the highwater field because my XML isn't ordered by update time.

# Answer
Updating all nodes every couple of minutes is bound to kill your performance. It's write-heavy and invalidates caches and there is no way around it in any possible CMS, not only Drupal.

If you cannot decide which nodes needs to be updated on XML read, try to decide on export, and export only nodes that changed since last time. Perform full export-import once a day, deep at night.

Other way around it is to write a custom module that would perofrm following steps:

1. Download XML file to local variable
2. Compare checksums of current and previous XML
    * If checksums was equal, exit.
    * If checksums was different, perform import.
3. If changed update XML checksum.

That way you will only write anything if XML was changed - couple of times a day instead of every other minute.
> 2 votes

# Answer
As Mołot points out, you are doing a lot of writes, which will be a considerable problem, regardless of how you do it.

> force Migrate to update via hashes or something

My experience with Migrate is that the module is highly flexible. Even if this particular functionality isn't there already, I'm fairly certain you could add it yourself.

If you absolutely *must* do all those writes, consider using MongoDB and its corresponding module. It only implements field storage for the Drupal 7 version though, so you'd need to upgrade core for that to be meaningful for you.

Otherwise, look at improving your I/O speed in other ways, such as an SSD disc.

I'm not 100% sure about the details of how transactions are handled one a low level, so take the below suggestion with a grain of salt.

You could also consider looking at an approach where you do the update in the background on a different physical harddrive, (mysql can be configured to do that within the same db-server, not sure about other dbs), and then when the data is updated, initiate a transaction, switch out the old data with the new, and commit. That way you can consolidate the disc writes on the primary disc to a single large one, which should be significantly faster.
> 1 votes

---
Tags: 6, performance, cron, migrations
---


# Question
Title: Use taxonomy terms to set node access for a user
I have a vocabulary with two terms.

Vocab: A

Terms: b,c

I use them in two places.

> 1. First in the registration: in the `config->account->fields`.
> 2. And second one of my content type.

Now I want when a post tagged as b Just people that they are tagged with "b" in the registration can see that post.

And when a post tagged as c just the users that tagged as "c" can see the post.

Can I do this with context module? How?

# Answer
> 1 votes
I don't think you can set this up with Context.

There is Access by Term where grants (view, update, delete) are based on the relationship between the user-\>term\<-node.

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


# Question
Title: How i can add new fancybox-style (theme) for display uploaded image in WYSIWYG / CKEditor with Media module?
When I upload new image with Media Browser (WYSIWYG + CKEditor + Media), I see themes: original, small, large... How i can add my own template to this list for fancybox?

```
<a href="full.jpg"><img src="preview.jpg" /></a>

```

Maybe already have a module for this theme?

# Answer
Go to configuration, media, image,styles, add style, or directly

```
http://example.com/admin/config/media/image-styles/add

```

And add a custom image style.
> 0 votes

---
Tags: wysiwyg, media
---


# Question
Title: How to link a view to a user profile created using views
I created a view which displays users on my site. In the view, the "name" of users links to their individual profile.

Now i want to have more control over information displayed to users when they view other peoples profile.

To achieve this, I am of the opinion that i need to create another view to display the user profile. Where i see a challenge ahead is how to make my first view link to the individual user profile based on my new view.

Please, how do i achieve these or is there a better way?

Thanks in anticipation.

# Answer
Hope this will help you,

As I understand you have 2 views, first view is to list the users and the second view is to show the particular user detail information.

In Drupal 7 you can achieve it easily.

Let say the first view path will be **users/listing** and the second view path is **user/%/other**.

Steps

* In first view where you are listing all the users, add another field **UID** and pull it to the top and **exclude it**.
* And go to **USER NAME** field and *uncheck* **Link this field to its user** and goto **Rewrite results** and *check* **Output this field as a link** and enter **user/\[uid\]/other** and save it. \[uid\] is taken form the **Replacement patterns**
* Now its time to create new view which will be showing the user information based on the *user id*. In this view we need to add the contextual filter, based on that the user detail will be shown.
* Add contextual filter
> 4 votes

# Answer
It is possible if you relate the user to a form he or she submitted, using the data module, schema module, and mysql views module. Assuming you are using a mysql backend. This video shows you how: http://vimeo.com/18701843
> 0 votes

---
Tags: views, users
---


# Question
Title: is there any way to make the webform components labels translatable?
Just wondering how to make the webform components labels translatable. I found this post with a link to a sandbox project but I don't where to download the module: Make Webform multilingual (i18n) aware through contributed modules

I also find this function to just make what I need but it doesn't work, maybe with a few change it will work: Source: work around

```
function module_name_form_webform_client_form_xx_alter(&$form, &$form_state) {
  foreach (element_children($form['submitted']) as $element) {
    // Pass each webform component title through the t() function.
    $form['submitted'][$element]['#title'] = t($form['submitted'][$element]['#title']);
  }
}

```

The function provided by ***@lenni*** does the job but I get these error messages.

> Warning: strlen() expects parameter 1 to be string, array given en drupal\_validate\_utf8() (línea 1600 de/Applications/MAMP/htdocs/tonisacristan.com/includes/bootstrap.inc).
>
> Notice: Array to string conversion en filter\_xss() (línea 1366 de /Applications/MAMP/htdocs/tonisacristan.com/includes/common.inc).
>
> Notice: Array to string conversion en format\_string() (línea 1552 de /Applications/MAMP/htdocs/tonisacristan.com/includes/bootstrap.inc).

The source of the problem is a Markup component. This function is working fine.

```
function webform_extras_node_view($node, $view_mode, $langcode) {
  if($node->type == 'webform' && $view_mode == 'full') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      //to skip Markup components
      if($key != 'my_markup_component'){
        $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
      }
    }
  }
}

```

# Answer
> 1 votes
Similar (a litte bit more generic) solution but still not a clean one:

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'webform' && $view_mode == 'full') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
    }
  }
}

```

# Answer
> 0 votes
And if you actually want to translate your markup fields as well, which is often the case:

```
function mymodule_node_view($node, $view_mode, $langcode) {

  if ($node->type == 'webform') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      if($key != 'your_markup_component' && $key != 'your_markup_component_2'){
        $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
      }
      else {
        $node->content['webform']['#form']['submitted'][$key]['#value'] = t($node->content['webform']['#form']['submitted'][$key]['#value']);
      }
    }
  }
}

```

---
Tags: webforms, i18n-l10n
---


title: Deleting Content Manually

text:
# Question
Title: Deleting Content Manually
If I were to delete the latest row of the node table in the database would all traces of the latest added content be gone from my site without errors from core modules after clearing the cache?

# Answer
If you delete a row directly from the node table you can expect:

1. At *best* \- you will just have a bunch of orphaned data in the system. Tables containing this orphaned data include, but are by no means limited to,

* `node_revision`
    * `taxonomy_index`
    * `url_alias`
    * `search_node_links`
    * Any number of `field_data_FIELD_NAME` and `field_revision_FIELD_NAME` tables

Those are just a few of the core tables that can be affected; there are others, and many contrib modules will install tables to store node-related data. Those will also potentially contain orphaned data.
2. At *worst* \- there's no telling how this could affect your site, it completely depends on how it's configured. You might get lucky and experience nothing but the orphaned data, but I wouldn't advise counting on that. Before you do anything, take a backup of your data.
> 1 votes

---
Tags: 7, nodes, database
---


# Question
Title: Rules: how to programmatically set the bundle of an entity?
For some tasks, rules requires to know the bundle of a given entity, the most obvious situation being when you need to set a field of a node and rules requires the type of node.

Normally you can solve this in the "condition" side of rules, where you can check that your entity is of a given bundle or that it has a specific field. However there are situation where this approach is not possible, as when the entities derives from the result of an action, in my case they are loaded from a VBO view. Hence how can you tell rules that a given list of entities - or a single entity - is of a given bundle, so I can use its specific fields ?

# Answer
> 1 votes
Actually, if you need to do something that's like an additional 'condition-then-action' within your rule's Action section, what you need is a **Rules component**!

You've loaded some entities in your action (perhaps in a loop) and now you need to apply a condition and action to those entities. Here's the basic recipe for using components in your action section:

* Go to /admin/config/workflow/rules/components to create a new rule component to run for each of the items in your loop (or for a single item you've gotten in your rule action). Click the 'Add new component' link at the top of the page
* Select '**Rule**' from the drop-down options, since this will be a component that contains both a condition and an action
* Name the rule, and in the 'Variables' section, we have to let it know we're going to pass it a parameter to work with. In your case, this will be the entity you want to check.
* Once you've named your components and named the parameter you'll pass it, the next screen looks very much like a regular rule. Just set up the condition (make sure the entity is of type whatever) and the action (use the appropriate fields of that entity to do something).
* Finally, save your component and call it in your original rule's action section (within the loop if you have one), passing it the entity to work with

Sorry that this is rather text-y. I actually just recently answered a question about using rules components with commerce items in another question and included screenshots there, so see if you can use that as a reference too: https://stackoverflow.com/questions/17797285/drupal-commerce-order-object-extra-data/17843597#17843597

Let us know if rule components solve your issue!

---
Tags: rules, entities
---


title: Get field content from tid

text:
# Question
Title: Get field content from tid
I am wondering how to retrieve the actual data of a field instead of the tid on a node. Googling around I found a solution to a similar problem, by constructing a query on my own. However, it is usually the case that a function already exists for this. Do you know how I can achieve this?

What I get is something like this

```
field_category (Array, 1 element)
  -> und (Array, 1 element)
    -> 0 (Array, 1 element)
      -> tid (String, 2 characters ) 18

```

# Answer
> 3 votes
Specifically for taxonomy terms you have `taxonomy_term_load()`, e.g.

```
if ($field_items = field_get_items('node', $node, 'field_category')) {
  $tid = $field_items[0]['tid'];
  $term = taxonomy_term_load($tid);
}

```

---
Tags: entities, nodes
---


# Question
Title: How to build a module which calls a JS file on one certain node?
There’s one site (A) which via an API of one other Drupal site (B) gets an already rendered views block displayed on one node - finally with hook\_menu() and hook\_block\_view(). So now I have that node (/stuff) here with it’s views rows and views fields containers.

Since these things really have nothing to do with (B) (where I also don’t have access to) I want to build a module (button) on (A) which calls a JS to manipulate the DOM only on /stuff. Which hooks and syntax will I need?

# Answer
I think you're looking for something like `hook_page_alter()` \+ `drupal_add_js()`, e.g.

```
function MYMODULE_page_alter(&$page) {
  // Check that we're on the right page.
  if (arg(0) == 'stuff' && !arg(1)) {
    // And add some JS.
    drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/MYMODULE.js');
  }
}

```

This could also be done in `hook_preprocess_page()`, `hook_init()`, and probably a bunch of other places. I chose `hook_page_alter()` at random out of those, each should be equally effective.
> 1 votes

---
Tags: 7, hooks, javascript
---


# Question
Title: Include Full Taxonomy Term inside a Content Type?
I'm working on a project where we want to pull in the title, description, and an image from selected taxonomy terms and include them in content of a predetermined content type. The content type is already displaying the Term with a link, but I want to display the description and an image along with it.

While I am sure this is possible, I'm not sure what the best method would be to accomplish this. I'd rather not hard-code it into a content-type template.

# Answer
The content type UI doesn't allow you to render a taxonomy term entity. So, you can solve this one of three ways.

1. Create all the fields in the taxonomy you need and add the term to the content type via a reference then use the custom code found here: https://stackoverflow.com/questions/12705389/displaying-content-of-term-reference-instead-of-link-drupal-7

```
$term = taxonomy_term_load('taxonomy_term', array($hotel["und"][0]["taxonomy_term"]->tid));
$view = taxonomy_term_view($term);
print render($view);

```

**Note:** In most cases, you will find that you actually do not need to run taxonomy\_term\_load since the values in the array \['taxonomy\_term'\] is exactly the same. Therefore you can use:

```
    $term = $hotel["und"][0]["taxonomy_term"];
    $view = taxonomy_term_view($term);
    print render($view);

```
2. Create a taxonomy view and use a contextual filter to limit the view to the nid from URL.
3. Don't use taxonomy for this. What you're trying to do is display content, not organize content. In Drupal, when you want to display content, you should use a content type. Once you have a content type, you can reference it with an entity reference and display it in a teaser format. You could then add a term reference to THAT content type to limit it by category.
> 0 votes

---
Tags: taxonomy-terms, nodes
---


title: 2 Pagers showing for Views Block

text:
# Question
Title: 2 Pagers showing for Views Block
I created a Custom View block in Drupal 7 which it is simply pulling random "Did you know Tips" for visitors. I created a mini pager for the block to allow visitors to toggle through them (Ajax enable as well for the asynchronous refresh of the block)

Everything is working accordingly except one tiny issue... I have 2 Pagers on my home page??? One is the mini pager under the block which is desired, but an additional Full pager is created at the bottom of my main page. Oddly, it's only found on the main page!!! No other nodes pages have this issue.

It seems that the behavior is along the lines that the additional pager is being "promoted to the front page" however, the content type has that excluded. Is there a way to hide this additional pager in template.php / views-view.tpl.php? Perhaps I missed something along the way?

# Answer
> 0 votes
This issue just happened to me there's a field on the pager detail screen that allows you to set an id for the pager. This is usually set to 0. I updated the id and the second full pager at the bottom of the page went away. Wanted to post this in case anyone finds this page as I did.

# Answer
> 0 votes
In investigating this issue further, I resided to installing the Views Litepager module as it's an increase in performance and it resolved my issue as well with the 2 pagers.

---
Tags: views
---


# Question
Title: Path breadrumb crumb displaying just first letter of title
I am using the module path breadcrumb, is it possible to create a crumb which displays just the first letter of the title?

# Answer
> 0 votes
Maybe it helps someone so I will respond my own question: It resulted to be very easy using the module custom tokens with the following code:

```
    <?php
$node = node_load(arg(1));
$title = $node->title;
$rest = substr($title, 0, 1);
return $rest;
?>

```

---
Tags: breadcrumbs
---


# Question
Title: Drupal javascript file loading and jQuery
I have several javascript files in custom modules containing many functions which are used across the code. In D6 I simply added them during hook\_init() and it was fine.

```
drupal_add_js("/scripts/jquery.url.js", array('group' => JS_LIBRARY));
drupal_add_js("/scripts/jquery.cookie.js", array('group' => JS_LIBRARY));
drupal_add_js("/scripts/mymod.funcs.js", array('group' => JS_DEFAULT));
...
drupal_add_js("/scripts/otherfuncs.js", array('group' => JS_DEFAULT));

```

However, in D7, I am now getting the "$ is not a function". Wrapping all my code as described in the D6 to 7 conversion wasnt't seeming to work since I was then getting "\<one of my functions\> is not defined". Using

```
var $ = jQuery.noConflict();

```

at the start of my 'parent' file resolved the error. But that doesn't seem like a good idea either. Below is an example of the javascript.

```
//in main file: mymod.funcs.js, global functions
function my_storage(key) { return value; }

//in another file: otherfuncs.js
Drupal.behaviors.myMod = { attach: myMod_Splash }

function myMod_Display(splash) { ... }
function myMod_Splash() {
  var splash = my_storage('splash');
  if (splash) { myMod_Display(splash); }
}

```

What is wrong when simply wrapping all of it with the recommended? What else should be done, aside from converting the function groups to objects (which still wouldn't necessarily resolve the wrapping problem)?

EDIT: I was wrapping my code like:

```
//(function ($) { //tried here
Drupal.behaviors.myMod = { attach: myMod_Splash }

(function ($) { //and here
function myMod_Display(splash) { ... }
function myMod_Splash() {
  var splash = my_storage('splash');
  if (splash) { myMod_Display(splash); }
}
})(jQuery);

```

UPDATE: I just removed the "var $ = jQuery.noConflict();" from my file to begin messing with the problem again, and am now getting no errors at all, in Web/Error Console or Watchdog. None of the code was wrapped. I was constantly clearing cache in Drupal before so really have no clue what is going on now. Could the JS aggregation still have been placing the files in the wrong group, hence loading in a conflicting order?

# Answer
I was wrapping the functions correctly according to the conversion documentation. This, however, was creating a scope for all the functions that had previously resided globally, which is why I started getting the 'not a function' errors, but the code still worked if all the calls were to functions within the same file (since they were all wrapped in the same anonymous function).

So, the dirty fix was simply to create some global variables and assign the functions to them:

```
var myfunc;
(function ($) {
    myfunc =
    function myfunc() { ... }
})(jQuery);

```

While this works (if I get the time) it would be better to create global objects to hold the functions and settings. And, also place the loading of those files in the .info file of the module(s).
> 0 votes

# Answer
By the docs You should wrap your code that way:

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

})(jQuery);

```

What's wrong with other methods? Nothing fundamental, only Drupal's own scripts are not tested to work with them, and redefining `$` globally may interfere with non-jQuery libraries some modules use, rendering either their or yours code not working.

For "jQuery is not defined", there are couple of possible problems. My surest bet was to skip drupal\_add\_js() altogether. Unconditional module (or theme) scripts can be added in info files:

```
scripts[] = somescript.js

```

and form related ones can be added directly to a form:

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/js/a.js',
  drupal_get_path('module', 'mymodule') . '/js/b.js',
);

```

I prefer to leave conditions in javascript itself, it means I only need one aggregated file for all pages on my site (plus one per form), so this is a performance boost in addition to problem prevention.
> 0 votes

---
Tags: javascript, hooks
---


# Question
Title: Drupal 7, Looking for a module that can geo-locate a user and feed them specific data?
I'm trying to build a site where I can geo-locate anonymous users when they visit the site and feed them the appropriate data.

Example: I want to display a certain block if the anonymous user's IP is located within 100 miles radius of NYC.

Is there a module that can plug into Rules as a condition and geo-locate anonymous uses?

# Answer
Smart IP module (https://drupal.org/project/smart\_ip) will do the job. It will locate the visitor based on his/her IP address. Anything better than that (e.g. street address) requires Device Geolocation, which comes as a submodule of Smart IP.
> 2 votes

---
Tags: 7, blocks, users, location
---


title: Hook isn't invoked

text:
# Question
Title: Hook isn't invoked
I try to add some fields to content type through this hook as it done in node\_example module in Drupal 7 examples but it's not even invoked. What can be wrong?

```
function education_node_type_insert($content_type){
            $fields = _anketa_installed_fields();
            foreach($fields as $field){
                field_create_field($field);
            }

            $instances = _anketa_installed_instances();
            foreach($instances as $instance){
                $instance['entity_type'] = 'node';
                $instance['bundle'] = 'anketa';
                field_create_field($instance);
            }
    }

```

# Answer
This hook will only get called when node\_type\_save() is called - ie. when a new node type is saved to the database.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Theming a node edit Form - Move Author Information to another positon
I am theming the DRUPAL 7 NODE EDIT FORM following the instructions in the post.

Everything is working fine.

However, I want to move the "Authoring Information" from the bottom of the page to another position on my node. How do I do that?

I thought I would be able to use this:

```
<?php print drupal_render($form['author']); ?>

```

But it does not seem to work.

# Answer
> 2 votes
The only solution I found to this was to use a View.

* In Views under relationship, select Content: Author The in fields, add an author field.
* Then in under Contextual Filters select Content NID
* Use the following settings for Content NID: WHEN THE FILTER VALUE IS NOT AVAILABLE: Provide Default Value / NODE ID from URL

Then simply create a block and display it on the node page.

# Answer
> 2 votes
You can use the Display Suite module.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (Drupal 7 only) is available for even more drag and drop fun!

# Answer
> 0 votes
Try the following:

```
<?php print drupal_render($form['author']['name']); ?>
<?php print drupal_render($form['author']['date']); ?>

```

The author fieldset is part of the additional\_settings group. To render the author field you have to call it directly.

Display Suite is great, but it won't let you access the author field directly.

---
Tags: theming, nodes, forms
---


# Question
Title: Colors to my header and footer not applying by using color scheme options in my theme
I am trying to incorporate color scheme which is available in bartik, into my theme. I am able to generate the files which will be located at

> sites/default/files/color/theme-4855b5/colors.css

after making options in color scheme of my theme.

But in the head tag of styles files, it still points to my theme directory colors.css instead of above mentioned directory, Which results in no change of colors for my theme.

My theme is actually a sub theme. What am i doing wrong ??

* I have included color folder and inside that have color.inc files.
* Also included `color.css` folder inside css folder.
* `hook_process_page(&$variables)` and `hook_process_html(&$variables)` these functions included in `template.php`
* included css file in info file too. `stylesheets[all][] = 'css/colors.css'`

What am I missing in not getting that css being replaced by dynamically generate one? Thanks in advance.

# Answer
> 0 votes
I am able to apply css for my header and other things, I found an alternative way to include the css.Even though I can't find a way through `drupal_add_css()`, the following helped me in adding css.

This is the way I included dynamically generated css file which is located at `sites/default/files/color/theme-768/color.css`

In the theme folder in the html.tpl.php after `<?php print $styles;?>` include this

```
<?php
       print '<style>';
       print '@import url("' . $filepath . '")';
       print '</style>';
?>

```

This includes the css file and provided colors for header, footer etc.

---
Tags: 7, theming, javascript
---


# Question
Title: Drupal 7 Commerce - What permissions do I need to set to give access to a specific role to view ANY order for administration?
In drupal 7 commerce i setup a staff role to access and manage commerce orders, but they are getting an access denied even though i have all the Orders permissions checked off. Is there somewhere else I need to check off to enable permissions for a specific role?

>

# Answer
> 1 votes
This is how my permission look like --

>

As you can see, Site Admin & Shop Keeper can manage orders along with administrator(I have several kind of users). Site Admin & Shop Keeper doesn't have access to toolbar, so I have created a menu with name "Manage Order" & set it to the path "admin/commerce/orders"(I have several menu items of this kind).

Placed this menu in one region with permission set to be viewed only by these users type who are intended to use it. These users have permission to use admin theme, so they access it just like administer do by clicking on those menu item.

---
Tags: 7, commerce, users
---


title: SQLSTATE[HY000]: General error: 1366

text:
# Question
Title: SQLSTATE[HY000]: General error: 1366
I'm using Feed Importer to import data from a csv file, and I got this error

`SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xA0 a TN...' for column 'message' at row 1`

All values are in english characters, and I really don't know how to solve this problem

Help please. thanks

# Answer
What is the origin of your CSV file? Are you sure that it is properly encoded using UTF-8? This error is coming from an issue with the database handler trying to process non-UTF8 characters (see: http://drupal.org/node/1140194).

The particular character it is having problems according to your error above is the "&nsbp;" character or 0xC2 and 0xA0, you'' want to convert your file to UTF-8 or alternatively if you have control over what ever is generating your export, strip it out using php following the advice here
> 5 votes

# Answer
If you got the error while using the db\_insert then you can use the following code

```
$val = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

```

if it is just matter of one field value.
> 1 votes

---
Tags: feeds, importing-exporting
---


# Question
Title: configuring drupal to use unicode characters
I'm working on a site for mathematics so every so often I have to deal with Unicode characters like "". Right off the bat, this causes trouble for my Drupal 7.15. For example: I create a Basic Page with Full HTML format, and paste that character in, and I get this error:

```
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value:
'\xF0\x9D\x94\x85' for column 'body_value' at row 1: INSERT INTO {field_data_body}
(entity_type, entity_id, revision_id, bundle, delta, language, body_value,
body_summary, body_format) 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); Array (
[:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 86234
[:db_insert_placeholder_2] => 29768 [:db_insert_placeholder_3] => page
[:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => en
[:db_insert_placeholder_6] =>  [:db_insert_placeholder_7] =>
[:db_insert_placeholder_8] => full_html ) in field_sql_storage_field_storage_write()
(line 448 of /home/joe/staging/drupal_planetary/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

Now, I recognized that this was probably something to do with the way the database was set up, so I followed some guides around the internet, like this one: http://cameronyule.com/2008/07/configuring-mysql-to-use-utf-8/ and things are looking good, after a fresh install:

```
mysql> show variables like 'collation%';
+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database   | utf8_general_ci |
| collation_server     | utf8_general_ci |
+----------------------+-----------------+
3 rows in set (0.00 sec)

mysql> show variables like 'character_set%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)

```

I even adjusted the way the database is invoked inside settings.php:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'MYDB',
      'username' => 'MYUSER',
      'password' => 'MYPASS',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
                     PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                     )
    ),
  ),
);

```

But, no luck, I still get the error when pasting my . Are there further database tweaks I should try?

One further note: I've tried running utf8\_encode(...) on the content that I expect to have unicode symbols in it, and this works as a temporary work around. In other words, I can save content, the pages display without problem. But then I wait a while (24 hours?) and come back and the pages are full of garbled unicode expressions!

Can you help me figure out how to either make this workaround unnecessary, or how to make it work and stay working?

# Answer
After further investigation: "" and other characters beyond the Basic Multilingual Plane need to be stored in a database set up with the "`utf8mb4`" charset. The general configuration steps are very nicely described here:

http://mathiasbynens.be/notes/mysql-utf8mb4

In addition to updating MySQL to 5.5.28, and doing the basic tweaks outlined in that link, in order to get this working with Drupal, I needed to take some further steps:

* Replace `SET NAMES utf8` with `SET NAMES utf8mb4` in includes/database/mysql/database.inc
* Modify settings.php to include the following

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB',
      'username' => 'UN',
      'password' => 'PW',
      'collation' => 'utf8mb4_general_ci',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
                     PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
                     )
    ),
  ),
);

```
* And modify the table and column (per the page linked to above) where the fancy UTF8 characters are to be stored:

```
ALTER TABLE tn CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tn CHANGE cn cn longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

```
> 7 votes

# Answer
I am thinking that converting the whole txt file to UTF-format and parsing the CSV is not a good idea. The issue happens when the character set is not in UTF-8 format.
If you got the error while using the `db_insert()` then you can use the following code, when it is just matter of some field values.

```
$val = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

```
> 0 votes

---
Tags: database
---


# Question
Title: Show link only to user with permission to edit
I'm using the following code to show the *Edit* button to edit pages in my blog teasers and others content types.

```
<a href="<?php echo '[node:edit-url]';?>">Edit</a>

```

It works fine, but it shows for all users, even the users with no permission to edit. How can I hide it for users that don't have permission to edit?

# Answer
Assuming that you are talking of the *blog* content type, you should need to use code that checks:

* If the user who is currently viewing the blog node is the author of the node and has the "edit own blog content" permission
* If the user who is currently viewing the blog node is not the author of the node and has the "edit any blog content" permission

```
<?php
  if ('[node:author:nid]' == $GLOBALS['user']->uid) {
    $permission = user_access('edit own blog content');
  }
  else {
    $permission = user_access('edit any blog content');
  }
?>
<?php if ($permission): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit</a>
<?php endif; ?>

```

A more generic code would be the following one.

```
<?php $item = menu_get_item('[node:edit-url]'); ?>
<?php if (!empty($item['access'])): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit</a>
<?php endif; ?>

```

This code is more generic because it shows the link whenever the current user has access to the edit link, whatever permissions are required to see that link. It could be a module alters which users can see the node edit page, and this code would take that in consideration.
The code is assuming \[node:edit-url\] is a URL like node/10/edit; if the URL is /node/10/edit or http://example.com/node/10/edit, then the code needs to be changed to extract the node/10/edit part, since that is the string menu\_get\_item() is expecting. See for example the code used by blog\_menu\_local\_tasks\_alter().

```
  // Add action link to 'node/add/blog' on 'blog' page.
  if ($root_path == 'blog') {
    $item = menu_get_item('node/add/blog');
    if ($item['access']) {
      $item['title'] = t('Create new blog entry');
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }

```

That code is part of the Blog module, and it uses `menu_get_item()` to check if the currently logged-in user has access to the page to create a new blog. It doesn't merely verify the user has the permission to create a blog node, since that would not be enough if a module changes when a user can access the node create form.
Also note that the argument passed to `menu_get_item()` doesn't have a / at the beginning.

Notice that the Token module defines a URL token type, for which it makes available the following sub-tokens:

* path, the path component of the URL
* relative, the relative URL
* absolute, the absolute URL
* brief, the URL without the protocol and trailing backslash
* unaliased, the unaliased URL
* arg, the specific argument of the current page (e.g. 'arg:1' on the page 'node/1' returns '1')

Unfortunately, at the moment the type for node:edit-url is not set to url; when it is, the following code will work.

```
<?php $item = menu_get_item('[node:edit-url:path]'); ?>
<?php if (!empty($item['access'])): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit</a>
<?php endif; ?>

```
> 5 votes

# Answer
You can use the node\_access function to see whether the current user can perform operations on a given node:

```
<?php if (node_access('update', $node)): ?>
  <!-- edit link here -->
<?php endif; ?>

```

https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_access
> 2 votes

# Answer
Use user\_access function. Pass target permission as parameter. For node edit access you can use `'administer nodes'`.

```
<?php if(user_access('administer nodes')): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit</a>
<?php endif; ?>

```

**Update**

You can work with permission for editing own content. Permissions are set in drupal per each content type. For example for `article` content type permission will be `edit own article content`.

```
<?php if(user_access('edit any article content')): ?>
   <a href="<?php print '[node:edit-url]';?>">Edit</a>
<?php endif; ?>

```
> 1 votes

---
Tags: nodes
---


title: Add CSS class to a flagged node

text:
# Question
Title: Add CSS class to a flagged node
I want to add CSS classes to flagged nodes in order to theme them.

Found the documentation How to add CSS classes to nodes, based on flags set, but this solution is for D6.

Can someone help me to figure out how to make it work with D7?

# Answer
> 4 votes
Try this in your template.php of your theme. Change MYTHEME to the name of your theme and bookmark to the machine name of your flag. And change node-flag-bookmark to the css class you want to be added to your node.

```
/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $flag = flag_get_flag('bookmark'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-bookmark';
  }
}

```

---
Tags: 7, theming, flags
---


title: Drupal Distribution best practices

text:
# Question
Title: Drupal Distribution best practices
I have a site with drupal commons distribution. I updated the existing content type to add some fields which made the feature in overriden state. Now, I am not sure the best practice to follow. Should I update the feature in profiles/commons/modules/... or is there another way to update the existing content type without changing the default code? Should I move all profile modules under sites/all/modules/...? Please help me to follow the best practices. Thank you.

# Answer
Once your features are overridden you have stepped away from the distribution. Sure you could struggle with Features overrides and such but I really think you will end up in a stressful situation.

There might be update hooks in an upcoming release of Commons that reverts all your features, another administrator unknown to the overridden state of things might get terrified and ninja click revert on all overridden features.

I'm not so sure about features overrides also as a long term solution to keep you changes working. Let's say the original feature changes a lot, then your feature override might actually try to override things that no longer is a configuration. I haven't worked that much with the module so I can't say for sure, but it gets messy...

The effort you need to invest in each update of Commons is also depending on what kind of overrides you do. In one installation of Commons I have made a subtheme to what is shipped with Commons. So all changes goes in there and Features is left as is. There might be some work that needs to be done in each update of Commons to keep my sub theme good looking and up to date. But having to double check that all feature overrides etc play along with the update is a lot of work!

Another way is to simply say that Commons is a starting point to your platform. That you take what Commons have, override it all over. Then export what you have into features and say that's your version of Commons. It's a bit of work to get done but it is possible to export all components from a site into new features and then disable the old features. You are now detached :)

Last words :)

It's really hard to override a distribution and still benefit from updates. The distribution itself must sort of be compatible with it. If you feel you still benefit from keeping your overrides up to date in each update of Commons, go for it. If you're not ready to spend time in each update to verify your overrides, don't override or just do simple stuff in the theme or new modules. Or third go bananas and build your own thing but don't expect upgrade paths to play nice.
> 3 votes

# Answer
Once your features are overridden, then the configuration is moved from the files to the database (i.e. Drupal no longer looks for the configuration supplied by the feature module and uses your configuration in the DB). This means you can update the files without overriding your changes/additions (Just don't hit the revert button in the Features admin UI). That being said, if you changed/updated a content type, you will no longer be able to take advantage of any changes/updates that were made to the commons distro supplied content type. This is the same for views, contexts, rules, etc. Some devs will use the Features Override module to allow them to store their site specific overrides in a feature. This allows you to store your overrides in files and still leverage any changes/additions from the distro.
> 4 votes

---
Tags: 7, distributions
---


# Question
Title: How to add comment form to drupal pages not having node and content type?
mymodule.module

```
function mymodule_theme() {
return array(
    'mymodule_results' => array(
        'variables' => array('var1' => null, 'continent' => null, 'country' => null, 'location' => null, 'query' => null, 'total' => null,'comments'=>null),
        'template' => 'templates/mymodule_results'
    ),
    }

```

mymodule.pages.inc

```
function mymodule_details($beaches = null) {
 drupal_set_title('Beaches Details');
 if (!isset($beaches->comment_count))
    $beaches->comment_count = 0;
return array(
    '#theme' => 'mymodule_results',
    '#beaches' => $beaches,
    '#attached' => array(
        'library' => array(
            array('iks_libraries', 'jquery.tinycarousel'),
        ),
    ),
);
}

```

mymodule\_results.tpl.php

```
<?php if ($comments): ?>
<?= render($comments) ?>

```

I need to include the comment form in the template page, But i have not created a content/node type for this. I'm displaying the results in the template page.

# Answer
Comments needs to be attached to a content. If you want to use built-in comments module, you need to:

* Use "simple page" content type to create dummy nodes, or create similar one
    + it might be wise to strip your dummy content type from everything except title and comments
    + revoke edit and delete rights, no one should be able to do it
* In your module's install file, make sure this content type is enabled and create a dummy node for each of pages you need comments on
* Set node's paths to match paths of the pages, so people cannot access them directly
* Setup Global Redirect or similar to always redirect from /node/$nid to path
* In your module load node and pass it to theme so you could render comments in tpl.php file

That would be about it, if you need more details on any of these points, I guess it'll be worth a separate question.
> 0 votes

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


# Question
Title: Login menu which I added in main menu still displaying even after logged-in
I have used login (`user/login`) as menu item in the main menu. While I am logged out, it displays login menu link properly.

When I am logged in, still displays me `login` as a menu item. But I dont want to be displayed or instead 'logout' over their.

I tried adding logout(`user/logout`) as seperate menu, but still no luck it shows as a separate menu item. Any suggestions?

Thanks in advance.

# Answer
> 4 votes
You need two have two menu items, login and logout.

For the login link the path is: user/login and for logout the path is: user/logout

Make sure you don't enter a absolute URL to the links, just user/login and user/logout.

I have just tested this by adding two menu items to the primary menu.

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


title: Order groups in grid layout

text:
# Question
Title: Order groups in grid layout
When I create a grid view, I can create groups of elements. However I have no control over the order of these groups. I can sort on the grouping variable, but that is not what I want. I want to specify the order, not sort alphabetically. The default is the order the groups were created which suggests reordering the database rows might work as a kludge. Anyone know how to do this?

# Answer
The module Draggableviews could be a solution here. It adds a table drag handler and a order field that is saved after you have rearranged the view. The same order field can then be used in another display if you want.
> 0 votes

---
Tags: views
---


# Question
Title: Use hook_hook_info() to implement hook_form_FORM_ID_alter()s in a separate file
I have a lot of mymodule\_form\_FORM\_ID\_alter()s in my module and I want to move them to a separate file (mymodule.form.inc), I found hook\_hook\_info() but I couldn't figure out how to use it for that specific case.

I tried adding:

```
$hooks['form_alter'] = array(
  'group' => 'form'
);

```

to mymodule\_hook\_info() but it didn't run the form alterers that I moved to the separate file. Any ideas how to get it to work?

# Answer
> 3 votes
It works pretty well, the only thing is that if you want to implement `hook_form_FORM_ID_alter()`, you need to add:

```
  $hooks['form_FORM_ID_alter'] = array(
    'group' => 'form'
  );
  return $hooks;

```

# Answer
> 3 votes
Don't. This is not supported by Drupal core. In fact, hook\_hook\_info is intended for modules declaring hooks, not modules implementing them.

In addition, if two modules on a site declare a group for the same hook, all uses of the hook in $module.$group.inc files will break.

Instead, create stubs that do a module\_load\_include, and then a function call.

# Answer
> 2 votes
You can also use the solution found here.

Here's an easy way to get ALL hook\_form\_FORM\_ID\_alter() implementations loaded from a .inc file, WITHOUT declaring them each separately in `hook_hook_info()`.

In MY\_MODULE.module add the following code.

```
/**
 * Implements hook_hook_info_alter().
 */
function MY_MODULE_hook_info_alter(&$hooks) {
  $hooks['form_alter']['group'] = 'form';
}

```

Then in MY\_MODULE.form.inc make sure to add the following code.

```
/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
}

// Add all MY_MODULE_form_FORM_ID_alter() functions below here.

```

With the above `MY_MODULE_form_alter()` declared in this .inc file (even if it's empty), all `MY_MODULE_form_FORM_ID_alter()` implementations declared in the same file will get loaded properly. Without this function the file will not be loaded at all.

This works because `drupal_prepare_form()` calls `hook_form_alter()` (and loads this .inc file) before calling `hook_form_FORM_ID_alter()` for each form build.

---
Tags: 7, hooks
---


# Question
Title: Status message appears multiple times on status stream
I have user relationship and Status modules installed. Each time a user posts a message on his/her profile it appears 12 times in his/her status stream while it appears once in other users stream.

Please does anyone know what can be wrong?

# Answer
> 2 votes
According to this that module uses Views to create the blocks, so it could be just a matter of "Reduce Duplicates" on the filters, or checking the "Distinct" option on the view itself.

---
Tags: users
---


title: Validation issue

text:
# Question
Title: Validation issue
The first validate function works fine, however the second doesn't. Is there something I'm missing / doing wrong. I want to get the basics of too many characters inputted or too few. Using Drupal 6.

```
function form_example_form_validate($form, &$form_state) {
  //print('<pre>'.print_r($form_state['values'],1).'</pre>');die(); //THIS LINE WILL   PRINT THE INFO ON A BLANK PAGE FOR TESTING
  if (!is_numeric($form_state['values']['mynumber'])) {
    form_set_error('mynumber',t(' Validation: You must enter a valid number for the number field'));
    return FALSE;
  }
  return TRUE;
}

$minlength = 5;
if (strlen($form_state['values']['mytextfield']) > $minlength) {
  form_set_error('mytextfield',t(' Validation: The my text field is greater than 5 characters! needs to be smaller'));
  return FALSE;
}
else {
  return TRUE;
}

```

# Answer
You should not put in return TRUE, FALSE. form\_set\_error will make the user come back to the form. The function `return` will return to the previous function which means the rest of your code in `form_example_form_validate` will not be run.

In your example after your first if statement you accidentally close the function with `return TRUE; }`. You have a `}` extra in there. The rest of the code is being run on every load right now (outside a function scope).

Here is a corrected version of you validate function.

```
function form_example_form_validate($form, &$form_state) {
  if (!is_numeric($form_state['values']['mynumber'])){
    form_set_error('mynumber', t(' Validation: You must enter a valid number for the number field.'));
  }
  $minlength = 5;
  if (strlen($form_state['values']['mytextfield']) > $minlength) {
    form_set_error('mytextfield',t(' Validation: The my text field is greater than 5 characters! needs to be smaller'));
  }
}

```
> 4 votes

---
Tags: forms
---


title: Detect 403 or 404 in page.tpl.php

text:
# Question
Title: Detect 403 or 404 in page.tpl.php
I'm looking for a **working solution**, to **detect a current 403 or 404 state** from within a template (page.tpl.php) in Drupal 7.

Unfortunately, Drupal seems to be unable to handle error pages.

# Answer
If my assumption is correct, then you are looking for the way to handle 404 and 403 pages.

If that is the case,

> Goto **configuration**-\>**Site information**, there you can specify your own page for handling **404** or **403** pages.

For that particular page, you can write tpl file like `node--type--nid.tpl.php`
> 4 votes

---
Tags: 7, theming
---


title: Several fields in view

text:
# Question
Title: Several fields in view
I've got content-type includes 'field1' and 'field2'. These fields are integer value. Thanks to Views module I created page 'Page1' with contents. In main menu I've got search whit some filters. After filling filters and entering, we can see appropriate contents in 'Page1'. I'd like to create filters or fields in search to allow user to fill in 'min' and 'max' values. After it I want to choose a content only if 'field1' and 'field2' of that content is beetwen 'min' and 'max'. How can I do it?

# Answer
> 0 votes
Make use of the contextual range filter module to create a filter range on your field 1 and field 2 and expose the filter

> is a simple plugin for Views that adds the option to contextually filter, not just by a single value, but also by range.
>
> Numeric, alphabetical (string) and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on the "created" (posted) and "updated" (last modified) node properties is also supported, provided you use the correct format as dictated by Views. So, YYYYMMDD for full dates or one of the shorter year+month, year-only, month-only, week-only and day-only formats.

**UPDATE:**

Once you have installed the modules. Go to the views display you are working on, and under the filter category, select add.

Choose the field1 you created with an integer field and click add to display

Check the box expose filter to visitors. In the operator drop down, select is between and two text box should appear(min and max). Click on apply and you should see the form on top of your display. Do the same for field 2

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


title: How to translate new-added text?

text:
# Question
Title: How to translate new-added text?
I use Contact and Locale modules. I wanted to change text included in e-mail so I went to modules/contact/contact.module and I replaced appropriate lines. Unfortunately, that text is not translate to my national language (of course is understanding). How can I add translation to new-added text?

# Answer
> 1 votes
You should never change code in Drupal core, change back to the original code in contact.module first.

When you have the Locale module enabled and have added your language (Configuration -\> Regional and language -\> Languages) you can translate strings. You will find the translate interface under Configuration -\> Regional and language -\> Translate interface.

Search for the English phrase first to find the string you want to translate (use exact spelling, it's case sensitive) and add your translation.

---
Tags: 7, emails, i18n-l10n
---


# Question
Title: Does Drupal CORE have any built-in analytics?
I've always used Google Analtyics for my sites, but for one however I've forgotten to set it up.

Does Drupal have any built-in analytics, i.e. a module that comes with Drupal core, that I can look at just to get an idea of traffic volume?

# Answer
> 7 votes
The only module that comes with Drupal core is the `statistics` module. And by default it is normally turned off. To use it, you have to enable it. So if it was not enabled initially, you will not be able to get the stats for dates prior to the date it was enabled.

---
Tags: 7
---


# Question
Title: How to access the external database in drupal?
I want to get the values of the current drupal database and the values from an external database in to a same template file. How can I achieve this

# Answer
> 6 votes
First you need to setup your external database as a second database in settings.php.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'standard_db',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external',
      'username' => 'username',
      'password' => 'password',
      'host' => 'db.external.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

Then before you do your database queries you need to set the active database. In this example, to switch to external you need to execute `db_set_active('external');`

When you want to switch back to the default database you execute `db_set_active();`

Example code to switch to and query the external database:

```
db_set_active('external');
$query = db_select("your_table_name", "t");
$query->addField("t", "field_name");
$result = $query->execute();
while ($row = $result->fetchAssoc()) {
  drupal_set_message($row['field_name']);
}

db_set_active();

```

---
Tags: 7, theming, database
---


# Question
Title: How and where is the $variables variable used in templates etc. generated in Drupal?
How and where is the `$variables` variables that is used in templates and theme functions generated in Drupal?

Is there documentation anywhere that defines `$variables`?

# Answer
> 1 votes
The `$variables` associated array that are passed into functions such as `MYTHEME_item_list($variables)` are initialized by the caller of that function.

# Answer
> -1 votes
You can use associated array $variables that are taken from template.php or yourmodule.module so that, you can pass that variables to page of your theme.

```
 $imageOutputinner = “You can have  images variable here”;
$vars['innerImages'] = $imageOutputinner;
//you can print this variables to page of  theme as
print_r($innerImages);

```

---
Tags: theming
---


# Question
Title: Node comments don't show up in view when they should
I'm creating a view that lists full view of nodes.

These nodes have comments and the comments are showing up as they should on their node page, but not when they're listed in the view.

"Display Comments" option is checked in Views in the row style settings.

Here is the exported view, it may be helpful. There is a second Block display where I list Full nodes, showing comments is checked.

```
$view = new view();
$view->name = 'flickr_images';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Flickr Images';
$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'] = 'See What Others Are Sharing';
$handler->display->display_options['use_more_always'] = FALSE;
$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'] = 'none';
$handler->display->display_options['style_plugin'] = 'grid';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_image']['element_type'] = '0';
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_image']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'flickr_thumb',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image']['field_api_classes'] = TRUE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<a href="#" class="photo-container" data-reveal-id="<?php print $data->_field_data[\'nid\'][\'entity\']->field_flickr_id[\'und\'][0][\'safe_value\']; ?>">
  <div>
    <div class="photo-tweet photo-container"><?php print $data->field_field_image[0][\'rendered\']; ?></div>
  </div>
</a>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* 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(
  'flickr_image' => 'flickr_image',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['view_mode'] = 'full';
$handler->display->display_options['row_options']['links'] = FALSE;
$handler->display->display_options['row_options']['comments'] = TRUE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$translatables['flickr_images'] = array(
  t('Master'),
  t('See What Others Are Sharing'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Block'),
);

```

Do you know what could be the problem?

# Answer
Create node display with Display Suite module.

And then set the display mode to Display Suite from Content
> 2 votes

# Answer
try this:

Usually the comment are displayed in the "Links" display. Go to your content type and in Manage display tab, make sure that you have the "Links" field enabled. If so, you sould have something like this in your views (after saving):

> Read more | "TITLE OF THE NODE" | 2 comments("x comments") | Add new comment
> 0 votes

# Answer
Node comments will not show up as you are displaying fields instead of Nodes (named Content in Views). The setting display comments is in effect when you show Content in Views.

If you switch to show: Content instead of Fields you get the line saying something like "1 comment Add new comment".

If you still want to use fields to display your data I suggest you add the fields **Content: Add comment link** and **Content: Comment count** to create your own comment information to the node.
> 0 votes

---
Tags: 7, views, comments
---


# Question
Title: How do you customise the Group subscription format
I have assigned user profiles the field Group Type and set it to default as "is group type" so that users can subscribe to each others profiles. This is all fine but i would like to customise the link that allows the users to subscribe, i.e. the display format 'Group subscription'. It currently says: "Subscribe to group", "Unsubscribe from group" or "You are the group manager". Is it possible to customise this text?

# Answer
> 2 votes
You can make use of the string override module

> Provides a quick and easy way to replace any text on the site.

---
Tags: organic-groups
---


# Question
Title: What is the difference between a view mode and a style plugin?
It is possible that you can define the difference between a view mode and a style plugin. As far as I understand a view mode defines what fields are outputted and a style plugin decides how to render those fields. However, is a style plugin always connected with a panel?

# Answer
> 4 votes
A `view mode` is an entity specific concept. It defines how to render a, which could for example determine which fields are displayed and how, but nothing prevents a view mode of a "gallery image" to pull in and render a `View` that shows the other images in the same gallery for example.

A `style plugin`, as a Panels specific concept, does a similar thing to view modes, but on a "Pane" level in Panels.

A style plugin mostly makes sense on generic styles that one wants to apply across many different types of panes, where a view mode makes sense for things that apply on a per entity or bundle basis.

In my own experience, I've mostly implemented designs that had a consistent look across panes, making it easier to make global style changes to the pane template, but styles can allow a site administrator to mix and match styles across panes at will.

# Answer
> 4 votes
I'll give this a shot.

A view mode is a concept that exists for entities. A node has for example the view modes **Full content**, **Teaser** and **RSS**. And as you say different view modes can have different settings. An image might be just an URL in the RSS view mode and a large rendered image in the Full content view mode. It is also possible to have different order and visibility settings for each field in each view mode.

A Panel region or a Panel pane has something called a Style setting, this is also a Style plugin. There are styles such as **No style**, **Rounded corners** etc. Changing style will change the markup that surrounds your region or pane. In most cases the Style setting for the pane is something you do not change.

But to answer your question, yes a region or a pane always has a set "Style" and that Style is by default set to use the style plugin "No style".

A **style plugin** is a concept that also exists in Views. Under the setting Format in Views you have the option to choose between Style plugins such as **Grid**, **HTML list**, **Jump menu**, **Table** and **Unformatted list**. When you choose a different style plugin the markup surrounding and in between each row changes.

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


# Question
Title: how to programmatically check if a context is active
I am reading through the API of the drupal 7 context module, and searching for examples, but I can't find a working example of how to programmatically test if a context is active for the current page.

I tried to call the context\_isset() function defined in context.module, but what are the namespace and the attribute values? I only know about the context name and it's tag.

# Answer
What can be done is to use the context\_active\_contexts() function.

Sample code, to see if the is\_iframe context is active for the current page:

```
$contexts = context_active_contexts();
if (array_key_exists('is_iframe', $contexts)) :
    watchdog('te','context is_iframe is set');
endif;

```
> 12 votes

---
Tags: 7
---