# Question
Title: How to conditionally book an appointment on calendar module?
I would like to offer the opportunity for users of the site to book a visit to the doctor, do not let book if the day is full of appointments and show the day in red on the calendar.

Is this possible?

# Answer
> 2 votes
I'm not aware of any way to use the Calendar module for this. However, there are some distributions and/or contributed modules for managing such bookings. More details below.

# Option 1: Distributions

The Clinic Appointment distribution is a brand new distribution for D7. Some more details about it (from its project page):

> It is a doctor appointment management system. It manages patient profile, doctors profile, and appointments. It supports multiple offices. It creates all kinds of reports that help clinic's day to day operation and business growth. It is a great choice for doctors to have an excellent management system built on a free open source software.
>
> Appointment Management System is the quickest way to get up and to run with patient appointment management. It includes the latest version of Drupal core, FullCalendar, and the other modules it is depending on. It lets you create a fully functioning appointment book, managing system out of the box. It comes with comprehensive reports powered by views module.
>
> Who should use Clinic Appointment? Anyone who want to build an appointment booking system. Anyone who wish to use it to schedule an appointment with doctor and patient. Customize patient, doctor content type by adding and deleting fields to the need for your business.

According to Comment nr 2 in issue # 2646628 it "*Can be used for appointments made by patients*" also.

# Option 2: Contributed modules

These modules have a stable release, and can be used for either D6 or D7 (quotes are from their project pages):

* Availability Calendars (D6 or D7).

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation (D6 or D7).

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
* MERCI (D6 or D7).

> ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.
* Resource Conflict (D6 or D7).

> ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

### Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

### Deciding which module to go for

When deciding between multiple modules, a typical consideration is often about the "maintenance status" of the various modules. To illustrate some of the criteria I often use for that, please checkout the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

> ... contains a list of 23 criteria (=28-5) that might help to evaluate the maintenance and support of contributed modules. Below is an attempt to apply those criteria to each of the native charting modules ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).

---
Tags: 7, datetime
---


# Question
Title: Importing non-unique terms with Feeds Importer
I'm trying to import a large chunk of data to our site using Feeds Importer. However, I've come to a small problem when trying to map a piece of our data to a collection of taxonomy terms.

The problem is as follows:

We have a vocabulary called Categories with two levels. Every parent term has a list of child terms. In some of our terms, both the parent and the child have the same name, e.g.:

parent; child Cozinhas; Cozinhas

This is absolutely necessary as we need both the main category and the sub category to be listed and presented in this fashion.

With Feeds Importer we simply import all the main (parent) categories once and the every sub (child) categories related to it (e.g.: "Casas de Banho" -\> "Banheiras"). However, in this case, it simply maps the term to the parent and lists it twice. We are using Hierarchical Select to save the terms, so we use Tamper to explode the terms we've imported and send it to the correct field.

I've tried importing the alias of the sub-category term ("Cozinhas-0") and the unique ID to map it correctly but it simply doesn't work that way, it seems it has to be the term name.

Is there any way to map this correctly?

tl;dr:

We need to import several values, with Feeds Importer, into a single Hierarchical Select field and we need them to be unique, in order to map same-name taxonomy terms to their correct ID. Is there a way to do this?

# Answer
> 1 votes
Obviously, there is a way to map by term ID on the mapping settings of the Feeds Importer.

Problem solved!

---
Tags: taxonomy-terms, feeds
---


# Question
Title: Group result and display count in a view
I want to create a view and group the result like display only 1 record and along with it display the count of the similar records along with it. Can i do it in views with out writing any code. i.e. result should look like

```
Football (3)

Tennis (6)

Cricket (4)

```

# Answer
You can create a Contextual Filter for whichever field you want to sort off of. If the filter value is not in the url it will display a list like you have above.
> 5 votes

# Answer
My example is based on 1 Content Type and 1 field (City).

1. **FIELDS**. Add 2 same fields in fields area you wanna group and show counter.
2. **FORMAT**. Group by required field
3. **PAGER**. Set 0 in Pager area.
4. **ADVANCED**. Enable aggregation in advanced settings
5. **COUNT**. Enabled 'count' for second field (which is not used to group)
6. **Sorting**. Set sorting as your group field.

**FINAL**

This is how looks my view

**RESULT**
> 6 votes

# Answer
I need this feature and see this Q&A, I try it but not getting desire result, keeping on my search and I found Views Aggregator Plus . this is exactly I need and good solution for future guys that search for this feature.

> As the Views and Views Calc modules rely on the database to perform aggregation, you only have limited options at your disposal. As the great Merlin himself said: "You can't aggregate a PHP expression in the database. :/ ". That's where Views Aggregator Plus comes in. In addition to what Views and Views Calc do, this module:
>
> ```
> enumerates group members
> produces tallies, i.e. textual histograms
> aggregates on Views PHP code-snippet evalutations
> can filter out result rows on regexp patterns
> gives you sorting on Views' Math expressions
> can process Webform submissions
> lets you add your own custom aggregation functions
>
> ```
>
> ... and it puts summary statistics at the bottom of your aggregated table as well! Recap: what is aggregation again?
>
> In the context of Views tables and this module, aggregation is the process of grouping and compressing result rows on the identical values of one column, while at the same time applying "summary" (aggregation) functions on other columns. For example, you can group the result set on a taxonomy term, so that all rows sharing the same value of the taxonomy column are represented as single rows, with aggregation functions like COUNT, ENUMERATE or SUM applied to the remaining columns. Example
>
> Say the original View based on raw database results looks like below. Industry Company Name Turnover IT AquiB $ 25,000,000 Clothing Cenneton $ 99,000,000 Food Heiny $ 66,000,000 IT PreviousBest $ 5,000,000 Food McRonalds $500,000,000
>
> Then with the grouping taking place on, say Industry, and aggregation functions TALLY, ENUMERATE and SUM applied on Industry, Company Name and Turnover respectively, the final result with a descending sort on the last column will display like below. Note that the module identified three groups. It also added a totals row, Views Calc style. Industry Companies Turnover Food (2) Heiny, McRonalds $566,000,000 Clothing (1) Cenneton $ 99,000,000 IT (2) AcquiB, PreviousBest $ 30,000,000 Totals 5 $695,000,000
>
> But that's just the beginning. Remember, you can aggregate on Views PHP expressions, so the possibilities are endless! See the README for examples using PHP code snippets.
>
> For the "totals" row you may use the module's Math expression column aggregation function and replacement tokens to calculate a field as, say, the product of two preceding fields.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Export nodes inside Panels by their UUIDs through Features
In D7, I have a panel page that uses several nodes as content. When I export the panel into a feature on my Dev using UUIDs and UUID Features, and import the feature into my Test environment, Drupal creates new nodes with the UUIDs as expected, but the Panel isn't updated to reference these new UUIDs and their respective new NIDs. Instead the Panel keeps referring to Dev's NIDs.

I've looked high and low for a solution to no avail. The closest I have come to a solution was: https://www.drupal.org/node/827466 But it has been years and no update. Does anyone have any ideas/solutions? Thanks.

# Answer
> 0 votes
Try this module https://www.drupal.org/sandbox/danylevskyi/2399993 It will work fine, if you don't have reference fields in your node.

---
Tags: 7, panels, importing-exporting, features
---


# Question
Title: Field with type 'Term Reference' (only if I use View as data source) display N/A as first value
I have a field with type 'Term reference' and widget 'Check boxes/radio buttons'. As a first value I have a N/A and I've no clue why it appears there.

Term reference works fine if I do not use View. It's not required to be filled.

Is it possible to remove it in proper way?

Thanks.

# Answer
> 1 votes
A very late answer, but hopefully it will still help you. I think if you change the term reference field, you have an option if it is optional or mandatory the field. When you choose mandatory, it should be removed that option.

# Answer
> 0 votes
If you make a list field mandatory, the N/A option automatically goes away

**OR**

```
<?php
unset($form['field_name']['und']['#options']['_none']);
?>

```

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


title: How to display panels region title?

text:
# Question
Title: How to display panels region title?
How can I say Panels to show region title while rendering the page?

I have a panel region containing 4 node previews and I want to print a title before them. It would be like a "wrapping section" in my home page.

Is it possible?

# Answer
You can create a template for your panel and add whatever div or wrapper you need there, by wrapping it around the content div. This post is a great resource: https://www.drupal.org/node/1678810

In brief, for panel panes, your template file should be named: panels-pane--\[pane type\]--\[pane subtype\].tpl.php

This post also shows you how to find your panel's machine name.

If you aren't familiar with templates, this is also a great resource: https://www.drupal.org/documentation/theme
> 0 votes

---
Tags: 7, panels
---


# Question
Title: using EntityFieldQuery with flagging condition
I would like to perform a query to find the node flagged with a "myflag" based on a node field value. Is it possible to use EntityFieldQuery to accomplish that? If not, how can I use Views api to do it?

# Answer
> 1 votes
Don't need to use EntityFieldQuery or views to perform this flag module has already give function to get is\_flagged(). All you need to call functions like.

```
$flag = flag_get_flag('myflag');
$flag->is_flagged($node->nid);
if($flag && $flag->is_flagged($node->nid)) {
  print "This node is myflag!";
}

```

---
Tags: views, flags, database
---


# Question
Title: How to avoid module specific jQuery plugin script running globally?
This is my first time working with Drupal (Drupal 7).

I've created a jQuery plugin which populates a target div. The target div is added to the node via panelizer.

I only want to run the script for when it's needed. Just now it runs all the time. Even on the dashboard, this causes script errors.

I'm not sure what the best approach is for this.

EDIT (SOLUTION):

Thanks for the input. I decided to use a Javascript approach.

```
var elementExists = document.getElementById('target');

if (typeof(elementExists) != 'undefined' && elementExists != null) {
  // Script
} else {
    return;
}

```

# Answer
From my experience it's usually best to leave this check to JS and don't bother on PHP side. Of course it all depends on your definition of *best*, but benefits I see are:

* It's easy and stable to test for div existence with `$("#myid")`, opposed to more mysterious tests in PHP. Now you know that this div will appear when `X` is true and `Y == Z`. Will you remember that in two months? Sure, we have comments. But will future developer understand what you meant? Will you be disciplined enough to write them, and do it really clearly?
* It's easier for caching - if you aggregate your scripts, you will use the same aggregated file for pages with and without div, so one less check / download for browser
* It lessens the chance for conflict between your module and other ones.

+ Modules shouldn't just overwrite `[#attached]` array, but I encountered some that did.
    + If you are using `drupal_add_js` instead, making sure test for conditions is run when it is supposed to might be hard, if other modules will try to reorder hooks. So this isn't a sure way to avoid problem described above.
    + Various caching systems might miss the conditions you use. Probably nothing as severe as Boost and Mobile Tools issue, but risk is there.
    + Theme shouldn't need to know about blocks - if you will leave test to theme, point above will not apply, but you risk crashes whenever theme is switched or block is disabled. Testing for it on both sides will add a lot of code.
    + And I'm sure there are other things I simply never encountered yet.

Of course you *could* say most of those are bugs in other modules, and you would be right, but being right does not help if you need your site up and running.
* It's easier to quickly see scripts added via `.info` file than to search code for `drupal_add_js` or `attached` or... you see, there are many ways to do it in code, happy hunting if you are new developer and need to find where this one script came from.
> 2 votes

# Answer
In template.php add this code:

```
function mytheme_preprocess_html(&$variables) {
  $theme_path = path_to_theme();
  $path = drupal_get_path_alias();
  if($path == 'my/path') {
      drupal_add_js($theme_path . '/js/example.js');
    }
}

```
> 1 votes

# Answer
As alternative solution you may use tracking code. That would allow you to load JS or anything else only on specific pages. It would also give you overview what and where you run extra stuff.

Like this:
> 1 votes

---
Tags: javascript, panels
---


# Question
Title: How can I use aggregation in multiple field in view
I want to group by multiple field but I don't know how it works.

In my view, I have :

Code A | cmd Date | Quantity | Price A | Total |

And I want to regroup by *Code A* then regroup by *cmd Date*.

For each CodeA I have multiple order in the same month and I want to regroup them, then sum quantity and total. Like :

|Code1 | 09/2015 | 15 | 5 | 75€ |
|----------|10/2015 | 10 | 5 | 50€ |
|Code2 | 08/2015 | 11 | 7 | 77€ |
|----------|11/2015 | 10 | 7 | 70€ |

Someone can help me ?

Thanks

# Answer
> 0 votes
First you have to enable fields in your view. Then in your formatting settings you can now use "group by". You can also use more than one grouping field. Hope it will help!

---
Tags: views
---


title: Hiding menu items dynamically

text:
# Question
Title: Hiding menu items dynamically
I am developing an application based on Drupal 7 and web services. Some application pages have a menu which should be customized (menu items should be removed) based on the response from the web service, but am not sure on how should implement it.

In general the logic is the following: I will get a parameter from the request and call the web service with PHP (I know how to do this). Then, based on the response, I should show or hide some menu items.

The problem is that the menu should be customized in every request, so `hook_menu_alter` does not help me, because it is only called once when the menu is created. Is there another hook that I should be looking into, or any other method I should be using?

# Answer
> 4 votes
use `theme_menu_link()` to modify your menu links on the fly:

* `style="display:none"`
* `class="invisible"`

e.g.

```
function mytheme_menu_link(array $variables)
{
   if ($variables['element']['#href']=='temp-menu-link') {
       $variables['element']['#attributes']['class'][] = 'invisible';
   }
   return theme_menu_link($variables);
}

```

Security note: It'll still be possible to access the URL, thus a "state check" must be implemented on the receiving end if temporarily invisible also means 'not permitted to call'.

# Answer
> 1 votes
You can use hook\_menu\_alter if it's solve your problem. You can call this hook as many as you like with `module_invoke_all('menu')`. Note that you need to clear the menu cache after altering a menu.

# Answer
> 1 votes
I was able to accomplish this by loading the menu with the link in question. I then acted upon this menu item using its link path. I set the links hidden attribute to 1 to hide it. I then saved the menu link. Then I cleared the menu cache. For the use case for this question, you would just do this when the web service call happens that is requesting to hide the menu. Here is what the code looks like.

```
$links = menu_load_links('secondary-navigation');
foreach($links as $item) {
    if ($item['link_path'] == 'blog') {
        $item['hidden'] = 1;
        menu_link_save($item);
        menu_cache_clear('secondary-navigation');
        break;
    }
}

```

---
Tags: routes
---


title: How to enable block programmatically

text:
# Question
Title: How to enable block programmatically
I need to enable block from my custom module, to show block when the module is enabled, I set the status 1, but nothing happens until I manually change in **Structure \> Blocks** .

```
function test_block_info() {
   $blocks['my-block-id'] = array(
    'info'   => t('My block'),
    'status' => 1,
    'region' => 'sidebar_first',
    'cache'  => DRUPAL_NO_CACHE,
      );
    return $blocks;
 }

```

# Answer
> 5 votes
For drupal 7 the best way will be write hook\_enable function in \*.install file of your custom module:

```
<?php

function YOUR_MODULE_NAME_enable() {
          $blocks = array(
            array(
              'status' => 1,
              'weight' => 20,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*",
              'module' => 'instruments',
              'delta' => 'instruments_sidebar',
              'theme' => 'markets',
            ),
            array(
              'status' => 1,
              'weight' => 19,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*\n<front>",
              'module' => 'instruments',
              'delta' => 'instruments_search',
              'theme' => 'markets',
            )
          );

          foreach($blocks as $block){
            db_merge('block')
              ->key(array(
                'module'=>$block['module'],
                'delta'=> $block['delta'],
                'theme'=> $block['theme']
              ))
              ->fields(array(
                'status' => $block['status'],
                'weight' => $block['weight'],
                'region' => $block['region'],
                'visibility' => $block['visibility'],
                'pages' => $block['pages'],
              ))
              ->execute();
          }
    }

```

This is code from my custom module, and it works :) Here I enable my custom blocks, so I modify 'block' table. For custom blocks you should update 'block\_custom' table too.

If you don't know how drupal store settings, just make changes manually and then check DB.

NOTE: db\_merge function is very useful - it inserts data if they absent (if you just installed your module) or updates it (if you disabled and then enabled module)

# Answer
> 3 votes
you also can utilize Context API. Below is what I did to enable/place a block programmatically.

```
function MYMODULE_context_load_alter(&$context) {

  $your_custom_requirement = ... Whatever you define ...;

  if ($your_custom_requirement === TRUE) {

    $context['reactions']['block']['blocks']['block-machine-name-here'] = array(
      'module' => 'module_that_defined_the_block',
      'delta'  => 'block_delta_name',
      'region' => 'sidebar_first', // place to sidebar
      'weight' => '-10', // block weight in the region
    );
  }

}

```

# Answer
> 3 votes
You have to update database table `block` like Drupal core does:

```
  db_update('block')
    ->fields(array(
      'status' => $block['status'],
      'weight' => $block['weight'],
      'region' => $block['region'],
    ))
    ->condition('module', $block['module'])
    ->condition('delta', $block['delta'])
    ->condition('theme', $block['theme'])
    ->execute();
  // Flush cache
  cache_clear_all();

```

I didn't test it. Maybe you also need to flush block cache before query.

# Answer
> 0 votes
You just have to additionally call hook\_block\_info\_alter() like in the following example. Don't know why. Seems the block needs to be registered first with hook\_block\_info(). And only after that you can alter its settings to enable and place it programmatically. Please feel free to add any better explanation to this answer in the comments.

The downside of this approach is, that this block ain't configurable through the back-end. I mean, indeed it is, but the new values always will always get overridden by the code below.

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
    $blocks['mymodule_block'] = array(
        'info' => t('A Super Duper Custom Block (ASDCB)'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}
/**
 * Implements hook_block_info_alter().
 */
function mymodule_block_info_alter(&$blocks, $theme, $code_blocks) {
    if (!path_is_admin(current_path())) {
        if (isset($blocks['mymodule']['mymodule_block'])) {
            $blocks['mymodule']['mymodule_block']['status'] = 1;
            $blocks['mymodule']['mymodule_block']['region'] = 'Header';
            $blocks['mymodule']['mymodule_block']['weight'] = 2;
            $blocks['mymodule']['mymodule_block']['visibility'] = BLOCK_VISIBILITY_LISTED;
            $blocks['mymodule']['mymodule_block']['pages'] = '<front>';
        }
    }
}
/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
    $block['subject'] = t('ASCDB');
    $block['content'] = _mymodule_block_content();
    return $block;
}

function _mymodule_block_content() {
    return t('Hello World');
}

```

# Answer
> 0 votes
Managing blocks through code can be very valuable, especially if you are running clean deployments of just the codebase. You can use hook\_block\_info\_alter() to configure the default blocks disable/move/change visibility status.

```
<?php
/**
 * Implements hook_block_info_alter().
 */
function mymodule_block_info_alter(&$blocks, $theme, $code_blocks) {
  // move navigation to footer
  $blocks['system']['navigation']['region'] = 'footer';
  // disable the powered by drupal block and login block
  $blocks['system']['powered-by']['status'] = 0;
  $blocks['user']['login']['status'] = 0;
  // change the visibility to front page only
  $blocks['search']['form']['visibility'] = BLOCK_VISIBILITY_LISTED;
  $blocks['search']['form']['pages'] = '';
}

```

The same options can be used to manage your own blocks:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['mymodule_block_example'] = array(
    'info' => t('MyModule: Block example'),
    'status' => 1,
    'region' => 'header',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '',
  );
  return $blocks;
}

```

---
Tags: 7, blocks
---


# Question
Title: Create a view field that contain the sum of specific fields for a specific user
I created a content type (Donation) that contains 3 fields:

* a Donor Name field (user reference).
* a date field (for the donation month).
* the amount of the donation.

I am trying to create a view that returns a table with 2 columns:

* one for Donor Name
* one for the total/sum of all donation for that Donor.

**My question**: How can I achieve the second column (the sum of donations for the specific Donor/user) using views?

# Answer
> Try View Aggregation setting:

* Goto Advanced tab, scroll down below and set `"Use aggregation"` to `'Yes'`.
* Filter Your View with `Name field (user reference)`.
* Now there must be `"Aggregation settings"` inline with your field `"the amount of the donation"`
* Goto `"Aggregation settings"` for `"the amount of the donation"` field and select `'Aggregation type'` to `'Sum'`.

> Thats it, you are good to go now.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Can I theme fields depending on view or block that contains them?
Let's say I have a contact content type with fields address, tel, fax, etc. My task is to create 2 views - with following markup:

First view

```
<ul>
   <li>[address]</li>
   <li>[tel]</li>
   <li>[fax]</li>
</ul>

```

Second view

```
<div>
   <div>[address]</div>
   <div>[tel]</div>
   <div>[fax]</div>
</div>

```

The above is just a simple example, in general I want to know how much control can I get over fields html markup, can I somehow change it depending on view or block that contains the field or even depending on field itself. If so - what is the best way ?

# Answer
> 0 votes
Here is introduction for views2. To read manuals exactly for your views version, use Advanced Help module.

You can template everything, overriding template files in complex manner.

# Answer
> 0 votes
There are some theme plugins available depending upon the you are using (for example for bootstrap theme, there exists a module named views\_bootstrap. So if you can give various formats to your contents.

Also you can change the style settings for each field in views, as shown below:

you can change field wrappers, add your own classes to your wrappers etc..

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


title: Twitter not working on HybridAuth

text:
# Question
Title: Twitter not working on HybridAuth
I have uploaded the website on pantheon. Users aren't able to login by using twitter provider on my website. I'm using the HybridAuth module. When I try to login, it shows this error

> Fatal error: Cannot redeclare class OAuthException in /srv/bindings/6349f4db8cd54067ae94453f36acb8ec/code/sites/all/libraries/hybridauth/hybridauth/Hybrid/thirdparty/OAuth/OAuth.php on line 11

How do I fix this issue? I have a Facebook login as well and it works. And both the logins work on local host.

# Answer
This is how I solved it, I removed the OAuthException class from the OAuth.php file which can be found in `sites/all/libraries/hybridauth/hybridauth/Hybrid/thirdparty/OAuth/OAuth.php` and twitter login started working.
> 1 votes

# Answer
You should update the HybridAuth library to the latest version
> 2 votes

# Answer
I just ran into this issue. In your Twitter App settings, make sure you specify the Callback URL. Should be http://YOUR\_URL/hybridauth/endpoint
> 1 votes

---
Tags: authentication-authorization, social-network
---


# Question
Title: How to add validation on 'next' button using fieldgroup module
I am creating a multiple page registration form using the field group module and I want to add validation on 'next' and 'previous' buttons.

If the first page's field is empty, the user can not go to next page they show some alert or message. I am using jquery but not successful with it.

# Answer
1. Create own module and add

`function MY_MODULE_form_alter(&$form, $form_state, $form_id) {`

```
  if ($form_id == "FORM_ID") {
        $path = drupal_get_path('module', 'MY_MODULE');
        drupal_add_js($path . '/validations.js');
    }
}

```
2. Create validations.js file to the MY\_MODULE folder and put this there

`(function ($) {` `Drupal.multipageControl.prototype.nextPage = function() {`

```
        // Group check here, otherwise every pages required fields invoke error.
        if (this.wrapper.hasClass('GROUP-NAME')) {
       $('input.required').each(function(index) {
        $(this).rules("add",
            { required:true, messages: { required: "field is required."} }
        );
    });

validated = 1;

$('input.required').each(function(index) {
                // You might want $("#YOUR-FORM-ID") here instead of just form.
    if (!$("form").validate().element(this))
        validated = 0;
});
}

if (validated == 1)
    this.wrapper.next().data('multipageControl').focus();
else
    $('html, body').animate({scrollTop:0}, 'slow');

```

} `})(jQuery);`

This actually checks all fields in your form that are required.
> 0 votes

# Answer
You can use Field Group Ajaxified Multipage module plus Inline Form Errors, it should work.

The most important code is:

```
  $form['actions']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
    '#submit' => array('_field_group_ajaxified_multipage_form_submit'),
    '#ajax' => array(
      'wrapper' => $wrapper_id,
      'callback' => '_field_group_ajaxified_multipage_form_callback',
    ),
  );
}
if ($step > 1) {
  $form['actions']['prev'] = array(
    '#type' => 'submit',
    '#value' => t("Previous step"),
    // Since all info will be discarded, don't validate on 'prev'.
    '#limit_validation_errors' => array(),
    // #submit is required to use #limit_validation_errors
    '#submit' => array('_field_group_ajaxified_multipage_form_submit'),
    '#ajax' => array(
      'wrapper' => $wrapper_id,
      'callback' => '_field_group_ajaxified_multipage_form_callback',
    ),
  );

```

Alternatively use: Clientside Validation module (see: Clientside Validation Code Examples).

Check also the outstanding ticket for Field Group module: Validation per multipage for some other ideas.

See also Drupal tutorial: Ten Step-by-Step Code Samples for Learning Form API \- especially: Basic form with button validation and Multistep form
> 0 votes

---
Tags: 7, javascript
---


title: Reset Serial module annually

text:
# Question
Title: Reset Serial module annually
I'm a newbie to drupal 7 for a year by now. I'm trying to make a unique id field that would increment per node of content type I create.

The **computed fields module** \+ **serial module** is the likeliest method accomplishing my goal, yet I'd like to restart the serial number starting each year, I'm totally lost, please help.

This is the code I've used.
The output: 20150001, 20150002 and so on.
Is there a method to restart the serial num. back to 0001 again when it's a new year?

* **Computed Code (PHP)**

```
$entity_field[0]['value'] = $entity->field_serial[LANGUAGE_NONE][0]['value'];

```
* **Display Code (PHP)**

```
$display_output = date('Y') . sprintf('%04s', substr(str_pad($entity_field_item['value'], 4, '0', STR_PAD_LEFT), -4, 4));

```

This is another method I've found, it works on the D6 website, but turns into a blank on my D7 published contents. It's from a field on D6 using **php filter module**.

```
<?php
$case_id_query=db_result(db_query("select  max(field_case_id_value) as id  from {content_field_case_id} "));

$case_id = date("Y") . sprintf ( '%04s', substr ( $case_id_query, 4, strlen ( $case_id_query ) - 4 ) + 1 );
return array(
  0 => array('value' =>$case_id),
);
?>

```

can I transform the method above to D7?

# Answer
> 2 votes
I recommend in the future to peruse the Module issue queue. :)

There are a number of patches in the following issue thread, one of which I've used to reset yearly (and actually modified to reset monthly): https://www.drupal.org/node/2168071

---
Tags: entities
---


# Question
Title: Getting "The form has become outdated" error
I have a multistep node form. Half way through the form through a popup dialog user is asked to login if they have not logged in prior.

Upon successful login when proceeding with next page of the node form, I get this validation error:

> The form has become outdated. Copy any unsaved work in the form below and then reload this page.

I understand it is because `drupal_validation_form()` verifies `$form['#token']` and `$form_state['values']['form_token']` are the same.

How do I avoid this, as this is a special use case (and it's not forgery by some external stuffs).

Any input on this front?

# Answer
Your post just saved me from serious misery. Don't quite know how that connection was made but your post lead me to a small change in my module code. Easy to understand why the "The form has become outdated" error was occurring now though. So see if this might jog your thoughts and help for your case.

My page admin/mymod had a menu item set up that included the following.

```
'page callback' => 'drupal_get_form',
'page arguments' => 'mymod_main',

```

In `mymod_main($op = '')` I am conditionally building one of 2 forms but each build is of course a new form, e.g. `$build['mymod_admin'] = drupal_get_form('mymod_admin')` or `$build['mymod_delete'] = drupal_get_form('mymod_delete')`.

No problem when the page admin/mymod first loaded and mymod\_admin is called. But when the submit button created in mymod\_admin is clicked then mymod\_delete is called and creates it's form. There comes the "The form has become outdated" error that ruined the form processing. The fix is simply to use `mymod_main()` as page callback.

Now there is no crossing up of forms when the admin/mymod page reloads for each of the forms as there is not a starting form from the manu callback and then the second form defined in `$build`.
> 2 votes

# Answer
The error means that `form_token` needs is invalid and needs to be regenerated. This is basically a hidden form field (generally used to protect against cross-site forgeries).

Normally a token element is automatically added to each Drupal form by `drupal_prepare_form()`, so you don't generally have to add one yourself, unless you're writing your own code.

If you're trying to program some multi-page form, you probably need to re-generate the token on each submit using `drupal_get_token()`, e.g. as shown here:

```
$form_state['input']['form_token'] = drupal_get_token($form['#token']);

```

---

As for workaround to force regeneration of form token in form\_alter, check the following example:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id === 'your_form_entityform_edit_form' && !empty($form_state['input']['form_id'])) {
      $form_id = $form_state['input']['form_id'];
      $form ['#token'] = $form_id;
      $form ['form_token'] = array(
        '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
        '#type' => 'token',
        '#default_value' => drupal_get_token($form['#token']),
        '#parents' => array('form_token'),
      );
    }
}

```

---

### Troubleshooting

* Double check if your form is not hardcoded, otherwise add the token as suggested by @thirdender:

```
<input name='form_token' type='hidden' value='<?php print drupal_get_token('MY_FORM_ID'); ?>'>

```
* Check if the error happens on your form, as it could on other form (e.g. form within the form).
* Debug `drupal_valid_token()`.
> 1 votes

---
Tags: forms
---


title: Calls wrong image file path

text:
# Question
Title: Calls wrong image file path
I have simple Image field, its file path is set to `field/image` so when you upload a file, its path is something like `/sites/default/files/field/image/image.jpg`.

But when I create content and upload the file, first of all, the thumbnail preview doesn't show up and when saved, the image is not loaded, because for some reason it's calling a wrong path of `sites/default/files/styles/large/public/field/image/image.jpg`.

But why? Why that path? There's no such path. Who is calling the wrong URL? It should call the correct path where the picture was uploaded and that's `/sites/default/files/field/image/image.jpg`.

I've tried using "Original Image" for the image field display, instead of the "Large" style, but no matter what I use, `/styles/large/public/` is added to the URL.

Permissions are correct on the /sites/default/files folder (the original image is uploaded successfully), there are no related errors in the dblog report, and there's no problem with GD/Imagemagick in the status report.

What could be adding the extra part to the image URL?

# Answer
You might simply be editing the wrong "display". Happened to me :)

If you have the Display Suite Drupal module installed, node types can each have several option sets (called "displays") how to display their fields, and a template or view then selects one of them to show the node. With the Taxonomy display Drupal module, the same is possible for taxonomies.

In these cases, you might simply be trying to adapt the image style setting in the wrong display. Check if you have a second line of tab-like options (starting with "Standard") for either nodes or taxonomies. In that case you have multiple displays for this node type / taxonomy, and you have to configure the image type for the *right* one.

You'll have to visit one of these admin menu items to check for displays:

* "Structure → Content Types → \[your content type\] → Manage Display"
* "Structure → Taxonomy → \[your taxonomy\] → Manage Display"
> 1 votes

---
Tags: 7, media, uri
---


title: Using token in page.tpl.php?

text:
# Question
Title: Using token in page.tpl.php?
I downloaded the social media module and I found this token: \[socialmedia:sm-twitter\_username\]. I want to show it where the *Read more* / *Add new comment* section is, under an article. Since I can't find a block that is for that sections how can I just insert it into the code?

# Answer
The *Read more* link is added by `node_build_content()`, while *Add new comment* is added by `comment_node_view()`; other links like those can be added by any module implementing `hook_node_view()`.

So, to answer your question, there aren't theme regions you could use to add links where you see *Add new comment*, and you don't add them in page.tpl.php. You need a module implementing `hook_node_view()`, for example using the following code.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  $links['socialmedia_twitter'] = array(
    // Depending on what the token returns, you need to use one of these lines.
    'title' => token_replace(' [socialmedia:sm-twitter_username]'),
    'href' => token_replace(' [socialmedia:sm-twitter_username]'),

    'attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => format_username($node)))),
  );

  $node->content['links']['mymodule'] = array(
    '#theme' => 'links__node',
    '#links' => $links,
    '#attributes' => array('class' => array('links', 'inline')),
  );
}

```

Rather than calling `token_replace()`, I would look at the module code, and see which function generates the token, and use it instead of calling `token_replace()`, since you are replacing a single, static, token you already know which one it is.
In any case, you need to check the code implemented by that module, as some token require an extra parameter passed as `$data`; without that, they don't work, or they don't produce the expected output.

In a theme, you would implement hook\_node\_view\_alter().
> 0 votes

---
Tags: nodes, hooks, tokens
---


title: How to Customize View Output

text:
# Question
Title: How to Customize View Output
I'm working on some views and I came across a requirement I'm not sure how to handle.

I need the title for each returned item to link to a specific URL. However, if another field (a link field) isn't empty, link to that link instead. I believe I need to edit the view template files but I'm not sure how to get started.

* In my view, I've found the "Theme: Information" section and am able to get template files working for my view. However, it's listing display, style, row, and field templates. Where would I incorporate the logic I described above for the title field?
* Once in a template file I am unsure of what variables are available to me. Is there a list or a way to discover these?

# Answer
Views is rendered by some of \*.tpl.php files, they are:

* views-view.tpl.php. Main view template.
* views-view-unformatted.tpl.php. Default simple view template to display a list of rows.
* views-view-fields.tpl.php. Default simple view template to all the fields as a row.
* views.view-field.tpl.php. This template is used to print a single field in a view.

If you want to use two different fields from one view in one file, I recommend to use `views-view-fields.tpl.php` where you can manipulate of all fields which you assign to view.

The `views-view-fields.tpl.php` has three variables to use: `$view`, `$fields` and `$row`. I suggest to use only `$fields`.

Then, if you have field named `field_image` you can render its using `$fields['field_image']->content` or `$fields['field_image']->raw`.

Also, I recommend to read more about it: Views template files
> 1 votes

---
Tags: views, theming
---


title: University hierarchy in drupal 7

text:
# Question
Title: University hierarchy in drupal 7
I'm completely new to Drupal. I've been reading a lot of questions but I could not find anything that fits my needs. I need to create an internal site for my university.

There is one person that is the university coordinator (UC). This person should be able to add a department coordinator (DC) in a way that there are two fields in the form: department name (text field) and the email of DC. After submitting the form a new user should be created with the username the same as name in the email (before @) with a random password that is sent to the email address. This user should be below UC in the hierarchy. DC then should be able to add institute coordinators (IC) the same way. Each DC should be able to manage their ICs. How can I set-up this scenario? Which modules should I install? Is it possible without writing code?

# Answer
1. We need `university coordinator` role, we can create it in `People > Permissions > Roles`.
2. Next, we create `department coordinator`. We do it just like in first step.
3. `University coordinator` can make a new user and set a role to it. So we create user `DC`, set the e-mail `dc@example.com` and set the password `loremipsum`. Standalone Drupal has not possibility to generate a random password.

Then, to let `department coordinator` manage the `insitute coordinators` you should install Administer Users by Role. One problem - this module don't let you to manage content created by the users.
> 1 votes

---
Tags: users
---


# Question
Title: Node registration form block - hide if registered
I'm using "Node registration: this page's form" block, but I want to hide it when user has registered for this node already. I know i should use **'If' statement** but i don't know what condition to use.

# Answer
> 0 votes
Node registration not providing a function in it's API for that, however you could include the "node\_registration\includes\node\_registration.api.inc" file and use their internal function that the module use to check for user access for a specific node.

```
// Include the file
    module_load_include('inc', 'node_registration', 'includes/node_registration.api');

 if (_node_registration_user_registered($node, $account)) {
    //do something
  }

```

---
Tags: nodes
---


# Question
Title: Insert a countdown in each node based on a pre-existing date field
I would like to put a countdown for each node using a field expiration date (whose values users have already entered).

I explain you my case:

My user publishes an event that have an expiration date (I already have many values for this field inserted by the users and some of them are of events still in progress). I would like to insert a countdown in each page of the events, based on the expiration date inserted by the user and the date when the user has published the event on my website.

I tried with this module: field timer but I don't know how to do the connection between this module and the expiration date.

Thanks in advance for your help.

# Answer
> 1 votes
I assume you have two fields in one content type - `countdown_date` and `expiration_date`. Both values user has to insert manually. And after submit action, you want to assign `expiration date` to both fields, yes?

Read about hook\_node\_submit(). In your `MYMODULE_node_submit($node, $form, &$form_state)` you can check the type of content, then assign `expiration_date` to `countdown_date`. This method works with save and preview's action.

For more detailed answer I need more details about these fields.

---
Tags: 7, rules, datetime
---


# Question
Title: Filter based on the current node field value
I have a Webform where it's used to get product comments. This webform is exposed in a node page and has a field that is populated automatically with a value from the current node, lets say "Manufacturer" and this is just a plain text field. So there are multiple products with the same manufacturer. For example Intel i5 2500k and Intel Motherboard Model-No-1.

I'm using the Webform 7.x-4.x for this. What I have done is use the Webform Submission Data field in Views to display the different data but now what I'm trying to do is when I go to a product, I want the view to filter all the Webform submission by the current product's manufacturer. So when I go visit the i5 2500k page, the view will list also the Webform submissions for the Intel motherboard.

# Answer
> 0 votes
So I have found the awesome way to achieve this and it's using Views Contextual Filter, Content pane arguments and Panel pane arguments(automatically added when you add an argument in Views contant pane).

1. In the View, add a Relationship w/c is Webform Submission Data where it's set to the Webform and field you want to get from the contextual filter.
2. Add a Contextual filter for the relationship you have created.
3. Select provide default value and choose Raw value from URL and just choose 1.
4. Go to the view content pane argument and click edit. You should see a field to reference the contextual filter you have created and add a label you want.
5. Go to the panel pane's setting you want to get the data from.
6. Go to it's settings and you will be presented with a field where you can place the tokens provided by you panel page.

---
Tags: 7, views, webforms
---


title: Creating a NICE collapsible menu

text:
# Question
Title: Creating a NICE collapsible menu
Does anyone know how to create an expandable menu like they have on this page?

http://www.geofunders.org/events/geocc/registration

Note: scroll down to see the menu under 'Conference Policies'. First one is 'Participant Eligibility'.

# Answer
It's just simple jQuery.

SEE THIS EXAMPLE I MADE FOR YOU

**In Drupal to use jQuery you need to wrap it in**

```
(function ($) {

    //code goes here

})(jQuery);

```

so your code should look like this

```
(function ($) {

    $(document).ready(function() {
         $(".button").click(function () {
             $(this).next('.content').slideToggle();
         });
    });

})(jQuery);

```

Remember that you need to add to your css `.content { display: none; }` OR you could do it with jquery

```
(function ($) {

    $(document).ready(function() {
       $(".content").css("display", "none");
         $(".button").click(function () {
             $(this).next('.content').slideToggle();
         });
    });

})(jQuery);

```

**Note:** this code works assuming there are no divs in between your `.button` and `.content`. If there are divs in between them, you might need to modify the slideToggle line.
> 1 votes

---
Tags: routes
---


# Question
Title: "File (Field) Paths" and "Media" modules: files not saved in the intended folder
I'm trying to use both the "Media" module (1.4) (to manage uploaded files) and the "File (Field) Paths" (to keep the uploaded files organized in various subfolders).

Basically, I have a content type that has several taxonomy fields and a media field. The taxonomy fields are mandatory and accept only one value each. I want the media file to be uploaded in a folder that uses the various taxonomy fields as a path, and I've configured the file field accordingly (using the "file (field) paths" options). So the file should be saved to e.g.:

```
sites/default/files/documents/[taxonomy-term-1]/[taxonomy-term-2]/filename.extension

```

My problem is that, when manually creating a new node and adding a file to it, the file is just saved to the root of the public files directory:

```
sites/default/files/filename.extension

```

So the "file (field) paths" configuration for this field seems to be ignored. This also happens if I add a file *after* the node has been created and saved.
Since I expect the site will have a lot (thousands, maybe tens of thousands) of uploaded files, I fear that storing all of them in the same folder will have an impact on the performance of the site.

What's strange is that when I use the feeds module to import and create nodes in bulk (via a CSV file), the "file (field) paths" configuration is working as intended. The files are saved in the "complex" path.

So why wouldn't it work when creating a node manually?...
Any idea for a solution?

Thanks in advance.

# Answer
> 0 votes
No definitive answer so far, but I should note that I have been able to make this option work again simply by enabling the (very intimidating) option **"Active updating"** in the field's settings. (So in `admin/structure/types/manage/[content-type]/fields/[field-name]`)

The "File (Field) Paths" developer warns that *"This feature should only be used on developmental servers or with extreme caution"*, but since it's the only solution I've found so far, I'm going to keep this option enabled for now.

Hope this helps someone.

# Answer
> 0 votes
Update to File (Field) Paths \>= 7.x-1.0-rc1 and issue is resolved.

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


# Question
Title: In Drupal 7, how do I create a custom rules event for any and all file entities?
I'm having trouble creating a small module to add an Event scenario to Rules using the Rules API. Basically, I'm creating a rule that should detect to see if certain fields of a file entity have certain values upon saving that file. Then, if the conditions are met, the action is to change the URL path alias of /video/ to point to the newest video file in my system (file/\[fid\])

But I'm getting stuck even creating the new Event to even work. My code below does succeed in making it appear in the Rules event list, and then when setting conditions, the Data Selector exposes the correct file fields. But, when I set a very simple condition or even no condition, my action does not fire.

(A bigger aside: shouldn't the Rules module come pre-packaged with functionality for dealing with file entities? There are plenty of events for nodes, users, and comments, but nothing for files.)

So, what is wrong with my code below?

```
/**
 * Implementation of hook_rules_event_info().
 */
function rules_extended_rules_event_info() {
  return array(
    'rules_extended_rules_event_file_insert' => array(
      'group' => t('Entity'),
      'label' => t('After saving a new entity'),
      'module' => 'rules_extended',
      'variables' => array (
        'file' => array ('type' => 'entity', 'label' => t('created entity')),
      ),
    ),
    'rules_extended_rules_event_file_update' => array(
      'group' => t('Entity'),
      'label' => t('After updating an existing entity'),
      'module' => 'rules_extended',
      'variables' => array (
        'file' => array ('type' => 'entity', 'label' => t('updated entity')),
      ),
    ),
  );
}

```

# Answer
You can't just declare `hook_rules_event_info()`, it just tells rules about an event type, but you still need to invoke that event.

To invoke a declare event, use `rules_invoke_event()`.

*Example*

```
/**
 * Implements hook_entity_insert().
 */
function rules_extended_entity_insert($entity, $type) {
  if ($type == 'file') {
    rules_invoke_event('rules_extended_rules_event_file_insert', $entity);
  }
}

```
> 1 votes

---
Tags: 7, rules, files, entities
---


title: add unrestricted html to ckeditor

text:
# Question
Title: add unrestricted html to ckeditor
I am having issues with drupal and ckeditor. I would like to saev following code:

```
<div class="a2a_kit">
    <a class="a2a_button_facebook_like" data-action="recommend" data-href="http://example.com/" data-layout="box_count" data-width="55"></a>
</div>

```

However due to ckeditor's filters almost everything gets stripped. I tried various advices - turning off advanced content filter or adding `config.allowedContent = true;` inside custom javascript configuration window. Nothing what I tried works. Thank you for any advices.

# Answer
> 1 votes
go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.

**If the above does not do it**, depending on which one you are using (filter or full html) You need to go to

/admin/config/content/formats/filtered\_html

OR

/admin/config/content/formats/full\_html

try unchecking the correct faulty and chopped off html box.

---
Tags: 7, wysiwyg
---


# Question
Title: Need to find and disable an email that may be coming from a module
Drupal 7 question: There is an email that goes to users that seems to be produced by a module (on a role change) that is confusing to a specific client's users. They would like me to disable that specific email, but I have not been able to figure out where to do that.

I've gone through the users and roles and configuration for the module. I've done a search on the text in the site files (the snippets of text that do not have field-specific data) and come up empty.

So, generically, I'm wondering about how to disable emails from being sent if there doesn't seem to be a setting to do so in the dashboard. I would be happy to add more information here that is about the module specifically, but it seems that it would be helpful to have some generic pointers of where to look, in case the situation comes up in other modules, as well.

# Answer
> 1 votes
If you have the Rules module enabled, go and check the rules

```
/admin/config/workflow/rules

```

It's very likely that there is a rule that is sending the emails. So just disable it.

# Answer
> 0 votes
Search the module code for usages of 'drupal\_mail'.

---
Tags: users, emails
---


# Question
Title: Why does file_create_url() not work for theme images?
With the latest Drupal 6 update, `file_create_url()` stopped working for all the files other than public or private files.

I think the assumption is that a file must be either in the public files or in the private files directory.

How can I get the image URL for those images that are in a theme or a module directory?

# Answer
You don't need `file_create_url()` to turn those URIs into a URL to use in `theme_image()`.

For theming images in Drupal 6, just supply a path string relative to `base_path()` (the base of the Drupal install directory). For module/themes this can path can be retrieved with `drupal_get_path()`.

For example:

```
//Render an image under the admin_menu project
print theme('image', drupal_get_path('module','admin_menu').'images/bkg_tab.png'))

```
> 2 votes

---
Tags: 6, files
---


# Question
Title: Create a view to display the list of content created by user and any published content
I am creating view for displaying content list and some exposed filters. I wanted to display **all published content of any user** and **all content created by user(current user)**. Currently i am able to display only own content list by using contextual filter:

* Click "Advanced" \> "Contextual Filters"
* "Add" \> "Content: Author uid"
* "Provide default value" \> "User ID from logged in user"
* Save

How can i display in list **a combination of All published contents from all authors + published and unpublished contents of logged in user**?

# Answer
> 1 votes
You can use Filter **"User :current"**.if you not get desire result add relation of user table then try it

# Answer
> 0 votes
You anyway want to display all content from all the authors and current user so no need to add contextual filter, then it's going display all the content from your site with logged in user's content too.

Also you can try this link

---
Tags: views
---


# Question
Title: How do I make an object available as a token?
I have created a custom token. Inside my token's code, I'm getting a node object. I want to give the users the option of displaying this node's properties. So, for example, assuming that my token's name is `[mycustomtoken]` I want them to be able to write:

`[mycustomtoken:author]` so that they get the node's author or

`[mycustomtoken:title]` to get the node's title.

Is there a way to do this in Drupal?

# Answer
Yes, by making your token a dynamic token in `HOOK_token_info()` and using the provided name during `HOOK_tokens()` to dynamically create your replacements.

*Example*

```
function HOOK_token_info() {
  ...

  $tokens['mycustomtoken'] = array(
     ...
     'dynamic' => TRUE,
  );

  ...
}

function HOOK_tokens($type, $tokens, array $data = array(), array $options = array()) {
  ...

  if ($type == 'mycustomtoken' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      if (isset($node->{$name})) {
        $replacements[$original] = $node->{$name};
      }
    }
  }

  ...
}

```
> 1 votes

# Answer
Check this code:

```
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
    $replacements = array();
    $sanitize = !empty($options['sanitize']);

    if ($type == 'node' && !empty($data['node'])) {
        $node = $data['node'];

        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'pathauto':
                    $replacements[$original] = str_replace(
                            array('&', '&'),
                            'and',
                            $sanitize ? filter_xss($node->title) : $node->title
                    );
                    break;
            }
        }
    }

    return $replacements;
}

```
> 0 votes

---
Tags: 7, tokens
---


# Question
Title: How to call external api to pull data into json format?
There is an api that is used to expose data from an external website. How can I use the drupal API to call the external api and pull the data into json format?

the external api would be, for example, "api.website.com/api/get\_data".

return results would be in json format "{"data":\[....\]}

How would I use a module to call the external api and return the data in json?

# Answer
> 2 votes
It depends on what you wish to do with said data.

If you are looking for a purely code approach, you could do something like:

```
$response = drupal_http_request($url);
$result = json_decode($response->data);

```

If you want a Rules based approach, you could could use the Rules HTTP Client module, which allows you to do essentially the same as the above code but via the Rules UI.

# Answer
> 2 votes
Drupal offers two functions for encoding and decoding JSON. To encode an array into `JSON usedrupal_json_encode()` and to decode a JSON object into an array use the - can you guess it? -`drupal_json_decode()` function.

**Encoding JSON**

First, let’s look at encoding an array into JSON. Take this array for example:

```
$array = array('Boat', 'Car', 'Ship', 'Building');

```

If we were to encode the above array into JSON, you will get `["Boat","Car","Ship","Building"]` returned. Here is a code example:

```
$array = array('Boat', 'Car', 'Ship', 'Building');
$output = drupal_json_encode($array);
// $output will be ["Boat","Car","Ship","Building"]

```

**Decoding JSON**

Now let's look at decoding a JSON object. If you were to running the following code:

```
$json = '["Boat","Car","Ship","Building"]';
return drupal_json_decode($json);

```

The `drupal_json_decode()` function will return an array.

**Pulling In JSON Objects**

The next example I want to demonstrate is how to pull in a Twitter account using Twitter's GET users/show REST API.

First, we’ll need to get the JSON object and for this we’ll use the drupal\_http\_request() function:

```
$request = drupal_http_request('https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true');

```

Within the `$request` variable, there will be a data property `$request->data`. This stores the JSON object.

The only thing left to do is decode the data property to get access to all the information.

```
$request = drupal_http_request('https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true');
return drupal_json_decode($request->data);

```

**JSON Endpoints**

The last item I want to demonstrate is how to create a JSON endpoint for content on a Drupal site. For example, if you navigate to example.com/node/1/json the website will output a JSON version of the content. This will show you how to output a full JSON page using the drupal\_json\_output() function.

1. First we must implement a menu item using the hook\_menu. The menu item path needs to be "node/%node/json". For more details on how to use hook\_menu check out the API documentation.

/\**

* Implements hook\_menu(). \*/ function ww\_json\_example\_menu() { $items\['node/%node/json'\] = array( 'page callback' =\> 'ww\_json\_example\_endpoint', 'page arguments' =\> array(1), 'access arguments' =\> array('access content'), ); return $items; }
2. Create a "page callback" function for the menu item. Also, make sure that you add a $node variable to the function signature. For this example, the page callback is "ww\_json\_example\_endpoint". Finally, we pass the $node object through to the drupal\_json\_output() function. If you go to node/1/json you should just see outputted JSON code.

function ww\_json\_example\_endpoint($node) { drupal\_json\_output($node); }

---
Tags: 7, javascript
---


title: How to css Views Tree module theme

text:
# Question
Title: How to css Views Tree module theme
I am using the module Views Tree. Apparently, it gets the hierarchical listing of taxonomy terms, and outputs a tree with indentation levels (two levels).

However, I am not able to style or css it, because the overriden tpl.php ( views-tree.tpl.php ) does not exist, and when I copy views-view-row.tpl.php in the theme folder, renaming the file to views-tree.tpl.php I almost get it, except that the rendering is: first the parent taxonomy terms, and next the children terms. Exactly as without the module.

So I am unable to use none of the available .tpl.php for **Views**, and cannot change the style, only with css, which is not adequate (there are ul tags which I want to have different classes, for example).

So, sadly, I must use template.php and views\_get\_view\_result to recover the View and css it, which is exactly as not having the module installed at all! What am I doing wrong?

# Answer
> 0 votes
Finally, I discovered that the module uses the core listing resources, so the theming can be achieved via template.php and function **NAMEOFTEMPLATE\_item\_list**($variables). The only caveat is that, as the call to this function is recursive, you will need some tricks to know in which level you are. Those tricks could depend on the listing itself; another solution would be to modify the module itself to send the level.

Honestly, I think this in an example of a module whose existence is questionable. A direct treatment of the View\_results is much faster and easier to theme.

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


# Question
Title: How to select a view inside a custom module form
I would like to have "select" with some views so I can chosse one of them and the submit the selection to display the result. something like this:

And this is close to what I want :

```
  $form['title'] = array(
'#type' => 'select',
'#title' => t('Display amount'),
//'#required' => TRUE,
'#options' => drupal_map_assoc(array('1','2', '3', '4', '5', '6', '7', '8')),
'#default_value' => 5,
'#ajax' => array(
    'callback' => 'form_ajax_submit',
    'wrapper' => 'contenido-div',
    'method' => 'replace',
    'effect' => 'fade',
   ),
    );

 $form['content'] = array(
'#type' => 'select',
'#title' => t('Content'),
'#options' => array(node_type_get_names()),
'#ajax' => array(
    'callback' => 'form_ajax_submit',
    'wrapper' => 'contenido-div',
    'method' => 'replace',
    'effect' => 'fade',
),
);

$form['views'] = array(
'#type' => 'select',
'#title' => t('views'),
'#options' => array(),
'#ajax' => array(
    'callback' => 'form_ajax_submit',
    'wrapper' => 'contenido-div',
    'method' => 'replace',
    'effect' => 'fade',
 ),
);

```

Thanks

# Answer
As Views is a CTools Export UI based module, the correct way to load all views is by using the CTools Export function: `ctool_export_crud_load_all()`

*Example*

```
ctools_include('export');
$views = ctools_export_crud_load_all('views_view');
$options = array();
foreach ($views as $view_id => $view) {
  $options[$view_id] = $view->human_name;
}

```
> 1 votes

---
Tags: views, hooks
---


title: Get the field data in email body

text:
# Question
Title: Get the field data in email body
whenever user creates content, I want to get the few fields data of content in the mail body and trigger mail,, as of now i have created rule to trigger mail with text comparison condition for specific field.

ex: I have content with user id, pancard Id fields etc,now i want to get this content field data in mail body and send mail to user.

# Answer
Depending on the kind of rule event which I expect to be "When a new content is created" in your case.

When you choose action of rule as "send email" it allows you to use tokens, as declared by token modules. You will see the node tokens for the field as well, use it and those will get automatically replaced.
> 1 votes

# Answer
you can use the hook\_node\_insert.

```
function yourmodule_node_insert(&$node) {
  $body = $node->body;
  drupal_mail('yourmodule', 'your_key', $to, user_preferred_language($user), array('body' => $body), $from, TRUE);
}

```

This hook will trigger whenever you create a node.

and then use hook\_mail

```
function yourmodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'your_key':
      $message['body'][] = t('@body', array('@body' => $params['body']));
      $message['subject'] = $subject;
      break;

  }
}

```
> 0 votes

---
Tags: emails
---


# Question
Title: how to print db_select result using watchdog?
I'm trying to debug below code:

```
$perishables = db_select('userpoints_txn', 'up_txn')
    ->fields('up_txn', array('txn_id', 'uid', 'points', 'remainder', 'time_stamp', 'tid', 'operation', 'description'))
    ->condition('status', 0, '=')
    ->condition('expired', 0, '=')
    ->condition('expirydate', 0, '!=')
    ->condition('expirydate', REQUEST_TIME, '<')
    ->execute();
 watchdog('userpoints', 'perishables->remainder  %perrr', array('%perrr' =>$perishables), WATCHDOG_DEBUG);

```

Can anyone help me how to get $perishables in the report log files?

# Answer
> 1 votes
Use `print_r()` with the `$return` argument set as `TRUE`.

*example*

```
watchdog('userpoints', 'perishables->remainder %perrr', array('%perrr' => print_r($perishables, TRUE)), WATCHDOG_DEBUG);

```

# Answer
> 2 votes
1. execute(): - this will not return query results to you. All it will return is database connection object and query string. See the screen shot.
2. In order to get query results, you need to call any of the retrieve function. For example

fetch(); // Use the default fetch mode.

fetchObject(); // Fetch as a stdClass object.

fetchAssoc(); // Fetch as an associative array.
3. Debugging queries:

I would recommend you to use devel module and its help functions as dpm() and dpq() . They will make your debugging process a lot more faster can clean than watchdog.
4. watchdog() - I confirm the answer by @Decipher(+1) will record the query object in database, see the scrrenshot tested with a simple query

Might be that log is not something that you want to see, a small change to @Decipher answer if you want to see the query String

```
watchdog('userpoints', 'perishables->remainder %perrr', array('%perrr' => print_r($perishables->queryString, TRUE)), WATCHDOG_DEBUG);

```

**You can definitely make it better the way you want with above mentioned tools**

---
Tags: database, debugging, log-messages
---


# Question
Title: how to prevent user from clicking button twice on server side in jqx
```
$('#save').on('click',function(){
  $('#form').jqxValidator('validate');
});

```

How can I prevent user from click button twice on server side?

# Answer
> 1 votes
Preventing users from submitting forms twice becomes very easy with that module hide\_submit.

Take a look at the issues as many features patched but not yet in the master branch of that module.

It may guides to achieve the same thing for (non submit buttons).

---
Tags: javascript, ajax
---


# Question
Title: Make a views listing of nodes in Search API with multiple parameters to sort and more
***Facts*:**

I'm working on a classified ads (Cars and Parts) website that people can post their ads with the ability to make the ad `Featured` or `Promoted` (Using Flag module)

**What is a featured Ad**: if an ads is featured it will show up and stays at the top of the list and the design is a bit different (like any other websites with featured ads)

**What is a Pormoted Ad**: Users can promote their ad and boost the ad to the top of the list everyday so it stays at the top, wether it's Featured or not.

On the search results page, I'm using Search API, Search API Sorts and FacetAPI.

***Requirements***

Since there is a lot of options to filter the search results, I wanted to use Ajax for better user experience and performance, also I want to keep the result page in this order even if it gets sorted or filtered:

1. Featured Ads (Prioritized by Promoted date Featured Ads then Submitted Date)
2. Promoted Ads (Prioritized by Promoted date and submitted date)
3. Free Ads (Prioritized by Submitted date)

So I want to be able to sort and filter my results but still keep the main priority.

so I tried Ajax Facets module but since it doesn't generate URL the rest of my website functionality kinda breaks!

Also tried Search API Sorts and Facet API for filtering and sorting, but it breaks my priority of displaying the ads (featured, promoted, free), even if I add some criteria in it's views.

***Case Study:***

A good case study is http://jobs.drupal.org, it has everything that I want except the Promoted part!

Thank you so much in advance.

# Answer
> 1 votes
In Search API you can assign a 'boost' for results depending on defined field:

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


# Question
Title: How to create a button on module configuration page that calls a custom php function?
I am creating a custom module that has a button on the module's configuration page. When the button is clicked, a custom php function (located in the `custom_module.module` file) needs to run to perform some task.

How can I create a button on the custom module's configuration page that allows me to click the button to manually run the custom php function?

# Answer
Each different button on your form can perform a different function by assigning it the **#submit** property:

```
function mymodule_my_form($form, &$form_state) {
  $form['button1'] = array(
    '#type' => 'submit',
    '#value' => 'Perform 1st Action',
    '#submit' => array('mymodule_my_form_action_one')
  );

  $form['button2'] = array(
    '#type' => 'submit',
    '#value' => 'Perform 2nd Action',
    '#submit' => array('mymodule_my_form_action_two')
  );
}

function mymodule_my_form_action_one($form, &$form_state) {
  // Perform the 1st action
}

function mymodule_my_form_action_two($form, &$form_state) {
  // Perform the 2nd action
}

```

Only the specified submit function will run for each button click.
> 1 votes

# Answer
You should use the Drupal Form API for it.

Please, check it: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#submit (it is about adding button).

And it: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#submit\_property (it is about run custom function).
> 1 votes

---
Tags: forms
---


# Question
Title: Permission for specific role to edit ANY comment
I'm using the default Drupal 7 comments for my website and I would like to give specific roles the ability to edit any comment. My role can edit just about everything about a comment(Name, email, time etc.) but not the comment itself.

Only as user 1 I can edit the comments it seems.

Am I missing something here?

**EDIT** I just figured out that it's not the permission for the field. It's the permission for the Rich Text Editor that was wrong. Checking the normal Administer comments and settings was enough. I'm an idiot.

# Answer
> 1 votes
The permission drupal gives by default says 'edit own comments'. I do not see a permission which allows 'edit any comment'. Try using User Tweaks module. Module page says

> edit any comments (and edit any comments), which allows user with the Post comments permission to edit comments. The permission is not required for users with the Administer comments permission.

**Updated Answer-**

I just saw the comment module code. You simply have to give Administer Comment Permission for that Role, but it will give delete permission as well.

If you are comfortable in custom coding you can alter the access callback for comment edit menu item.

If you see hook\_menu implemented by comment module, here is the delete menu item code

```
 // Every other comment path uses %, but this one loads the comment directly,
  // so we don't end up loading it twice (in the page and access callback).
  $items ['comment/%comment/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'comment_edit_page',
    'page arguments' => array(1),
    'access callback' => 'comment_access',
    'access arguments' => array('edit', 1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
  );

```

which basically calls comment\_access function as

```
function comment_access($op, $comment) {
  global $user;

  if ($op == 'edit') {
    return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  }
}

```

You can implement hook\_menu\_alter to change access callback for edit, something as below.

```
  // Implements hook_menu_alter
  function mymodule_name_menu_alter(&$items)  {
    $items ['comment/%comment/edit']['access callback'] = '_my_module_name_custom_callbck';
  }

```

// Access Callbck for comment edit.

```
  function _my_module_name_custom_callbck($op, $comment) {
     if ($op == 'edit') {
     global $user;
      return (in_array('your_user_role', $user->roles) || $user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
    }
  }

```

**Note: I have not evaluated why drupal is not giving it by default, it will still be important to identify.**

# Answer
> 0 votes
Comment Permissions

> The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

ACL

> The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.

---
Tags: users, comments
---


# Question
Title: Add some extra text(html+content) before start view. (Within the div from the view)
I'm trying to put some extra hard coded HTML into a view before the sum of the view starts.

www.peace-in-the-city.be

On the homepage you see a section 'visitors'... it shows 4 recent visitors. If my client add a new visitor in the backend... This new visitor will show up a older one is disappearing...

But now my client wants to show one visitor (kermit the kicker) always on the left.

So i want to put that visitor hard coded in... First i tried to put into the home.tpl... But then it shows up out of the div around the view, and that f\*** up my design. I used the classes from the view to style...

So now I want to put the HTML-code into the view self (within the divs from the view), put i don't find the solution...

Anybody? I tried some options "HEADER" in the view, but there is no space showing up where i can put the HTML-Code in...

Thanks for reading and support :-)

Kristof

# Answer
> 3 votes
In the header add the type **Global: Unfiltered text** and enter your HTML there.

A more Drupalish way would be

1. Mark "Kermit the Frog" as *Sticky at top of lists* in it's *Publishing options* on it's node edit form.
2. Alter the *Sort criteria* your View to have two criteria: *Content: Sticky (DESC)* followed by *Content: Post date (DESC)*.

---
Tags: views, theming
---


title: I want to create a custom Rule?

text:
# Question
Title: I want to create a custom Rule?
I have to create a custom rule . Basically its a site for faculty.Before a faculty is added to site an authentication is done by there ldap server on first time login.After user is authenticated it redirects to site.Each faulty has there own vsite.So issue is that a faculty who has been removed from ldap then his/her vsite must be disabled. Now is it possible to do it through Rule ??

# Answer
> 0 votes
Rules are very important and most common using thing in Drupal. We can create custom rules programmatically using the hook\_rules\_action\_info. There is a useful hook `hook_rules_action_info()` provided by rules api to create custom rules programmatically. Using this We can use our custom functions to perform the actions that we require.

Following is a sample of the hook\_rules\_action\_info implementation

```
function sample_custom_rules_action_info() {
  return array(
    'sample_custom_action' => array(
      'label' => t('Custom Rule Action'),
      'parameter' => array(
        'param1' => array(
          'type' => 'int',
          'label' => t('Sample Label'),
        ),
        'param2' => array(
          'type' => 'commerce_order',
          'label' => t('Sample Label2'),
        ),
      ),
      'configurable' => FALSE,
      'group' => t('sample Custom module action'),
      'callbacks' => array(
        'execute' => 'sample_custom_action',
      ),
    ),
  );

```
* Label for the rule action appears in the Rules interface.
* Parameter that needs to be passed to the custom action function
* A group for this element, used for grouping the actions in the interface.
* callbacks are array of custom functions that to be used for this action's functioning.

This function has more parameters, but the above are most required ones to create a custom action.

**Video tutorial**

Creating a Rules Action

---
Tags: rules, users
---


title: How to send mail based on date field?

text:
# Question
Title: How to send mail based on date field?
In a user profile I have `start date` and `end date`, I want to send the mail to user every months once based on the `end date`.

The `end date` also needs to get updated automatically, based on the start date i.e. every months from current date (`start date`).

Can anyone help me on this?

# Answer
To achieve this you have to use Rules as well as Scheduler module. Please follow the documentation links: Rules documentation: https://www.drupal.org/documentation/modules/rules Scheduler documentation: https://www.drupal.org/node/108984

You can also refer: http://www.webwash.net/tutorials/how-send-follow-emails-using-rules-scheduler-drupal-7
> 1 votes

# Answer
This question seems like a variation of the question about "Rule to store user's last post date and scheduled rule based 30 day reminder". I don't think it is a duplicate of it, but my answer to that question should be pretty close to what you're looking for.

If you'd replace `field_next_article` by your "end date", you already have what's suggested in "Step 1". You should be able to reuse most of the Rules component included in Step 2, and the Rule included in step 3, with only some minor changes.

I don't think you would need your "start date" for the purpose of sending such eMail. Though you might want to keep that "start date" for whatever other reason you'd want to keep it.
> 0 votes

---
Tags: rules
---


# Question
Title: Organic Group activity with grouped results
I'm currently running a D7 system and want to build an admin-only view of Organic Group activity.

I want that view to have two exposed filters:

* Group name
* Date posted

In a nutshell user should be able to select the 'group name' and 'date posted' and gets presented with a list of content which was posted within the group X form 'x date' to 'y date'.

Something like: Following items has been posted in the group 'X'

* news total 32
* webforms total 12
* galleries total 10

Any help would be much appreciated.

# Answer
> 0 votes
I achieved this by creating two different views and two exposed filters:

**Filters** \- Group id \- Date filter **Views** \- View 1 with content base table \- View 2 with comments base table

.Then I have used views aggregation to present results

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


# Question
Title: How to check if a new node is correctly created using Entity Metadata Wrapper $wrapper->save()?
I'm programmatically creating a new node using Entity Metadata Wrapper.

How to check if last instruction:

```
$ewrapper->save();

```

creates correctly the new node without errors?

# Answer
Check that the entity has an identifier:

```
if ($ewrapper->getIdentifier()) {
  // Save happened.
}

```

A better approach might be handling any errors:

```
try {
  $ewrapper->save();

  // Try to do something with $ewrapper->getIdentifier()
}
catch (\Exception $e) {
  // Recover...
}

```
> 4 votes

# Answer
Try to chech the following: `$wrapper->getIdentifier()`, it should return nid of new node.
> 1 votes

---
Tags: 7, entities
---


title: Generate test data bulkly in drupal 8

text:
# Question
Title: Generate test data bulkly in drupal 8
I setup a website based on Drupal8,create some content type(with several fields),Now I want to enter some test data in my site.
**How can I generate test data bulky in drupal8?**

# Answer
Devel module will Do it for you and happy Devel module is ported to Drupal 8 https://www.drupal.org/project/devel

Enable Devel and Devel Generate

go to "`/admin/config/development/generate/content`" give the number of content it will generate bulk content for you.
> 3 votes

---
Tags: 8, debugging
---


# Question
Title: Is it possible to get relation in Views to Commerce products?
I made View by Taxonomy term. Using Relations I got Content which has this Taxonomy term.

Now I want to see couple of Commerce fields (SKU and Price) which are referenced from Content type. Is it possible from Taxonomy View go to Content (I have already done it) and then to Commerce fields from Content?

# Answer
> 0 votes
Make the relationship with commerce product then you will see the related fields in fields list.

---
Tags: views, commerce
---


# Question
Title: how to get all the last level term id's of taxonomy in drupal 7?
i have a taxonomy

```
 State
      - district 1
          -block 1
            -village 1
            -Village 2
          -block 2
          -block 3
      - district 2
      - district 3

```

How to get all the term id's of all the villages in a state?

# Answer
```
<?php
function get_term_depth($tid) {
  $limit = 5; // level of your term
  $depth = 0;
  while ($parent = db_select('taxonomy_term_hierarchy', 't') ->condition('tid', $tid, '=') ->fields('t') ->execute() ->fetchAssoc()) {
    $depth ++;
    $tid = $parent['parent'];
    if ($depth > $limit) {
      break;
    }
  }
  return $depth;
}
?>

```
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to extend (alter) webform submit function to add more funcitionality?
I have created a webform, whose id is `webform_client_form_1`, I have 3 fields:

> Name:
> Email:
> Phone number:

Now I want to extend webform submit function to send SMS to that `Phone number`. I have a working PHP script which sends SMS, using 3rd party service.

So my question is **how to extend the submit function for webform?** **Is there any hook available or there is other method to do it?**

Submit function for webform is: `webform_client_form_submit`

# Answer
Just append your function to the `#submit` element to add it to the list of handlers.

```
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'webform_client_form_1') {
    $form['#submit'][] = 'webform_client_form_submit';
  }
}

```
> 3 votes

# Answer
A cleaner solution would be to implement hook\_webform\_submission\_insert. This let's you do it using a native webform hook rather than hacking the form directly.

```
function MYMODULE_webform_submission_insert($node, $submission) {
  if ($node->nid == 123) {
    // send sms if node id is the one you wanted
  }
}

```
> 2 votes

---
Tags: 7, webforms, forms
---


# Question
Title: Charge user after status of order is changed with eCommerce
I am using the Drupal 7 eCommerce kickstart distribution.

I want to sell service (like cleaning, gardening...), and I want user to be able to create order, but I want to give them ability to do payment after service is done.

Is there any way to do this, to make user able to make payment after they create order.

# Answer
You can use a payment gateway that allows for Authorization Only transactions. This will authorize a certain amount, but will not actually charge the credit card. This is what gas stations, hotels, etc. do. They charge a preset amount, and then finalize the actual amount later.

commerce\_authnet offers this capability. In the settings for the payment gateway you just set Authorize Only.

Once the administrator is ready to finalize the payment, they would go to the Orders page, and choose Payment on the Order. You then 'capture' the amount to finalize the payment.

You can fine tune who has access to the Payments page on the Permissions page.
> 1 votes

---
Tags: commerce
---


# Question
Title: Will I be able to run my site on PHP 7.0?
I've started reading about some performance benchmarks with PHP 7.0 which suggest that it is spectacularly much faster. I've searched all over for information on Drupal support for PHP 7.0, but all that I can find concerns Drupal 8 whereas I am still working for the moment on Drupal 7.

I have found this article that concerns Drupal on Windows, which suggests that D7 on PHP7 works, however since I am running on Centos or Ubuntu I would welcome any information anyone might have on this.

My concern is particularly strong because I am just getting started on a project with massive data inputs, which will thus be very performance sensitive.

# Answer
> 3 votes
The canonical Drupal 8 issue is tagged "Needs backport to D7", which indicates the community intends to support Drupal 7 on PHP 7 but it may take a little time.

---
Tags: 7
---


# Question
Title: adding the field tokens while creating the component
I created the component, in body of the message i added the token based on machine name but i am unable to fetch the data of the fields of content i,e when email triggers to user in the body of the email field data is not showing based on the content created, i have followed this method Get the field data in email body. please give suggestion why is this happening?

# Answer
> 0 votes
In Rules you need to use `-` not a `_`

Try

```
[node:field-working]
[node:field-remoz]

```

**EDIT**

Click on replacement patterns, it will show you all the fields that you can use. Look for your field on the list, and then use the code that is given there, and copy and paste it into the message body.

---
Tags: emails
---


title: Taxonomy in multilingual site

text:
# Question
Title: Taxonomy in multilingual site
I have developed a multilingual blog (two languages). Some of my articles are both languages.

I'm trying to do the following:

As you can see, this article is tagged with the 'Drupal Gardens' tag: (This is not my site. It's a blog with the functionality I would like to implement)

http://reyero.net/es/drupal/construyendo\_sitios\_web\_multilingues\_con\_drupal\_gardens

When you click on the taxonomy link, the next page is showing the articles with the 'Drupal Gardens' tag, but only in spanish. http://reyero.net/es/taxonomy/term/85

Then, if you change the language to english http://reyero.net/taxonomy/term/85 is showing the articles with the 'Drupal Gardens' tag, but only in english.

How can I implement this functionality in my blog. reyero.net is not my site. It's a blog with the functionality I am searching for.

# Answer
> 3 votes
You must activate the module `Taxonomy translation (i18n_taxonomy)` then go to `admin/structure/taxonomy/YOUR_TAXONOMY_NAME/edit` and select:

* Translate. Different terms will be allowed for each language and they can be translated.

Add a term and select the language and click the button `Save and translate` in the next page click the link `add translation` and create the translation.

Then create a node with this term that you hace create and you will have this functionality in your site.

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


# Question
Title: Translate Entity Permission per Content Type
I'm using Entity Translation and I have a user role that should be able to translate nodes of type article but no other content types:

User A should see the Tabs "View, Edit and Translate" for a node of type article but not on node of type "company".

Within the permissions there is only allow translation or not at all. How can I do this? Right now I'm hiding the tabs in my page.tpl if the content type is "article" and the user role fits, but that is not the same as revoking the permission.

# Answer
It won't be possible unless you write the code yourself or find someone willing to code it.

This feature request is now **Closed (won't fix)**
> 0 votes

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


# Question
Title: Massive spam users and spam entries despite triple layer protection
I'm going a little nuts here. The entire point of my site resides on the idea of people registering for the site to contribute content. But I get spam accounts created at least once every minute. Im mass deleting these accounts and the content they create every single time I visit my own site.

I currently use Mollom with the CAPTCHA as the default method (not text analysis) and I have text analysis set to every other form across my site, I use the AntiSpam module set to and properly configured Akismet (had good results from Wordpress), and also have Spamicide enabled and properly configured.

But spam users are still being made in some very insane amounts, and generating content all over my site; which leads me to wonder if they're even using the forms at all any more to generate content on my site..

**EDIT** may have been a little paranoia but I changed the user credentials to my database just to be sure. And yeah, user accounts by the dozens still being created..

I just tried out the Spamicide module by exposing the form element with Firebug and writing anything in it. Sure enough the form doesn't register the account.

The Captcha works perfectly too.

**Note**: I understand Captchas is not good enough (Spam bots these days can solve captchas), but its the only option I get from Mollom.

# Answer
I recommend you try something different from the usual enter text Captchas.

> **I personally use Are You A Human module. This is a video tutorial on how to set it up: Drupal 7 Are You a Human PlayThru Module - Daily Dose of Drupal episode 78.**

If you want another option, I suggest you try Draggable Captcha here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam

A new one that came to my attention is reCAPTCHA. Uses the Google reCAPTCHA web service to improve the CAPTCHA system and protect email addresses.
> 3 votes

# Answer
While there are many approaches different people follow, here is the approach that I follow and generally works for me.

*Anti-spam suit should include the following three*

1. Centralised blacklisting or whitelisting.
2. A quality scoring mechanism.
3. Honeypots and user behaviour analysis.

*I use the following generally.*

At the server level Install Fail2Ban on server.

1. Use httpbl for centralised DNS Blacklisting.
2. Mollom is getting better with time.
3. Botcha or Spamicide.
4. Captcha I still prefer text captcha or math captchas :)

This combination has been working out very well for me.
> 3 votes

# Answer
Consider adding either of those modules (quotes are from their project pages):

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on a Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

> BOTCHA Spam Prevention is a highly configurable non-CAPTCHA spam protection framework.
>
> BOTCHA, doesn't abuse human users, BOTCHA protection is completely transparent to them and non-intrusive.

If these modules still don't help to reduce your issues, then I would go for plan-b, i.e:

* Consider reviewing (extending if needed) your registration form, by adding 1 more or fields so that it becomes AbitMORE difficult to complete registration requests. Either some obvious question for which your target audience should know the answer by heart, or something for which the answer can be found by first browsing around on your site. Yet another option is to ask some question about their real name or address, which may help later on how "serious" the request is.
* Make admin approval required for every new user registration request. This will reduce the speed of "registered" users to the speed of an admin approving / reviewing such requests.
* Set appropriate permissions so that "creating content" requires a user to be logged in. This will imply that a new user starting to create content can only start after their account (registration request) has been approved.

Pretty sure this plan-b will help a lot ... Up to you to decide if it fits with "the entire point of your site".
> 3 votes

# Answer
I would recommend you changing the default admin pathes. Most of the spam bots are only trying `/user/register` etc. to create accounts. There is a module that helps you, doing it: Rename Admin Paths

This should dramatically reduce spam accounts.

Together with Honeypot and Are You A Human PlayThru it is almost possible to get rid of spam completely.
> 3 votes

---
Tags: users, advertising
---


title: Switch to data selection meaning?

text:
# Question
Title: Switch to data selection meaning?
I'm setting up rules, trying to setup HTML emailing. I've it setup but not sure how to configure it. What does *Switch to data selection* mean?'

# Answer
> 0 votes
For an email action, there are 2 different input modes for the fields in *Send HTML email* action.

1. **Direct input mode:** You're supplying most of the data (e.g. the HTML body) with different token (e.g. `[site:slogan]`) inserted in it.
2. **Data selector mode:** You're using a widget (see image) that lets you drill into data that the Rules action has available. This is useful for finding contextual data (e.g. retrieving the current user's email when a node is updated).

---
Tags: rules, theming
---