# Question
Title: Add rules to the email recipients in webforms
I am currently working on a Drupal 7 site in which the contact form must email a particular representative based on whether the user belongs to a certain company or is in a certain location. The first check would be based on the company of the user so that if that company has a rep then they would get the email. If not then a country rep would be sent the email. Currently I am using webforms for the contact form.

I was thinking that if it was possible to add rules or conditions to the recipient emails of the webform based on fields in the form, that would be a good place to start. However after looking around and talking to a few people I'm not sure if this option exists at the moment. I would also be open to any suggestions on a different way to achieve this. Thanks to anyone who may have any advice.

# Answer
What you want to do, certainly cannot be done with just webform.

But you may be able to pull it off when combining Webform with Rules and Webform Rules.

You can add a rule to fire at the event of a webform submission. As condition you will add the nid of the webform so you are sure this specific webform only triggers this workflow. You can also add you own php code as a condition (or no code at all if you are just going to do simple comparisons.). The good thing in this process is that all the submitted data are available through Rules so you can just grab them in your code/conditions to see if the data meet the criteria. If all the conditions are met then you will add an action to send an e-mail to either a specific user or all users of a role.
> 2 votes

# Answer
I'd go for a custom module.

1. Build the form using FAPI.
2. In the submit handler get the properties of the user.
3. User drupal\_mail() to send your mail.
> 1 votes

# Answer
Webform already supports basic conditional e-mailing as per the Conditional recipients documentation page.

If that's insufficient for your purposes, other advanced options are reviewed on the Webform Bonus Pack: email routing in webforms blog post.

Do as little custom work as possible (only if you need it) so that'll you'll have an easier time upgrading and maintaining your code.
> 0 votes

---
Tags: 7, webforms, rules, emails
---


# Question
Title: How to add some pictures under the slideshow on my homepage?
This is how the homepage of our website looks like for now:

I want to add some pictures under the slideshow (where it says "Welcome"). And if you click any of these pictures, you go to another page on the site (history, tour dates, song texts, ... ).

How do I do this?

# Answer
You can do this in two way:

Static way: Create a page, set it as your home page, insert your images in the content of the page and link them manually to each of your pages

Dynamic way: Create a content type, lets say HomeImage. Add two CCK Field to this content, one for the image, one for the link Then follow @Shabir solution...
> 1 votes

# Answer
For somebody new to Drupal, I recommend you to try to learn to walk before trying to fly. So here are some very basic steps, intended for somebody who's looking for a kind of "Hello Drupal"-page to get started ... Anything in italics refers to Drupal terminology you'll have to get used to ...

* Make sure you are logged in as the user with userid "1". That will ensure you will not get stuck (yet) because of some missing authorizations. So after logging in, you should see an URL like `/user/1`. Later on (when you're more familiar), you should create another user with appropriate "*permissions*", and only use `user/1` if really needed.
* Start with creating a "*node*", by navigating to `/node/add` (= Add new content). Pick whatever "*type*" fits for you, typically something like article or page (to get started).
* Complete the form to edit (create) the node, at least add a "*Title*" and "*Body*" (here you insert "Hello Drupal" for now ...), and hit the `Save` button. That will create a new "node", with an url that is something like `/node/x` (x= some digit, if you start a brand new site it is probably '1'). Make sure to memorize the value of "x" (you need it later on).
* Head over to `admin/config/system/site-information`, and find the field labeled "Default Front Page". For this field, enter the value `/node/x` (with "x" the value corresponding the node you created). Then hit the `Save configuration` button.
* Now navigate back to your homepage (also called "*Frontpage*"), eg by just clicking on the logo or some link in the upperleft of your site. After doing so, you should see "Hello Drupal" somewhere on that frontpage.
* On your frontpage, you should have some tabs (typically in the middle near the top) with labels such as "View" or "Edit".
* Use the "Edit" tab to start enhancing your (elementary) homepage. At this point, it may well be that by using the edit link, you get an edit form in which the body field is just some kind of HTML file (not a nice WYSIWYG editor). In that case don't worry too much yet, because it's pretty forward to integrate one of the many wysiwyg editors to simplify the editing of such pages (HOW to do that ... is another question ...). So from here use your HTML expertise and your own imagination to enhance the body of your page with images, hyperlinks, etc.

**Next step(s)**:

* at any time you can change your homepage to another "node" (just revisit `admin/config/system/site-information` to change it to anything else).
* there are waaaaay more sophisticated homepages you can create. And using modules such as Views or Panels you can do amazing things (but that's when you're ready to learn flying ...).

**Homework**:

If you want some type of challenge (extra homework?), try creating a homepage created with Views, and using a "*Grid*" as the views display, with a title and an image in each cell of such grid, and some hyperlink to another page if you click that link. When you're done, post an extra answer to explain the steps you performed ... and maybe a screenprint of the final result ...

**PS**: all paths mentioned are relative (add them after your domain name to create the URL that applies in your case).
> 1 votes

# Answer
Welcome to Drupal,

You can achieve this with following techniques.

1. Install views and all its dependencies.
2. Go to structure create a views of your content types.
3. Select block display instead of page.
4. Display Select image field and in setting click link to original content.
5. Now you will see the block in blocks list. Select the block and render it in your appropriate region on home page.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Rules Workflow: Data selector is invalid
A website that has a workflow system based on Rules, as detailed here

Some of the rules use the condition '**User has role(s)**', and all these rules now show the following error:

> Error: Data selector site:current-user for parameter account is invalid.

The condition must have been valid when it was created, or the rule would not have been saved.

The site uses **Entity API 7.x-1.0-rc3** and **Rules 7.x-2.2**.

Any suggestions? Even deleting and recreating the rule does not work, as I cannot seem to find site-current-user in the Data Selector dropdown.

# Answer
> 1 votes
The problem was with the UUID module. Updating it to the latest version fixed this issue.

Similar problem at: Enabling UUID breaks rules config set by Ubercart.

# Answer
> 0 votes
The error:

> Data selector %selector for parameter %name is invalid.

usually happens when specific parameter is not available at given time.

This is the condition which throws the error (`rules.core.inc`):

```
// ...
elseif (!empty($this->settings[$name . ':select']) && !$this->applyDataSelector($this->settings[$name . ':select'])) {
  throw new RulesIntegrityException(t("Data selector %selector for parameter %name is invalid.", array('%selector' => $this->settings[$name . ':select'], '%name' => $name)), array($this, 'parameter', $name));
}

```

and usually it happens, because the parent token is not listed in `$this->availableVariables()` as per code below:

```
public function applyDataSelector($selector) {
  $parts = explode(':', str_replace('-', '_', $selector), 2);
  if (($vars = $this->availableVariables()) && isset($vars[$parts[0]]['type'])) {
    $wrapper = rules_wrap_data(NULL, $vars[$parts[0]], TRUE);
    // ...

```

---
Tags: 7, rules, workflows
---


# Question
Title: "Languages" not found in Admin/Configuration
I have a Drupal 7.41 in a remote server linux configuration

Installed and Enabled

1. Internationalization
2. Locale
3. Variable
4. Entity Traslation
5. Content Translation

Next, want to Add the Spanish and French languages. But, there is no Languages option seen under "Regional and language" in Admin/Configuration.

What is missing? Tried flushing all caches. No difference. Logged in as admin user/1

# Answer
I found a permission named ***Administer languages***, I make some test with it and I can reproduce your issue. Go to `YOUR_SITE/admin/people/permissions` and search under the ***Locale*** section the ***Administer languages*** permission and give the permission to your user.
> 2 votes

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


# Question
Title: Is there a module or technique to display blocks or panels based on device width?
We have our ads set up as blocks or panels and we would like to prevent wide ads from rendering on narrow (mobile) devices. Additionally, we would like to render other ads only on wide (desktop) devices.

I'm new to drupal and new to the website in question, and I'm having trouble finding where the actual ad calls are made, so I figured the best solution would be to handle this at the block/panel level.

To be clear, I am trying to prevent the ads from even rendering, not just trying to hide them from view once rendered.

# Answer
I'd suggest using the Context Mobile Detect module, which will allow you to set up different contexts for your blocks based on device width.

Otherwise, you could (as suggested in he previous answer) use the Mobile Detect module directly, if the blocks are being rendered in `.tpl` files.

The ideal approach depends on how your theme is built, but without any additional information I'd prefer the Context-based approach.
> 1 votes

# Answer
How about using the Themekey and/or Mobile Detect for switching mobile and desktop version of themes? Here is a quote about these modules (from their project pages):

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.
>
> ... in combination with Drupal's theme inheritance you can easily achieve features like ... "**mobile themes for different auto-detected mobile devices**".

> ... intended to aid developers utilizing mobile-first and responsive design techniques who also have a need for slight changes for mobile and tablet users. **An example would be showing (or hiding) a block or content pane to a particular device.**
> 1 votes

---
Tags: blocks, database, theming
---


# Question
Title: How can I create menu links to external URLs?
With my module *MYMODULE* I would like to create external link and place it into `main` menu. Is it possible to do that in `MYMODULE.links.menu.yml` file or `MYMODULE.routing.yml`?

Something like this???

**mymodule.links.menu.yml**

```
mymodule.googlecom:
  title: 'Google'
  route_name: 'googlecom'
  menu_name: main

```

**mymodule.routing.yml**

```
googlecom:
  path: 'http://google.com/'

```

# Answer
> 6 votes
```
mymodule.menu_external_link:
  title: 'External link'
  url: 'https://www.drupal.org'
  menu_name: main
  weight: 10
  options:
    attributes:
      target: _blank
      class: my-class

```

# Answer
> 4 votes
routing.yml are routes of your site, so they can not be external.

links.menu.yml are links that point to routes, so they can not be external.

To create external links, you need to create them as a menu link content entity in your hook\_install() function.

Something like this:

```
  $menu_link = MenuLinkContent::create(array(
      'title' => 'Link title',
      'link' => ['uri' => 'https://www.example.com'],
      'menu_name' => 'navigation',
      'weight' => 0,
      'external' => TRUE,
      'bundle' => 'menu_link_content',
    ));
  $menu_link->save();

```

---
Tags: 8, routes
---


title: Add Extra fields in User Form

text:
# Question
Title: Add Extra fields in User Form
I want to add extra fields during user registration. I don't Understand Where I can access to user form and user twig, because I want to validate and reformat the Form.

My background is symfony, and I expect The model if I want to add some properties ( in drupal maybe is entity ) and the twig ( the view Parts ), Instead here I don't know where is the user form.

I'm trying to create the module and use some hook, but I don't know if the right way to customize the form

# Answer
You can go to `configuration -> account settings -> manage fields` and add your field. then in the settings check it to show in registration form

```
admin/config/people/accounts/fields

```
> 2 votes

# Answer
You can also create a new profile by going to structure -\> profiletypes and customize fields depending on the profile type if you have distinct profile types.
> 0 votes

# Answer
If you download and install the Address module, it will give you an Address field type you can add to the profile, including dropdown lists for country and region in many countries.

If this doesn't give you what you want, have a look at the Examples module, and in particular at field\_example, which will show you how to create your own field type that can be added to the profile (or any other Entity form in Drupal). This is a much better approach than hacking fields onto the form with hook\_form\_alter, as it uses the power of the Drupal platform and means you are creating a component you can use elsewhere.

Hope this gets you started!

James
> 0 votes

# Answer
The short answer to your question is that Drupal gets its power comes from bringing many different toolsets together. The user registration form is made up of functionalities from many different parts of Drupal's APIs. There is no one place to go to change the working of this form. You can get better help if you ask a number of more specific and focused questions.

You seem to have at least 5 different problems (as elaborated in your comments).

FIELD: You need a field, as @JamesShields said. This can either be a custom field from your custom module, or from the Address module. Installation process for Address requires composer, an is discussed here: https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/

FIELDS: You need to add the field to the user account settings, as @Shabir said, at admin/config/people/accounts/fields

EMAIL: You need to do something to do with emails, either a) modifying the built in emails at admin/config/people/accounts, b) waiting until March when the Rules module hopes to become usable, or c) sending emails from custom code in response to the user registration. I could not find a code example to help with c), you may have to start a new question for that.

REFORMAT: to reformat the form, you need to find the right twig template. Turning on twig debugging is a good place to start with this. See http://www.zyxware.com/articles/4531/drupal-how-do-i-turn-on-twig-debug-mode-in-drupal-8

VALIDATE: If you require validation beyond what is supported by the available fields already, then you want either the entity validation API or the Form API, from custom code. The examples module is a good reference, or a more basic tutorial from Google.
> 0 votes

---
Tags: forms, users, 8
---


title: Commerce order access checks in Views

text:
# Question
Title: Commerce order access checks in Views
I realize this is quite a specific Drupal commerce question, but perhaps I can get some insights as I am stuck here.

I need to control access to commerce orders on a per-order basis based on an entity reference field. So users will not have access to view commerce orders, except if they are related to them.

My custom access check requires an operation, and entity and a user.

Looking at all the hooks Drupal commerce executes in order to determine access:

* `commerce_order_access()` calls the generic access helper, `commerce_entity_access()` for view operations, this constructs an access query based on the entity, which relies on Database API invoking hook\_query\_TAG\_alter(). For orders, this is `hook_query_commerce_order_access_alter()`.
* commerce order's implementation of this hook, `commerce_order_query_commerce_order_access_alter`(), calls a generic implementation back in commerce module, `commerce_entity_access_query_alter()`.
* `commerce_entity_access_query_alter()` checks entity type and user access permissions for the entity and builds an OR conditions array that you can alter for Orders using `hook_commerce_entity_access_condition_commerce_order_alter()`.

All these functions however never get a specific entity to operate on and always check 'global' permissions with `user_access()`. The committed patch Pass entity to Commerce entity access check contexts changes this so the entity is added to the query metadata in `commerce_entity_access()` and as such can also be used in `hook_commerce_entity_access_condition_commerce_order_alter()`.

So far so good, this works and I can check access to my order in `hook_commerce_entity_access_condition_commerce_order_alter()`.

## The real problem

The problem I run into occurs when loading the orders through Views;

Views does not load the entity but just adds it to the select query and then performs the above access checks, starting with `commerce_order_query_commerce_order_access_alter()` (`hook_query_TAG_alter()`). This way the entity is not set (`commerce_entity_access()` is never called) and thus not available for access checking and all there is for me to alter is the query.

## The thing I came up with

Actually the only thing I could think of was to load all commerce order entities, run them all through my access check and save the id's of the allowed orders. Then in `hook_commerce_entity_access_condition_commerce_order_alter()` add all these id's to the query in a condition. I am however afraid this will be a huge performance drop once there have been made some orders

So is there a way I can fetch entities from a Views select query? Or id's? Or do I need to implement my check elsewhere?

# Answer
Your **thing you came up with** is certainly one way of doing it, though you're adding a step. If you can guarantee that your entity reference field will always be on the order, then you could just join your query to the entity reference table and check it against the current user's UID.

Something to the effect of:

```
INNER JOIN `field_order_user_reference` ON `commerce_order`.order_id = `field_order_user_reference`.entity_id
...
WHERE
`field_order_user_reference`.user_id = ***CURRENT_USER***

```

Or something to that effect.

The way you have it implemented now, you will start to see performance degradation since you're adding a lot of overhead. Using pure SQL will help tremendously and you shouldn't see any slowdown.

Alternatively, since your order has an entity/user reference field attached to it, you *should* be able to just add it as a filter and set the filter user as the current one. Maybe not, but if you haven't tried it, it'd be worth a shot.
> 2 votes

---
Tags: commerce, entities, database
---


# Question
Title: GMAP Module map not showing markers after updates with js error: Clusterer is not defined
I've recently taken a live site down for updates and development. I have updated from core 7.39 to 7.41 and updated numerous modules including jQuery update. After the updated, I noticed that my map was zooming to it's max extent and not displaying markers. The only diagnostic error I get is an `Uncaught ReferenceError: Clusterer is not defined.`I can confirm the the markers are being loaded by going into console and logging the drupal.settings.gmap.aut1map.markers variable. I don't have a lot of experience with the GMAP module, so any help would be appreciated. Thanks in advance.

UPDATE: tried to update to dev version, no real change. UPDATE: From what I can tell, it appears that the GMAP version I have installed is has this patch applied GMAP Clusterer.js issues

# Answer
So, it's actually a rookie mistake. Updating the module wipes out all the third party js files you download. took me longer than it should to figure this out.
> 1 votes

---
Tags: javascript, google-maps
---


# Question
Title: How to format QueryPath Xpath Mappings in Feeds Module
I have an XML document with the following structure:

```
<?xml version="1.0" encoding="utf-8"?>
  <ooh>
    <occupation>
      <title type="text">Accountants and Auditors</title>
    </occupation>
    <occupation>
      <title type="text">Another Title</title>
    </occupation>
  </ooh>

```

What do I enter in the QueryPath XML Parser to set the context to be Occupation and add the title as a new source? I tried //ooh//occupation but I keep getting this error: `CSS selector is not well formed.`

# Answer
The context should be the outer most wrapper of each item, so if your XML is

```
<ooh>
  <occupation>
   <title>Some Title</title
  </occupation>
</ooh>
<ooh>
  <occupation>
   <title>Another Title</title
  </occupation>
</ooh>

```

The context would be `//ooh` and the children of 'ooh' would be entered as `occupation` and `occupation/title`.

If occupation is the outermost wrapper of each item like:

```
<ooh>
  <occupation>
   <title>Some Title</title
  </occupation>
  <occupation>
   <title>Another Title</title
  </occupation>
</ooh>

```

The context would be `//occupation` and the title would be entered as `title`
> 1 votes

---
Tags: 7, feeds
---


title: Conditional display of paragraphs items

text:
# Question
Title: Conditional display of paragraphs items
We use Paragraphs quite extensively in our site. We have about 10 bundles available.

What we' like to do is alter how the paragraphs are displayed on various pages; Ie, we'd like to remove bundle a and display only bundle b. Then, in an alternate view, we could have only bundle c and none others displayed.

Short of writing some page/node/paragraphs alters I'm looking for a nice clean way I can achieve this. Maybe 'view modes' for an entire paragraph.

Note paragraphs behave similarly to field collections, so any suggestions for FC are welcome also.

# Answer
> 0 votes
So, I fixed this by writing a new module that creates custom panels panes.

Using the base Panels plugin code seen here http://fourword.fourkitchens.com/article/creating-custom-panels-panes-and-use-substitution-too I created a custom panels pane.

With the custom panels pane, I added a setting for bundles;

```
$bundles = paragraphs_bundle_load();
$options = array();
foreach ($bundles as $key => $data) {
  $options[$key] = $data->name;
}

$form['display_bundles'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => $conf['display_bundles'],
  '#title' => t('What bundles should be displayed?'),
);

```

So when adding a pane in Panelizer, there is a setting for selecting which paragraph bundles are displayed.

Then, when rendering the pane, I check which bundles are allowed and then render them, returning an html block.

```
$nid = $args[0];
$node = $contexts['panelizer']->data;

if ($node->type == 'article') {

  $para_ids = $node->field_nova_section_main[LANGUAGE_NONE];
  $para_ids_array = array();
  foreach ($para_ids as $delta => $data) {
    $para_ids_array[] = $data['value'];
  }

  $return = '';
  $paras = paragraphs_item_load_multiple($para_ids_array);
  $idx = 0;
  $keys = array();
  foreach ($paras as $entity_id => $entity_data) {
    if ($conf['display_bundles'][$entity_data->bundle] !== 0) {
      $return .= render(field_view_value('node', $node, 'field_nova_section_main', $node->field_nova_section_main[LANGUAGE_NONE][$idx++]));
    }
    $idx++;
  }
}

$block = new stdClass();
$block->title = '';
$block->content = $return;

return $block;

```

So now, rather than adding the node field to a Panelized layout, I add my custom pane and select which bundles I display.

---
Tags: 7, entities
---


# Question
Title: How can I change the title tag in header of just one page?
I tried Page Title module however it seems that it can configure page titles only on the content type level.

I can make a temple for this page and write the title directly in there but I don't feel like overriding the template file just for the title tag.

Is there any other way to set the title to just one specific page (node view page)?

# Answer
> 4 votes
You can manage this in template.php file.

```
function MYTHEMENAME_preprocess_page(&$vars) {
    $vars['title'] = $custom_title;
    $vars['head_title'] = $custom_title;
}

```

Just put the condition in the page like for specific path, content type etc. and change the title of the page.

```
function mytheme_preprocess_page(&$vars){
    if (isset($vars['node']) && $vars['node']->type == 'news'){
        drupal_set_title('News');
    }
}

```

# Answer
> 2 votes
Some how I had a problem for front page browser title. Our site name was working properly. But only for front page we can't see browser header title. I used the following code only for front page-

```
/**
 * implements hook_preprocess_html()
 * @param $vars
 */
function YOURTHEME_preprocess_html(&$vars) {
    if(drupal_is_front_page()){
        $vars['head_title'] = "Home | " . variable_get('site_name');
    }
}

```

# Answer
> 0 votes
Try this one:

```
/**
 * Override or insert variables into the html template.
 */
function THEMENAME_preprocess_html(&$vars) {
  switch ($vars['menu_item']['path']) {
    case 'profile-profile/%':
      $vars['head_title'] = implode(' | ', array('Hello!', variable_get('site_name')));
      break;
  }
}

```

---
Tags: 7, theming
---


# Question
Title: How to associate the current Node ID when running from Block layout?
I created a Drupal 8 View that creates a block of content associated with a content type. The block has a context filter of "Content: Node ID". I can place the Node ID of different nodes in the Views Preview and receive different content for each Node ID. The Views Block seems to be working well in Views Preview.

I would like to place this Views Block in a region of Block layout. I need the block to obtain the Node ID of the current node so it will display unique content for each different node -- just like in Views Preview. I have not been able to figure out how to associate the current Node ID when running from Block layout. Some blocks have this ability -- for example "Page title" and "Main page content" that ship with Drupal 8. Is it possible to give me Views Block this ability?

I've thought of two alternatives to what I have written above:

1. write a module that creates the block I need -- obtain the current Node ID and display the Views Block.
2. integrate the Views Block into the twig file associated with the content type -- when the node is displayed, twig will call Views with the Node ID and return the needed content.

Any suggestions?

# Answer
This feature is already present in form of the contextual filters in views (not limited to D8). To do this:

1. Add a contextual filter in your view block of "Content: nid"
2. In "when filter not present" select "provide default value".
3. Select "Content id from the URL".

And this block will automatically take in the nid from the URL.
> 7 votes

---
Tags: blocks, views, 8
---


# Question
Title: Created view is not visible to user one who is not admin
I created a view. If I login as admin I can see the view when I click on the menu link, but if I login as user \[non admin\] then I am not able to see it. I have checked the permissions set but normal user can't access the view, only admin.

Note: If I check the box "Bypass content access control" under node on permission setting page than user is able to see, but edit option is also showing up for user and I don't want user to edit the view.

Can anyone tell me why is it? Apart from this view everything else is working perfectly.

# Answer
> 2 votes
It is definitely a permissions issue. 1. Permission in views edit page under block settings i.e. Access:Permission | View published content

2. May be you have set the permissions for the content type / content to authenticated users. Like if you have set the permission that only Authenticated users can view the Basic Page Content, then as an anonymous user you will not be able to view the content or view.

Thanks.

---
Tags: views
---


title: Dynamic pages through view

text:
# Question
Title: Dynamic pages through view
I need to create dynamic page using `Views`. I created many of static page using `views`, for this simply define page link in view, but when I create `Dynamic page` like `'practice-areas/%'` then it is not working. Here `%` is using for `node id`.

# Answer
> 1 votes
All the pages should share the common path like www.domainName.com/practice-areas/1 www.domainName.com/practice-areas/2 www.domainName.com/practice-areas/3

Like if we need to display a particular block on these URLs then we will write

practice-areas/\*

Similarly % will only work if there is a common path.

Thanks.

# Answer
> 1 votes
You can do it by using views arguments check this video to explain about drupal views arguments, using arguments in views we can create dynamic views of 'page' type display.

# Answer
> 0 votes
You can use contextual filter in views which will pass the argument nid for your path. path will be "practice-areas/%" and for "%" you can set argument nid in contextual filter and set Content id from the URL. So it will work as per your requirement.

---
Tags: views
---


# Question
Title: Is there a module for migrating data from a SQL file?
I have an SQL file containing the data for a Drupal 7 site. I want to migrate data from this SQL file to a fresh, minimally-installed Drupal 8 site that already has all the needed modules.

Is there a module that could load the data from that SQL file and create the required database tables with all the data?

# Answer
> 0 votes
No, that makes no sense. Import it into a database and migrate it from there.

---
Tags: 8, migrations
---


# Question
Title: Which is the preferred way to change field content before rendered?
I'm working on an existing Drupal 7 module in order to make it work with Drupal 8. And for a peculiar aspect of its operation I'm currently a bit lost.

Th problem is that I must be able to make some changes in content of *any* text field, *everywhere throughout all contents*, before they're rendered.

In Drupal 7 I solved it behaving as a formatter, which I "grafted" before any existing formatter.
You can look at this SO post (I didn't know Drupal Answers at this time) to see more precisely how it worked.

After reading a lot of Drupal 8 documentation (which is currently quite messy) I can't yet realize **which is the preferred way to achieve what I want**.
I noticed some candidates such as the `hook_entity_view_alter()`, but also services and/or plugins, but keep totally undecided.

So I look for some advices pointing me to the right way.

# Answer
> 4 votes
`hook_entity_view_alter()` is for altering the render array of an entity, that is coming out of a view mode. It is not for a single field and changes in this hook would have no effect, when using the field alone, for example in a view. Using this hook would be the answer to the question *Which is the preferred way to change the display (view mode) of an entity, before it is rendered?*

(When using this hook, don't digg to deep, you can only change the render elements in the top level. Not the referenced objects, they are only to get information, not to change the rendering)

But the question is to change the rendering of a field, you asked *"everywhere throughout all contents"* For this the right solution is a field formatter, this can be used everywhere in drupal, whenever a field is rendered, no matter if you define a display mode (aka view mode) of an entity or use the field in Views.

To make the picture complete, you can change a field twice while displaying content, first in a field formatter and the second time, when the whole content is build and this build array can be altered in `hook_entity_view_alter()`

In drupal 8 field formatters are no longer hooks, they are now plugins.

https://api.drupal.org/api/drupal/core!modules!field!field.api.php/group/field\_formatter/8

The documentation does not help to setup this plugin. I would copy an example from core and put my own code in it, for example:

```
core\modules\datetime\src\Plugin\Field\FieldFormatter

```

# Answer
> 3 votes
You can do the same in Drupal 8 as well. You can create a new formatter or can extend existing formatter. You need to create a field formatter plugin inside `src/Plugin/Field/FieldFormatter` directory.

```
/modules/random/src/Plugin/Field/FieldType/RandomDefaultFormatter.php

```

You can created a formatter for specific fields type types based on Annotations :

```
/**
 * Plugin implementation of the 'Random_default' formatter.
 *
 * @FieldFormatter(
 *   id = "Random_default",
 *   label = @Translation("Random text"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */

```

You can extend any existing formatter or extend `FormatterBase` class:

```
class RandomDefaultFormatter extends FormatterBase {

```

The method you may want to use :

```
FormatterInterface::viewElements()

```

**Related Links that can help :**

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

http://realize.be/drupal-8-field-api-series-part-1-field-formatters

---
Tags: entities, 8
---


title: Expanded navigation in Books

text:
# Question
Title: Expanded navigation in Books
By default the navigation in books is collapsed:

* **Fruits**
* **Vegetables**

Is there any way to make them expanded, so that the entire tree would be visible?

* **Fruits**
    + Apples
    + Bananas
* **Vegetables**
    + Tomatoes
    + Cucumbers
    + Carrots

Thank you!

# Answer
> 2 votes
The BookTree module does the job. Some details from its project page:

> A simple tree presentation of one book.
>
> What it does is to take as input a series of Book nodes and create a tree-like structure using Book node relationships.
>
> Usage of the module is quite simple and flexible, and options exist to set the root node, the tree depth and to shorten long titles.

The BookTree Example contains a demo of it.

# Answer
> 0 votes
The Menu\_block module allows this. When you create a new menu block you get an option to select book as a menu. More details from its project page:

> So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
>
> So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).

---
Tags: routes, navigation, nodes
---


# Question
Title: geofield types failed to add with commerce services
I have added field of type Geofield that failed to save through services despite working well with node and user modules

It returns that error **400 : Invalid field\_geoloc value given** I am using the same field structure for node and user.

I did some debugging and found that the error comes from file **commerce\_services.module** line 1406 that piece of code

`if (count(array_diff_key($value, $field_info['columns'])) > 0) { return services_error(t('Invalid @field value given', array('@field' => $field_name)), 400);
 }` here is the field structure

```
"field_geoloc": {
    "und": [
        {
            "geom": {
                "lat": "22",
                "lon": "22"
            }
        }
    ]
}

```

Please help me fix it or guide to fix it. Thanks in advance

# Answer
> 0 votes
The answer is to send computed values via the **geofield** module api itself by Implementing the **hook\_request\_parsed\_alter** like:

```
function my_module_request_parsed_alter(&$data, $controller) {
switch ($controller['callback']) {
case 'commerce_services_product_create':
case 'commerce_services_product_update':

  if (isset($data['field_geoloc'])) {
    $data["field_geoloc"] = geofield_compute_values($data['field_geoloc']['und'][0]['geom']);
  }
}

```

But I still wonder why not working by default as node create request

---
Tags: commerce, services, location
---


# Question
Title: Views exposed filter - Replace '-Any-' by Select All
I have a view with an exposed filter of taxonomy terms. Because I'm using charts, when I select the option '-Any-', the chart gets messed up. I noticed that, if I select all terms available instead of '-Any-', the chart looks ok.

So my question is, it is possible to replace the '-Any-' with a select all or, in some way, force the any to select all?

# Answer
> 1 votes
This question is already answered. Please find the answer in below link https://stackoverflow.com/a/5975294/5093173

or use this code

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'view name') {
      $form['filter_name']['#options']['All'] = t('select all');
}

```

}

---
Tags: views, charts
---


# Question
Title: Image style in views field template on image
I'm struggling with a piece of code in my views field template.

A short overview of the situation:

* Node product has a field with filename for an image
* Images are added with filezilla in default/files/products

What is the best way to implement image styles on these images. My code:

```
<?php
 print theme('image_style', array('style_name' => 'product_overzicht', 'path' => $img_url));
?>

```

Where $img\_url is just a simple variable, like: img\_filename.jpg

This doesn't work because the folder of that image style is empty. I know the easy way is to use an image field on my product node but this can't be done here. I use a excel import for all products and the image filename is a column in that excel file. Images are all together in a folder.

Does anybody know a way do this or a good workaround. CSS markup is not good because the image size needs to be as low as possible in the view but on de node details page I would like to show the entire image.

Any tips or advice is welcome!

# Answer
> 0 votes
Try something like this :

```
<img src="<?php print image_style_url('product_overzicht', $img_url);?>">

```

Where **$img\_url** should be **uri**, which in your case can be : *public://products/img\_filename.jpg*

---
Tags: theming, media
---


# Question
Title: How to use user profile fields location fields in a rules component?
I have a case where users will register with the site from foreign countries. I'd like to be able to let the admin know to update the geocoding settings for the country that they register from.

I'm working with rules, location and User-location, and Gmap. What I have so far is this:

```
{ "rules_email_admin_update_geocoding_" : {
    "LABEL" : "Email Admin to update Geocoding",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "site:current-user" ], "field" : "field_location_opt_out" } },
      { "AND" : [
          { "data_is" : { "data" : [ "site:current-user:field-location-opt-out" ], "value" : "0" } }
        ]
      }
    ],
    "DO" : [
      { "component_rules_send_email_to_admin" : {
          "subject" : "Update Geocoding Configuration ",
          "body" : "A new user [site:current-user] has registered with location information, check to see if the user\u0027s address is outside of the US and if the geocoding settings need to be updated to show the user on the map. Go to admin\/config\/content\/location\/geocoding and see if their country is configure. ",
          "from" : "admin@phisigmarho.org"
        }
      }
    ]
  }
}

```

This sends an email to the admin when the location-opt-out field is false, that is that the user entered location information. The issue is that I can't drill any further into the location information than the fact that the user hasn't opted out. This works ok for new users, but I will need to have another rule when a registered user updates their address. This leaves me with a problem, because I can't check the actual values in the locations fields.

So, what's the next step? can I access those values with a php snippet, and if so, how?

UPDATE: So, this appears to be an issue with how Rules interacts with the Fields API.Rules Fields

# Answer
> 0 votes
Install Countries module add field in your registration page. when user register you can value of its location by selecting user country use this value in rules

---
Tags: rules, users, location
---


# Question
Title: How do I make the administrative UI feel like Joomla?
I am working on a way to make a node/add/article page like joomla but but by now I haven't got any remarkable result. I've written this code to hide a part and print it in another part:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['#type'] = 'hidden';
}

```

but I need to di it in preprosess time in order to have more performance. so I use this one:

in .module file:

```
function template_preprocess_article_node_form(&$variables) {
  if (!module_exists('nodeformcols')) {
      hide($variables['form']['additional_settings']);
   }
}

```

in article-node-form.tpl.php

```
<div class="node-add-wrapper clear-block">
  <div class="node-column-sidebar">
    <?php if($sidebar): ?>
      <?php print render($sidebar); print_r($variables['form']['comment_settings']);//['additional_settings'])?>
    <?php endif; ?>
  </div>

```

but I don't have access to all field in this way. any alternative or simpler approach will be appreciated.

# Answer
> 0 votes
You were going in the right direction with:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['#type'] = 'hidden';
}

```

However, you have a bug in that code. The code above will modify *every* form. Instead, use hook\_form\_FORM\_ID\_alter to target the specific form.

---
Tags: theming, 7
---


# Question
Title: Couldn't create range_filter for search index(commerce price)
I'v a Search Api indexing server, I've added an index for price on it, and I want to create a **price range filter** on my created view. I've added the price to the `CONTEXTUAL FILTERS` on my created `view`, but when i go to the `contextual_range_filter` configuration page (`admin/config/content/contextual-range-filter`), I couldn't see the `indexed price` field, so I couldn't use the `contextual_range_filter`.

Note : I need to use Contextual Range Filter module to be able to use the filters with services.

How to make it work by default?

# Answer
> 0 votes
There is an opened issue for the module contextual\_range\_filter with search\_api and the patch patch-contextual-range-filter-search-api.txt will make the range filter work with views based on search api though you could use it for a resource for services.

Another way of achieving that scenario is to use search\_api\_ranges but it won't be controlled by services module.

Hope that helps with your case.

---
Tags: commerce, views, search
---


# Question
Title: how to create a free shipping coupon code in drupal commerce
coupon code with free shipping ,example if coupon is applied to the order, estimated shipping rate (of $4.95) should become $0.00,i have a expedited\_shipping in shipping methods with base amount of 4.95 which will be applied on order .how should i create a coupon for making the expedited shipping to amount zero.

# Answer
Use Commerce Discount and Commerce Coupon.

1. Create a discount that uses the Free shipping offer.
2. Set the conditions (if any).
3. Add a coupon that links to this discount.

Now when the coupon is added to the order and the conditions (if any) are met the shipping method specified in the Free shipping offer will free.
> 1 votes

---
Tags: rules, commerce
---


title: Restrict commerce coupon by user role

text:
# Question
Title: Restrict commerce coupon by user role
I am making a drupal commerce site. For coupon functionality I am using commerce\_coupon module .

My question is How can I restrict a coupon by user roles i.e. a particular coupon should be applicable only for authenticated users .

I have already installed Commerce Coupon - Per user redemption installed which gives me coupon per user functionality . But I want commerce coupon by user roles.

How can I achieve this ?

# Answer
> 0 votes
The coupon's applicability is tied to the discount. Use Commerce Discount and Commerce Discount Extra. Commerce Discount Extra provides an inline condition that lets you specify a user/role condition for an order, which is exactly what you want.

---
Tags: rules, commerce
---


title: AJAX form default values

text:
# Question
Title: AJAX form default values
I'm using an AJAX form to match multiple values of a field to an other entity, to do so i've implemented the example we have in the ajax\_example ( https://api.drupal.org/api/examples/ajax\_example!ajax\_example\_graceful\_degradation.inc/group/ajax\_degradation\_example/7 ), see ajax\_example\_add\_more\*

It is working great (except i would prefer being able to remove the field i want and not always the last one but we can't have everything).

When i submit the form, my chosen values are saved in database and the page is refreshed. The problem is that the form became empty, i might have multiple names for one fieldset and now i only have one empty textfield.

If we continue with the ajax\_example, what i can do is this :

```
$myValues = variable_get('my_var', '');

```

And on this part add a default\_value (let's assume that in my $myValues\['name'\] there is the list of the names)

```
$form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => $myValues['name'],
);

```

In the case where i add only one name, it will work. But if i have multiple name, it will only display the last one.

Do you know how can i do to recreate all the form as it is store in the db ?

Thanks by advance

**\[EDIT\]**

Thanks to sareed, i found the way to do so. I'll show the modification to ajax\_example\_add\_more. In the example there is only one fieldset, in my work there is x fieldset so i will add $fieldsetName to know which one :

Change :

```
 if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }

```

By

```
     $myValues = variable_get('my_var', '');
     if (empty($form_state[$fieldsetName]['num_names'])) {

          if(isset($myValues[$fieldsetName])) {
            $form_state[$fieldsetName]['num_names'] =
              count($myValues[$fieldsetName]) > 0 ? count($myValues[$fieldsetName]) : 1;
          }
          else {
            $form_state[$fieldsetName]['num_names'] = 1;
          }
      }

```

AND

```
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
  }

```

TO

```
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => isset($myValues[$fieldsetName][$i]) ? $myValues[$fieldsetName][$i] : '',
  );

```

# Answer
> 0 votes
Loop through the myValues (only use the foreach if you are not already in a for loop) and use the appropriate array element:

```
foreach($myValues as $index => $name) {
  $form['names_fieldset']['name'][$index] = array( // Already using $i here. Are you in a for loop?
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => $name, // Or $myValues[$i]['name'] if you are already in a for loop (it looks like you might be).
  );
}

```

Depending on the structure of the array you may have to change this a little. If these don't work and you can't figure it out, add a print out of one of your smaller arrays using print\_r to your question and we can help.

---
Tags: forms, ajax
---


# Question
Title: How to get a list of modules implementing hooks?
Is it possible to get a list of defined hooks for debugging purposes?

I have implemented `mymodule_datalayer_meta()` for `datalayer`'s `hook_datalayer_meta()`. However, as far as I can tell, it's not firing. I'd like to look up a list of hooks that modules implement so I can see if my module is actually implementing it or not.

# Answer
> 4 votes
You are looking for the module\_implements function

> Determines which modules are implementing a hook.

Use this function in the devel/php form, for example.

```
dpm(module_implements('THE_HOOK'));

```

This way you can see easily if your module implements 'THE\_HOOK'.

# Answer
> 4 votes
If you've got access to drush (and you want to use it), you can use `drush hook menu` (this is obviously for `hook_menu`)

# Answer
> 1 votes
Hooks are not stored in the database, but they are actually cached into the table `cache_bootstrap`. See this answer for a clue on how to see a list of cached hooks.

# Answer
> 0 votes
The PhpStorm IDE can also tell you where a hook is used (= implemented).

* Click on the arrow up left to your hook implementation to go to the hook documentation in an .api file and there you can click on the arrow down to see all implementations of it.

---
Tags: hooks
---


# Question
Title: services display for search index based view
I am building a search page using view. the view get results from search index created and have indexed nodes and it works fine and display results as expected

the problem comes when trying to add services display for the same view it only display as in the picture

please help to make services display from views based on search api

# Answer
> 0 votes
You may use the "block" display on your view instead of "services" display to avoid this issue as the views has many issues with search api and services views

---
Tags: services, search, views
---


# Question
Title: Using view result as an input filter for another view
Let me explain my scenario at first.

I have two content types in my site.

First is **products** and second is **producer**.

Each product has only one producer and each producer has one or more products.

Now in every product page, I want to show the producer information. I made a view block for this issue and it works well.

but in the product page, I also have a plan to show all products of the producer of current product in another block.

In order to show the product nodes of a specific producer I need the node ID of producer content type.

I tried to use **Contextual filters** --- **Provide default value** "When the filter value is NOT available" via **Content ID from URL** but this function returns node ID of current product not producer id. (because we are in a specific page of single product)

Now I am searching to find a solution for this issue.

thanks a lot for your guidance.

# Answer
> 1 votes
Say, the term reference field in the product content type is called "field\_ref\_producer". You need to have this block of code, and a view that accepts a contextual filter for "term reference producer ID" ready.Let this view be called "other\_products\_producer"

```
$node = menu_get_object();
$output = '';
if(is_object($node)) {
  $producer_id = $node->field_ref_producer['und'][0]['tid'];
  $output = views_embed_view('other_products_producer', 'default',$producer_id);
}
echo $output;

```

Basic idea is, grab the node object from URL, get the producer tid from it and then embed a view passing the producer nid as contextual filter to the view.

Update:

Code to put in views PHP (default value of contextual filter):

```
$node = menu_get_object();
if(is_object($node)) {
  $producer_id = $node->field_ref_producer['und'][0]['tid'];
  return $producer_id;
}

```

Please replace the name of the field to what you have in your content type.

# Answer
> 1 votes
If the entity reference field is in the producer content type, this solution might work:

Add another field in your view - "the entity reference field" (i.e.field\_ref\_producer if your entity reference field is called field\_ref\_producer).

Use the relationship : Entity Reference: Referenced Entity

Use the contextual filter Content:nid Provide default value "When the filter value is NOT available" via Content ID from URL. (This function returns node ID of current product not producer id.) "

When you render the view, you will get a list of the products from the producer.

What this does is, it essentially (w.r.t. to the above case) uses the product id to locate the producer id (using the entity reference field) and then display the products ( i.e. all referenced entities) associated with the producer id.

# Answer
> 0 votes
Here is modified codes from Neo.

```
$node = menu_get_object();
if(is_object($node)) {
    if(isset($node->field_producer['und'][0]['nid']))
    {
      $producer_id = $node->field_producer['und'][0]['nid'];
      return $producer_id;
    }
}

```

I added isset function for the nodes that don't have specific referenced field producer. (for example in pages or articles)

Thanks a lot Neo for you help.

---
Tags: views
---


# Question
Title: How can I get more than 10 search results on one page?
By default search page shows only 10 results. How can I change it to display unlimited number of results?

# Answer
> 15 votes
I recommend using views for this. Views comes with a search view included (disabled by default). Use an exposed search term filter to provide the search functionality, and customize other aspects of the view as needed.

# Answer
> 5 votes
Drupal does not currently give you an option to change the number of search results per page. As @beeradb suggests, you can use the Views module (video tutorial for D7 at http://lin-clark.com/blog/intro-drupal-7-intro-views-pt-1).

There is a feature request for this to go into Drupal 8 http://drupal.org/node/702940.

# Answer
> 4 votes
In Drupal 7, I have been able to modify the core search result items per page using hook\_query\_alter in a custom module. The following code snippet can be used, if you're familiar with using hooks in code:

```
<?php
/**
 * Implements hook_query_alter
 */
function MY_MODULE_query_alter(&$query) {

  // This is a search result query and we want to change the
  // number of search results per page to 16.
  if ($query instanceof PagerDefault
    && ($tables = $query->getTables())
    && isset($tables['i']['table'])
    && $tables['i']['table'] === 'search_index') {
    $query->limit(16);
  }
}

```

# Answer
> 0 votes
I didn't find 'search view' in views module. I am using views 7.x-3.7.

To get more than 10 search results on one page in Drupal 7, I have used search\_config module. I used it's latest version '7.x-1.1-beta2'.

Once the module is enabled, you can configure the pager limit from Configuration-\>Search and metadata-\>Search settings (admin/config/search/settings) under 'ADDITIONAL NODE SEARCH CONFIGURATION' section. You will see 'Results' section there and you can specify pager limit to show more than 10 search results on one page.

# Answer
> 0 votes
The default search view seems to have been removed from the Views module, so here's one I knocked up quickly that you can use as a starting point for your own requirements. Use the Views import dialogue and paste in the code to import it.

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'search test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'input_required';
$handler->display->display_options['exposed_form']['options']['text_input_required'] = 'Enter some search keywords.';
$handler->display->display_options['exposed_form']['options']['text_input_required_format'] = 'filtered_html';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '20';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'No results found.';
$handler->display->display_options['empty']['area']['format'] = 'filtered_html';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Search: Search Terms */
$handler->display->display_options['filters']['keys']['id'] = 'keys';
$handler->display->display_options['filters']['keys']['table'] = 'search_index';
$handler->display->display_options['filters']['keys']['field'] = 'keys';
$handler->display->display_options['filters']['keys']['operator'] = 'required';
$handler->display->display_options['filters']['keys']['exposed'] = TRUE;
$handler->display->display_options['filters']['keys']['expose']['operator_id'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['label'] = 'Search Terms';
$handler->display->display_options['filters']['keys']['expose']['operator'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['identifier'] = 'keys';

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

```

# Answer
> -2 votes
You can use search limit module too or use following code in template.php

```
if(arg(0) == "search" && arg(1) == "site") {

$variables['quantity'] = 5;

}

```

---
Tags: 7, search
---


# Question
Title: Views block in custom region rendered outside of page.tpl
I have custom regions rendered inside of the node.tpl.php file which work as expected, but results in a php error when blocks created by the views module is placed in them.

```
 [:error] [pid 2563] [client 127.0.0.1:35606] PHP Fatal error:  Maximum execution time of 30 seconds exceeded in /filepath/sites/all/modules/devel_themer/devel_themer.module on line 333

```

Other blocks all work fine the regions and the views blocks work fine in all regions called by `page.tpl.php`. The error only occurs when the two are put together. There are no other log messages and the page just returns a blank screen so I'm not quite sure what the problem is or how to go about fixing it. I'm using the code below in template.php to make the region available outside of `page.tpl.php`

```
function smark_design_theme_preprocess(&$variables) {
  if (block_get_blocks_by_region('region_name')) {
    $variables['region_name'] = block_get_blocks_by_region('region_name');
  } else { $variables['region_name'] = FALSE; }
}

```

And this to call the region in `node.tpl.php`

```
<?php if ($page): ?>
  <?php if ($region_name): ?>
    <div id="region-name">
      <?php print render($region_name); ?>
    </div>
  <?php endif; ?>
<?php endif; ?>

```

# Answer
> 1 votes
It's not normal to render regions inside a node template, and this is one reason why. If you display a node in a block in one of these regions, that's going to result in an infinite regression in which node.tpl.php calls itself (indirectly, via several other theme calls).

Reconsider the structure of your theme.

# Answer
> 2 votes
Searh your php.ini and change the value of `max_execution_time` to:

```
max_execution_time = 300

```

By default php.ini have 30 seconds and PHP needs more time to process it, in this case you have 300 seconds.

**EDIT:** As you say in your comment that your problem persist, you can use the following solution, but you need know that your site can take a lot of time to process your request.

Edit the file `YOUR_SITE/sites/default/settings.php` and add this in the second line and save the file:

```
set_time_limit(0);

```

Read more about this function at php.net

---
Tags: 7, views, blocks, theming
---


# Question
Title: Should we use a separated database for our data set?
We are working in website and integrating the Drupal Commerce in our website. We are also adding multiple product per product display to allow user to select products while adding product to cart.

The website will have large data set with more than 10 million product display (node) and more than 30 million products (drupal commerce).

We have also integrated *apache solr* with *search api* and allowing user to keyword search and filtering the search result.

Can anyone suggest that if we would stored such large data into single database, will it effect our performance or we need to stored data into 'master/slave' concept of database?

As we have large dataset, so we are preparing architecture of our database, so it would not effect performance of our website.

# Answer
> 4 votes
**Talk to your hosting provider. If they can't answer these questions, get a new hosting provider.**

These really are concerns you should bring to your hosting provider. A quality hosting provider will be able to meet these needs and tailor a solution that ensures smooth operation of a site as a whole and within the individual components: Solr, MySQL, Apache/Nginx/Litespeed/etc.

How will they do this?

* **Benchmarking** \- Before launch, they'll launch a version of the site and then work to ensure that certain performance criteria are met. They'll tweak and scale to meet these numbers.
* **Infrastructure** \- Just having a master/slave DB isn't necessarily a solution. You have to have good infrastructure and equipment backing it up. It also has to be architected well. Good providers will have this.
* **Multiple Layers of Scalability** \- Having multiple strategies to handle load or large sites is key. This means not just having a huge DB but also effective content distribution (CDN) and internal Drupal caching (Redis) in addition to strong infrastructure.

# Answer
> 0 votes
Performance in drupal have many aspects to deal with as it pops up you will Implement the needed solution personally I don't think the numbers you mentioned scared you to go with drupal.

Suppose you have a big number of products as you mentioned but still your store is not famous to have big traffic so every thing will be ok with default settings as a regular drupal website.

Search api with solr is a great step will serve you a lot, varnish, mongodb or redis will reduce load on DB servers.

# Answer
> 0 votes
The database layer and query builder allows drivers to specify case-insensitive operators. This allows MySQL to use LIKE() for auto-complete and user name lookups instead of LOWER(), allowing these queries to use indexes rather than doing a full table scan.

There is also built in master/slave support with the database layer, although Drupal can’t yet set up your database replication for you (or fold your laundry).

Proper planning of your database structure and optimization techniques will lead you to a very good solution.

I would suggest to have a look at this.

---
Tags: 7, commerce, performance
---


# Question
Title: Update manager fails to move files from tmp
I've this configuration:

* Fedora Core 21 (64bit)
* vsftpd: version 3.0.2
* Drupal 7.41

I have a unix user called user1 who has home dir /home/user1 and Drupal root is at /home/user1/www

The Drupal temporary directory is at /home/user1/tmp

I'm trying to install the Corporate Clean theme using the update manager but it fails giving this message:

> corporateclean Error installing / updating File Transfer failed, reason: Cannot move /home/user1/tmp/update-extraction-5345b836/corporateclean/comment-wrapper.tpl.php to /www/sites/all/themes/corporateclean/comment-wrapper.tpl.php

I checked ownership and permissions of `/home/user1/tmp/update-extraction-5345b836/corporateclean` and it's owned by apache and permissions are like so:

> 755 drwxr-xr-x 7 755 apache 4096 Dec 9 07:05 corporateclean

Is this the right permissions / user for the extracted directory by the update manager? The owner / permissions is causing the issue and not allowing the move.

# Answer
> 1 votes
After reading Enable FTP on your server i applied the changes as mentioned in the `/etc/vsftpd/vsftpd.conf` file.

The changes applied are

```
Linux Instructions (UNSECURED):

Step 1:  sudo  yum  install  vsftpd

Step 2:  sudo emacs /etc/vsftpd.conf
Uncomment these settings:
listen=YES
local_enable=YES
write_enable=YES
local_umask=022
anon_upload_enable=YES
anon_mkdir_write_enable=YES

Step 3:  sudo service vsftpd restart

```

i then changed the ownership of the drupal root to apache user

`chown -R apache:apache /home/user1/www`

and this fixed the problems for me. am able to install themes via FTP method.

**Please note - the method i've used is potentially insecure. Don't use on production server.**

Thanks.

Yashesh

# Answer
> 0 votes
I am not sure it will help you or not. Please use the following command to sure the directory owner permission.

```
ls -l

```

If you see the www-data missing then you can try the following command

```
sudo chown www-data:www-data /home/user1/tmp

```

---
Tags: 7, installation
---


# Question
Title: Group search results by content type and limit count
I am trying to group search results by its content type. Also, I want to show not more than 4 results per content type.

For an assumption, it should look like this:
**Content type1-**
Result1
Result2
Result3
Result4
**Content type2-**
Result5
Result6
...

I am able to achieve this using TEMPLATE\_preprocess\_search\_results().

```
function custom_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  $resultTypes = array();

  // Divide results
  foreach ($variables['results'] as $result) {
    $resultTypes[$result['bundle']][] = $result;
  }

  // Create fieldsets
  foreach ($resultTypes as $resultType => $resultTypeResults) {
    $value = '';
    $i = 0;

    foreach ($resultTypeResults as $result) {
      $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
      $i++;
      if ($i == 4) {
        $value .= l(t('Show more'), current_path(), array('query' => array()));
        break;
      }
    }

  $variables['search_results'] .= theme('fieldset', array('element' => array('#title' => $resultType, '#children' => $value));
  }
}

```

But this is not an optimal method, since I trimmed down the results per content type (but actually they exist). Say if Content type1 has 10 actual results and Solr's maximum results per page is set to 10, then I will end up showing first 4 results of only Content type1.

Please suggest an ideal method to list 'n' matched results of every content type.

Thanks!

# Answer
You can increase the page limit by apache solr hook

```
function custom_apachesolr_query_alter($query) {
  if(strpos($_SERVER['REQUEST_URI'],'/bundle/') == false)
    {
  $query->replaceParam('rows', '400'); // Note that high value increases response time
  }
}

```
> -1 votes

---
Tags: search
---


# Question
Title: Is there a way to import Drupal variables into a the twig template?
I save a configuration setting using the following code.

```
$config = \Drupal::service('config.factory')->getEditable('report.settings');
$config->set('id', $values['id'])->save();

```

Is there a way to use this configuration in my twig template?

I thought about putting PHP code in the template, but it doesn't seem the PHP code added with `<?php ?>` is executed from the Twig template.

# Answer
You can't directly use these functions in a Twig file. Instead, you can preprocess the page and store your configuration settings in a variable that is passed to the template file, and display that variable in the template file.

```
function mytheme_preprocess_page(&$vars) {
  $vars['new_var'] = $config->get('id');
}

```

You can render your variable with `{{ new_var }}`.
> 6 votes

---
Tags: 8, theming, configuration
---


title: Group search result by content type

text:
# Question
Title: Group search result by content type
I am using apachesolr on my drupal 6 website for search. Now I wanted to use filter results by content type on search page. At first I was using a panel page as search page. Here I tried to use the apachesolr filter by content type block. But this didnt work. I tried all other facets available with apachesolr module and all others worked fine. Now I thought maybe filter by content type doesnt work with panels quiet well so i removed the panel page and used the apachesolr default search psge. Still it doesnt work for me.

Can someone tell me some method for grouping my search results by content type.

# Answer
I have used same thing in Drupal 7 . Please check if this can help

```
Function custom_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  $resultTypes = array();

  // Divide results
  foreach ($variables['results'] as $result) {
    $resultTypes[$result['bundle']][] = $result;
  }

  // Create fieldsets
  foreach ($resultTypes as $resultType => $resultTypeResults) {
    $value = '';

    foreach ($resultTypeResults as $result) {
      $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));

  $variables['search_results'] .= theme('fieldset', array('element' => array('#title' => $resultType, '#children' => $value));
  }
}

```
> 0 votes

---
Tags: search
---


title: Know field type usage

text:
# Question
Title: Know field type usage
I need to know if a field type is used on a website in a content type. How can I know that with Drush or Drupal BO?

# Answer
> 2 votes
This should give you a list of the fields and types on your site.

```
drush field-info fields

```

Should output something like this

```
 Field name               Field type            Field bundle
 body                     text_with_summary     page,article
 field_image              image                 article
 field_category           entityreference       article
 field_name               text                  article

```

---
Tags: entities, 6, drush
---


# Question
Title: Payment Gateway integration on selecting user profiles
I am working on a project where human resource agents can view a list of job applicants. On each job applicant profiles theres a **Confirm job applicant** link visible only to human resource agents. Once the HR agent clicks on **Confirm job applicant** link, the control should go to a payment gateway and after the HR successfully does the payment, the job applicant should get confirmed by that HR agent.

I was thinking to use ubercart module to handle all the payment transaction, but is ubercart the best choice for this type of workflow as theres no product shopping cart model here.

Is there any other module which can be used for the above workflow?

# Answer
> 1 votes
Drupal Commerce would probably be a better choice. I've used it on two non-standard ecommerce systems and it works well. It's very flexible and the rules integration would allow you to do things like comfirm and email applicant on order completion.

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


title: view handler date not working

text:
# Question
Title: view handler date not working
I am creating views handler for date in `hook_views_data`. All other fields working fine but date. I am assigning `views_handler_field_date` and `views_handler_filter_date` in fields and filter respectively.

The problem is that when I select date field in views I get empty response as well as got bunch of errors.

# Answer
I am not sure what your code looks like, but my suggestion is to use custom handler if the core is not working. I used custom handler in almost all my projects if I get any issue in core handler. Example is:

```
/**
 * A handler to display dates as just the time if today, otherwise as time and date.
 *
 * @ingroup views_field_handlers
 */
class views_handler_cusom_field_date extends views_handler_field_date {

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['date_format']['#options']['example_custom'] = t('My custom format');
  }

  function render($values) {
    $format = $this->options['date_format'];
    $value = $values->{$this->field_alias};
    // check for our custom format
    if ($format == 'example_custom') {
      // check to see whether value is whithin today range
      $timezone = new DateTimeZone("Australia/Melbourne");
      $date = new DateTime();
      $date->setTimezone($timezone);
      $today = strtotime($date->format('Y-m-d 00:00:00'));
      if ($value >= $today) {
        // this value is still within today
        return format_date($value, 'custom', 'g:i A');
      }
      else {
        // this value is older than today
        return format_date($value, 'custom', 'j M Y g:i A');
      }
    }
    // otherwise render the date using the normal date handler
    else {
      return parent::render($values);
    }
  }

}

```

And then call this custom handler in your date field

```
'date' => array(
           'title' => t('Date'),

           'field' => array(
              'handler'=> 'views_handler_cusom_field_date'
              'click sortable' => TRUE,
           ),

```
> 0 votes

---
Tags: 7, views, hooks
---


# Question
Title: Ctools modal_form not working with webforms
i have been trying all morning to get my webform to open up within ctools modal\_forms popup window. i’ve tried *everything*, but nothing has worked so far.

the module is working no problem. this form window displays as expected.

```
mywebsite.com/modal_forms/nojs/register

```

and my webform is published and working

```
mywebsite.com/webform/free-trial

```

but when viewing docs and tuts on the module, the URL would seem to be

```
mywebsite.com/modal_forms/nojs/webform_free-trial

```

i’ve also manually created links such as this

```
<a class="ctools-use-modal" href="/modal_forms/nojs/webform/free-trial">Modal Login</a>

<a class="ctools-use-modal" href="/webform/free-trial">Modal Login</a>

```

even went to the config page and set,

PAGE ACTIVATION SETTINGS/Only the listed pages

```
webform/free-trial

```

Mondo Aggro! any help would be greatly appreciated, thank you

# Answer
> 0 votes
I would recommend you to create your own menu item where you should load and print the webform using examples from the ctools module.

# Answer
> 2 votes
The issue is your modal link path isn't correct. When using Webforms the link needs to use the Node ID (nid), not the form clean-url (`/modal_forms/nojs/webform/[nid]`) Here's how the link would look considering your example above:

```
<a class="ctools-use-modal ctools-modal-modal-popup-large" href="/modal_forms/nojs/webform/123123">Free Trial</a>

```

---
Tags: forms, chaos-tool-suite
---


# Question
Title: Drupal 7 Date - Is there a way to change field settings if there is data in it already?
Currently I am using the date module for drupal 7 and I already have stored data in the existing date field. I want to make changes to the date field by adding "Repeating Dates", but obviously I cannot since I have data in there already. The options I came up with are:

1. Create a completely new date field for the content type with the additional "Repeating Dates" feature. Then copy all the old dates into the new field (im not sure how to do this easily)
2. Modify the existing Date field table via phpmyadmin or mysql console.

What is the suggested way to go about updating an existing field that already has data?

# Answer
You could take a look at this contrib module too https://www.drupal.org/project/entity\_recur
> 0 votes

# Answer
I got this working by doing the following without having to write any code. Keep in mind im only doing this for the DATE type fields:

example:

my old field: field\_eventdate

my new field: field\_placeholder

1. create the same field type with a different name and the options you want.
2. open up phpmyadmin
3. goto the table: field\_config
4. search for the new field you created (field\_placeholder)
5. click on the data column blob and download that.
6. search and **edit** field\_eventdate and upload the file you downloaded which contains the new settings.
7. do the same exact thing for the table: **field\_config\_instance**
8. now we have to update the table structures of the field to encompass these changes. I first inspected the strucuture of the new field i created and see what the old table was missing. Once you have that down, create the missing columns in the old field that exists in the new field.
9. Do #8 again but this time for the revisions table. In my case it would be: **field\_revision\_eventdate**
10. delete the field\_placeholder via the content type page as you wont need it anymore.

let me know if this worked for anyone else too.
> 2 votes

# Answer
A more secure way than touching the database...

1. First create your new field with the repeating date, let's call it field\_event\_date
2. Then copy everything from the first field (field\_date) to your new one

Code:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', {your_content_type})
  ->addMetaData('account', user_load(1));

$result = $query->execute();
foreach($result['node'] as $nid => $n) {
  $node = node_load($nid);
  $node->field_event_date = $node->field_date;  // Copy one field to another
  node_save($node);
}

```
> 2 votes

# Answer
I went about it by first capturing the original Date field with Features. Then, I created a field like I would like to target (similar to what you'd done with the placeholder) and Features-exported it. I compared the exported code and updated the original field's Feature export code, SQL-dumped the data from the field\_data\_field\_.. table, deleted the original field by Manage Fields screen, feature-reverted to the modified Features export code, and then SQL-imported from my export. voila!
> 1 votes

---
Tags: 7, entities, datetime, migrations
---


title: get node id of field collection

text:
# Question
Title: get node id of field collection
I have the following code. I am able to load the field collection item using entity\_load\_single. I want to be able to get the node id for a given field collection item. How can I achieve this?

```
function dc_car_guide_model($model_id)
{
    $model = entity_load_single('field_collection_item', $model_id);
    //How can I get nid?
}

```

# Answer
```
$model = entity_load_single('field_collection_item', $model_id);
$node = $model->hostEntity();
echo $node->nid;

```
> 9 votes

# Answer
Using EntityFieldQuery:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->fieldCondition('field_MYCOLLECTIONFIELD', 'value',  $model_id, '=');
  $result = $query->execute();

  if (!empty($result['node'])) {
    $nid = key($result['node']);
  }

```

replace `field_MYCOLLECTIONFIELD` with the machine name of the Field Collection field on your node.
> 0 votes

---
Tags: nodes, entities
---


title: Cannot Unflag a User Programmatically

text:
# Question
Title: Cannot Unflag a User Programmatically
This is all programmatic: in a module.

I have a flag that I can set successfully, but I cannot unset/unflag. I do not know why, as the code seems so similar.

The flag is set in a \_submit function of a form:

```
  // Enable the global user object
  global $user;

  //Flag the user as having MyExample credit
  // Invoke the Flag API to set the flagging. This also saves the flagging entity.
  $flag = flag_get_flag('MyExample_credited');
  $flag->flag('flag', $user->uid);

```

I can detect this flag successfully in other functions using this code:

```
if ($flag->is_flagged($user->uid)) {

```

However, unflagging is not working. Here is the code:

```
  // Enable the global user object
  global $user;

  $markup .= 'Removing credit...<br>';
  //Unflag whether the user has MyExample credit
  $flag = flag_get_flag('MyExample_credited');
  $markup .= 'Flag status:' . $flag->is_flagged($user->uid).'<br>';
  $flag->flag('unflag', $user->uid);
  $markup .= 'Flag status:' . $flag->is_flagged($user->uid).'<br>';

```

This produces the following output:

> Removing credit...
>
> Flag status:1
>
> Flag status:1

Testing the flag on other pages also confirms that it has not been unflagged.

Why could this be? Nothing in any of the error logs. Is it to do with how I have declared the flag, perhaps?

```
function MyExample_flag_default_flags() {
  $flags = array();
  $flags['MyExample_credited'] = array (
    'entity_type' => 'user',
    'title' => 'MyExample Credit',
    'global' => 1,
    'types' =>   array (),
    'flag_short' => 'Give credit',
    'flag_long' => 'Give this user a MyExample credit',
    'flag_message' => 'Credit given.',
    'unflag_short' => 'Remove credit',
    'unflag_long' => 'Remove a MyExample credit for this user',
    'unflag_message' => 'Credit removed.',
    'unflag_denied_text' => 'You cannot remove this credit.',
    'link_type' => 'toggle',
    'weight' => 0,
    'show_in_links' => array (
      'full' => 0,
      'heartbeat_user' => 0,
      'token' => 0,
    ),
    'show_as_field' => 0,
    'show_on_form' => 0,
    'access_author' => '',
    'show_contextual_link' => 0,
    'show_on_profile' => 0,
    'access_uid' => '',
    'module' => 'MyExample',
    'locked' => array (
      'global' => 'global',
      'status' => 'status',
    ),
    'status' => true,
    'api_version' => 3,
  );
  return $flags;
}

```

# Answer
Could it be a permission issue? Maybe set the "skip\_permission\_check" at true, as said in documentation here: https://www.drupal.org/node/1748148#flagging
> 0 votes

---
Tags: flags
---


# Question
Title: How do I automatically update database tables when changing custom entity fields
New Drupal Developer here.

I am currently working on a inventory management module for a friend. And I ran into a bit of a snag with Custom Entities in Drupal 8.

I have a custom "Customer" entity content type which stores various bits of information about the customer, first name, last name, a number which we assign each customer, etc...

When I added a new field post-module-install, after running update.php, cron, etc... The new field was never added to the existing SQL table.

I am wondering if there is something I'm missing, like a way to force update the database without having to manually add the new table.

Here is the new field I added.

```
$fields['l_number'] = BaseFieldDefinition::create('string')
        ->setLabel(t('L#'))
        ->setDescription(t('The Customer\'s L Number.'))
        ->setSettings(array(
            'default_value' => '',
            'max_length' => 8,
            'text_processing' => 0,
        ))
        ->setDisplayOptions('view', array(
            'label' => 'above',
            'type' => 'string',
            'weight' => -7,
        ))
        ->setDisplayOptions('form', array(
            'type' => 'string',
            'weight' => -7,
        ))
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE);

```

# Answer
> 1 votes
Using hook\_update\_N() as linked in @cilefen's answer is way to do it when you have an existing sites with data and want it to make easier for users to run your updates.

If you're doing the initial development on a development environment, then I'd consider just re-installing the module (that's pretty fast with drush pmu -y module; drush en -y module).

You can also try drush entity-updates. If you don't have/know drush yet, you're missing out: https://github.com/drush-ops/drush

# Answer
> 0 votes
There are published examples using hook\_update\_n().

---
Tags: entities, 8, database
---


# Question
Title: How to make the Charts module use the Highcharts legend option "useHTML" (required for RTL)?
I tried using the Charts module with Highcharts as my charting library (engine). And this for a block view in a multilingual site that flips between LTR and RTL.

I found out that the **legends** and **tooltips** break in RTL. The legends labels overlap the colored boxes and the text within the labels is pushed outside of the tooltip box.

I managed to make the tooltips presentable through the use of `$chart['#tooltips_use_html'] = TRUE;` (in 'chart\_alter'). Although the text is aligned wrongly the out of box issue disappeared.

However I found no similar option for the legend. I looked at the Highcharts documentation where I found a `useHTML` option for fixing this issue with legends. But I am unsure about how to apply it with the hooks provided by the Charts module.

Here is a picture of it:

# Answer
You should be able to get this to work using the approach as described in the issue about Pass library-specific options via existing #raw\_options, AFTER you apply the patch in comment nr 4 of this issue.

Disclosure: I'm a (co-)maintainer of this module.

PS 1: Would be nice/great if you could confirm that this patch also worked for you.

PS 2: after a similar patch becomes available to Google charts also, both patches will be committed.
> 2 votes

# Answer
Thanks to the help of Pierre.Vriens, here are the lines of code I used in a custom module to adjust Highcharts for display on localized RTL pages:

```
function hook_chart_alter(&$chart, $chart_id) {
  $chart['#tooltips_use_html'] = TRUE;

  global $language;

  if ($language->name == 'Arabic') {
      $chart['#raw_options'] = array(
        'labels' => array(
            'useHTML' => True
          ),
        'legend' => array(
            'useHTML' => True,
            'rtl' => True
          )
        );

      if($chart['#legend_position'] === 'left'){
        $chart['#legend_position'] = 'right';
      }

      if(isset($chart['yaxis'])){
        $chart['yaxis']['#opposite'] = TRUE;
      }
  }
}

```

This fixes almost everything, except the tooltips text alignment and the legend title positioning. Both persist to stay aligned to the left as shown here in the cropped chart to the right:

I found no options in Highcharts documentation for adjusting the legend title, so I settled for omitting it as shown to the left. As for the tooltip text misalignment, I managed to rectify it easily by adding the following CSS to Theme.styles-rtl.css:

```
.highcharts-container {
    text-align: right !important;
}

```

Another image of a column/line chart in RTL and LTR just because:
> 1 votes

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


# Question
Title: Validate and submit function for my fom aren't working
So I'm trying to create a form with a validate and submit function, here is my code :

the form :

```
    function custom_form() {
      $form = array();
      $form['field1'] = array(
        '#type' => 'textfield',
        '#title' => t('Field1'),
        '#required' => TRUE
      );
      $form['field2'] = array(
        '#type' => 'textfield',
        '#title' => t('Field2'),
        '#required' => TRUE
      );
      $form['field3'] = array(
        '#type' => 'textfield',
        '#title' => t('Field3'),
        '#required' => TRUE
      );
      $form['submit'] = array(
        '#type'=>'submit',
        '#value'=>t('Submit')
      );
      return $form;
    }

```

the validate function :

```
    function custom_form_validate($form, &$form_state) {
      if(empty($form_state['values']['field1']))
        form_set_error('field1','field1 is empty.');
      else if(empty($form_state['values']['field2']))
        form_set_error('field2','field2 is empty.');
      else if(empty($form_state['values']['field3']))
         form_set_error('field3','field3 is empty.');
    }

```

and the submit function :

```
    function custom_form_submit($form, &$form_state) {
       drupal_set_message("Form has been submitted");
    }

```

But when I click on submit nothing appends, do I forget something ?

EDIT : Here is all my code (I'm using shortcode module to create a custom shortcode in order to show my form)

```
    function custom_form_info() {
      $shortcodes['form'] = array(
        'title' => t('Link form'),
        'description' => t('A simple form.'),
        'process callback' => 'custom_shortcode_form',
      );
      return $shortcodes;
    }

    function custom_shortcode_form($attrs, $text) {
      $form = drupal_get_form('custom_form');
      $attrs = drupal_render_children($form);
      return $attrs;
    }

```

# Answer
Add the following lines to your custom\_form function:

```
$form['#validate'][] = 'custom_form_validate';
$form['#submit'][] = 'custom_form_submit';

```

Clear the cache afterwards and you will be good
> 0 votes

# Answer
Reading your comments, you mentioned you are using the shortcode module to create this simple form. I'm not familiar with this module, but, honestly, I think it's just easier to follow the "traditional" way of creating forms in Drupal explained in many tutorials, including this one, which uses `hook_menu()` in a custom module to create a path to the form. All your code in your first post will work just fine - the only difference is that, instead of using `custom_form_info()` you would use something like this.

Be sure to **name the implementation of hook\_menu()** with the name of your module (in this case below, the module would be called `my_module.module`).

```
function my_module_menu() {
 $items['path-to-my-form'] = array(
    'title' => 'Example Form', //page title
    'description' => 'My form.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_form'),
    'access callback' => TRUE
  );

  return $items;
}

```

Include the rest of your functions (`custom_form()` and the submit and validate handlers) in the same module.

To visit your form follow www.example.com/path-to-my-form
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to revolve TinyIMCE error 'The version of TinyMCE could not be detected'?
I installed these modules: Wysiwyg, IMCE Wysiwyg bridge, IMCE.

Then downloaded the libraries from:

https://www.tinymce.com/download/ (developer edition, community doesn't even have a non minified imce.js file...)

Now the file structure is not the same as the instructions from Drupal Backend:

```
Extract the archive and copy its contents into a new folder in the      following location:
sites/all/libraries/tinymce

So the actual library can be found at:
sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js

```

So I deducted I had to change folder structure from:

```
sites/all/libraries/tinymce/js/tinymce/tinymce.js

```

To:

```
sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js

```

But still not working, I get this error:

```
TinyMCE (Download)  Not installed.
The version of TinyMCE could not be detected.

```

# Answer
> 3 votes
You need use the last dev version of Wysiwyg, you can read more about this here.

And you need read the Supported Editors Matrix.

I download the 3.5.11 version of TinyMCE from here and copy the tinymce folder to `YOUR_SITE/sites/all/libraries/` so inside this folder you must have this:

So I have installed:

Wysiwyg 7.x-2.x-dev
TinyMCE 3.5.11

And it works ;-)

---
Tags: 7, wysiwyg, files
---


# Question
Title: How do I move the "Login or Register to Post Comments" links?
I would like to move the "Login or Register to Post Comments" link from above the comments to below the comments, yet above the comment form.

I have the link variable available in the preprocess\_node hook and I can unset it there, but when I try to add it as a variable with another name, it's not available in comment-wrapper.tpl.php.

I guess I'm asking what the Drupal way is to pass this variable from the node to comment-wrapper.tpl.php. It's important that we copy the variable value instead of manually creating the links in so we have the same value for the login and register links regardless of whether another module has acted/changed them.

# Answer
> 2 votes
The "Login or Register to Post Comments" link is created via:

```
theme('comment_post_forbidden', array('node' => $node));

```

so I'd create a variable with that in the appropriate preprocess hook that has `$node` available.

# Answer
> 1 votes
Use

```
theme('comment_post_forbidden', array('node' => $node));

```

---
Tags: 7, theming, comments
---


# Question
Title: How to get user data when I provide the uid or username - Services
I am using postman. I want to provide the *username* or *uid* and fetch the user's information. What should be the URL.

# Answer
URL to fetch the user information by providing uid as follows.

```
http://[yourdomain]/[endpoint]/user/[uid]

```

Example: `http://www.example.com/rest/user/2` will fetch user information, having user id 2.

You can get the user data by providing username, you can use pass name (username) as a parameter to the service URL like follows

```
http://example.com/<endpoint path>/user?parameters[name]=krishna

```

If you have enabled session authentication you might have to pass X-CSRF-Token in headers. For session authentication you can find my answer here
> 2 votes

---
Tags: services
---


# Question
Title: How to show files with lighbox/colorbox effect?
My goal is to create a gallery of all media of the site. I created a views-page of type file with bootstrap grid format that displays all file type of my site (File: Mime type (has word jpeg jpg png gif YouTube)).

My first problem is to get lightbox or Colorbox to display the file on click on the page. Is there any way I can get lichtbox in code (css, function,...) or views showing only file.(Note I'm not using fields but file). That mean when I'm on the views-created page, I can click on any file(image or video) and it react with lightbox overlay.

The second one is to remove certain content type files from the views display. (I don't want user profile images to be displayed or private files).

Thirdly, i want to create a menu to sort the file per type(image, audio, images, and taxonomy terms.) Maybe there is a good tutorial for this on google. I couldn't find anyone, ;)

# Answer
> > My first problem is to get lightbox or Colorbox to display the file on click on the page

For this you need to set either lightbox or colorbox module. Once you install and enable the site you will see the option in file field to show the file in lightbox.

> > he second one is to remove certain content type files from the views display

Add a filter criteria `File Usage: Entity type` or `File Usage: Entity Id` and exclude user entity.

> > Thirdly, i want to create a menu to sort the file per type

For this you need to add a sort criteria based on your `File:Mime Type`
> 2 votes

# Answer
1)install "Image URL Formatter" module

2)go to the field settings of your view find "image" field from which images are comming click on it a Configure field: dialogue box will open you will see "Formatter " option in it change it to "image url " by this you will get url of your image

3)add global custom:text field check replacement pattern fetch the replacement pattern of your image url

write some code like this in global custom:text-\>

`<a class="colorbox" href="[field_place_image_1]" rel="lightframe[|width:400px; height:300px; scrolling: auto;]" >image</a>`
> 0 votes

---
Tags: views, files, media, javascript
---