# Question
Title: Storing uploaded files according to node ID
When a file/image is uploaded via Drupal, they go into a common directory specified by the administrator.

However, is there a way to specify where the files will be uploaded, according to their node ID? For example, say, a person creates a page and Drupal assigns it an ID of `1234`; thus, the uploaded files will go into `{specified_location}/1234_files/`.

# Answer
> 3 votes
You can use the File (Field) Paths module in combination with the Token module for this.

1. Enable module
2. Go to admin/structure/types/manage/your\_content\_type/fields/your\_file\_field
3. Make sure **Enable File (Field) Paths?** is enabled.
4. Under **File (Field) Path settings** you can now use e.g. myfiles/\[node:nid\]

# Answer
> 1 votes
Try the File (Field) Paths module with Token module

Token

> Tokens are small bits of text that can be placed into larger documents via simple placeholders, like %site-name or \[user\]. The Token module provides a central API for modules to use these tokens, and expose their own token values.

File (Field) Paths

> The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.

On the file field edit page you can use Replacement Patterns for File Directory field

---
Tags: 7, files
---


# Question
Title: Text formatting in the "Help Text" section
I'm wondering where the formatting is set for the "Help Text" section. I was thinking that maybe it was plain text, but it does not appear to be so - I want to use the module Collapse Text to collapse the text and make the help text available to the user only if they want to view it, while filling out their registration form.

Is there a way to do this, or will I have to write a third party module?

This is the module I want to use with the help text.

https://drupal.org/project/collapse\_text

# Answer
The Advanced Help module will let you create help texts that can be tied to a help icon on any page, form or form item. Clicking the icon will pop-up a Ajax window with the text.
> 0 votes

---
Tags: 7
---


# Question
Title: Translated terms are not searchable with Search API
While using Search API it does not index the translated/localized terms.

So does it mean translated terms are not searchable with Search API?

any clue? thanks

# Answer
> 2 votes
I think that this is core issue that the search index does not add the localized term to the index, I solved that by implementing hook\_node\_update\_index($node) and fetching the localized term name by querying it from database because I don't know why i18n\_taxonomy\_localize\_terms function doesn't load the term properly. my code is below:

```
function mymodule_node_update_index($node) {
  $text = '';
  $tid = key($node->your_taxonomy['und'][0]['tid']);
  if($tid != 0) {
    $query = db_select('locales_target', 'lt');
    $query->addExpression('CONVERT(translation USING UTF8)', 'translation');
    $query->join('locales_source', 'ls', 'ls.lid = lt.lid');
    $query->condition('context', 'term:'.$tid.':name');
   $text = $query->execute()->fetchColumn();
  }

  return $text;
}

```

Note: in my case the text is Arabic so I converted the field character set from blob to utf8.

---
Tags: taxonomy-terms, i18n-l10n, search
---


# Question
Title: Show users pictures who have flagged a node
I have a event node and a flag to join the event. I want to show the user pictures who have flagged "Join event"

This is what I have done so far

1.Created a Node View

2.Added a relationship Flags: Node flag (select the required flags and tick "Include only tagged Nodes"

3) Added another Relationship Flags : User

4) Added Relationship "Content Author"

4) Added contextual filter: Content: Nid \> Content id from URL \> Specify validation criteria \> Flaggable = Join Event

5 ) Add field User Picutre

Many thanks for your help

# Answer
> 2 votes
I think you'll have to create a *user* view, displayed as a block, and use the flag relationship to the nodes. Then use a contextual filter, taking the node NID from the URL as default.

---
Tags: 7, views, flags
---


# Question
Title: What is a front page in drupal ($is_front)?
Nice to know for drupal beginners:

What is a front page in drupal and particularly in which case is $is\_front true ?

# Answer
> 11 votes
`$is_front` is set on any template from `_template_preprocess_default_variables()` (itself called from `template_preprocess()`). It uses the result of the `drupal_is_front_page()` function.

`drupal_is_front_page()` will returns TRUE, if the path of the current page matches the `site_frontpage` configuration variable. This variables can be set from the "*Site Information*" configuration page.

Usually there is only a single front page on a Drupal site. If you use the Variable translation module (part of the Internationalization project), then you could translate the `site_frontpage` configuration variable and have a different front page for each enabled language.

It may also be possible to have other module alter the value of the variables on each request to have multiple front pages. Additional module may also alter the value of `$is_front` in all or only a few specific templates. However, I cannot think of any useful use case for this, except torturing the template developer with inconsistency.

# Answer
> 1 votes
**`drupal_is_front_page()`** \- returns the bool value `true` if it's the front page.

---
Tags: theming
---


# Question
Title: How do I upgrade to Google's Universal Analytics using the Google Analytics module?
I have a site using version 1.4 of the Google Analytics module and I wanted to upgrade to Universal Analytics. The module page says that I need the 2.x version of the module, so I updated to 2.x-dev, ran update.php (no updates necessary), and cleared the cache.

I then logged into Google Analytics and went to **Audience -\> Demographics -\> Overview**, after which I clicked **Validate tracking code**, but this failed.

So, I went to the module's config page (*admin/config/system/googleanalytics*) and checked **Track display features** under **Search and advertising**. I then cleared the cache.

I again tried to re-validate but it continues to ask me to validate.

What more do I need to do to upgrade to Universal Analytics?

# Answer
I upgraded to 2.0, cleared the cache several times, and then waited about an hour-- now it works! So I guess sometimes you just have to wait a bit after upgrading.
> 1 votes

---
Tags: google-analytics
---


title: Building EntityForm in Drupal 8

text:
# Question
Title: Building EntityForm in Drupal 8
I'm continuously getting the error: `Drupal\Core\Config\Schema\SchemaIncompleteException: Incomplete or missing schema for mymodule.myentity.myentityname in Drupal\Core\Config\Entity\ConfigEntityBase->toArray() (line 248 of core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php).`

Here is how I'd implemented the EntityForm:

```
class MymoduleForm extends EntityForm {
  public function form(array $form, array &$form_state) {
    $form = parent::form($form, $form_state);
    $entity = $form_state['entity'] = $this->getEntity();
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => empty($entity->name) ? '' : $entity->name,
      '#required' => TRUE,
    );
    ...
    ...

    return $form;
  }
  public function validate(array $form, array &$form_state) {
    parent::validate($form, $form_state);
    $entity = $this->getEntity();
    //perform validation
  }
  public function save(array $form, array &$form_state) {
    $entity = $this->getEntity();
    $entity->save();
    print_r($entity);
    //throws error here

    $edit_link = \Drupal::linkGenerator()->generateFromUrl($this->t('Edit'), $this->entity->urlInfo());
  }

```

Doing a `print_r($entity)` shows two Object results: one showing all the values I'd filed up in the form and the other completely emplty.

# Answer
> 3 votes
That error has nothing to do with your form.

You need to provide a config schema for your config entity, see examples in node.schema.yml and many other places.

See also the configuration schema documetation.

---
Tags: forms, 8, entities
---


# Question
Title: How to get administration views to work?
As my content began to expand into a large repository I started to miss the feature of being able to filter content by a simple "title contains" criterion. I found out Administration Views that got installed by Admin Menu. However, the content view is contaminated by a known bug. It allegedly comes from incompatibility with VBO. This prevents the view from functioning or being edited.

Is anyone successfully running admin views, caring to list the module versions for Views, VBO, Admin Menu?

# Answer
I'm sure your problem is already gone by now but for those who might be searching for ways to make Admin Views and VBO work, the versions I'm using are 7.x-1.3 and 7.x-3.2 respectively.

You would need to clear Drupal cache for the default admin pages to be overridden by the newly added Admin Views.
> 2 votes

---
Tags: views, nodes
---


# Question
Title: How to display a field of a referenced entity in views contextual block?
I have read several questions on topic, e.g.   , but couldn't manage to get it work.

**My setup:** In a Drupal 7 environment, I have a node type called `organizer`, which contains two fields: node title (default) and a link (to the organizer's website). A second node type called `event` contains several fields one of which is an entity reference to `organizer`.

My site's design only has the node title and node body of an event being displayed in main content. All other fields are displayed in a sidebar using a views block with filter on node type (`= event`) and a contextual filter on node id. Among these fields is also the field `organizer` and it's displaying the organizer's name (title field) alright.

**My goal:** Now I want to have the organizer's name link to the organizer's website. But the link is actually a field inside the `organizer` content type.

**My approach:** I've added a relationship to `Entity Reference: organizer`. Then I added the link field that is used in the `organizer` content type to the list of fields using the relationship. I rearrange the fields to have this link field being loaded before the entity reference field. Then I set up the latter field to being rewritten as link using the plain url from the link field. \[The link field is currently being displayed for debug purposes, later I want to exclude it from display, of course.\]

**My result:** The link field is always empty. Hence, the organizer's name is never linked to the respective website.

***Questions I stumbled upon:*** When I add a relationship, I have two options like

```
Entity Reference: Referenced Entity
A bridge to the Content entity that is referenced via field_organizer
 Entity Reference: Referencing entity
A bridge to the Content entity that is referencing Content via organizer

```

My understanding is that I have to user the first one, because I want to load the organizer that is referenced in the event. \[The second one I would be using, if I have a organizer and want to get all events that are referencing this organizer, right?\] However, I tried both options to no avail.

Is the ordering of fields relevant? I've tried both having the link field before and after the entity reference field, it stays empty in both cases.

Since each event could have more than only one organizer, the entity reference field is set to allow unlimited values. Could that cause a problem?

Could anyone point me into the right direction of what I am missing?

---

***UPDATE:*** It seems to break the system if you have both relationship types set up at the same time or maybe the ordering plays a role, too. However, when the first relationship in list is the one I need it kind of works.

It is working absolutely fine for a **single** organizer, the name is displayed and linked to the organizer's website. But it will not work for any additional organizers. The block lists all organizers (when having more than one) but each of them is linked to the first organizer's website.

Thinking about how that works, that is reasonable, since the relationship only adds **one** related object. When displaying a field (e.g.) from that relationship it will be the same for each delta of entity reference field.

Actually, in that case I should be able to define how the entity reference field is displayed. It already has an option to link to the entity itself but you can't define any fields from the entity to be shown (e.g. instead of title).

# Answer
> 0 votes
I found a complete different approach which doesn't require relationships at all.

First, I installed the Display Suite module. It allows you to create new view modes for your content types. So, I created a new view mode called `entity`.

Next, I enabled this view mode in the desired content type (-\> manage display) and only view the link field.

Further, I edited `node.tpl.php` (you can use also a more specific theme file like `node--organizer.tpl.php`) to hide the node title when the view mode is `entity` using an `if` construction:

```
<?php if ($page && $title && $view_mode != 'entity'): ?>
  <h1<?php print $title_attributes; ?>><?php print $title ?></h1>
<?php endif; ?>

```

Last, I edited the view and set the display option for the `organizer` field from `Label` to `Rendered entity` using the view mode `entity`.

Et voilà, the organizers are now displayed linking to the organizers' respective websites.

Note: This works for me because each link in a organizer node has its title set to the node title.

# Answer
> 2 votes
The solution is a two step solution, but first you need to decided if you are going from Parent to Child or Child to Parent.

**Background info**

If you are going from Parent to Child, you setup a relationship using the "referenced" variable.

If you are going from Child to Parent, you setup a relationship using the "referencing" variable.

To make life simple for myself, when I specify the relationship, I also using the Administrative Option on the Reference Window and enter a more understandable name for the relationship. In you case, since I would make the Admin Name Event reading Organizer or something like that.

1. Setup a relationship for Event reading Organizer in the Relationship field under the Advanced tab.
2. Once you have related your Event content type to the Organizer content type, you should now be able to see the Organizer fields appear in your list of available fields. Select the fields from the Organizer content type that you want to appear in your view and hit Apply. Here is the CRITICAL part, once you have defined a Relationship, a new drop down menu (Relationship) will appear on the Configure field windows. For any fields that is in another table, you MUST choose the appropriate relationship for the field. In your case, you would choose the Event reading Organizer relationship. This relationship instructs view to go Organizer table and bring back that field. If you do not specify the relationship in the Configure field windows, this will not work.

Attached is a copy of the Configure field with a relationship. Note: In your example, you would want the referenced variable. But in my example, I was working with the referencing variable. Please do not let that confuse you. Just image the word in the relationship is referenced.

If you have any questions, please post them here and I will respond.

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


# Question
Title: Using Simple jQuery click() events in Drupal 7
I've been able to get jQuery to load and work for some basic things such as:

```
(function ($) {
  console.log('jquery called');

  $(document).click(function() {
    var h1 = $('h1').text();
    console.log(h1);
  });
}(jQuery));

```

However, when I try to do the following, nothing happens.

```
(function ($) {
  $("h1").click(function() {
    alert('clicked!');
  });
}(jQuery));

```

I'm wondering if this has something to do with when the .js file gets called. I suspect that the document element already exists, so having a click event on it is no problem. However, I think that the h1 elements don't exist by the time the click event is loaded. I've tried the .bind() and .on() functions as well, with no luck.

Any ideas?

I call my .js file from my theme's info file, not sure if that matters.

# Answer
```
(function ($) {
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.ss2 = {
  attach: function(context, settings) {

  $("h1").click(function() {
    alert('clicked!');
  });
}}

})(jQuery);

```

be careful with braces at the end, and rename ss2 as you want, it's just for example...
> 2 votes

# Answer
So figured out that having your jQuery called in the footer after all the dom elements load works much better for things like click events. Here is how I got it to work:

* Open your theme's **template.php** file
* In the **ThemeName\_preprocess\_html(&$variables)** function add the following:

> ```
>     drupal_add_js(drupal_get_path('theme', '**ThemeName**') . '/js/**FileName**.js', array(
>       'scope' => 'footer',
>       'weight' => '15'
>     ));
>
> ```

* Have your **FileName**.js file look something like this:

> (function ($) {
> //insert your jquery here $('h1').click(function() { $(this).hide('slow'); console.log('h1 clicked!');
> }); }(jQuery));
> -1 votes

---
Tags: javascript
---


title: Export my block configuration

text:
# Question
Title: Export my block configuration
I have used configuration management to export and import my drupal configurations.However,when i add a new block,the configuration management can't track the change of block and i can't export the configuration.I want to know whether the configuration management can track the block and export block configuration.

# Answer
Configuration Management module does not support exporting blocks. See https://www.drupal.org/node/2125089 for more info.

There are several other modules than can help you with this:
> 1 votes

---
Tags: blocks
---


title: Empty page.tpl.php renders data too

text:
# Question
Title: Empty page.tpl.php renders data too
I created my own theme in Drupal 7. It is not sub-theme. Simple I created a folder at sites/all/themes/my\_foundation, a template.info as usual, then an empty page.tpl.php.

I expected that a blank white page is obtained after enabling the new theme and visiting the home page. However, I have got a page with some contents as screenshot:

I need to know how it was occurred and how could I get the expected behavior?

# Answer
This is the expected behavior if page.tpl is missing:

Since your theme does not print anything in page, the Core system module (the one that defines page.tpl.php etc) takes over and drupal uses system's page.tpl.

I suppose that if page.tpl is **empty** the default page array is rendered with any region that exists in your theme's.info and has content.If regions exist, Drupal will try to render them even without template.
> 1 votes

# Answer
Use empty\_front\_page module.

By Install and active this module front pagecin drupal is clear.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: add a search bar on a page and limit it to search only under post titles?
I wand to add a search bar on a page called "dictionary" and want to limit it to post titles. I mean it should search only texts in posts tiles not the whole posts contents. Please explain me clearly step by step how to do it.

Regards Ismail

# Answer
> 0 votes
Use custom\_search module.

By this module you can create customize search form that searching on custome content type and custome fields on content type.

---
Tags: views
---


title: Empty <li> items within Rules UI

text:
# Question
Title: Empty <li> items within Rules UI
Has anyone encountered behaviour similar to this and have any idea how to resolve it? I've checked the issues for Rules and can't find anything similar. I've run update.php and flushed caches, neither make a difference. Also tried completely uninstalling Rules and Rules UI and reinstalling from fresh.

# Answer
> 0 votes
This is odd, but it's probably not rules-centric. It looks like the system itself is in a funky state. Have you had any other problems with white screens? Do your mysql logs show any errors (I have seen similar problems when the `max_allowed_packet` size was too small, for example, or when the mysql server ran out of disk space.)

---
Tags: rules
---


# Question
Title: Checking if a machine_name exists or not
My EntityForm has a field where

```
  '#machine_name' => array(
    'exists' => array($this, 'load'),

```

To check the validation of this, I wanted to know about writing the function `load()` in my `EntityListBuilder` to check its validation.

A way around would be to use `ctools`:

```
ctools_include('export');
$result = ctools_export_load_object('module_entityname', 'names', array($field_id));

```

However, I wanted to avoid using `ctools`. Are there any Drupal 8 APIs available to check the validation of `#machine_name`?

# Answer
> 4 votes
The `exists` key wants a callback that it can test for boolean true/false. The machine name to test will be passed as the first (and only) argument to that callback.

Since your entity class (not the list builder class) already has a load method, inherited from `Entity::load()`, which accepts an ID and returns either an entity object or a null/false value, you can (and probably should) use that.

So, assuming your entity is defined as `\Drupal\mymodule\Entity\MyEntity`, you would use the following:

```
'#machine_name' => array(
  'exists' => '\Drupal\mymodule\Entity\MyEntity::load',

```

Exactly the same method is used in the `CommentTypeForm`, and probably others:

```
$form['id'] = array(
  '#type' => 'machine_name',
  '#default_value' => $comment_type->id(),
  '#machine_name' => array(
    'exists' => '\Drupal\comment\Entity\CommentType::load',
  ),
  '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
  '#disabled' => !$comment_type->isNew(),
);

```

---
Tags: forms, 8, entities
---


# Question
Title: How to debug hook_form_BASE_FORM_ID_alter not working?
I am at wits' end. I have a clean install of Drupal 7.28 and a custom module with the following two hooks:

```
/**
 * Implements hook_form_alter().
 * /
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state, 'form_alter');
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 * /
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state, 'BASE_FORM_ID_alter');
}

```

And that is *all* there currently is in the custom module.

I have verified that the the `base_form_id` for the *Article* node form is `node_form`, by printing it out (using `dpm($form_state)`. This is what is printed:

```
base_form_id (String, 9 characters ) node_form

```

And yes, I *have* cleared the cache (I've even restarted apache and rebooted the server).

I believe my code is identical to what is shown in numerous tutorials about how to use `hook_form_BASE_FORM_ID_alter()`.

Still, when I open the form to create an article, the first hook (`hook_form_alter()`) fires, and the second (`hook_form_BASE_FORM_ID_alter()`) does not.

This hook is in 54 functions in the core, so it is very unlikely that it just does not work.

As I said, I am at wits' end.

Has anyone a suggestion for what to try next?

# Answer
Not sure if relevant but I while copying your code I did received a warning. Warning: Unterminated comment, but perhaps that sneaked in while placing the code in the question.
> 1 votes

# Answer
These are always fun... First, did you clear your cache? You always have to clear your cache when adding or changing a hook, and, to be honest, your code looks correct.

Second, to find out the BASE\_FORM\_ID, to better target a node edit form, you can do this to output all the form ids on the page:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  dsm($form_id);
}

```

You may discover that the more-targeted `$form_id` is something like `article_node_form`. I have seen it both ways.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How can render a Block on a Contact form Page
I want to render a Block on a special content type page and on the contact form page. All works fine, but i didn\`t found any way to print the Block also on the contact form page.

i use in the page.tpl.php:

```
if(isset($node) && $node->type === 'page') {
   ....
}

```

Hope someone can help! Thx

# Answer
Following the logic exactly as you have laid it out, you could test for

```
if (arg(0) == 'contact')

```

to output the block on the contact page. However, is there a reason you're not using the block admin page to place this block instead? Other options here that might be easier to maintain would be:

* place the block in the region you want using the Context module
* copy the page.tpl.php file from your theme to page--contact.tpl.php and add your block content there
> 1 votes

---
Tags: emails, theming
---


# Question
Title: Outputing the field as link doesn't properly show the field properties
I want to output an image field as a link in a view. I've seen many tutorials but get stuck at one point.

I already added the link on top of the image field. By clicking on the image at rewrite results, I could check *Output this field as a link*, but checking it won't give me the fields properties where I could fill in the link field details, as shown in this screenshot.

>

Do you know what I'm missing?

These are the other view settings for that field.

>

# Answer
Check this thread: https://www.drupal.org/node/1494860

Basically, upgrade to latest version of cTools and set the admin jQuery version to 1.5 via jquery\_update.
> 0 votes

---
Tags: 7, views, navigation
---


# Question
Title: Programmatically submit user reset password form
I have a register form that I am able to submit programmatically without any problems.

However when I try to do the same with the user reset password form, it doesn't send me any emails, nor does it do any validation.

Here's the code I'm using:

```
$form_state = array();
$form_state['values']['name'] = $_POST['username'];
$form_state['values']['submit'] = t('E-mail me new password');

drupal_form_submit('user_pass_form', $form_state);

```

Note: I've tried using `user_pass` instead of `user_pass_form`.

What am I doing wrong?

# Answer
> 1 votes
An alternative approach is this:

```
global $language;
$account = user_load_by_name($username);
if ($account) {
// Mail one time login URL and instructions using current language.
$mail = _user_mail_notify('password_reset', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
}

```

Essentially all you need is:

```
_user_mail_notify('password_reset', $account, $language);

```

More info: user\_pass\_submit

# Answer
> 1 votes
Have you verified that the username you are submitting is valid? If it isn't, this will fail validation. In addition, it is a bad practice to use $\_POST directly in Drupal. It should also definitely be drupal\_form\_submit('user\_pass',... not 'user\_pass\_form'.

---
Tags: 7, forms
---


title: presidency of drupal template file

text:
# Question
Title: presidency of drupal template file
I am new to drupal themeing, I have tried to find the presidency of template files(.tpl.php).. So my question is for a particular scenario if I have html.tpl.php, page.tpl.php, block.tpl.php, node.tpl.php, taxonomy-term.tpl.php, template.php,

1. which file going to run first?
2. if I want to make change some variable's value for page.tpl.php/html.tpl.php then I need to write a function XXX\_preprocess\_page()/XXX\_preprocess\_html() according to this listed presidency (https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7) ?

# Answer
Answer 1:-template.php file will runs first.you can check it by using die() on top of all files.

answer2 :-For changing some variable's value for page.tpl.php/html.tpl.php use function function XXX\_preprocess\_page().

**html.tpl.php** -\> Handles meta info, body classes

**page.tpl.php** -\> Handles content body display

**node.tpl.php** -\> Handles content display

**field.tpl.php** -\>Handles per field display

Template.php provide display alteration for all these files.
> 0 votes

# Answer
html.tpl.php will always be used before page.tpl.php (unless you hack core in some way). typically, variables available in html.tpl.php are not the same as variables available in page.tpl.php, so you shouldn't have an issue with conflicts. What exactly are you trying to do?
> -1 votes

---
Tags: theming
---


# Question
Title: How to create dynamic select list in form using FAPI
I am using Drupal 7. I have created two form (FAPI) fields of type `select` , State and District. The district field should contain the dynamic options based on the state selected.

State field:

```
 $form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
  ),
  '#options' => $options,
  '#required' => '1',
  );

```

District field:

```
 $form['district'] = array(
  '#title' => t('Name of your District:') ,
  '#type' => 'select',
  '#default_value' => array(
  ),
  '#options' => district_list($form_state['values']['state']), // district_list is the function which will return the list of district based on name of state passed.
  '#required' => '1',
  );

```

The above code doesn't work, is there anything I am missing ?

# Answer
> 1 votes
You need to use the #ajax property in your State select list, with a callback function that returns the district element. So something like this:

```
$form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
   ),
  '#options' => $options,
  '#required' => '1',
  '#ajax' => array(
    'callback' => 'MY_MODULE_state_ajax_callback',
    'wrapper' => 'edit-district',
 );

```

then create a callback called `MY_MODULE_state_ajax_callback($form, &$form_state)` and within the function,

```
MY_MODULE_state_ajax_callback($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    return $form['district'];
}

```

It may be slightly more complicated than this, based on your use-case, but this is the meat of it.

---
Tags: 7, forms
---


# Question
Title: Placing exposed filters (with BEF) in various Panel regions
So, my question is basically the same as How to show in different positions exposed filters in a View? However, the answer here did not work for me (and I could not post a comment there because I don't have 50 rep -- very sorry). I follow the steps outlined exactly and I only have the option to place "View exposed widgets" with no sub options.

Basically, I'm trying to place my exposed filters in various places within the display (almost identically to the referenced ticket). I'm running Views with type of Context and using Better Exposed filters. According to quite a few places, that should allow me to place the individual filters in whichever region of the Panel I desire. However, I don't see them.

Any advice?

# Answer
> 0 votes
did you finally find a solution for this? You could use the module MEFIBS which allows you to put your filters (and sort) into different blocks.

Anyway, MEFIBS didn't work for me because of the fact that all blocks get seperate submit button. So it would be interesting for me to hear how you finally ended up with this.

Best, Thomas

---
Tags: panels, views
---


title: Converting JSON to select list options

text:
# Question
Title: Converting JSON to select list options
I have an array that I have JSON decoded from a JSON object. Below is my array I am using for select options. The problem is each select options has a option group with a number (0-11). How can I convert this array to one that does not have these numbers in front of it?

Here is my array:

```
    array(21) { [0]=> array(1) { [198413]=> string(23) "option1" } [1]=> array(1) { [247598]=> string(24) "option2" } [2]=> array(1) { [195666]=> string(17) "option3" } [3]=> array(1) { [195632]=> string(22) "option..." } [4]=> array(1) { [243763]=> string(24) "option..." } [5]=> array(1) { [196600]=> string(13) "option..." } [6]=> array(1) { [196597]=> string(11) "option..." } [7]=> array(1) { [196592]=> string(16) "option..." } [8]=> array(1) { [196549]=> string(17) "option..." } [9]=> array(1) { [251324]=> string(10) "option..." } [10]=> array(1) { [195564]=> string(50) "option..." } }

```

Here is my code:

```
      $result = drupal_http_request('https://'.$key.'@'.$company.'.example.com/example.json');
    $feed_array = json_decode($result->data, TRUE);
    $projects = array();
    foreach ($feed_array['todo-lists'] as $project) {
    $projects[] = array(
    $project['id'] => $project['name']
    );
    }

```

# Answer
> 3 votes
The easiest way to do it would be to iterate through the array

```
$options = array();
foreach($project as $option_group)
{
   $options[key($option_group)] = next($option_group);
}

```

Or, if you can't count on there being only one element in each option group, do:

```
$options = array();
foreach($project as $option_group)
{
   $options = array_merge($options, $option_group);
}

```

---
Tags: forms, 8
---


# Question
Title: ajax form element sometimes triggers submit
I have found some strange behaviour of form ajax elements.

I have added #ajax to my form elements:

```
['#ajax'] = array(
  'callback' => 'mymodule_ajax_callback',
  'event' => 'change',
  'progress' => array('type' => 'none'),
);

```

and due to some other issues, i had to add ajax to my submit:

```
$form['actions']['submit']['#ajax'] = array(
  'callback' => 'mymodule_node_form_submit',
);

```

The issue is, when the form element ajax is triggered for "checkboxes" and "select" form field type at the same time, then submit callback is triggered but i never clicked submit.

Does anybody have any idea?

# Answer
> 0 votes
There is a quirk in the AJAX form api which causes the last button on the form to be submitted under certain circumstances. Without seeing all of your code, it would be difficult to isolate the problem.

---
Tags: ajax, forms
---


# Question
Title: Trigger highlight in maparea when mouseover on link
I've created a content type where I can load an image into a text editor and use Image Map Editor to create area to be highlighted when mouse moves over mapped region. At the same time, below the image, a list of persons in that image is displayed. This names are coming from a taxonomy terms list. How can I highlight the area when I move my mouse on the name below the image? I guess I need a javascript which looks for the id namelist, grabs the text for each link, finds in the map with the map id "mapname123" the area hith the same name and changes its state to hovered. I hope I've used the correct words to describe the situation. Thanks in advance.

```
<div style="background: url(http://image.url.jpg);">
  <canvas style="width: 800px; height: 450px;"></canvas>
  <img src="image.url.jpg" usemap="#mapname123" alt="" class="maphilighted"></div>
<map id="mapname123" name="mapname123">
  <area shape="circle" coords="213,301,36" alt="John Doe" title="John Doe" href="#1">
  <area shape="circle" coords="334,312,32" alt="Fred Flintstone" title="Fred Flintstone" href="#2">
  <area shape="circle" coords="437,317,33" alt="Wilma Flintstone" title="Wilma Flintstone" href="#3">
</map>

<p id="namelist">Name List:<br>
  <a href="/imagemap-ki%C5%9Filer/193" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="" class="kisiler">John Doe</a>,
  <a href="/imagemap-ki%C5%9Filer/192" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="" class="kisiler">Fred Flintstone</a>,
  <a href="/imagemap-ki%C5%9Filer/191" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="" class="kisiler">Wilma Flintstone</a>, </p>

```

# Answer
> 1 votes
An IT guy delivered the solution. Here the code

```
jQuery(document).ready(function() {
    jQuery('a[typeof].kisiler').each(function() {
        var txt = jQuery(this).text();
        var maps = jQuery('area[title="'+txt+'"]').attr('coords').split(',');

        maps[0]-= maps[2];
        maps[1]-= maps[2];
        maps[2] = maps[2]*2;

        jQuery(this).hover(function() {
            jQuery('.maphilighted').before('<div class="tagbox tagbox'+maps[0]+maps[1]+'" style="left:'+maps[0]+'px; top:'+maps[1]+'px; width:'+maps[2]+'px; height:'+maps[2]+'px; -moz-border-radius:'+maps[2]+'px; -webkit-border-radius:'+maps[2]+'px; border-radius:'+maps[2]+'px;"></div>');
        }, function() {
            jQuery('.tagbox'+maps[0]+maps[1]).fadeOut();
            setTimeout("jQuery('.tagbox"+maps[0]+maps[1]+"').remove();", 100);
        });

        console.log(txt, maps);
    });
})

```

# Answer
> 0 votes
You can simply achieve that by using the jQuery Map Hilight module

> It enables the **simple addition of mouseover highlighting of hotspots** to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.

**Features**

1. provides simple interactive graphics via HTML image maps (no flash required).
2. easy to use: either select the 'highlight all image maps' default setting or simply add class="jq\_maphilight" to the tag of any specific image map you wish to highlight.
3. no jquery or javascript knowledge required: plugin configuration is handled via an admin/settings screen rather than having to enter jquery code.
4. fully configurable: options for fill, fill color, fill opacity, outline, outline color, outline opacity, outline thickness, as well as a fade effect.
5. per image map settings: add image map specific options with an additional class.

---
Tags: taxonomy-terms, media, javascript
---


# Question
Title: Get field from another content type in Views
I have two content types, 'user' content type where I have some info about user and then 'post' content type.

Now I have a view that gets all 'posts' and shows them correctly but I would need to get image (field\_user\_image) from 'user' content type. How can I get in views from this another content type this image field?

EDIT: Can I do this somehow on code level in template.php?

# Answer
I cannot give you a very detailed answer, mainly because it has been too long since I built new things with Drupal 6, but also because I don't know which Views version you are using.

But anyway, the key to your answer is "relationships". Views allows you to define a relationship from one item to another (for instance: `node -> author (user)`) and then query properties of the related item (`node -> author[name]`). You can even chain relationships, so you can query a property of a related item of a related item. This seems to be what you need: `node -> author -> node[field]`.

For more info I recommend that you find some video's or tutorials about views relationships, like these ones:
> 1 votes

---
Tags: views, nodes, 6
---


# Question
Title: I need to add a date to a calendar without creating a node
I have a difficult use case. I am building a site for a beverage distributor. They want to put their sampling events on a calendar. The problem is the sampling events don't really have a title. They just have the beverage being sampled, the location, and the date/time. Is there a way I can add dates to a calendar without creating a node for them or create a node with no title field?

# Answer
> 1 votes
I would use the Automatic Entity Label module to hide the title field on the form, and automatically populate it with a title. It can work with tokens, so you could configure it to generate node titles like "Event on \[node date\]".

# Answer
> 1 votes
If you dont want to have to use Nodes then I would dump the Calendar module and use the FullCalendar module. This module can use Views and a Google Calendar to show a calendar on your website on a specific page -- viola no nodes needed. If you need a details page on your site, I recommend a node-based approach.

# Answer
> 0 votes
we can correct this in many ways

1. create nodes manually from code which allow you to add nodes with out titles.
2. remove the default submit handlers and validate functions, which will allow to create empty title nodes.

But the preferred option is to generate a random title, may be a dynamic entry with date and time will be the best option.

---
Tags: datetime
---


# Question
Title: Hide "Submit"/"Save" button until file has finished uploading
I'm having a problem where my site users are submitting a form before the files they are uploading into filefield are finished, this is causing an ajax error to pop up along the lines of "**an ajax HTTP request terminated abnormally**".

To stop this mistake from happening is there a way to hide the **"Submit"/"Save"** button until file has finished uploading?

# Answer
> 1 votes
Havent tried this, but you might be able to use jquery's global ajax event handlers, to hide the submit button, in particular the `.ajaxStart()` and `.ajaxComplete()` handlers. Something like the following, added in a .js file in a custom module (not tested):

```
(function ($) {
  Drupal.behaviors.YOURMODULE = {
   attach: function (context) {
     $(document).ajaxStart(function(e){
       $('#edit-submit').hide();
     });
     $(docment).ajaxComplete(function(e){
       $('#edit-submit').show();
     });
   }
  };
})(jQuery);

```

You'd have to edit that to work the way you need it to, save it in a js file, and add it to the node edit form (or any other form you need it for).

Aside from that, the "ajax HTTP request terminated abnormally" errors occur in D7 whenever a http request is made before an ajax request has completed. In my opinion this is undesirable behaviour. It's been discussed here, for example, and the prevent js alerts module suppresses such errors across your site.

# Answer
> 0 votes
try this....

```
$('#edit-submit').bind('click',function() {
    $('#edit-submit').hide();
    $.ajax({
    url: Drupal.settings.life_style.secure_base_url+'path_to_form',
    data: data,
    type:'POST',
    async:true,
    cache:true,
    success: function(result) {
        //
        $('#edit-submit').show();
    },
         dataType: "html"
});

```

}

---
Tags: ajax, javascript, files
---


# Question
Title: i want to disable the cloud zoom module in drupal commerce kickstart
I am using Drupal Commerce kickstart. I including the demo site also. Cloud Zoom not working properly in my site, Please any one guide to me. I am new to Drupal commerce kickstart. I am using Drupal custom html theme convert to the Drupal theme.

Cloudzoom module installed in core. I can't disable it.

# Answer
> 2 votes
Cloud Zoom is a module included in the Commerce Kickstart distribution, if you want to disable it to replace it with something else, just go ahead and disable it in the drupal Modules admin page as Molot suggests.

Update: You can't just disable the module as it's part of the product dependencies in Kickstart.

So the only way you can disable its effects is in each place you see it, for example for the product page, under the Products menu, click on Variation types and then Manage display. Find the view mode, i.e. Full content, and disable/change the cloud zoom options.

More info: http://www.drupalcommerce.org/questions/7582/disable-cloud-zoom

---
Tags: 7, commerce
---


# Question
Title: I can't add to cart without HTTPS enabled
I have a Nginx server with Varnish that runs a Drupal Commerce website. The *Add to Cart* button doesn't work on a session without HTTPS.

I'd really appreciate any help.

# Answer
> 1 votes
The problem is that the *Commerce Cart* module requires a valid session or a logged-in user. The site security settings prevented sessions being sent out to HTTP requests.
While the OP solved this problem via PHP.ini, there are other valid solutions:

* Require all users to use HTTPS
* Avoid the cart is shown to anonymous users

---
Tags: 7, commerce
---


# Question
Title: How to find and delete nodes with duplicate titles?
I used Feeds, and for some reason it imported several nodes multiple times; now I have many duplicates.

How could I easily find and delete such nodes?

# Answer
This Drupal 6 script should do the job for you.
> 2 votes

# Answer
You can use a SQL request:

```
SELECT nid, title, type
FROM node
WHERE title IN (
    SELECT title FROM node
    GROUP BY title HAVING count(*) > 1)
ORDER BY title, created DESC;

```
> 0 votes

# Answer
**You can try this.**

```
    $nids = db_query("SELECT nid FROM node
    WHERE  type=:type
    GROUP BY title HAVING count(*) > 1",
    array(':type'=>'node_type'))->fetchAllKeyed(0,0);

   //Now delete all the duplicate nodes.
    node_delete_multiple($nids);

```
> 0 votes

---
Tags: nodes, feeds
---


title: Field Collection vs Entity Reference

text:
# Question
Title: Field Collection vs Entity Reference
How is field collection an advantage? You can do the same thing with a new content type pointing to the parent with an Entity Reference.

Maybe someone can break down some situations where each one would be better.

Say for Task -\> Files, would field collection be better or a new content type with an Entity Reference?

Say for each file you needed more some other data about that file, sounds like a plan for a new type with an Entity Reference, but you can embed a field collection inside of a field collection.

I enjoy how Drupal has many ways of doing the same things, but I can't find much on how different or similar these two solutions are.

Maybe someone can help explain?

# Answer
This is a question I make myself when facing new projects, Field Collection vs Entity Reference + custom entity or if the structure is simple, Field Collection vs custom field with several db columns / Multifield. Here's **my opinion based in my experience**.

Multifield is a great concept, it'd be a "lightweight" version of field collection, instead of creating an entity structure with relationships, it covers the simple use cases without creating the entity. It has a number of issues, though, such as not complete Features integration, not really multilingual etc (so if you plan to use this, contributions will be probably really welcome).

Field Collection is a great solution if you're doing a site that can be done just with a few tweaks here and there, it gives site builders a powerful tool to create complex structures without worrying much about the internals. It will basically create an entity that relates with the "host" entity by the ids, allowing to add fields to it and everything. The disadvantages would come in the knowledge of the internals of Field collection that you need to perform complex operations such as managing a Field Collection with an Entity Reference on it, or migrate data. As it is a generic tool, it'd be fairly complicated to go one step beyond.

Another option you've got there is using ECK with Entity Reference, but my experience with this has been a disaster so far, I find it way easier to create the entity type by code without the helper.

It's a matter of what you need and what's the best fit for your project, if you've got the time and the developers to create entity types that relate with your data model through Entity Reference, you'll have more control over what's happening with your data structures, but then you're the "responsible" for that too.

After testing a while with all the solutions describe above, in my team we always go for the entity types + ER, but I can see that for small projects, without data migration or a complicated i18n setup, Field Collection is just the fastest way to go.
> 15 votes

# Answer
It really depends on the data you input in the fields and the use you want to do with them.

If you want to use Field Collection, be sure you can to whatever is in your scope, from normal views, to translation, solr indexing etc..

If you want to reuse the information you add into a field collection, it will be better to use a content type or a custom entity. Example: A school course has got 5 topics. A topics contains 3 fields: Title, hours and level. If you are going to reuse topics in several school courses, go for an Content type/Custom Entity and use Entity reference.
> 3 votes

# Answer
They should be roughly equivalent in performance, but field collection uses the Entity API and does not require creation of a custom content type.
> 0 votes

---
Tags: entities
---


# Question
Title: How to change the html of threaded comments?
I want to display the comments on a node in a thread.

Not sure if I should use views or a template.

I want to change the html so that it matches boostrap markup

By using comment-wrapper.tpl I can change some of the html,

but I cant change the indent class.

# Answer
> 0 votes
I ended up using the default comments for the node.

Make sure threaded is enabled on the node settings page.

By installing field group I was able to add a div class to change the threaded comments html.

# Answer
> 0 votes
Could you give a little more info on what you are trying to do?

If you want to add your view for displaying comments to a specific thread, please take a look at using panel from contrib (https://drupal.org/project/panels).

This module allows you to add views (and other components as well) to specific pages, other panels (when using mini panels) etc...

---
Tags: views, comments
---


title: Send mail to selected users

text:
# Question
Title: Send mail to selected users
I want to send mail on webform submission to selected users. Suppose I'm user and admin must select users from my account that if I submit webform, then how many user's can get that notifications of my webform submission via mail?

# Answer
Use simplenews module

Simplenews

> Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.
>
> Simplenews 7.x-1.0 has finally been released which includes a number of other important bugfixes, especially in the upgrade path.
>
> Features Sending nodes as newsletters to subscribers Multiple newsletter categories with separate settings Per category and multi-signup Blocks and Pages Subscriber management including mass-subscription and export Optional E-mail confirmations for anonymous users Customizable newsletter templates Support for HTML (including text alternative) newsletter when used in combination with a supported mail system module Views and Rules integration Support for multi-language newsletters
> 0 votes

---
Tags: rules, javascript
---


title: Drupal 6 + Twitter Bootstrap 3 theme

text:
# Question
Title: Drupal 6 + Twitter Bootstrap 3 theme
I need help in setting up bootstrap 3 theme with Drupal 6.

With a lot of research I found that we have BootStrap module that supports D7 . Can anyone tell me how I can use Bootstrap in Drupal 6?

# Answer
> 2 votes
Prerit,

I think there is indeed one custom port to BS3 and that can be used in Drupal 6. Follow post #3 to get the idea. However, this is a custom theme made by an Drupal developer and its not in the drupal's project yet. FYI, it does support jQuery version 1.7.2 by un-setting the default jquery 1.2.6 version which intern may break some functionality in your site. The link to the Github Repo.

Personally I would suggest to use Zen or Omega for a Drupal 6.x site.

---
Tags: 6, theming
---


# Question
Title: Display Google Search XML results onto site within HTML
I have created a custom module to search the site using google site search and so far I have been able to get search results back in xml format and I need to have these results display on the site in HTML

Thanks for any help with this

# Answer
> 0 votes
We can use the Google Search Appliance module for this.

This will retrieve the results as HTML and there are custom search-result(s) theme templates which will allow us to theme as per our requirements

---
Tags: 7, search
---


title: Where is theThe Comment Form Template?

text:
# Question
Title: Where is theThe Comment Form Template?
I can find the comments template at modules/comments/comment.tpl.php

But where is the comment Form Template please?

I want to add a users image next to the form

Thanks for your help

Charles

# Answer
It is in the default **comment module** , and editing the core options is not a good practice at all.

You can alter the comment form in your active theme **template.php** or **hook\_form\_alter()** function in your custom module

```
<?php
function THEMENAME_form_comment_form_alter(&$form, &$form_state) {
        //dpm($form); //shows original $form array
        //$form['author']['#type'] = 'fieldset';
       // $form['author']['#title'] = 'Your Information';
       // $form['author']['#collapsible'] = FALSE;
      //  $form['your_comment'] = array( '#type' => 'fieldset', '#title' => t('Your Comment'), '#collapsible' => FALSE, '#weight' => 2, );
        //Subject
       // $form['your_comment']['subject'] = $form['subject'];
       // unset($form['subject']);
     //   $form['your_comment']['subject']['#weight'] = -10;
        //Comment
        $form['your_comment']['comment_body']['#prefix'] = "<div>User picture</div>" ;
        $form['your_comment']['comment_body'] = $form['comment_body'];

}
?>

```

You can add user picture using prefix/suffix in the comment form. Try if it work for you.
> 0 votes

---
Tags: theming, comments
---


# Question
Title: Add country, state dropdown to user registrtaion
i am creating a user registration form. In this i want to add fields for country, state, area and the fields are dependent on each other i.e. state depends on country and area depends on state. Is there any module in drupal or any way to integrate it with user registration form.

# Answer
You can use Hierarchical Select module, which gives what you want, but you to have create vocabulary for it.

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
>
> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 0 votes

# Answer
I think you can achieve that by using the Conditional Fields module

> Define dependencies between fields based on their states and values.

check out A Drupal Dropdown List of Countries, States, Cities for more info
> 2 votes

# Answer
You can also achieve that by using custom module like follows

```
<?php
/**
* hook_form_alter
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'my_node_form') {

$country_default_value =$form_state['values']['field_cmn_city']['und']['0']['value'];
$state_default_value = $form_state['values']['field_cmn_state']['und']['0']['value'];
$city_default_value = $form_state['values']['field_cmn_city']['und']['0']['value'];

$country_options = _get_location('country');
$selected_country = $country_default_value;
$form['field_cmn_country']['und']['#options'] = $country_options;
$form['field_cmn_country']['und']['#default_value'] = $selected_country;
$form['field_cmn_country']['und']['#ajax'] = array(
'callback' => 'field_cmn_country_callback',
'wrapper' => 'field_cmn_state_replace',
);

$state_options = _get_location('state', $selected_country);// get state
$selected_state = $state_default_value;

$form['field_cmn_state']['und']['#prefix'] = '';
$form['field_cmn_state']['und']['#suffix'] = '';
$form['field_cmn_state']['und']['#options'] = $state_options;
$form['field_cmn_state']['und']['#default_value'] = $selected_state;

$form['field_cmn_state']['und']['#ajax'] = array(
'callback' => 'field_cmn_state_callback',
'wrapper' => 'field_cmn_city_replace',
);

$city_options = _get_location('city', $selected_state, $country_default_value);
$form['field_cmn_city']['und']['#prefix'] = '';
$form['field_cmn_city']['und']['#suffix'] = '';
$form['field_cmn_city']['und']['#options'] = $city_options;
$form['field_cmn_city']['und']['#default_value'] = $city_default_value;

}
}

function _get_location($type, $location_id = NULL, $country_id = NULL) {
switch ($type) {
case 'country':

return $country_options;
break;

case 'state':
return $state_options;
break;

case 'city':
return $city_options;
break;

}
// ajax country callback
function field_cmn_country_callback($form, $form_state) {

$form_field_state =$form['field_cmn_state'];
$form_field_city = $form['field_cmn_city'];

return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_replace("#field_cmn_state_replace", render($form_field_state)),
ajax_command_replace("#field_cmn_city_replace", render($form_field_city))
)
);

}
//ajax state callback
function field_cmn_state_callback($form, $form_state) {

return $form['field_cmn_city'];
}
?>

```

check source for more info
> 1 votes

# Answer
How about the Address Field module ?

> Address Field defines a new field type to store international postal addresses, implementing a subset of the top-level address elements defined in the xNAL standard.

It has country and state, and you may be able to override it with a small custom module to add 'area'
> 0 votes

---
Tags: users
---


title: profile 2 module with services module

text:
# Question
Title: profile 2 module with services module
i am creating a web service for user registration. I just add some fields in user registration form using profile2 module. How can i integrate this with services module. i just want to make a services with the new fields

# Answer
I'm assuming you're familiar with Services. In your endpoint, Copy the pattern here:

```
                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'A valid username',
                        'source' => array('data' => 'username'),
                        'optional' => FALSE,
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'A valid password',
                        'source' => array('data' => 'password'),
                        'optional' => FALSE,
                    ),

```

For your arguments, and add your field machine names.

Inside your callback, you can set $form\_state\['values'\]\[...\] with the passed values, and then use

```
 drupal_form_submit('user_register_form', $form_state);

```

To register the user.
> 0 votes

---
Tags: services, users
---


# Question
Title: What is the best way to show category by image?
I have a online store with commerce module .
I have a category/taxonomylike this :

Writing Product

* pen
* pencil

Art Product

* paper
* something

All i want is to show `writing product sub category` in a page with image.
i've added image field to taxonomy and create a views from taxonomy .

How can i get sub category (image field) from views ?
Thx

# Answer
> 0 votes
In you view change the **Format** section to show fields and after that add the image field from your taxonomy, then add the filter `Taxonomy term: Parent term`

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


title: Filter between two dates

text:
# Question
Title: Filter between two dates
Looking for a little assistance. I have Drupal 7 up and running with the View and Date module. I'm attempting to build a content type where the only additional fields other than Title and Body are, Post Date and Expire Date. Setting up the view is easy but I can't seem to figure out how to make the view only appear with values between Post Date and Expire Date. Does anyone have any experiance setting this up this type of view?

# Answer
If you installed the Date module, you don't need to add two fields (*Post* and *Expire*). You can add a date field with start and end date.

Other than that, the rest is simple: Add two filters to the view.
The first filter will select the start date and show the fields that are *less than or equal to* *now*. (You can write that only if you select *Enter a relative date*.)
The second filter will select the expire date and show the fields that are *greater than or equal to* *now*.

If *less than or equal to* and *greater than or equal to* don't appear as options, make sure you enabled the *Date Views* module. (It is installed as part of the *Date* module.)
> 4 votes

# Answer
There is a module for that!

Views between dates filter

> This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
>
> Creating this functionality with standard Date filters requires two filters: start date less than or equal (\<=) to the supplied date and end date greater than or equal (\>=) to the supplied date. The problem is two filters means users must enter a date range, when technically selecting "September" is a range: September 1st to the 30th.
>
> It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.
> 1 votes

# Answer
Just a heads up about this: When I first started down this path, I was using the node published date (not date field). The sorting between didn't work as expected due to the extra time information. I wanted to sort by day only and didn't care about what time something was created during the day.

Long story short: make sure you use the **date module** and create date fields for this type of sorting.

Another conflict I found was with regards to date-popup. I was also using better exposed filters, which has a different version of jquery\_ui calendar popup than date\_views (another shortfall of *not* using the date module is there is no calendar popup). Anyway, make sure you use the default popup with date\_views, because I had lots of issues with date formats getting wonky and not validating.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to control field visibility in Views based on permission?
I am displaying Flag links via Views. By default the Flag module provides settings to control whether the Flag link appears eg. only appear on own content, only appear on others content etc.

The dilemma is that when displaying the Flag links via Views this no longer has any effect, and the Flag link will always display in the View. I have two Flags; one for owners of content and another for non-owners of the content. Depending on whether the user viewing the content owns the content or not I would like to display one Flag link or the other. This will allow owners for example to "delete" their own content, while non-owners to only hide content which is not theirs. If Views fields respected permissions this would be straight forward, but they don't seam to at least in my experience. How can this be done?

# Answer
Take global php field in view and write below logic in.

```
global $user;
$node=node_load($nid);
$author=$node->uid;

if($user->uid==$author)
{
   print flag_create_link('flag_machine_name', $nid); // flag for author
}
else
{
  print flag_create_link('flag_machine_name', $nid);//flag for other users.
}

```

Hope this will help.

NOTE : replace `flag_machine_name` with your specific flag's machine name which you want to display.
> 1 votes

# Answer
You don't need any code. I have tested it and views works perfectly with flags permission settings. Just check your flag and view setting once more.

**UPDATE :**
You have to add relationships with both the flags and you have to add the flag link **twice**, once for each relationship.
> 0 votes

---
Tags: views, flags, users, entities
---


# Question
Title: infinit redirection loop with lightbox2 module
I have a redirection with `drupal_goto()` function like that :

```
drupal_goto($url, array('fragment' =>  'lightbox='.  $lb_path, 'alias' => TRUE));

```

this link, after redirection, automatically open a lightbox, but the lightbox itselef still open another lightbox and so on ... (infinit redirection and opened lighboxes)

the lightbox is a content of node, and the idea is to redirect users from google search if it index a content of a lightbox. here my code in `hook_node_view` :

```
function MYMODULE_node_view($node, $view_mode, $langcode){
    if(strpos(request_uri(), "/lb/") !== FALSE && strpos(request_uri(), "lightbox") === FALSE){
         // the "/lb/" in path is only for lightbox content
         // my code here to get the right $url of the node containing the lightbox link.
         drupal_goto($url, array('fragment' =>  'lightbox='.  $lb_path, 'alias' => TRUE));
     }
}

```

But unfortunately I get an infinit loop ! Maybe the `if` statement was my fault... Is there other alternative ? check for example if a lightbox is already open. But I don't think that would be possible in that php function! Any other help will be appreciated :)

Thanks in advance.

# Answer
> 0 votes
Fragments are not sent to the server as part of a GET request. That's why you aren't detecting them. You could try adding a query parameter, so the request would look like this...

```
http://www...com/node/5/?lightbox=yes#lightbox=<whatever>

```

---
Tags: 7, nodes, redirection, javascript
---


title: Get list of node dependencies

text:
# Question
Title: Get list of node dependencies
in Drupal 6, is there a way to list by programmation (function or SQL code) the dependancies of a node ?

For exemple, I have videos that are nodes. Thoses videos are refered in other nodes. Before deleting the video I need to update the nodes which refer it. I have the module "Node Dependencies" that lists the dependencies of a node in the UI, but I need to get this list with code.

Is it possible ?

Thanks.

# Answer
Drupal does not know "dependencies" on it's own, so I assume it's something provided by the module you named. Yes, it is possible. After all that module is doing exactly this. Just read it's code and see, PHP is an interpreted language after all. It seems there is no module with that exact name on Drupal.org, so I can't provide more detailed instruction now. To find it yourself, you need:

1. Find implementation of hook\_menu() in this module
2. Locate entry for GUI page that shows what you want
3. Find implementation of a function that obtains data for that GUI page
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: Commerce Search API with Custom Search Form
I have a search form with multiple fields on my front page. After clicking on submit button, user would be routed to search result page. The user fills out the form, clicks on a 'Search' button, and the browser replaces the front page with a results page. (Ideally, a Commerce search view). On search result page, all facets blocks are enabled.

I have created a page using Views exposed filter for front page and I am getting result as per filters. But I am not able to map that search filters with my facet search blocks on result page. Is there any way to do that ?

Another way I tried is created a custom form but not sure how to build URL so that user would be redirected to Search result page.

# Answer
I resolved it by creating a custom form and in submit hook, I have redirected user to my search result page using below code.

```
if (isset($form_state['values']['brand']) &&  $form_state['values']['brand'] != '') {
      $element[0] = 'field_product%3Afield_brand:'. $form_state['values']['brand'];
      $cnt++;
    }

    $elements = serialize(array('f' => $element));

    $form_state['redirect'] = array('search/parts/results', array('query' => unserialize($elements)));

```

I didn't find any better solution as my display widget types are different for both the pages.
> 0 votes

# Answer
You should use the same faceted search block on front page too. You can invoke the faceted search block on front page.
> 0 votes

---
Tags: commerce, search
---


title: Can I pass an argument as ?xxx=arg

text:
# Question
Title: Can I pass an argument as ?xxx=arg
In Drupal 7, on the home page /home, I have a list of News items in the left column, and want to click on one of the News items in the list, and have the full article for that item show in the right column of the page.

Is there a way to pass an argument that doesn't change the page, like /home?xxx=arg Everything I read talks about passing arguments in ways that change the page path (i.e., home/news1, or home/news2).

# Answer
As long as you have something (a custom module, for example) looking for the arguments, yes, you can pass as many arguments as you want.

Depending on the size of the articles, however, instead of requiring a page refresh, I would suggest either an AJAX call (more complicated) or using jQuery (less complicated) to hide the content, and simply show it on demand. If the articles are large though, the jQuery option would be cumbersome and slow the page, since it would load all of the material at page load.
> 1 votes

# Answer
if you are showing news items using block or view than you can do it like this

firstly go to news item block/view then make settings of news item .

and change it as given in below screenshot

may this will help you.
> 0 votes

---
Tags: views
---


title: Get taxonomy term field value?

text:
# Question
Title: Get taxonomy term field value?
I have some taxonomy terms that have an image field in them. I am trying to get the value of the image field in my templates. How can I do this? The field's name is `field_header_image`.

I have this so far but it does not work..

```
$headerimg = field_view_field('taxonomy_term', $term, 'field_header_image');
print render($headerimg);

```

I'm guessing I need something else for `taxonomy_term` but I'm not sure what that should be.

# Answer
You can get it like this :

```
$term = taxonomy_term_load($tid);
$field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
if ($field_header_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
}
print render($headerimg);

```

If you want to use an image\_style :

```
$headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'my_image_style', //place your image style here
  ),
));

```

Here is a contextual answer if you are on your taxonomy term page.

In your file `template.php` use the `theme_preprocess_page` function like this :

```
function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

```

Then in you `page.tpl.php` you can `print render($headerimg);`
> 9 votes

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


title: Drupal 7 js popup

text:
# Question
Title: Drupal 7 js popup
Trying to put a popup window on my drupal 7 site that hides/shows on click.

Here's the popup.js file:

```
Drupal.behaviors.my_custom_behavior = {
attach: function(context, settings) {

function donpopup(cat) {
  $('div.popup-dialog').hide();
  $('div#popup-dialog-' + cat).show();
  return false;
}

function closepop() {
 $('div.popup-dialog').hide();
}

}
};

})(jQuery, Drupal, this, this.document);

```

Here's the css:

```
 div.popup-dialog {
 display:none;
 background-color: #FFFFFF;
 border: 1px solid #000000;
 border-radius: 4px 4px 4px 4px;
 box-shadow: 3px 3px 3px #AAAAAA;
 left: 25px;
 padding: 10px 15px;
 position: absolute;
 top: 20px;
 width: 300px;
 z-index: 100;
 }

 div.popcls{
 float:right;
 display:block;
 overflow:hidden;
 }

```

And here's the html

```
 <div style="position: relative;">
  <div id="don-cat-ST" class="don-catpop">
    <div class="popcls"><a onclick="closepop();return false;" href="#">x</a></div>
      <!-- Place the content here. -->
  <div>
</div>

```

I made sure that I added my js file in the theme .info..

But it doesn't work. Can anyone tell me what I'm doing wrong? Thanks!

# Answer
I just did this for a small website and I used some drupal modules, rather than trying to hardcode stuff like this.

I used ctools\_automodal. You supply a `hook_menu` function with a special key `modal => TRUE`. You then supply a page callback that uses `drupal_get_form` to show your modal content. The content need not be a full on form persay, you can use `$form['#markup']` to show non form stuff like paragraphs and images. From the project page it looks like this:

```
function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE, // This line is where the magic happens.
  );
}

// your custom form content could look like this:
function mymodule_form($form, &$form_state) {
  $form['info'] = array(
  '#markup' => "<p>Some Info here ...</p>",
  );
}

```

Then the last part you need to do is put a link to this custom modal window using the l() or the url() function, or like views\_linkarea. The link must be generated by Drupal and not plain old HTML as you've done.

By using the modules above and the drupal API your popup window is more incorporated into Drupal, and if you want to add Panels or alter forms to include this popup link it's very easy. Also, note you haven't written an Javascript -- the ctools\_automodal module is *hiding* all the complexity from you :).

Simply add CSS rules that target this modal form to style it as you need.
> 1 votes

---
Tags: 7, javascript
---


title: How to show the brothers taxonomy term?

text:
# Question
Title: How to show the brothers taxonomy term?
I have a tree of taxonomies, these taxonomies are the menu of my site and they are working with taxonomy\_menu module, I am displaying the menu through a view, but I'm only showing the children as low level, for example:

* Parent 1
    + Child 1
    + Child 2
    + Child 3
        - Test 1
        - Test 2
        - Test 3
        - Test 4
* Parent 2
    + Child 4
    + Child 5
    + Child 6
* Parent 3

If access to view link parent1 show me only:

* Child 1
* Child 2
* Child 3

If access to Child 3 links show me the children of child 3

* Test 1
* Test 2
* Test 3
* Test 4

But if access to test 1 show brothers need taxonomies:

* Test 1
* Test 2
* Test 3
* Test 4

If filter by parent term works for me but when the taxonomy have more children, but when you have no more children need to show the brothers.

Any idea?

# Answer
> 1 votes
You could create a custom module that looks for the children of that element, if returns 0, look for the parent of the element and print that parents children.

You could also try views, they have a function that helps to deal with results behavior when you don't find any elements related to you query.

Hope this helps.

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


title: How to strip <img> tags from teasers?

text:
# Question
Title: How to strip <img> tags from teasers?
I have nodes with text and images in the body field. I wish to remove the images from the teaser texts, currently created with the "Summary or Trimmed" field display option.

Is there a hook or similar for altering the field before it's output in the teaser? Or would this require writing a custom field formatter?

# Answer
I have had good luck using the Smart Trim module. (This module is now available for Drupal 7 and 8.)

Choose the Smart Trimmed field formatter and check the Strip Out HTML checkbox to remove the image tags (and other formatting that you probably don't want in a teaser text).

It also gives you some other handy formatting options (limit to number of words or characters, add "read more" links, etc) and makes the formatting options available for fields in Views, as well.
> 8 votes

---
Tags: nodes, entities
---


title: Adding javascript to a view?

text:
# Question
Title: Adding javascript to a view?
I have a view in Drupal 7 that displays a list of all the nodes of a content type in alphabetical order. What would be the best way to implement javascript that only displays nodes starting with a specific letter, say, all nodes starting with the letter 'A'? I would also like to add a list of letters as links at the top to trigger the show/hide effects.

It's probably worth noting that I currently have javascript to achieve this using data gathered from an external database and implemented via a custom module. Ideally, I want the same functionality but want all the data to be coming from Drupal nodes.

# Answer
> 0 votes
Why do you need a javascript way explicitly? Drupal can do these Filters and make the glossary view, an index by letters, at top for you already in the views administration area.

---
Tags: views, javascript
---


# Question
Title: D7 Rules - User Profile Field in Send Email Action
I'm using D7 with Rules 7.x-2.7. I am trying to create a Rule that will email and BCC all users of a particular role when a node of a certain content type is created. I've added the event: `After saving new content of type...`, and the action: `Send mail to all users of a role`. What I'm now trying to do is pull in the user profile data to populate the email body. Something like:

```
Hi [user-field-firstname],

A new announcement has been released. Please log in to your profile and browse to http://examplesite.com/user/[user-id]/announcements.

regards

```

I've been unsuccessful thus far. I've tried to add another action of `Fetch entity by Id`, but could find any decent selectors in the data selector. Any advice for me, please?

# Answer
> 0 votes
**SOLVED!!!**

After breaking my head for a full day on this, I remembered something I read on a blog a while back about using views in Rules. So here goes and I hope this helps someone.

1. Download and enable the Drupal Views Rules (`drush dl views_rules`)
2. Configure and customize a new view with a `Rules` display as below:

with the `row variables` configured similar to:
3. Back in Rules, you will now see a new `Add view loop` method which can then be used as follows:

I really hope this helps someone else. Note that I'm not using the Rules Tokens or Profile2 modules - just the Views Rules module. :)

# Answer
> 0 votes
I might try the Rules Token module (if you haven't already). It might contain what you need

---
Tags: 7, rules
---


title: Field Validation and Highlighting

text:
# Question
Title: Field Validation and Highlighting
How can I get custom Form API validation to highlight a field the same way the failed #required validation does? (See attached graphic)

Note Graphic:

1) (Green Line) Company Name is empty. '#required' Error is noted and field is highlighted red.

2) (Blue Line) Website is incorrect. 'Custom Validation' Error is noted, but field is NOT highlighted.

How can I automatically highlight the 'Website' field on validation fail and remove it upon success?

Currently using: `form_set_error('', t('Your website address is incorrectly formatted.'));`

See

# Answer
> 2 votes
Have you tried using hook\_field\_validate()? (edit) I just realized you are not using the new Field API but instead just the Form API. Perhaps, you can build it as a field? If you are familiar with the Form API in d6, you can pick up the Field API in a couple of hours. The Field API is another level of badassness.

i have a custom field that records business hours. I have it set that if a to day is selected there must be a from day. I more or less just implemented the example giving in api.drupal.org.

```
*  Implementation of hook_field_validate()
*/
function hours_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['end_day'] != '--' && $item['start_day'] == '--') {
      $errors[$field['field_name']][$langcode][$delta][] = array(
        'error' => t('A from day needs to be choosen if a to day is selected. If they are the same -- forexample, Monday and Monday, the whole line when viewed will only be for Monday.'),
      );
    }
  }
}

```

# Answer
> 3 votes
As the first parameter to `form_set_error()`, pass the name of the field to be highlighted. If it's a nested structure, pass it with square brackets, like so:

```
form_set_error('[your][nested][field]', 'Your Error Message');

```

There's a convenience wrapper around this, `form_error`, which takes the element instead of the string, like so:

```
form_error($form['your_field'], 'Your Error Message');

```

Also see the docs to `form_set_error()` (d7).

# Answer
> 2 votes
If your form element is defined like that:

```
$form['panes']['webform_nid31'][0]['contact_person'] = array( ... );

```

your form\_set\_error call should look like that:

```
form_set_error('panes][webform_nid31][0][contact_person',
                t('You must select a name for this group of settings.'));

```

You need to set full path to element, without outside `[` and `]`. You could have many "contact\_person" fields in one form, just in different branches of a form tree. Using only last index would made setting errors ambiguous, thus it's not supported. At least officially. Might work, but only as an undocumented feature.

Formatting this string is described in API:

> Parameters
>
> $name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo\]\[bar\]\[baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

*Copied from form\_set\_error() field not highlited red*

---
Tags: 7, forms
---


title: Drupal Sub Sites with or without Aegir

text:
# Question
Title: Drupal Sub Sites with or without Aegir
We're currently using Aegir to manage sites, essentially, domains and sub domains. However, we have a need for sub sites. For e.g., domain.com would the parent, and the children sites would be domain.com/division1, domain.com/division2 and so. The databases could be the shared or not; themes could have a parent-child relationship or not. Looks like this is not in Aegir yet (although the university crowds are asking for it)

What options exists to create and manage sub sites using Drupal? How do folks typically do this? I looked at the subsite module, while looks like it is still in dev for D7.

Many thanks!

# Answer
Thank you all for the suggestions. We've decided to stick with Ægir's functionality for now, and see where that gets us.
> 0 votes

# Answer
Drupal sites in subdirectories are now fully supported in Aegir 2.x since version 2.0
> 2 votes

# Answer
We use the Domain Access module to do what your talking about.
> 0 votes

# Answer
This very question was brought up during DrupalCon Chicago when the Aegir maintainers were present. Their answer was that they didn't want to support this because it's a generally bad idea, and instead subdomains should be used.
> 0 votes

---
Tags: aegir, subsites
---


# Question
Title: Modules to set up audio podcast functionality
I am looking for modules to set up audio podcast functionality which allows playing of uploaded audio files as well as take audio source as external links like iTunes links. Any recommendations?

# Answer
Successfully Tested with combination of

remote\_file\_source

> Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.

Jplayer

> The jPlayer module provides a wrapper around the jPlayer JavaScript library. This library provides an HTML5-based player, that uses a Flash fallback for browsers that do not yet support it. This module provides a default presentation for the player, as well as integration with CCK file fields and a display style for Views. This makes it possible to easily convert the display of any file field into an audio player.
> 0 votes

# Answer
Take a look at FileField Podcaster

> Using Views2, this module delivers a way to podcast with nodes that have CCK FileFields included as RSS file enclosures. It provides a podcast-compatible (as determined by Apple) RSS feed, using node variables, getID3, filefield in cck, and filefield meta data to generate the RSS tags
> 0 votes

---
Tags: files
---


# Question
Title: How to check if user has access to node creation page from passed parameter?
I have set some users with 'update' access to some books and all other users have only 'view' access. I have used hook\_node\_view\_alter() to remove the 'Add child page' link for users with 'view' only access. The problem this only hides the link from the corresponding node pages, those users are still able to add a child page by manually going to the url: /node/add/child-content-type?parent="mlid" where mlid is the "menu link id" for the parent node. The users might not know particular parent node link id's, however this is a security hole I want to get rid of.

How can I get this passed argument as "?parent=" in a php variable and what hook function should I use to run the condition checks for user access? I am using drupal 7.

# Answer
After some more internet research and experimentation on my side, I solved the problem.

1. The passed argument as "?parent=" was acquired using `$_GET['parent']`.
2. I programmatically checked if the user has access to create a child with the provided parent using the `hook_FORM_ID_alter()`.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How Not To Update Existing Taxonomy Terms At Migration
I am using migrate and migrate\_d2d to migrate taxonomy terms from a d7 site to another d7 site.How can I specify in my migration that nothing be done if the term already exist in the target? So far, in "prepare" function, I am querying the target to find out if the term already exist, but I am not sure if this is the right way to go about it or where to go from here.

```
function prepare($entity, stdClass $row) {
  $term_name = $entity->name;
  $query_checking_if_term_exist = db_select('taxonomy_term_data', 'ttd')
    ->condition('ttd.name', $term_name)
    /* TODO: fetch vid from taxonomy_vocabulary table instead of hardcoding it */
    ->condition('ttd.vid', '2')
    ->fields('ttd', array('name'));
  $term_exists = $query_checking_if_term_exist->execute()->fetchAll();
  if(isset($term_exists)) {
    //TODO
  }
}

```

# Answer
If found the solution, if the term exists return false from prepareRow($row) and the term won't be updated or migrated again. like this:

```
public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }
  $term_name = $row->name;
  $query_checking_if_term_exist = db_select('taxonomy_term_data', 'ttd')
    ->condition('ttd.name', $term_name)
    ->condition('ttd.vid', '2')
    ->fields('ttd', array('name'))
    ->execute()->fetchAll();
  if(!empty($query_checking_if_term_exist)) {
    return FALSE;
  }

```

}
> 0 votes

---
Tags: taxonomy-terms, migrations
---


# Question
Title: JQuery hoverIntent / Drupal contrib hoverIntent module not working
I'm trying to get the jquery plugin hoverIntent to work on my Drupal 7 installation. No luck.

1st, I tried the logical approach; simply the following to the theme .info file. scripts\[\] = js/jquery.hoverintent.js Doesn't work, and causes other problems.

Then I tried the contrib hoverIntent module. I can see that the script is loaded on the page, but calling .hoverIntent from within Drupal results in nothing happening.

```
$(function() {
  $(".views-field-field-profile-picture").hoverIntent(teamIn);
  $(".team-name-info").mouseleave(teamOut);
});

```

Anyone with success in getting hoverIntent to work? Why is this so difficult?

# Answer
Found it. First, you will most likely see an error in the logs like this TypeError: cfg.out is undefined

The problem in my code is not that .hoverIntent wasn't loaded, it was that that method requires two parameters. (Obvious error)

Solution:

```
$(function() {
  $(".views-field-field-profile-picture").hoverIntent(teamIn, function(){});
  $(".team-name-info").mouseleave(teamOut);
});

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: EntityListBuilder only shows the last Entity that was added
I've build up an Entity for my module. The problem is that the EntityListBuilder doesn't show all the entities that I've added. Only the last entity that I added shows up.

Here is the drupal sandbox link

```
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
/**
 * Provides a listing of Example.
 */
class myentityListBuilder extends ConfigEntityListBuilder {
  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['name'] = t('myentity name');
    $header['status'] = array(
      'data' => t('Status'),
      'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
    );

    $header['status'] = array(
      'data' => t('Status'),
      'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
    );

    $header['myentity_status'] = array(
      'data' => t('myentity Status')
    );
    return $header;
  }
  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    $row['title'] = array(
      'data' => $this->getLabel($entity),
      'class' => array('myentity-label'),
    );
    $row['status'] = $entity->status;
    $row['myentity_status'] = 'green';
    return $row + parent::buildRow($entity);
  }

  public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);
    return $operations;
  }

  public function load() {
    return parent::load();
  }

  public function render() {
    $build = parent::render();
    $build['#empty'] = t('No myentitys available. <a href="@link">Add new myentity</a>.', array(
      '@link' => \Drupal::urlGenerator()->generateFromPath('admin/config/search/mymodule/myentitys/add'),
    ));
    return $build;
  }

}
?>

```

The entities are getting saved as I checked them from the config table in my database.

# Answer
Problem is that the entity annotation contains `"id" = "machine_name"` while the configuration schema does not contain `machine_name` and so the saved entities won't contain `machine_name` and they can't load. Make sure the id (which is often simply called `id` in this case it's called `cluster_id`) is in the schema and also in the entity class (in this case, it's `cluster_id` that is being manipulated, `machine_name` is the type of it in the form).
> 2 votes

---
Tags: 8, entities
---


# Question
Title: How to show the number og members views members views
How do you show the number of members in a group using views please?

I had a look at this post bu unfortunately the relationship have changed in drupal og 7.2

How to show the count of members that belong to a group?

Many thanks for your help

# Answer
It's look the same, please follow instructions from image:

Full image: https://i.stack.imgur.com/45olm.jpg
> 3 votes

---
Tags: organic-groups, views
---


title: Render fields in a custom bean.tpl.php

text:
# Question
Title: Render fields in a custom bean.tpl.php
I have a custom tpl for bean block called: `block--bean--image-footer-block.tpl.php`, also I have custom tpl for both fields:

```
field--title-field--footer-block.tpl.php
field--field-block-footer-imagen--footer-block.tpl.php

```

I don't want to use the default `<?php print render($content); ?>`

But If I try to use

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

```

or

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

```

I get this error

```
Fatal error: Only variables can be passed by reference in

```

The beans fields are:

```
title_field
field_block_footer_imagen

```

Any idea to print both fields?

Thanks

Oskar

# Answer
> 2 votes
*Note, to avoid getting the 'pass by reference' error, assign the output to a variable before passing it in as an argument to the `render()` or `drupal_render()` functions*

**Partial Solution, without preserving display settings**

For reference, I tried: How do I render a field value including its format?

Which gave me something similar to:

```
<?php
$banner = field_view_field('bean', $bean, 'field_banner_image')
echo render($banner);
?>

```

The only problem being that it was ignoring my output display formatting I had set on the block type. You can specify one, but I couldn't find a source readily available with the values of the `$display` array which would be passed as 4th parameter to `field_view_field`.

**Full solution, preserving display settings**

Since I wanted to preserve the setting specified by the configuration of the field, and not rely on display defaults (ie: showing the label above an image) I looked back at the `bean.tpl.php`. Within the content they were building the $elements array, and using drupal\_render. Giving this a shot and it worked:

```
<?php
$banner = $elements['field_banner_image'];
echo drupal_render($banner);
?>

```

This also preserved my removal of the field label.

This was all done within my **bean--banner.tpl.php** which should be a similar setup to what you're facing. Hope this helped!

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


# Question
Title: ajax_command_invoke Question related to Commerce + Colorbox + AJAX
I am displaying a Drupal Commerce node with AJAX add to cart functionality in a popup, with the Colorbox Node module. In my custom form callback, I have the following code.

```
// Form callback function
function ajax_module_form($form, &$form_state){
  drupal_add_js(drupal_get_path('module','colorbox' . '/colorbox.js'));
  $commands = array();

  $commands[] = ajax_command_invoke('colorbox-node', 'colorbox.close');

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

I am trying to use Drupal's ajax\_command\_invoke to close the Colorbox window after AJAX form submission is complete, but cant seem get it to work. I tried 'parent.colorbox.close' as well but doesnt seem to work. The colorbox link has iframe and sample link is -

example.com/node/45434345?width=500&height=500&iframe=true and link class is .colorbox-node

Also the Colorbox module setting - invoke on all pages is also active.

Any lead/help is greatly appreciated.

# Answer
> 1 votes
I'm editing my answer to directly address your question first:

ajax\_command\_invoke takes a css selector as its first argument.

```
 node-colorbox

```

isn't a css selector (or at the very least, not a valid one).

In addition, ajax\_command\_invoke does not allow for the execution of arbitrary javascript, but only allows for triggering registered jQuery events. If you want to create a custom jQuery event for colorbox, you will have to manually create it and attach it to the colorbox object, using Drupal.behaviors.

http://www.sitepoint.com/jquery-custom-events/ should get your started.

Colorbox seems like it might be a good solution for your use-case, but it really isn't. If you want a good floating window with ajax forms and automatic closure, using the chaos tools modal system is a better bet. It supports what you're looking for right out of the box and makes working with forms easy. In addition, almost everyone uses ctools, as it is a dependency for many different modules.

http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 should get you started.

---
Tags: forms, ajax, commerce, javascript
---


# Question
Title: Disable a 'enter/return' key function in a form
I have a form in which a user needs to fill the fields. As only two fields are the required fields, so when user fills the required fields and press `enter`(windows)/`return`(mac) key the form gets submitted. I'm trying to disable the `enter/return` key function. So, for this I tried to inject a `jQuery` within the form.

my jQuery is as follows:

```
(function ($) {
Drupal.behaviors.YOURTHEMENAME = {
attach: function(context, settings) {
$("input").keypress(function (evt) {
var enterCode = evt.charCode || evt.keyCode;
if (enterCode  == 13) { return false;
}
});
  }
});
}
};
})(jQuery);

```

The jQuery part is familiar to me, but it doesn't work in the site. And the form responds to enter/return key press.

Is there any other way to disable enter/return key press. something like a module..

# Answer
Resolved the issue. Added the Query using `JS injector`.

```
(function ($) {
Drupal.behaviors.YOURTHEMENAME = {
attach: function(context, settings) {
$('#id').keypress(function(event) {
   if (event.keyCode == '13') {
       event.preventDefault();
   }
});
}
};
})(jQuery);

```

return/enter key press is now disabled.
> 0 votes

# Answer
You need to use evt.preventDefault();

I wrote a blog post on making this work with drupal and ajaxified forms, which may let you see a slightly larger example including Drupal.behaviors.
> 0 votes

---
Tags: 7, javascript, navigation
---


# Question
Title: Why can i not add a new link to the main menu?
I cannot for the life of me figure why i cannot add a new link to the main menu?!

the error i get reads

```
'The path 'events' is either invalid or you do not have access to it.'

```

i have tried numerous work arounds, tricks, checked permission, menu modules, everything i can think of but i cannot understand why.

am clueless, does anyone here know?

# Answer
> 0 votes
Go to Modules list `/admin/modules` and make sure the **Path** module is enabled.

---
Tags: routes
---