# Question
Title: How to disallow node authors to change node content if comments were submitted for that node?
On my site we have enquiries (nodes) and price offers (comments). So if there's at least one price offered (a comment submitted) the enquiry details (node) shouldn't be changed. Is there any way to do that?

# Answer
If coding this is an option, you should look at `hook_node_prepare`. As mentioned there on the first line:

> Act on a node object about to be shown on the add/edit form.

A code snippet idea that could do this for you:

```
function SOME_MODULE_node_prepare($node) {
  if (isset($node->nid) && $node->type == 'YOUR_CONTENT_TYPE' && $node->comment_count> 0) {
    drupal_set_message('You cannot alter this node anymore', 'warning');
    drupal_goto('node/' . $node->nid);
  }
}

```

Good luck!
> 3 votes

# Answer
If you don't want to write custom code, you can use the Rules and Flag module for this, as described below.

# Step 1: flag nodes with comments

Use the Flag module to create a (global) flag with a label of something like "Has price offers".

# Step 2: register comment submission

Use Rules to create a custom rule with Rules Event "*After saving a new comment.*".

This rule should perform a Rules Action "Flag node" (using the flag created in step 1).

# Step 3: disallow edits for nodes that have price offers

Use Rules to create a custom rule to disallowing 'edit' for nodes that have price offers (= were flagged). This rule is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work this case also:

* The paths containing `node` should be extended by adding `/edit` at the end (I'm assuming that's how the URL for your edit link looks like).
* Add a Rules Condition to check if the node was flagged (with the flag from step 1).
* Change the "Message" in the Rules Action to something to indicate that the edit is not allowed because it already has price offers.
* Modify the Rules Action to fit your own requirements, e.g. to issue a redirect to some 'help page' with more details about this.

If you've problems adding the appropriate Rules Conditions (to find the relevant data selector), it might be because of what's mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

Remark: this will block edits from anybody. Should you only want to block that for the node author, then (in step 3) add an extra Rules Condition to verify if the currently logged on user matches the node author. Variation of this could be that you want to allow such edits anyhow for some selected roles (by adding an appropriate Rules Condition to verify the role of the current user).
> 1 votes

# Answer
I'd propose to not even show the edit link anymore if the user is not allowed to edit it. It is bad user experience to have a user click a button and then tell him he is not supposed to be there.

Drupal has an excellent content control system which you can use. It does involve some coding (\< 20 lines), but I guess the result will be better than the other answers here.

You will have to create a custom module (a small one). Read that tutorial for information on creating a `mymodule.info` file.

Also create a `mymodule.module` file and implement `hook_node_access`:

```
function mymodule_node_access($node, $op, $account) {
  // If this user is the node author and he wants to edit a node?
  if ($account->uid == $node->uid && $op == 'update') {
    // Get comment count
    $comment_count = db_query('SELECT COUNT(cid) AS count FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
    // If there is 1 comment or more
    if ($comment_count > 0) {
      // Deny the user access (and hide the edit link).
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}

```

That is all you need to put in this file. It allows admins and other privileged user to still edit the node (remove the `$account->uid == $node->uid &&` part if you want to block those as well).

So you need only two files and a folder and this is in my opinion more user friendly than giving the user the impression he can edit something and then tell him he cannot.

An optional addition can be to show a message that the user can no longer edit the node during the viewing. Add this to the module file:

```
function mymodule_node_view($node, $view_mode, $langcode) {
  // Fetch the current user.
  global $user;

  // Compare
  if ($user->uid == $node->uid) {
    // Get comment count
    $comment_count = db_query('SELECT COUNT(cid) AS count FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
    // If there is 1 comment or more
    if ($comment_count > 0) {
      // Show the message
      drupal_set_message(t('This enquiry has received at least one price offer an can no longer be edited.'), 'warning');
    }
  }
}

```
> 0 votes

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


title: Why I cannot get translated entities

text:
# Question
Title: Why I cannot get translated entities
I wrote service to get all necessary data for my page. Now I wanted to load them with translations. But whey I try, I got error:

> InvalidArgumentException: Invalid translation language (id of language here) specified.

When I open page in default language it works fine. Does it mean that I need to translate all of the things in order to make it work?

My service:

```
namespace service;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use entity\Entity;

class PostTypeService
{
    public static function getEntititiesByPostType($postType, $entities = array(), $nid = NULL)
    {

        if ($nid != NULL) {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->condition('nid', $nid)
                ->execute();
        } else {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->execute();

        }

        $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
        $returnValues = array();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        foreach ($nodes as $index => $node) {
            foreach ($entities as $entity) {
                $type = $entity->type;
                $entity_name = $entity->entity;
                if ($type == 'image') {
                    $returnValues[$postType][$index][$entity->entity] = file_create_url($node->$entity_name->entity->getFileUri());
                } else if ($type == 'url') {
                    $returnValues[$postType][$index][$entity->entity . '_uri'] = $node->$entity_name->uri;
                    $returnValues[$postType][$index][$entity->entity . '_title'] = $node->$entity_name->title;
                } else if ($type == 'list') {
                    foreach ($node->$entity_name as $list_item) {
                        $returnValues[$postType][$index][$entity->entity][] = $list_item->value;
                    }
                } else {
                    $translation = $node->getTranslation($language);
                    $returnValues[$postType][$index][$entity->entity] = $translation->$entity_name->$type;
                }
            }
            $returnValues[$postType][$index]['node_id'] = $index;
            $options = array('absolute' => TRUE);
            $url = Url::fromRoute('entity.node.canonical', ['node' => $index], $options)->toString();
            $returnValues[$postType][$index]['node_url'] = $url;
            $returnValues[$postType][$index]['lang'] = $language;
        }
        return $returnValues;
    }

```

# Answer
This solves the problem:

```

namespace service;

use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use entity\Entity;

class PostTypeService
{
    public static function getEntititiesByPostType($postType, $entities = array(), $nid = NULL)
    {

        if ($nid != NULL) {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->condition('nid', $nid)
                ->execute();
        } else {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->execute();

        }

        $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $defaultLang = \Drupal::languageManager()->getDefaultLanguage()->getId();

        $returnValues = array();
        foreach ($nodes as $index => $node) {

            if (!array_key_exists($language, $node->getTranslationLanguages())) {
                $translation = $node->getTranslation($defaultLang);
            } else {
                $translation = $node->getTranslation($language);
            }

            foreach ($entities as $entity) {
                $type = $entity->type;
                $entity_name = $entity->entity;
                if ($type == 'image') {
                    $returnValues[$postType][$index][$entity->entity] = file_create_url($translation->$entity_name->entity->getFileUri());
                } else if ($type == 'url') {
                    $returnValues[$postType][$index][$entity->entity . '_uri'] = $translation->$entity_name->uri;
                    $returnValues[$postType][$index][$entity->entity . '_title'] = $translation->$entity_name->title;
                } else if ($type == 'list') {
                    foreach ($translation->$entity_name as $list_item) {
                        $returnValues[$postType][$index][$entity->entity][] = $list_item->value;
                    }
                } else {
                    $returnValues[$postType][$index][$entity->entity] = $translation->$entity_name->$type;
                }
            }
            $returnValues[$postType][$index]['node_id'] = $index;
            $options = array('absolute' => TRUE);
            $url = Url::fromRoute('entity.node.canonical', ['node' => $index], $options)->toString();
            $returnValues[$postType][$index]['node_url'] = $url;
            $returnValues[$postType][$index]['lang'] = $language;
        }
        return $returnValues;
    }
}

```
> -1 votes

---
Tags: 8, entities, i18n-l10n
---


# Question
Title: Send email to users, except author comments
**Hello!**

---

I have node with field **\[field\_users\]** *(entity reference)*

I create rule **\[after saving new comment\]** Actions: Loop for field: \[comment:node:field-users\] inside loop i create var **\[users:mail\]** And add action for sending emails...

---

**But problem is:**

if comment-author in list of field\_users, emails sent also to author comment

**Q:** How to remove comment author from loop?

---

## Thanks for any help!

# Answer
You need a condition to check if the author of the node and the current user in your loop are the same; if not, then you can send the email.

To do that, you need to do the following:

1. Create a Rules component of type "Rule", this will give you an action option inside your loop.
    * URL: /admin/config/workflow/rules/components/add
    * Component Plugin: "Rule"
2. Configure your component to expect two parameters; the node's author and the comment's author. Both should be of Data type "Entity \> User".
3. The component must have a condition to trigger only if the comment author NOT EQUALS the node author
4. The component's actions can be the same as the ones you have already created.
5. After you save your component, go inside the loop of your original rule and add an action; you should be able to choose the component you created earlier.

Good luck!
> 1 votes

# Answer
You can install Rules Conditional module, which will give you an option to run conditional logic inside a Rules Action, in your case related to the loop that you created.

So, you'll do a check in the loop as follows:

```
IF comment:author:mail NOT EQUAL users:mail THEN send email

```
> 2 votes

---
Tags: 7, users, entities, rules, emails
---


title: Using Guzzle with SELinux setenforce 1

text:
# Question
Title: Using Guzzle with SELinux setenforce 1
is there anyway to run drupal 8 with guzzle to access remote server rest server without turning off selinux.

for example in httpd, i can do:

> setsebool -P httpd\_can\_sendmail on

to be able to make apache send email without turning off selinux.

Thank you,

# Answer
> 0 votes
I think it is:

`setsebool -P httpd_can_network_connect on`

---
Tags: 8
---


# Question
Title: menu_tree_output() not returning full menu array
I'm building a function that takes a drupal rendered menu and removes the classes from it so that I can pass it to a jQuery function that'll build a menu from it.

The code i'm using for that is:-

```
<?php
     $tree = menu_tree_all_data("devel-frus");
     $menu = drupal_render(menu_tree_output($tree));
     $nocss = preg_replace('/class=".*?"/', '', $menu);
     echo($nocss);
?>

```

However `menu_tree_output()` seems to be only returning the first level of a six level menu when it should be returning the complete menu.

I've tried `dsm()`'ing `$tree` to see if all of the menu items are being returned by `menu_tree_all_data()` and that's fine, however when I `dsm()` the output of the `menu_tree_output()` function only the root and first level are returned in the array.

Am I doing something really obviously wrong here?

# Answer
> 1 votes
From what I understand about `menu_tree_all_data()` you need to supply it a link and depth to give it context (where in the menu tree am I at & how far do I go?). Also `drupal_render()` expects an argument passed by reference, so there will problems passing the output of function.

```
// Default to root link w/ a depth 5.
$link = menu_get_item();
$tree = menu_tree_all_data("devel-frus", $link, 5);
$tree_output = menu_tree_output($tree);

// Supply a variable for drupal_render to reference.
$menu = drupal_render($tree_output);

$nocss = preg_replace('/class=".*?"/', '', $menu);
echo($nocss);

```

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


title: Help with contextual filters needed

text:
# Question
Title: Help with contextual filters needed
I'm trying to understand how arguments get passed into a view.

I have a view which **was** working using
content: type (=PersonStory) which is a join table
connecting via Views Relationships to
content: type (=Person)
content: type (=Story)

Here is the old view.

I have installed Panelizer and have a default page for content: type (=Person). When an author's page is loaded, I want to load a view of stories which they have written.

As you can see from the preview, the NID finds the correct author's name, but none of that author's stories are showing. The NID comes from content: type (=Person) and not from the base table in the view content: type (=PersonStory).

Current view:

# Answer
The contextual filter needed to be linked to Content entity referenced from field\_personstory\_person\_id) Content: Nid and then it worked.

This does not help me understand how to pass the argument from the panel, though ;)
> 0 votes

---
Tags: 7, views
---


# Question
Title: Show required user profile fields after the account is verified during first login
The user can register with their username, email and password. Once the account verifies their account i need to show custom required fields like age, sex , profession to be filled.

Complete profile comes in handy to force filling of required fields.

But, if i mark the fields as required they show on the registration form. Is there a way to hide the required fields of the user profile in the registration form???

I tried Field Permission and removed permission for anonymous users to see the fields. Though it doesn't show the fields, once the form is submitted it returns the hidden fields as required.

# Answer
1. Use this module: https://www.drupal.org/project/required\_by\_role
2. In rules you can add rule "**After login user**" -\> Do: redirect to "**profile edit**"

Or add rule if user **view content** -\> **redirect** to "profile edit" and show status message "**required fields need to be filled**"
> 2 votes

---
Tags: 7, users
---


title: Collapsible Search Bar

text:
# Question
Title: Collapsible Search Bar
I have an exposed form (from a view) in a block. I'd like to make this block collapsible so that a user is presented with a search box and one other field and when a user types in the search box the form expands out to include the remainder of the form fields. I know I can use ctools\_collapsible to make content collapsible but how do I extend this to any div/region?

# Answer
> 1 votes
If I understood you correctly: You have exposed filter in block, which have for example two fields, search by title and checkboxes.

So you can use: https://www.drupal.org/project/better\_exposed\_filters

1. After installing module: change **Exposed form style** from **Basic** to **Better Exposed Filters**
2. Click to **BEF Settings**
3. Check **Enable secondary exposed form options**
4. Expand yours fields what you need to hide before type in search box and check this: **This is a secondary option**
5. Use jQuery:

```
$("input.yourSearchBox").keyup(function(){

    $(".views-widget-filter-secondary a").trigger('click');

});

```

---
Tags: chaos-tool-suite
---


title: How to get the list of field-types?

text:
# Question
Title: How to get the list of field-types?
I'm porting a module from Drupal 7 to Drupal 8. In this module's configuration settings I need to get the list of the currently existing field-types.

In Drupal 7, this was achieved using the `field_info_field_types()` function.

In Drupal 8 (8.0.0-rc3), I get an error "function does not exist", despite the information stated by a Drupal API Reference Help page, clearly out of date.

Then investigating I found a DrupalContrib page, where the function is declared deprecated, and proposing to now use `Drupal::service('plugin.manager.entity.field.field_type')->getDefinitions()`.

But using it fires another error "Unknown service plugin.manager.entity.field.field\_type", fortunately associated to the suggestion "Do you mean plugin.manager.field.field\_type?"

So I tried using `Drupal::service('plugin.manager.field.field_type')->getDefinitions()` and wow: I got the expected array of field-types.

But each array member (one field-type) is now an object (instead of a child array), and the data I'm looking for is nested within protected properties, so I can't access them.

At this stage, I'm stuck. I considered it might exist some class I could expand to navigate through these data, but with no luck: I notably couldn't even figure out which is the component in Drupal 8 where field-types definitions is centralized.

# Answer
The first level is an array. The keys are the plugin id's. You can list them:

```
$defs = Drupal::service('plugin.manager.field.field_type')->getDefinitions();
foreach ( $defs as $key => $value ) {
   echo $key, "\n";
}

```

This is the result:

```
comment
datetime
file
image
link
list_string
list_float
list_integer
path
text_with_summary
text
text_long
email
boolean
created
changed
timestamp
string_long
language
decimal
uri
float
password
string
integer
entity_reference
uuid
map
taxonomy_term_reference

```

You can pick one and dump the plugin definition.

```
var_dump($defs['comment']);

```

If you are interested in a special object, you can digg deeper with the help of api.drupal.org. But it will be easier, if you search for the plugin in the core directory.

To access an object, locate it in the var\_dump and use a method:

```
$defs['comment']['description']->render();

```

In this case it is the object TranslatableMarkup, which has the method render to access the translated string.
> 17 votes

# Answer
Every string that is passed through t() is an object now. You can access them as strings, in fact, you should do so.

There are only very few exceptions where you can't just use such an object as-is, for example array keys, for those, you need to cast them to a string. Anything else should just work.

PS: The official API documentation is http://api.drupal.org/api/drupal/8. Use that for core.

Another good resource are change records: https://www.drupal.org/list-changes/published?keywords\_description=field\_info\_field\_types&to\_branch=&version=&created\_op=%3E%3D&created%5Bvalue%5D=&created%5Bmin%5D=&created%5Bmax%5D=

Edit: Responding to your comment, I don't quite understand what you mean. All the information you need is right there, just use it.

```
$definitions = Drupal::service('plugin.manager.field.field_type')->getDefinitions();
foreach ( $definitions as $field_type => $definition) {
  print $definition['label'];
  print $definition['description'];
  print $definition['provider'];
}

```

Again, just ignore that label/description are objects. They have \__toString() methods that are automatically called when you print/use them.
> 4 votes

# Answer
Google seems to find this Question when searching for these

If you are using Drupal Console you can also use:

```
drupal plugin:debug field.field_type

```

There is also this on Drupal.org which can also help:

Defining and using Content Entity Field definitions

Its not easy finding examples of useable though
> 3 votes

# Answer
Updated version for @Berdir answer. Use in shell.

```
$definitions = Drupal::service('plugin.manager.field.field_type')->getDefinitions();
foreach ( $definitions as $field_type => $definition) {
  print 'Label: '. $definition['label']. PHP_EOL;
  print 'Machine name: '. $field_type. PHP_EOL;
  print 'Descritpion: '. $definition['description']. PHP_EOL;
  print 'Provider: '. $definition['provider']. PHP_EOL . ' ---' . PHP_EOL;
}

```

Output here: https://gist.github.com/sobi3ch/70635cc62defff606242
> 1 votes

---
Tags: entities, 8
---


title: Multiple Field Values on Separate Page

text:
# Question
Title: Multiple Field Values on Separate Page
I have multiple values for a field in a node, and am displaying only the top 5 using CSS, however, I would like to display the full list of values on a separate page with a, 'View More' link to that page.

My initial reaction would be to create a views page, but how would I associate that view page with a specific node, and then how would I link to that views page from the original node?

The example:

* The main node would be a content type for, 'Author'
* Another content type that get's referenced from Author are, 'Publication'
* The Author's node will display the top 5 Publications and then have a View More link to the full list of publication.

Is there any better way to accomplish this? All thoughts will be much appreciated.

# Answer
Using Views would be the most common way to do this. I will show you a Display Suite method though.

Install these modules:

Display Suite (or any model that can give you extra view modes such as Entity view modes

> 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 (D7 only) is available for even more drag and drop fun!

View Mode Page

> Create separate pages for different view modes for a given content type.
>
> On the manage display page for a given content type, you can assign patterns for view modes so that they will become a page at the given path. For instance, if you want to show the teaser at a specific URL, you could do node/%/teaser. If you also use Display Suite or other modules that allow you to create new view modes, you can use these modes to display one or more fields from a node at a separate URL.

Field multiple limit

> This is a simple module that provides settings to limit the number of values to display on fields with multiple values.

Token

> Provides additional tokens not supported by core (most notably fields), as well as a UI for browsing tokens.

**Default View Mode:**

On your content type's default view mode activate One Column Display Suite layout and click on the gear next to your multi value field and set it to show the first 5 of the multi value field. Use Display Suite to create a `Code Field` on entities node, with Field code:

`<a href="[current-page:url]/more">Show all</a>`.

Tick Token. Back on the manage display for the default view mode you will now see that field: Show all. Drag it to where you want it displayed

**Show all View Mode:**

Use Display Suite to create an additional View mode. Go to Manage display for the new View mode and set the 'View mode pages' URL pattern to `node/%/all`. Make sure you set the multi value field to show all values.
> 0 votes

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


title: Display node field into cart

text:
# Question
Title: Display node field into cart
how can I display node info(not only title but all fields) into cart? Example: My site has a lot of stores and each store can buy some books. How can I display stores info into user cart? Thanks in advice

# Answer
The Drupal cart is a views display of commerce line items. Depending on your setup you'll have to alter the existing cart view and add one or two views relationships (in the advanced section).

* The first relationship is from commerce line-item to commerce product. It is called something like `Commerce line-item: Product`. This exposes all product properties to the view.
* If you use a product display with custom properties, you can also add `Commerce Product: Referencing Node` (depending on the fields you need this one is optional).

Now you have all field of your product (and product display) available to views and you can add them in the **Fields** section.
> 1 votes

---
Tags: commerce
---


# Question
Title: How can I Eliminate render-blocking JavaScript and CSS in above-the-fold content?
I am using drupal 7 and Page speed in 82 for desktop on Google Page Insights. I am having some issues regarding eliminating render blocking js and css. How can I do this for aggregated js/css ? I know we cannot enable Leverage browser caching for external js. I have used following modules: 1. Minify 2. Advanced CSS / JS Aggregation.

Please see the attached screenshot of Google Page Insights.

# Answer
> 1 votes
They are not render blocking. That is the main Drupal's js and css aggregated. Because they have most of the site's js and css in them, they end up quite large, and that makes most optimizers detect them as problematic.

There is a high probability that you don't want to do anything about this.

# Answer
> 1 votes
Use Frontend sub-module and move JS to footer as a start.

# Answer
> 1 votes
You can also have a look at the Advanced CSS/JS Aggregation module. It allows you change the way the CSS and JS are compressed, bundled and optionally move (parts of) them to the footer.

It is quite an extensive module with lots of options and there are quite some tutorials out there, you can google for them. I once used a quite extensive one that I cannot find at the moment. So apologies for that.

Keep in mind that once you move things to the footer, not all Javascript might work anymore so you'll have to play with the settings a bit. And also if you move CSS to the footer, the browser will display an unstyled page and update it once the CSS is loaded. Depending on the size of your page and the CSS file, and your server configuration this can take noticeably long (and I find it ugly). So also do not forget that pagespeed is a tool and in no way science. Do not forget about the end user ;)

---
Tags: 7
---


# Question
Title: How to properly skip apostrophe in db_select?
In my mysql database I have texts full of apostropes which are used as stress marks. I need to implement keyword search ignoring these marks.

I tested it first by using direct sql in PhpMyAdmin:

```
SELECT * FROM `drupal_corpus_text` WHERE replace(text, "'", "") LIKE "%sinka%"

```

It perfectly finds the record containing `sin'ka`.

But I cannot figure how to do it using Drupal features.

Here is what I try to do:

```
  $apostrophe = "'";
  $query = db_select('corpus_text', 'n')
    ->fields('n', array('text_id', 'speaker', 'text'))
    ->condition('n.text', '%' . db_like($key_search) . '%', 'LIKE')
    ->orderBy('speaker', 'ASC');
  $query->addExpression('REPLACE(n.text, "'.$apostrophe.'", "")');
  $query->execute();

```

And here is the error I get:

```
PDOException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column ''' in 'field list':
SELECT n.text_id AS text_id, n.speaker AS speaker, n.text AS text,
REPLACE(n.text, "'", "") AS expression FROM {corpus_text} n
WHERE (n.text LIKE :db_condition_placeholder_0 ESCAPE '\\') ORDER BY speaker ASC

```

I cannot figure out how I must properly use all the quotes and the apostrophe mark to make it work.

The symbol used in those texts is U+0027.

# Answer
> 3 votes
There are a couple of points here:

1. Your Drupal query is wrong insofar as it wouldn't produce your example SQL. You don't need to add an expression, rather a where clause
2. Quotes are fun in MySQL (see SQL modes). Your default mode would appear to be `ANSI_QUOTES`, which means:

> Treat “"” as an identifier quote character (like the “\`” quote character) and not as a string quote character.

Which explains why MySQL is trying to interpret the single quote as a column name. PMA probably sets a different mode per-query, so the same SQL works in that environment.

Taking those into account, this is more like what you're hoping for:

```
$query = db_select('corpus_text', 'n')
  ->fields('n', array('text_id', 'speaker', 'text'))
  ->where("REPLACE(n.text, '''', '') LIKE :search", array(':search' => '%' . db_like($key_search) . '%'))
  ->orderBy('speaker', 'ASC');

```

Which produces:

```
SELECT  n.text_id AS text_id, n.speaker AS speaker, n.text AS text
FROM
{corpus_text} n
WHERE  (REPLACE(n.text, '''', '') LIKE :search)
ORDER BY speaker ASC

```

Notice that the single quote is escaped with two single quotes, MySQL's way of handling this situation.

# Answer
> 0 votes
The Drupal database layer has support for query arguments. A good example of this is the db\_query syntax:

```
$query = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid))

```

As you can see there are placeholders in the query, which are appended in the end. These placeholders are recognizable by the colon (`:`) and are sanitized in the end by Drupal to prevent SQL injections and syntax errors.

The SelectQuery::addExpression function also has support for these arguments `SelectQuery::addExpression($expression, $alias = NULL, $arguments = array())`. So you might want to try something like this:

```
$apostrophe = "'";
$query = db_select('corpus_text', 'n')
  ->fields('n', array('text_id', 'speaker', 'text'))
  ->condition('n.text', '%' . db_like($key_search) . '%', 'LIKE')
  ->orderBy('speaker', 'ASC');
$query->addExpression('REPLACE(n.text, ":apostrophe", "")', NULL, array(':apostrophe' => $apostrophe));
$query->execute();

```

If that fails, you can safely rewrite your query to the slightly faster db\_query method. This is perfectly safe for SELECT queries (and for select queries only!) and faster because it involves less abstraction, so less processing to transform into a final query. It is however less flexible in cases where you want to add conditions based on variable values. So you cannot do this:

```
$query = db_select(...);
if ($foo) {
  $query->condition(...);
}

```

Just remember to use the placeholders for all user entered input. So I guess it will be something like this. Not sure if the apostrophe needs escaping and you can always place it in a placeholder.

```
$query = db_query('SELECT * FROM {drupal_corpus_text} WHERE REPLACE(text, "'", "") LIKE "%:search%"', array(':search' => $key_search));

```

---
Tags: database
---


# Question
Title: Drupal Commerce - Product Variation Type missing Nodes
I've installed kickstart 2.0 with the demo data. I tried creating my own product variation types and product displays. I can't see to get my products to display in the same way to the commerce built-in demo products.

I think this is my custom product variation type **seems to be missing the correct "Node: Product list" and "Node: Full Content" options** (Product Variation Type -\> Manage Display section)

Please see attachments. "Tops" is the built in product variation type delivered with CK 2.0. "Photos" is a product variation type i created.

Drupal commerce is my first exposure to drupal hence my knowledge of nodes isn't sound, please let me know what I'm missing?

# Answer
You can add and remove Displays to your content types by expanding the 'Custom Display Settings' section right under all those fields in the 'Manage display' tab. It's hard to notice because it's collapsed by default.

You'll probably see a different list than me, because it also depends on the modules you have enabled on your site:

However, my feeling is that - though I haven't used kickstart and its examples - the differentiation in the look of your content type and theirs also has a lot to do with theming. That's a big topic, but I'd check to see whether there are templates and css styles that apply to those sample content types that you can copy over to yours...
> 0 votes

# Answer
Getting the new "display modes" to show is the first step to recreating the look / feel of the Kickstart views.

From there, I recommend opening the Commerce Kickstart views and replicating the setup. For instance, when you first activate the "Product List" display, many more fields are visible. You can edit that in the "Manage Display" tab.

Each time you create a new Product type, you will need to repeat this process. It's a bit of a chore, but requires the setup once :)
> 0 votes

---
Tags: commerce
---


# Question
Title: How to put pager between multiple views?
I am finding the way to combine more than one views through pager, I would like to connect them using the pager. And I would like to provide the pager like what is on drupal site(documentation part) as shown in following image. So they show previous and next node. I am searching but did not find the way to combine multiple views. The views default pager is for its own content and can not apply to the direct to other views. Thanks

# Answer
IMHO, you might have to rethink your content architecture. The type of pager your are looking for ideally applies to *content* and not *views*.
drupal.org uses the book navigation that comes from the `book` module in Drupal 7 core.

If you do not want to use the book module, you could also go with the Nodequeue module, which provides a similar pager (except the middle link `Up`).

If you still really need to add such pager to connect the views, you can do it by adding the markup to the view footer to link to other views (and theme it as per the design). Or to make it dynamic, implement `hook_views_pre_view` (or any similar hook) and change the link from from the footer. **Note:** This however, is very hard to maintain and not recommended.
> 1 votes

---
Tags: 7, views, paging
---


# Question
Title: In a view of products, add the word "Added" to all products already added to the cart
I have a view that lists all my products, I want to display the word "Added" below every product that has already been added to the shopping cart.

How can I accomplish this?

# Answer
> 1 votes
Sorry for the late answer, I meant to answer this, but for some reason got lost and today this Q just randomly popped into my mind.

If you think creatively, you can accomplish this using CSS like this:

1) Create an **attachment** clone of your cart, by clicking the +Add button and selecting attachment. Remove all fields and add a unique field to it, such as SKU. (Make sure you use **For:** this attachment override, so you don't affect your actual cart view).

2) Rewrite your SKU field to be like this

```
<style>
.[field_sku]:before { content: "Added"; position: absolute; }
</style>

```

3) In in the header section of your products view, add the attachment clone of your cart.

4) In your Products view, wrap each product inside a div class that has the SKU#

```
<div class="[field_sku]">...</div>

```

You could try doing the re-writes through the Views UI, else you can use a template file (hopefully you know how to use template files in Views).

---
Tags: 7, views, commerce
---


# Question
Title: How do I filter exposed taxonomy terms with other exposed taxonomy terms?
OK, so I have 3 different Taxonomy Vocabularies filled like this: One for Carriers \[AT&T, T-Mobile\] One for Manufacturers \[Samsung, iPhone, etc\] And one for the Models \[Galaxy S3, S4, etc\]

All of these are set as an Exposed Filter for a custom view, But what I want is for the last Exposed Filter, "Models" to be Filtered by whatever Selection is made in "Manufacturers"

So if I Select iPhone, I only see Models for iPhones.

I've searched everywhere without the solution I need. And if it is what I needed, I wasn't able to set it up, or directions weren't clear enough.

I have Term References Linked from the Models to the Manufacturers, but idk how to Filter the Exposed Filter to only show Model choices for the selected manufacturer.

How do I filter exposed taxonomy terms with other exposed taxonomy terms? Any help is appreciated!

I'm Working with Drupal 7.

# Answer
Use the Search API. Totally awesome. It will provide you with the Facets you need. Don't be intimidated. The instructions below are great.

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/
> 0 votes

# Answer
Simple Hierarchical Select did the trick, I just need to Combine the Manufacturers & Models list, and make the Models Childs to the Manufacturers, so when I select Samsung, it poofs another dropdown that lets me Select the Samsung children I set up in the Taxonomy Terms! I set Depth to -1

I tried to get it to work earlier to no avail, but it works now! Found out it was Conflicting with another Module.
> 0 votes

# Answer
Another option would be this module : Views Selective Filters

A new kind of filter is available in the Views listing (named "your field (selective filter)". You may add three selective filters, each related to a vocabulary (even different ones). When you select a value in the first filter, the two others will only suggest possible values for contents with the first tag.
> 0 votes

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


# Question
Title: mapping of menu Name "Main Menu" with variable name: primary_nav
I am new to Drupal and would like to know the details of constant/global variable: $primary\_nav Observed this variable is pulling list of links from a Menu with Title : "Main Menu" . I try to see the mapping of these in UI and DB, but could not find. Can you please help me to find out the mapping of this menu Name ( "Main Menu" ) with variable name : primary\_nav and where is it defined.

# Answer
> 0 votes
`$primary_nav` is template variable in Garland's **template.php** file. It's a variable specific to this Drupal core theme. The HTML markup is rendered by the `theme_links()`.

The main argument to the theme function is page template variable `$main_menu`, which is defined in **theme.inc**. This variable is set by `menu_main_menu()`, which will retrieve a menu id setting then use that to look up data in the `menu_links` table (noted by `menu_name` column).

---
Tags: theming, navigation
---


title: Image Upload in a Custom Module

text:
# Question
Title: Image Upload in a Custom Module
I'm writing a custom module, and I need it to upload an image. I'm having trouble finding good documentation on this, but I think I'm close.

What am I missing? $file returns false in the form submission.

```
function mymodule_custom_content_block_form($form_state){
    $form = array();
    $form['custom_content_block_text'] = array(
        '#type' => 'textarea',
        '#title' => t('Block text'),
        '#default_value' => variable_get('mymodule_custom_content_block_text'),
        '#required' => true,
    );
    $form['custom_content_block_image'] = array(
        '#type' => 'file',
        '#name' => 'custom_content_block_image',
        '#title' => t('Block image'),
        '#size' => 40,
        '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Update'),
    );
    return $form;
}

function mymodule_custom_content_block_form_submit($form, &$form_state){
    if(isset($form_state['values']['custom_content_block_image'])){
        $validators = array('file_validate_extensions' => array('jpg jpeg'));
        $file = file_save_upload('custom_content_block_image', $validators, 'public://');
        if($file == false){
            drupal_set_message(t("Error saving image."), $type = "error", $repeat = false);
        }
        else{
            $file->status = FILE_STATUS_PERMANENT;
            $file = file_save($file);
        }
    }
    variable_set('mymodule_custom_content_block_text', $form_state['values']['custom_content_block_text']);
    drupal_set_message(t('Custom Content Block has been updated.'));
}

```

# Answer
> 20 votes
If you don't mind my saying you're doing this the hard way. Drupal has a `managed_file` element type that handles most of this logic for you:

```
function mymodule_custom_content_block_form($form, &$form_state) {
  $form['custom_content_block_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_content_block_image',
    '#title' => t('Block image'),
    '#size' => 40,
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#upload_location' => 'public://'
  );

  return $form;
}

function mymodule_custom_content_block_form_submit($form, &$form_state) {
  if (isset($form_state['values']['custom_content_block_image'])) {
    $file = file_load($form_state['values']['custom_content_block_image']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}

```

# Answer
> 5 votes
With Clive answer my image got deleted after 6 hours. So if someone experienced the same problem that I got. Here is the solution (from Clive's answer with a little addition).

```
function mymodule_custom_content_block_form($form, &$form_state) {
  $form['custom_content_block_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_content_block_image',
    '#title' => t('Block image'),
    '#size' => 40,
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#upload_location' => 'public://'
  );

  return $form;
}

function mymodule_custom_content_block_form_submit($form, &$form_state) {
  if (isset($form_state['values']['custom_content_block_image'])) {
    $file = file_load($form_state['values']['custom_content_block_image']);

    $file->status = FILE_STATUS_PERMANENT;

    $file_saved =file_save($file);
    // Record that the module is using the file.
    file_usage_add($file_saved, 'mymodule_custom_content_block_form', 'custom_content_block_image', $file_saved->fid);
  }
}

```

The solution is to add `file_usage_add`. From API documentation:

> Note: New files are uploaded with a status of 0 and are treated as temporary files which are removed after 6 hours via cron. Your module is responsible for changing the $file objects status to FILE\_STATUS\_PERMANENT and saving the new status to the database. Something like the following within your submit handler should do the trick.

See: https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x#managed\_file

# Answer
> 1 votes
This attribute should be added to your form in order for it to work with file uploads.

```
$form['#attributes']['enctype'] = "multipart/form-data";

```

---
Tags: 7, forms, files
---


# Question
Title: How to use Rules to restrict the edit and delete options if a field has value "approved"?
In my website I have 3 roles: user, tester and admin. When a user submits the content, tester will check and approve it.

As long as the content is not "approved", users can edit and delete their own content. But after the content is "Approved" (indicated via a field with value "approved"), users are not not allowed anymore to edit or delete their content.

How to do this with the Rules module based on roles?

# Answer
Under permissions give the role ability to update only their own content. Then set a rule when node is published, author of role is set to another site user? That would be a quick implementation.
> 0 votes

# Answer
You can get this to work with the Rules module. The rule you'd need is something like so:

```
{ "rules_disallow_edit_of_approved_nodes" : {
    "LABEL" : "Disallow edit of approved nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "6" : "6" } }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_approval_status" } },
      { "data_is" : { "data" : [ "node:field-approval-status" ], "value" : "approved" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, edit is not allowed (admin status is approved).",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment, e.g:

* this rule assumes that the tester role has role id = 6 (change to whatever role id that fits).
* the machine name (`field_approval_status`) and the field value (`approved`) of the field that contains the approval status.
* adapt the "Sorry, ..." message to be shown, if needed.
* the URL to redirect to.
> 0 votes

---
Tags: 7, users, rules
---


title: Dynamically add input field using #ajax

text:
# Question
Title: Dynamically add input field using #ajax
As the question says, im not clear on how to go about adding new input fields depending on values of certain fields in the form.

I got as far as setting a callback and a wrapper, but i just can't seem to rebuild the form, i can do basic returns of values from the callback, but that's about it.

If anyone could show me a clean, simple way where i could go from, that would be great!

```
<?php

//Create raffle form
function raffle_create_form($form, &$form_state)
{

    //Basic raffle info
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "<h5>Raffle information</h5><hr>",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "Number of allowed members",
        "#required" => TRUE,
        '#element_validate' => array('element_validate_number')
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
        ),
    );

    if(isset($form_state['values']['raf_prize_type']))
    {
        $form['raf_steam_options'] = array(
            '#type' => 'textfield',
            '#title' => 'Added div',
            '#prefix' => '<div id="steam_options">',
            '#suffix' => '</div>'
        );
        $form['raf_steam_options']['#description'] = 'configure some steamy steam steam';
    }

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '<div id="steam options"></div>',
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';

    return $form;
}

function raffle_create_form_validate($form, &$form_state)
{

}

function raffle_create_form_submit($form, &$form_state)
{
    dsm('i printed');
}

function raffle_create_form_type_steam($form, &$form_state)
{
    dms('hi');
    return $form['raf_steam_options'];
}

```

# Answer
> 0 votes
You should do something like this

```
$form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
            'event' => 'change',
           'method' => 'replace',
        ),
    );

$form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '<div id="steam options">',
        '#suffix' => '</div>'
    );

```

And your callback function should be

```
function raffle_create_form_type_steam($form, $form_state){

    return $form['raf_prize_name'];
}

```

# Answer
> 0 votes
The trick was to:

1. Define ajax method as `append`.

Append keeps adding the input field on change, replace works swifter in this case.
2. Set a prefix on any of the input field to create a div. CLOSE THE DIV ON THE PREFIX FIELD AND NOT ON THE SUFFIX FIELD. E.g.

```
'#prefix' => "<div id='div_to_replace'></div>"

```
3. Then set the callback function to return required input

```
   <?php

//Create raffle form
function raffle_create_form($form, &$form_state)
{

    //Basic raffle info
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "<h5>Raffle information</h5><hr>",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "Number of allowed members",
        "#required" => TRUE,
        '#element_validate' => array('element_validate_number')
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#required" => TRUE,
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
            'event' => 'change',
            'method' => 'append',
        ),
    );

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        "#prefix" => "<div id='steam_options'></div>",
        "#required" => TRUE
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';

    return $form;
}

function raffle_create_form_validate($form, &$form_state)
{

}

function raffle_create_form_submit($form, &$form_state)
{
    dsm('i printed');
}

function raffle_create_form_type_steam($form, &$form_state)
{
    return  $form['raf_steam_options'] = array(
            '#type' => 'textfield',
            '#title' => 'Added div',
            '#prefix' => '<div id="steam_options">',
            '#suffix' => '</div>'
        );
}

```

# Answer
> 0 votes
Please note that form function should contains all form variant. So the way stated by @Haider Ali did is not acceptable because `$form['raf_steam_options']` is appended in the `#ajax` callback.

The code in question is not working because there is no `<div id="steam options"></div>` printed in page in the very beginning.

Please check below for the reference.

```
/**
 * Create raffle form.
 */
function raffle_create_form($form, &$form_state) {
  $form = array();
  $values = &$form_state['#values'];

  // ...

  $form['raf_prize_type'] = array(
    '#type' => "select",
    "#options" => array(
      'gift' => 'Steam Gift',
      'hardware' => 'Gaming peripherals'
    ),
    "#title" => "Prize type",
    "#required" => TRUE,
    "#ajax" => array(
      'callback' => 'raffle_create_form_type_steam',
      'wrapper' => 'steam_options',
      'event' => 'change',
      'method' => 'append',
    ),
  );

  if (isset($values['raf_prize_type']) && !empty($values['raf_prize_type']) {
    $form['raf_prize_name'] = array(
      '#type' => "textfield",
      '#title' => "Prize name",
      '#prefix' => '<div id="steam options">',
      '#suffix' => '</div>',
    );
  } else {
    $form['raf_prize_name'] = array(
      '#prefix' => '<div id="steam options">',
      '#suffix' => '</div>',
    );
  }

  // ...

  return $form;
}

/**
 * Ajax callback.
 */
function raffle_create_form_type_steam($form, $form_state){
  return $form['raf_prize_name'];
}

```

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


# Question
Title: How do I hide the link to the RSS feed on the term page?
I want to keep the feed functionality, but I want to hide the "Subscribe to \[term name\]" link on the term page.

# Answer
Under "Structure", "Views", open the "Taxonomy term" view, on the `Feed display`, under `Feed settings` set `Attach to` to none.
> 10 votes

---
Tags: views, taxonomy-terms, 8, feeds
---


# Question
Title: How to insert 2 answers using Quiz submodule Short Answer?
I am using the Quiz module and enabled its submodule Short Answer.

How can I insert two answers instead of one?

**Note**: Multiple choice is fine, but my problem is at Short Answer: I'm only able to add 1 correct answer, but my Quiz question has 2 correct answers.

# Answer
> 0 votes
I guess no solution, so I just hack the module.

/public\_html/testserver/the-exaple.com/sites/all/modules/contrib/quiz/question\_types/short\_answer

```
public function evaluateAnswer($user_answer) {
  ...
  switch ($this->node->correct_answer_evaluation) {
  case self::ANSWER_MATCH:
    if ($user_answer == $this->node->correct_answer) {
      $score = $this->node->max_score;
    }
    break;
  case self::ANSWER_INSENSITIVE_MATCH:

   ////////////////edit your code here

    break;
  case self::ANSWER_REGEX:
    if (preg_match($this->node->correct_answer, $user_answer) > 0) {
      $score = $this->node->max_score;
    }
    break;
}
...
}

```

Since I chose my answer is insensitive, I will edit second case.

---
Tags: 7, quiz
---


title: How can I write dynamic query?

text:
# Question
Title: How can I write dynamic query?
Can anybody suggest to me how I can write a dynamic query in Drupal for the below MySQL query. Any suggestion will be appreciated.

```
select * from cap_pas where pas_uid not in
  (select pas_uid from cap_boat_to_pas)

```

# Answer
> 2 votes
There are many similar questions on Drupal Answers.

```
$subquery = db_select('cap_boat_to_pas', 'cp')
  ->fields('cp', array('pas_uid'));

$query = db_select('cap_pas', 'cp')
  ->fields('cp')
  ->condition('cp.pas_uid', $subquery, 'NOT IN');

results = $query->execute()->fetchAll();

```

**Note**: to write this in a single query (by using joins), take a look at leftJoin().

---
Tags: 7, database
---


title: Page content differs from editor

text:
# Question
Title: Page content differs from editor
I've inherited Drupal 7 website. I'm having some difficulties figuring out why one of the pages is showing different content then it actually has in the edit page.

This site is multilingual (3 languages), same page is displaying properly on 2 other languages. But on this one language instead of rendering proper content, that I see in the editor, it renders completely different content. This is the only page I'm having trouble with.

To be exact it shows sharing buttons instead of just plain text and hyperlinks content. These sharing buttons aren't supposed to be there in the first place.

This isn't a front page, just regular page created through add content \> regular page.

Has anyone had successfully resolved the same/similar problem and could share knowledge?

# Answer
It depends on how the developer did on the website. It could be very difficult if it is done by a developer who is not familiar with Drupal. For your situation, I can share some possible places of code for your reference.

Drupal developer may do it in:

* Preprocess function in theme template.php
* Field pre render function in custom module.

PHP developer may do it in:

* PHP condition code in node.tpl.php

Frontend developer may do it in:

* DOM manipulation in theme js file.
> 0 votes

---
Tags: 7
---


# Question
Title: Display users created only by the current user in Admin/People
Below is the site's user access level hiearchy:

There is a user `myid_administrator` which has a role `MYID ORGANIZATION ADMINISTRATOR`. The `administrator`, `aegono`, had enabled 'Administer users' to enable the user `myid_administrator`, create users.

In the url `admin/people`. `myid_administrator` can see users which has a higher level of user access than it. For example, It can see 'aegono', the administrator of the site.

I want it to display only the users , the `myid_administrator` created and below its user level. Is it possible ? How? Do I have to create a customized form for the users with roles `MYID ORGANIZATION ADMINISTRATOR`, to add users and only see the users it created? Or is there any module than can help my problem?

# Answer
> 4 votes
Are you aware of the Subuser module? It appears to be capable of doing exactly what you want.

> This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.

# Answer
> 1 votes
Have you try User Create By module? The features looks promising:

> * Saves uid of user who creates other users. And if user registers then anonymous users uid is saved which is 0.
> * User Created By module provides view handler which allows to make relationship in view and add user creator's name or other corresponding fields of user creator in view.

Here you go https://www.drupal.org/project/user\_created\_by

# Answer
> 0 votes
You can ***hide*** the `administrator` role (and its users) for users with not sufficient permissions by doing this:

1) I would suggest you to install the admin views module, in case you haven't done already and override the `admin/people` page.

2) Implement the following hooks: hook\_form\_alter and hook\_views\_query\_alter

```
 /**
  * Implements hook_form_alter().
  */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  // Hide the 'administrator' user role filter option.
  if ($form_id == 'views_form_custom_view_name_system_1' && !_allowed_roles($user)) {
    $role = user_role_load_by_name('administrator');
    unset($form['rid']['#options'][$role->rid]);
  }
}

// Return if the logged in user can view the administrator role.
function _allowed_roles($user) {
  return in_array('Role 1', $user->roles) || in_array('Role 2', $user->roles);
}

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(&$view, &$query) {
  global $user;

  if ($view->name == 'custom_view_name' && !_allowed_roles($user)) {
    $role = user_role_load_by_name('administrator');

    $join = new views_join();
    $join->table = 'users_roles';
    $join->field = 'uid';
    $join->left_table = 'users';
    $join->left_field = 'uid';
    $join->type = 'INNER';
    $join->adjusted = TRUE;

    $query->add_relationship('users_roles', $join, 'uid');
    // Hide the 'administrator' role users from the actual users' list.
    $query->where[] = create_views_where_expression($field = 'users_roles.rid', $value = $role->rid, $operator = '<>');
  }
}

```

3) Don't forget to add to the (above) users overridden view the `User: Roles (exposed)` filter.

So far we have the administrator role hidden from the users list, let's now **restrict the access** (edit) to the actual accounts as well.

4) Again, we implement some hooks and an access callback function: - hook\_permission, it let us to define user permissions (UI) - hook\_menu\_alter allows us to alter the default callback function and `_admin_edit_callback` the custom callback to implement our logic.

```
/**
 * Implements hook_permission().
 */
function my_module_permission() {
  return array(
    'edit administrator profile' =>  array(
      'title' => t('Edit administrators profiles'),
      'description' => t('Perform changes to administrators accounts'),
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = '_admin_edit_callback';
  $items['user/%user/edit']['access arguments'] = array(0, 1, 'edit');
}

/**
 * Access callback for admin user edit operations
 * @param $type
 *  The entity type.
 * @param $entity
 *  The entity object.
 * @param $op
 *  The operation to the entity.
 *
 * @return bool
 */
function _admin_edit_callback($type = NULL, $entity = NULL, $op = NULL) {
  global $user;
  $account = user_load($user->uid);

  // Selected users with full access.
  if (_allowed_roles($user)) {
    return user_edit_access($account);
  }
  else {
    // Check users access.
    if ($op === 'edit') {
      if ((user_access('edit administrator profile', $account) || $user->uid == $entity->uid) && $account->uid > 0) {
        return TRUE;
      }
      else {
        return FALSE;
      }
    }
  }
}

```

Apparently this is a custom way to resolve your issue, not a module, but taking advantage of the Drupal's API will benefit you more in the future, happy coding!

# Answer
> 0 votes
Subuser module should fulfill your requirement, but according to your screenshot the administrator user can watch all users because for admin there is a default global user variable there. Uncheck that user subuser module and you will get the permission for the subuser, then you can manage their access.

---
Tags: 7, forms, users
---


# Question
Title: how do I add contextual edit links in block template for a block entity?
In Drupal 8, how do I add contextual edit links in a block template?

This is for block entities created at /block/add, not block plugins created by a class in a custom module.

I want an edit link to display on the front end. I want an edit link for the block, not for the block content type (bundle). For example, a link to /block/123.

I believe it's supposed to be output by

```
{{ title_prefix }}

```

But I don't see the links showing up and I'm not sure where to turn them on.

I was able to get them to render with this code, but then realized this only works for block plugins, not block entities:

```
function exampletheme_preprocess_block(&$variables) {

  if (!empty($variables['elements']['#contextual_links'])) {
    $variables['elements'] = ContextualLinks::preRenderLinks($variables['elements']);
    $variables['links'] = array(
      '#prefix' => '<div class="contextual-links-wrapper">',
      '#suffix' => '</div>',
      '#theme' => 'links__contextual',
      '#links' => $variables['elements']['#links'],
      '#attributes' => array('class' => array('contextual-links')),
      '#attached' => array(
        'library' => array(
          'contextual/drupal.contextual-links',
        ),
      ),
      '#weight' => -10,
    );
    $variables['attributes']['class'][] = 'contextual-links-region';
  }

}

```

This added some links to edit the content type (although I never got them to render).

Finally, I just rolled my own:

```
$entity_view = $render_controller->view($block);

$entity_wrapper = [
  '#type' => 'container',
  '#attributes' => [
    'id' => ['block-' . $block->id()],
    'class' => ['example-container-class'],
  ],
];

$entity_wrapper['content'] = [];

$edit_link = $block->toLink()->toRenderable();
$edit_link['#title'] = t('Edit');
$edit_link['#attributes'] = [
  'class' => ['edit-link'],
];
$entity_wrapper['content'][] = $edit_link;
$entity_wrapper['content'][] = $entity_view;

$build[] = $entity_wrapper;

```

After that, I dug around a little and found a way to render the built-in contextual links for block\_content entities. You have to do a little legwork while building up your render array:

```
use Drupal\contextual\Element\ContextualLinks;

```

First load up your block\_content entity:

In this case, I'm only expecting one of this bundle or type:

```
 $blocks = \Drupal::entityManager()->getStorage('block_content')->loadByProperties(['type' => 'footer_middle']);
    if (!empty($blocks)) {
      $block = array_shift($blocks);

}

```

Now we render the entity using the entity manager:

```
  $render_controller = \Drupal::entityManager()->getViewBuilder('block_content');
  $footer_middle = $render_controller->view($block);

```

The really tricky part is that block\_content entities don't have a theme function or template, so you have to add the contextual links to a parent item, such as a container:

```
   $build['footer_middle'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'footer-middle',
        'class' => ['footer-container'],
      ],
    ];

      $build['footer_middle']['#contextual_links'] = $footer_middle['#contextual_links'];

Now we need to generate the links:

      $footer_middle = ContextualLinks::preRenderLinks($footer_middle);

```

Then set up the render array on the parent container, passing in the rendered links:

```
  $build['footer_middle']['links'] = array(
  '#prefix' => '<div class="contextual-links-wrapper">',
  '#suffix' => '</div>',
  '#theme' => 'links__contextual',
  '#links' => $footer_middle['#links'],
  '#attributes' => array('class' => array('contextual-links')),
  '#attached' => array(
    'library' => array(
      'contextual/drupal.contextual-links',
    ),
  ),
  '#weight' => -10,
);

```

And now add the rendered entity as a child of the container:

```
$build['footer_middle'][] = $footer_middle;

```

And now you have contextual links for your block\_content entity!

Just make sure your container.html.twig is outputting

```
  {{ title_suffix }}

```

Since that's where the contextual drupal module puts it.

# Answer
You probably want to have a look at `contextual_preprocess`.

If you add this to the render element or variables array before contextual\_preprocess is called, it will handle the rest and add the stuff to `title_prefix`. Note I haven't tried this as an alter, only on entities I've created myself.

```
$render_element_or_variables['#contextual_links']['ENTITY_ID'] = [
  'route_parameters' => ['ENTITY' => $ID_OF_ENTITY],
];

```

If it's a render element, you should add it to the `element` key otherwise it should be the root of the array in the process/preprocess function you use.
> 1 votes

---
Tags: theming, 8, blocks
---


title: How to add Mini Panel

text:
# Question
Title: How to add Mini Panel
I can´t mini panel in panel page because this not showing in content of panels.

I have mini panel module enable but... How can I enable mini panels in content panels??

# Answer
Thanks for your answers. Already solved the issue.

You have selected a layout Panopoly, I changed it to one of the "Extra laytous panels" and matter settled.
> 0 votes

---
Tags: 7, panels
---


title: How do I sort a view by content type?

text:
# Question
Title: How do I sort a view by content type?
I use a View to show search results (core Search module). In the view I have grouped the grid on the field "Content type". This works fine, each content type is shown under it's own title.

But under "Sort" in the View I can only sort the content types by ASC or DESC. But I would like to use a custom sort order like "node type = product", followed by "node type = accessories" and so on.

How to do that? I have tried using hook\_views\_query\_alter() and hook\_search\_api\_query\_alter() and a few other tings, with no luck.

# Answer
If you're looking to arbitrarily order nodes, that is the use case of Weight module. The module lets you add a field to any node type with a customizable weight range. Once added to your node types, you can configure any View to use this field to sort your nodes.
> -1 votes

---
Tags: 7, views, search
---


# Question
Title: Site got an error after moving from local to a server
I finally wanted to move my site from localhost. After importing db and connecting it to the Drupal I got these errors:

> The website encountered an unexpected error. Please try again later. Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42000\]: Syntax error or access violation: 1142 INSERT command denied to user 'bpcoders\_44'@'10.254.34.28' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> DrupalKernel \[:db\_insert\_placeholder\_2\] =\> Container cannot be saved to cache. \[:db\_insert\_placeholder\_3\] =\> a:0:{} \[:db\_insert\_placeholder\_4\] =\> 3 \[:db\_insert\_placeholder\_5\] =\> \[:db\_insert\_placeholder\_6\] =\> \[:db\_insert\_placeholder\_7\] =\> \[:db\_insert\_placeholder\_8\] =\> \[:db\_insert\_placeholder\_9\] =\> 1465229026 ) in Drupal\dblog\Logger\DbLog-\>log() (line 79 of core/modules/dblog/src/Logger/DbLog.php). Drupal\dblog\Logger\DbLog-\>log(3, 'Container cannot be saved to cache.', Array) (Line: 104) Drupal\dblog\Logger\DbLog-\>log(3, 'Container cannot be saved to cache.', Array) (Line: 136) Drupal\Core\Logger\LoggerChannel-\>log('error', 'Container cannot be saved to cache.', Array) (Line: 66) Drupal\Core\Logger\LoggerChannel-\>error('Container cannot be saved to cache.') (Line: 869) Drupal\Core\DrupalKernel-\>initializeContainer() (Line: 437) Drupal\Core\DrupalKernel-\>boot() (Line: 627) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

How can I fix it? Do I need to contact hosting support?

# Answer
The database user you specified in settings.php does not have INSERT privileges on the watchdog table. Contact your hosting provider support.
> 1 votes

---
Tags: 8, debugging
---


title: Sort by closest to today?

text:
# Question
Title: Sort by closest to today?
I've got an show/performance relationship, where a show can have multiple performances, and each performances has a single date (when the performance takes place).

I'm showing these in a Drupal view, but it's becoming a bit problematic.

I need to sort this list so that the shows with the closest performances to now appear at the top, the problem is that shows with only past performances also need to show.

The last part appears particularly problematic, I think I could just sort this by greater than or equal to now, but I don't think that will be sufficient in this case.

Is this possible? Or do I need to try and argue for a different way of displaying this content

# Answer
> 2 votes
I would make two view lists, one to show forthcoming performances and one to show past performances.

This way you can title each list so it's clear to users which is which. It would be feasible through careful CSS to make it look like they are one list. And each list will only show as required.

Filter on the date, either '\>= now' or '\<= now', to make each list work as you wish.

# Answer
> 0 votes
If you're going to have all events in one view, you're going to need to define an ordered set of rules so that current/upcoming events are placed ahead. If there's some expired flag field (e.g. a checkbox that notes the event has expired) on these events that might do it (e.g. sort by expired status, then sort by ascending date).

However, if your expired/non-expired events have different sorting criteria (e.g. show non-expired events in ascending date order & expired events descending order) you're going to run into problems with Views' sorting criteria.

I'd say your intuition about creating 2 separate views is probably the right one. You can display multiple views on a page. Most likely, you want them visually distinct so this solution works well on theming level as well as site building level.

---
Tags: views, 8
---


title: How can I upload a .eps file?

text:
# Question
Title: How can I upload a .eps file?
I added an image field to my user on this page admin/config/people and marked the allowed file extensions to be `eps`, `png`, `jpg`. However, it doesn't allow me to upload `.eps` file, but only `.png` and `.jpg`.

I get this message:

> The specified file gold coins elements vector5.eps could not be uploaded. Only files with the following extensions are allowed: `jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp`.

How can I upload an `.eps` file?

# Answer
I had to change the field type to "file" , and then I can add eps files
> 0 votes

# Answer
I'm pretty sure EPS files can't be displayed in browsers, which may be why you're having a problem. There's a module which will allow for EPS files to be converted on upload, which may solve your particular issue:

https://www.drupal.org/project/imagefield\_eps
> 0 votes

---
Tags: 7, files, media
---


# Question
Title: How can I add a new module to existing Examples Module?
I have created a **New Drupal 8 Module** that could be added to existing Examples Module. So, How I can proceed?

# Answer
> 3 votes
Thank you so much on starting on this! Examples module have helped many developers overcome the Google fail!

And contributing to it is pretty easy. Personally, to add the module to the main module, I would follow the steps below:

1. Create a sandbox project with the name **foo\_example** (*foo* being the nature of your module.
2. Check if the module satisfies the checklist : https://www.drupal.org/node/2209627
3. Create an issue in the issue queue with

* Title : Add foo\_example to the D8 repo.
    * Category : Plan
    * Version : 8.x-1.x-dev
    * Component : Other
    * Status : Needs Review
4. Inside the body give a description of what your module does, link it to the sandbox project.

Next, you wait for the reviews :) You might get it reviewed by your peers or friends/IRC so that some obvious issues are spotted on early. And the maintainers of the examples module should be able to review it. And you should also get credits for your work!

---
Tags: community-official-site
---


title: Anchor links not working in Firefox

text:
# Question
Title: Anchor links not working in Firefox
So I know this might not necessarily be a "Drupal" issue, but because I am using Drupal and this issue only happens in my Drupal site, I'm wondering if it has something to do with the way Drupal handles URL's.

SO, I have an anchor on my home page like so:

```
<a id="we_know_digital" name="we_know_digital"></a>

```

There is a link in the main navigation that is on all pages to this anchor like so:

```
<a href="/#we_know_digital">We Know Digital</a>

```

So this works in all browsers, including Firefox, when I am ALREADY on the home page, however, if I am on one of the internal pages and then click this link, it takes me to the homepage, but does NOT go down to the anchor in Firefox. It does go down to the anchor in Chrome and Safari and other browsers, but for some reason it wont in Firefox, even in the latest version. The reason I believe this has something to do with the way Drupal handles URL's is that if I create a standalone plain vanilla HTML page outside of Drupal and replicate the same thing where I have 1 page that has the link and the anchor and then a separate page that has the link to the first page and the anchor, it works as expected in Firefox where it goes to the first page and then down to the anchor. It's only when I try to do this within Drupal, that it stops working. Anyone have any idea what might be going on here? I'm thinking it has something to do with the URL re-writing. ???

# Answer
WOW, so sorry for the wild goose chase on this one. On a hunch, I decided to completely disable JavaScript in Firefox just to see what would happen and lo and behold, the problem went away and I started to get the behavior I expected. SO, I went into my custom.js JavaScript file that I had and went line by line to see if there was anything that looked obvious and I found this line:

```
$(this).scrollTop(1);

```

I have NO idea why I had that in there. I'm not sure if I was testing something at one point in time and just accidentally left it in there or if it was meant to do something important, but either way, I removed it, and now it works correctly in all browsers including Firefox. Thanks for all you're help on this one though. I learned more than I ever wanted to know about anchor links! :-)
> 0 votes

# Answer
> ```
> <a id="we_know_digital" name="we_know_digital"></a>
>
> ```

The *empty* anchor target might be the problem. The browser may be having a "problem" fixating the empty (non-visual) target as the page loads.

Ideally, you would attach the `id` to *something*. eg. an `Hn` tag.

The `name` attribute on the anchor is deprecated in HTML5 if that is of concern. Reference: https://www.w3.org/TR/2008/WD-html5-diff-20080610/#absent-attributes
> 0 votes

---
Tags: navigation
---


# Question
Title: If linking entities with a multi-value entity reference field, what about properties of the association?
In this thread I need a link from base table to join table it was suggested that it is better in Drupal to join two entities with a multi-value entity reference field than to use a relational style join table to join them (assuming many to many relationship). But, what about the case where there is a property of the association. E.g., stories win awards, but each award is or may be granted every year. So, in a relational design, one would use a join table to link a particular story with the award it had won and put the year into the association. What is the Drupal Way to do this with a multi-value entity reference field?

OK, here is a simplified diagram of the relationship between Story and Award showing the property on the association.

# Answer
First, there is no Drupal way. Drupal is flexible and the same result can be achieved in many ways. If you feel comfortable using join tables, go for it. In the other thread OP wanted to use a relation between entities in View, what entity references offer out of the box, where a join table would not. Therefor that was suggested.

For a situation where a relation needs to have properties on its own, you might want to look into the Relation module. It provides a relation between two entities, but the relation can have properties (fields) on its own (such as as year).

I just don't know how stable the module is for Drupal 8, but it works great in Drupal 7.

*Update after the question of Asy:*

The entity principle in Drupal 8 is similar to 7, so it would not change the answer much, except that the relation module for Drupal 8 is not yet finished. The problem with this specific question is that the answer is spread over 3 different posts. The combined essense is: nodes are pretty 'resource heavy' entities, as they invoke access checks, path aliasing, etc. Using them just to attach a property to a 'relation' works, but consumes more resources than a system that was designed to do just this (the Relation module, which for instance avoids the node access check and path aliasing on the in-between node). Especially when combining 3 nodes with 2 fields, this becomes SQL heavy too. Nothing SQL can't handle, just don't do it too often. So in the end is all depends on the application. If this is not a page that gets much views, you might not even notice it.

A better alternative (but I did not test nor benchmark this) might be to create a custom entity using the ECK (Entity Construction Kit). These entities are presumably lighter than nodes. Combined with Drupal 8's default entity referencing and something like Inline Entity Form to fill the field on the relation could make quite a nice interface.

In the end however you still need to join like this:

```
Node > entity reference field > ECK entity > entity reference field > node
  v                                  v                                  v
fields                            fields                             fields

```

Where the relation module (if finished) would offer something that probably looks more like this:

```
Node > relation > node
  v       v         v
fields  fields    fields

```
> 0 votes

---
Tags: navigation
---


# Question
Title: prevent script to run twice after 2 ajax loads
I use colorbox node, which loads a node inside colorbox overlay. Inside colorbox I load a jquery script to add some parameters to all links inside. However, the loading is done by 2 ajax calls and I end up with doubled parameters on all links. I tried to use .once() but that does not return anything, probably because it fires after first ajax call. How to wait until second ajax call? Thank you.

my script:

```
(function($){ // Create local scope.
Drupal.behaviors.jjj = {
  attach: function (context, settings) {

$('#colorbox #block-book-navigation a', context).once('jjj', function () {
       $("#colorbox #block-book-navigation a").each(function(){

                       $(this).addClass("xxx");
console.log( "test" );
       });

 });
}};
})(jQuery);

```

# Answer
I figured it out. The wrong code came out of misunderstsatnding .once function. "nav" means a class that the selector #colorbox #block-book-navigation would be marked, so code is not fired multiple times on that selector. http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors Correct code should be:

```
(function ($) {
  Drupal.behaviors.myCustomJS = {
    attach: function(context, settings) {
      $('#colorbox #block-book-navigation').once('nav', function() {

        $("#colorbox #block-book-navigation a").each(function(){
            $(this).addClass("colorbox-node");

       });

      });
    }
  };
})(jQuery);

```
> 1 votes

# Answer
A couple of things to improve your own answer...

If a second element that matched the selector "#colorbox #block-book-navigation" were added, the addClass() would run again on all anchor tags in both elements including the ones it's already run on.

This code fixes a couple of issues:

```
(function ($) {
  Drupal.behaviors.myCustomJS = {
    attach: function(context, settings) {
      $('#colorbox #block-book-navigation', context).once('nav', function() {
        $("a", this).addClass("colorbox-node");
      });
    }
  };
})(jQuery);

```

**Notes:**

* In *"$('#colorbox #block-book-navigation', context)"* the *", context"* is added which means that this selector is only searched for in the current context which is the whole document on the initial page load or the content loaded via AJAX on an AJAX call.
* Likewise in *"$("a", this)"* the *", this"* makes sure it only finds anchor tags inside the "#colorbox #block-book-navigation" element that is currently being processed. I've taken away the earlier part of the selector as it's redundant now.
* If you're not doing any other logic for every link then the *".each()"* is redundant. I've removed for this example.

This code should be more perfomant (jQuery doing less DOM traversal) and more robust in that it should prevent any unnecessary repetition of logic.
> 1 votes

# Answer
Can you try this?

```
(function($) {
    // Create local scope.
    Drupal.behaviors.jjj = {
        attach: function (context, settings) {
            $('#colorbox #block-book-navigation', context).once('jjj', function () {
                $(this).find('a').addClass('xxx');
            });
        }
    };
}) (jQuery);

```
> 0 votes

# Answer
Currently the other solutions assume that no a tags are inserted inside an existing `#colorbox #block-book-navigation` in any other ajax calls.

This solution would also work in that case and is also a bit simpler than the other solutions as long as you aren't using the each loop for any other purposes:

```
Drupal.behaviors.jjj = {
  attach: function(context, settings) {
    $('#colorbox #block-book-navigation a', context).once('jjj').addClass('xxx');
  }
};

```
> 0 votes

---
Tags: 7, ajax, javascript
---


# Question
Title: How can I specify a "Text Field" as an "Attribute Field Setting" for a Product Variation in Drupal Commerce?
I am working with a client that handles distribution for an array of goods that do not fall into traditional sizing schemes (S, M, L). Instead, some products are characterized by length in mm, weight in kg, qty in a kit, etc. Because of the wide array and volume of nodes, it doesn't make sense to create a new vocabulary/category out of so many unrelated terms.

* Set 1: 160mm, 180mm, 203mm
* Set 2: 1xsm + 2xlg; 2xsm
* Set 3: 25 mL, 250 mL, 1 L, 5 L
* etc (totally different kinds of sets that are not reused across product types)

I specified a "text field" as "Product specific size", allowing the user to insert whatever size type made sense up to 100 characters. I thought I could use that as a dropdown menu so that the size could be selected by the shopper in the "Add to Cart" form.

However, it looks like that's a no-go for text fields. Because the size varies across other parameters (qty in kit x color), having the variant name be the selection method seems pretty hokey.

What have others done for this use case?

Thanks - keb

# Answer
6/5 Follow up:

Looking into this further, the "Cart" module calls the "Options" module in order to determine which fields are eligible to be "Add to Cart" form attributes:

```
// If the current field instance is not locked, is attached to a product
// type, and of a field type that defines an options list...

```

In the "Options" module, it looks for data that is entered/stored as an array, e.g. a select list, taxonomy list, etc.

Thinking this through, it seems like it won't be possible to call the user-entered data in a text field for multiple Product Variations because it isn't stored in req'd format.

There may be a way to write custom code to work around this, but I relented and made an absurd list of "Product Specific Options" that takes care of the use case. Since most products on the site will be imported, the burden on editor/user won't be too high.
> 0 votes

---
Tags: commerce
---


# Question
Title: Track Simplenews newsletter open per user
I send newsletters from my Drupal 7 site, using the Simplenews module. I'm using this tracking code, but it isn't tracking uniqueness:

```
<img src="http://www.google-analytics.com/collect?v=1&tid=test-

1&cid=123445678&t=event&ec=email&ea=open_my_newsletter_june2016&el=recipient_id&cs=newsletter&cm=email&cn=Campaign_Name">

```

I change the `tid` according to my Google Analytics account and the `ea` attribute to the name of my newsletter and the date, but these aren't unique URL's for users.

How can I track unique opens of my newsletter, using Google Analytics?

# Answer
> 1 votes
As you mentioned, you need a unique values for GA tracking pixel. You need to utilize Simplenews's integration with the Token module so you can insert unique values into the URL for each newsletter copy that goes out.

For example, the inserting the token `[simplenews-subscriber:user:uid]` will let embed the unique user id into each tracking pixel copy.

The tokens will vary depending on the details you need to track, but Token integration should provide almost every detail you need.

---
Tags: 7, emails, google-analytics
---


# Question
Title: Access Denied when redirecting to alternate view
I've designed a view that shows a table of data. Within the global header, I've written

> Click here to see your events in a calendar format.

The intent is to redirect to another view if the user clicks the link(s). This works correctly if the user is using Chrome or IE as a browser. However, if FireFox (on Windows), or, Safari (on Mac), are used, the user gets:

> Access Denied You are not authorized to access this page.

And, they are asked to login again. I've checked permissions and everything seems to be in order. Does anyone know why this is happening?

# Answer
> 0 votes
Please check if cookie & javascript is enabled on the test machines for Mozilla & Safari browser.

---
Tags: 7, views
---


title: How to use remote file source module

text:
# Question
Title: How to use remote file source module
I would like to use the Remote File Source Module.

But I could not find any documentation related to it.

Has anyone succeeded using it?

How to provide ftp hyper link inside a blog, article, forum.

I would like to insert a node url inside CKEditor. The node must be a custom node which will fetch a file from an FTP url some think like a reverse proxy.

# Answer
Go to your content type and click edit on your file field in question.

* Click on File Sources.
* ☑ Remote File.
> 0 votes

---
Tags: 7, files
---


# Question
Title: How can I correct a word on the CKEditor field?
When editing a text area in Drupal 8, right clicking a highlighted spelling error doesn't produce a context menu option to correct the misspelled word. How can I correct the word on the CKEditor field?

# Answer
According to AdamPS in Enable browsers' (native) spell checker in CKEditor

> 2) **If you browser supports spelling suggestions, the way to access them in Drupal is slightly different**. When you are in an edit area, then the normal browser context menu may be replaced by the editing context menu. However you can access the browser menu **by clicking Control**. \[But on a Mac it is potentially command and on a tablet ....??\]

You need to hold down CTRL before right clicking. (which worked for me on Windows OS)

---

An alternative would be to install the SpellCheckAsYouType(SCAYT) plugin for CKEDITOR

> **Note:** You have to build a custom module to install CKeditor plugins in D8.
> 3 votes

---
Tags: 8, wysiwyg
---


title: How do I find a template?

text:
# Question
Title: How do I find a template?
How I determine which template or form is responsible for processing node of page with this URL: mysite.com/node/node-number/edit ?

I think, that Drupal find the template of edit in this files:

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

```

However, in my theme folder I have only `page.tpl.php` without the code of edit template, but edit template is worked.

And in template.php i heve this preprodsse\_node:

```
function my_theme_preprocess_node(&$vars) {
    $node = $vars['node'];
    switch ($node->type) {
        case 'page':
            break;
    }
}

```

Now I think that the CCK module to generate this form. I can change one field or a behavior of the form?

P.S.

I need to change some input in edit form. And I can't use a different version of Drupal :(

# Answer
> 0 votes
If you want to change the default value of fields in node edit form. You should looking on any \*.tpl.php files. You have to define your own custom module and use hook\_form\_alter

You can use this if-statement inside the hook function.

```
// remember change [nodetype] to the one you want to alter.
if($form_id == 'nodetype_node_form'){
    // your code here
}

```

---
Tags: theming, nodes, 6
---


# Question
Title: How to invite multiple users when editing user account?
I've installed the Invite module. I see that there is an extra block that you can active. When you do this you will see a block like this on your page:

But I would like to have this field on my `user/edit` page. And make sure that they can enter multiple e-mail addresses separated by `,` .

But how can I do this?

# Answer
> 0 votes
You question consists of actually 2 questions:

1. ... have this field on my user/edit page.
2. ... enter multiple e-mail addresses separated by `,` .

To answer the 2nd question (= *... enter multiple e-mail addresses separated by `,`* ), have a look at the issue about Multiple emails support for Invite form. The patch contained in comment nr 5 of it can be used to create a new invite entity for each email address. Attention: it seems that this patch still needs to be rerolled for the latest dev version (which is also what explains the "needs work" status of this issue).

---
Tags: forms, users, 7, blocks
---


# Question
Title: How to add a class to more link of a view?
I want to add a class to a views **more link** available under pager section using `template_preprocess_views_view()`.

# Answer
> 9 votes
You can do it by implementing template\_preprocess\_views\_view() in your theme under THEMENAME.theme file as shown below:

```
/**
 * Implements template_preprocess_views_view()
 * @param array $vars
 */
function THEMENAME_preprocess_views_view(&$vars){
  if (YOUR CONDITION FOR ADDING A CLASS){
    $vars['more']['#options']['attributes']['class'] = [
      ENTER YOUR CLASSES AS ARRAY ELEMENTS
    ];
  }
}

```

Alternatively, if you want to add a class to the `.more-link` wrapper instead of the link itself, you can use the following code in the same preprocess function as above:

```
$variables['more']['#theme_wrappers']['container']['#attributes']['class'] = [
  'more-link',
  'my-class',
];

```

Reference: http://www.drupalthemez.com/blog/d8-adding-class-more-link-view

---
Tags: views, 8
---


# Question
Title: do some action when order status is changed to complete
In drupal commerce I want the rules module to do some action when the order status changes to `completed`. In fact, after buying some product an order is added to order list. Then, what I need is that when the moderator comes and change the order status to `completed` the order owner get permission to see some content type.

I have tested these rules but none of them worked!!

* Event: After updating an existing commerce order
* Condition: Execute custom PHP code

```
if([commerce-order:status] == 'completed') return TRUE;
else return FALSE;

```

or this one:

* Event: After updating an existing commerce order
* Condition: Data comparison

```
Parameter: Data to compare: [commerce-order:status], Data value: Completed

```

or this one:

* Event: After updating an existing commerce order
* Condition: Data comparison

```
Parameter: Data to compare: [commerce-order:state], Data value: Completed

```

In fact, without adding any condition the reaction is done after adding an order by customers (do not wait for moderators to complete the order) and with any of these conditions, rules never fire and the is reaction never done.

# Answer
According to the details provided by you in comments, your rule is assigning new role to the user who is currently editing the order `[site:current-cart-order:owner]`.

You need to use `[commerce-order:owner]` token in `"Add User Role"` action.

*`[commerce-order:owner]` represents the user who created the order, and not the user who is editing it.*
> 0 votes

# Answer
Given below is the example rule to update user role on order status update:

```
{ "rules_update_user_role_on_order_complete" : {
    "LABEL" : "Update user role on order complete",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "order" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "completed" } }
    ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "commerce-order:owner" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ]
  }
}

```

Here you need to change the user role of the order owner in action.
> 0 votes

---
Tags: 7, commerce, rules
---


title: How to edit CCK form?

text:
# Question
Title: How to edit CCK form?
How I change node edit form, which created by CCK module?

Now if the form is submitted, CCK update some field in mysql database. I need to change this, because in one form input contains three values, and this values need to be recorded in three fields in databse. How can I do this?

Jimmy Ko said, that I can retrieve the submitted value in `$form_state['#values']`, but I don’t know in what .php file I can do this?

# Answer
> 2 votes
For achieving this goal you have to implement hook\_nodeapi

In `presave` operation you can get desired value.

Example code you can get from the D6 release of the Examples for Developers module.

---
Tags: forms, 6
---