# Question
Title: How to implement global messaging system in drupal for multiple sites?
I have more than 100 sites that need to be maintained. So I am looking for way to put up a notice message for this group of sites. For example: **We are having maintenance scheduled for tomorrow 10 PM.** The message will be persisting for a time being for all the sites.

Here I am assuming that there should be a central node from where we can push a message to all sites at once and delete when required.

So, I am looking for some help if there is already existing set of tools or way I can implement the workflow.

> I have tried Drupal Remote Dashboard module, the module seems to offer site monitoring from master node (site), but it doesn't seem to offer the global messaging option.

# Answer
The nice thing in the "Drupal Remote Dashboard" module that you can run cron on your sites, so I would suggest that you build a custom messaging module that pull messages from master site (using cron to fire that). \- you can use services module to push your messages out
> 3 votes

# Answer
You can have a separate maintenance.html page in your web root and copy of vhosts file for all of your sites something as

```
site.conf.live
site.conf.maintenance

```

Inside site.conf.live webroot will be drupal installation while in site.conf.maintenance webroot will be maintenance.html page.

So at a time any of the two file will be synlinked to original vhost file which will decide whether site is live or in maintenance. You can create a script to update all symlinks from live to maintenance and another one from maintenance to live.

As a admin you will have to login using server ip

**Updated Answer**

Option 1.

You can use combination of features module + strongarm and a custom module. Custom Module will hold configuration form and logic to show splash message. On one of your site you will update message to show in the configuration page from your custom module, pull it in features, push the feature across all sites, it will require scripts to automate code push/pull, feature revert and turn on/off of custom module.

Option2.

You can try using third party tools like Web-Engage. It has a drupal integration module also. You can try it can provide you one place for setting up notification.

Option3.

You can have a custom table in all your sites. with columns as `Message ID`, `Message`, `Timestamp`, write a small scripts which loops over all your sites connect to mysql one by one and insert a new message row to the message table. To show the message you can create a custom module which pulls the latest entry from your custom message table and show on a popup, again a small script which all turn on/off this module by drush command looping all your sites.
> 2 votes

# Answer
Worth looking.

https://www.drupal.org/project/site\_notice

Use cases for notices may include:

`Scheduled downtime`
`Holiday office hours`
`Policy updates`
`New features`
> 2 votes

# Answer
**Solution 1:**

If the websites are hosted on the same **machine** you could use redis module and Implement the pub/sub messaging protocol between websites using redis api in your case you could have one website(node) acts as publisher and others acts as subscriber and using nodejs to run queries against DB to put site under maintaince or what ever you want

**Solution 2:**

Or you could implement the same technique with socket io with nodejs too if it was not in the same machine using any headless browser tools like phantomJs to start socket connect without opening browser session.

My solutions may need extra work outside drupal framework
> 1 votes

# Answer
Below is an approach based on site building techniques only, which only uses commonly used modules with a stable release, and leaves a lot of options open for further refinements.

# Step 1

Define a content type in your "master" site (= cfr. your "central node"), with these custom fields:

* `notice message`: to store the actual message to be shown.
* `date/time from`: the start date and time for the message to be shown.
* `date/time to`: the end date and time for the message to be shown.

Using content editing features, create a node in this master site for each message to be shown "somewhere in the future". You may want to set permissions for these kinds of nodes to be created by selected roles only.

# Step 2

Define the same content type in each "slave" site (= cfr. your "group of sites"). You can probably automate this process (so that you don't have to do this manually "over 100 times" ...), using export/import features, e.g. by using the Features module.

# Step 3

Implement a process to periodically "copy" the nodes created in the master site to each of the slave sites. A few possible solutions for this:

# Step 4

In each of the slave sites, use the Rules module to create:

* a Rules component "Display notice messages" with these specs:

+ use the "node id" as a parameter.
    + **Condition**: current date/time is between `date/time from` and `date/time to`.
    + **Action**: display `notice message` in the Drupal message area.
* a rule with these specs:

+ **Event**: when (selected) content is "going to be viewed". Attention: that's different from "when viewing content"!
    + **Action**: Loop over each of the existing nodes as created in step 3, and execute the Rules component "Display notice messages" (passing the node id as a parameter).

# Step 5

To remove the obsoleted nodes later on (cfr. your "delete when required"), simply build a list of them using the Views module, and combine it with the Views Bulk Operations module so that the resulting list can be processed by the Rules module (to delete those nodes again).
> 1 votes

# Answer
You will not find a simpler solution

TL;DR : **Use RSS and PHP!**

Caveat : Unfortunately not as elegant as a simple module installation & configuration, This involves creating a feed view, and php code to process the rss in a block.

**Step 1**

a) On the control site, use nodequeue to easily insert and remove message nodes. In a Feed(rss) type view add Nodequeue as relationship and sort criteria

**Step 2**

Make a block on each other site with the following php :

```
<?php
    $rss = new DOMDocument();
    $rss->load('http://mydrupalsite.org/message/feed/');
    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array (
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            );
        array_push($feed, $item);
    }
    $limit = 1;
    for($x=0;$x<$limit;$x++) {
        $title = str_replace(' & ', ' & ', $feed[$x]['title']);
        $description = $feed[$x]['desc'];
        echo '<h2>'.$title.'</h2>';
        echo '<p>'.$description.'</p>';
    }
?>

```

Adjust the output to your own liking.

The advantage of using Nodequeue, is that you can keep your node(for sytle or generic message), and just remove it from the queue.

(We tried going with contrib modules such as aggregator, feeds, etc, but had issues with cache and specifically cron being used to import items, that would persist once messages were removed from the source feed!)
> 1 votes

---
Tags: 7
---


title: Tabbed Multipage Ajaxified Forms

text:
# Question
Title: Tabbed Multipage Ajaxified Forms
I need a way to create a form with tabbed navigation at the top, "save and next"/"save and back" navigation at the bottom, and saving the data for an individual page using ajax, with the following business rules:

-A user may access and work in any part of the form at any time.

-Individual pages can be saved, even if nothing in the rest of the form is filled out.

-Changes in any page result in a "exit without saving? prompt", implemented as a separate module (but which can detect switching between tabs).

I have attempted to do this using fieldgroups: Root is a horizontal tab group, which has a single child in the form of a multipage group, which has 1 tab item child for each page, which in turn each have 1 multipage child, in which I place the forms. The hirarchy looks like this:

Horizontal Tab Group-\>Multipage Group-\>Tab Item-\>Multipage

This doesn't work; apparently the fieldgroups module doesn't let groups search beyond a single level. If they could search beyond that, this may have worked fine and I could have applied the ajaxified multipage fieldgroups module.

What is the best way to go about accomplishing this in D7?

# Answer
You can look at Multipage jumplist module which provides a block that allows you to access all multipages.

To apply the ajaxified multipage fieldgroups, use: Field Group Ajaxified Multipage module which allows you to enable AJAX for multipage groups It also provides developers with special variables attached to form array regarding page status to allow them further customize the form (e.g. form\_alter) depending on active page (in this case saving your pages).
> 1 votes

---
Tags: forms, ajax, navigation
---


# Question
Title: Is it possible to create in Drupal a multiple pages on single page
Please check screenshot , without moving to any new URl when i click on Q&A it shows at right side the result even i can edit and save without going to new URL, everything happens on same page Is it possible in Drupal to do that

# Answer
> 2 votes
Of course it's possible, with or without Drupal. Here is the second link from google: Ajaxify Drupal with JQuery Ajax

> Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.

# Answer
> 1 votes
If this is a content type or entityform, you can use install Field Group with Field Group Ajaxified Multipage and this thing on the left can be a block (Multipage jumplist).

Alternatively consider Quick Tabs.

---
Tags: ajax
---


# Question
Title: Combining two node forms: is that possible?
I am using Drupal 6 and I got a node form for a content type. I want to alter the other content type node form inside the first one; is that possible?

# Answer
> 2 votes
You can also use Flexifield to get 2 content types on the same form.

Like docs says:

> You define a field combination by creating a node type and adding fields to it. On a different node type, you can add a flexifield, and then on its configuration form, specify which node types to use as items within the field.

# Answer
> 1 votes
You may implement hook\_form\_alter to add some custom fields (Take a look at FAPI) that should represent your second type fields, and treat them in hook\_nodeapi with $op presave, (as mentioned by dobeerman).

To save the fields you previously set in your form as new or even and existing node, you may create/load a node object and save them with node\_save.

# Answer
> 0 votes
If you want to add values from 1st form to 2nd form you can use hook\_nodeapi() to altering 2nd content types node.

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL){
  switch($op){
    case 'presave':
      if($node->type == MY_NODE_TYPE){
        // $other_node = node_load($other_nid);
        // or
        // $other_node = new stdClass();
        // $other_node->title = ...
        // ...
        // some code to altering other node
        // $other_node = node_submit($other_node);
        // node_save($other_node);
      }
      break;
  }
}

```

# Answer
> 0 votes
you can take a look at this module http://drupal.org/project/formblock

Some details from the module's project page:

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Or just use `drush en formblock -y`

---
Tags: 6, nodes, forms
---


# Question
Title: How to add a menu tab programmatically to a views page?
I have a view page showing fields of an entity. The pages URL set in Views is

```
entity/%

```

Now I would like to add some tabs to this views pages that I can't generate with views it self, but have to do it programmatically. Si I tried:

```
function MY_MOODULE_menu() {
  $items['entity/%eid/edit'] = array(
    'title' => 'Edit',
    'page callback'   => 'MY_MODULE_entity_edit_callback',
    'access callback' => true,
    'page arguments' => array('eid'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );
  return $items;
}

```

As a menu of the type is `MENU_NORMAL_ITEM` with the base path `entity/%` is created by the mentioned view, I thought this should simply work, but it does not: The tab does not show up. (Of course I cleared all caches). Did I got something wrong?

# Answer
Path hierarchy is based on string matching; so `entity/%eid/edit` doesn't come under `entity/%` (because `'%' != '%eid'`)

There are a couple of other issues, reading between the lines I reckon this is what you're going for:

```
function MY_MOODULE_menu() {
  $items['entity/%/edit'] = array(
    'title' => 'Edit',
    'page callback'   => 'MY_MODULE_entity_edit_callback',
    'access callback' => true,
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );
  return $items;
}

function MY_MODULE_entity_edit_callback($eid) {
  // ...
}

```
> 2 votes

---
Tags: views, routes
---


# Question
Title: How to download Database results as PDF or in EXCEL
I have a custom query to fetch the details from database (oracle). The results are generating properly as expected. Now i need to download these results either a PDF or an EXCEL file. Any way to achieve this

# Answer
By Views PDF module you can output a View as a PDF.

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

Since you have your custom query, by Custom query in Views you can alter the results of the View. The print the output of view is PDF using the above module.

---

**UPDATE**

Since you created a node and fetch database result via that node you must use Printer, email and PDF versions module

> This module allows you to generate the following printer-friendly versions of any node:
>
> * Printer-friendly version (webpage format) (at www.example.com/print/nid)
> * ***PDF version (at www.example.com/printpdf/nid)***
> * EPUB version (at www.example.com/printepub/nid)
> * Send by email (at www.example.com/printmail/nid)

where nid is the node id of content to render.

so by `www.example.com/printpdf/nid` you can create a PDF output of the node.
> 2 votes

# Answer
Using these modules you can do that

views\_export\_xls

> Simple module that allows to export Views data to Excel (xls). Uses php-excel class with UTF8 support.

views

> * You like the default front page view, but you find you want to sort it differently.
> * You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
> * You use /tracker, but you want to restrict it to posts of a certain type.
> * You like the idea of the 'article' module, but it doesn't display articles the way you like.
> * You want a way to display a block with the 5 most recent posts of some particular type.
> * You want to provide 'unread forum posts'.
> * You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
> "Month, YYYY (X)" where X is the number of posts that month, and
> displays them in a block. The links lead to a simple list of posts
> for that month.
>
> Views can do a lot more than that, but those are some of the obvious uses of Views.

views\_data\_export

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS
> * Microsoft DOC
> * Basic TXT
> * XML.

Forena

> The current version allows you to create reports using SQL from Drupal, or using data stored in XML files.
>
> It comes bundled with a couple of sample reports that will both demonstrate how reports are created, and provide useful information on your existing Drupal site.
>
> Some key features include:
>
> * Create custom reports from your Drupal database.
> * Create custom reports against PDO supported database (SQLite, MySQL, MS SQL, etc).
> * Create custom reports against any Oracle database.
> * Create charts in SVG format.
> * Export data to CSV, EXCEL or XML versions of reports.
> * Create and edit HTML reports using a simple web UI (includes WYSIWYG editor support).
> 1 votes

# Answer
Try out this module. https://www.drupal.org/project/pdf\_using\_mpdf

```
API Function : pdf_using_mpdf_api()

      This API function is available to content developers that prefer to generate a pdf file of custom path. The function takes two parameters, first a rendered html content and an optional second parameter, name of the pdf file. E.g: pdf_using_mpdf_api($html) where $html is any html content.

```

The module provides API to create pdf for your custom pages, in order to create pdf without pager you can make pager conditional passing a url .parameter or you can have two pages one without pager to create PDF from
> 0 votes

# Answer
# Module Forena

You could use the Forena module (disclosure: I'm a co-maintainer of it) as your 1-stop-solution (using only 1 contributed module) to:

* Build your custom query to fetch the data, whereas these data can be retrieved directly from an external database such as Oracle.
* Format the look and feel of your results (the report) using xHTML (and/or charts if you'd like).
* Download the results in any of the typical formats, such as PDF, XLS, CSV, XML, JSON, etc.

To get an idea how its **Custom Queries** (SQLs) and/or **Report Specifications** look like, refer to the example in my answer to the question "How to retrieve data directly from a Drupal database.".

The Forena Video demos and tutorials contain quite some links to live demos.

# Download options

For any report that you create (using Forena), just add `.csv` as an extention to the report (output) URL. That contains the CSV equivalent of that report.

As a sample, consider the sample report located at `/reports/sample.states` (in your own site, one of the samples shipped with Forena). Change the URL to `/reports/sample.states.csv` (= just add `.csv` to it) to get the same report in `.csv` format. By adding such `.csv` to the URL of the Simple Table of States in the demo site, the result is like so ...

Same technique applies for other supported extensions (export formats), such as:

Moreover, when building a report, you can also specify for which of these Document Types an hyperlink should be made available in the report.

# Direct access to data blocks

All data blocks are also accessible directly via their url, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:
> 0 votes

# Answer
```
$link_download = l(t('Download Report'), 'path/to/report/export');

function custom_menu(){
  $item['path/to/report/export'] = array(
    'page callback' => 'custom_report_export',
    'title' => 'Data Export',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $item;
}

function custom_report_export() {
  $file = "report_name.xls";
  $table = callback_to_generate_theme_table_output_of_query_result();
  header("Content-type: application/vnd.ms-excel");
  header("Content-Disposition: attachment; filename=$file");
  echo $table;
}

```
> 0 votes

---
Tags: database, files
---


title: Form submission redirect to white page

text:
# Question
Title: Form submission redirect to white page
I've created a simple form:

```
/**
 * Implements hook_menu().
 */
function test_menu() {
    $items['admin/config/test'] = array(
        'title' => 'Test form submission',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('test_form'),
        'access arguments' => array('administer users'),
        'type' => MENU_NORMAL_ITEM,
    );

    return $items;
}

/**
 * Implements hook_form().
 */
function test_form($form) {
    $form['test_text'] = array(
        '#type' => 'textfield',
        '#title' => t('Test text')
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save')
    );

    return $form;
}

function test_form_submit($form, &$form_state) {
    drupal_set_message(t('Your form has been saved.'));
}

```

On submission, I see a white page. What's wrong with the code?

# Answer
This is Drupal 6, so

```
function test_form($form) {

```

Needs to be

```
function test_form(&$form_state) {

```

Currently you're returning a form that has the initial form state data attached to it, which Drupal is probably objecting to on submission.
> 2 votes

---
Tags: 6, forms
---


# Question
Title: drush up fails to update, though it says it deos
Here's my output...

```
# drush up drupal-7.39
Failed to get available update data for one project.                                                                                [error]
Update information last refreshed: Wed, 09/16/2015 - 14:21

Update status information on all installed and enabled Drupal projects:
 Name         Installed version  Proposed version  Status
 Drupal core  7.38               7.39              Specified version available

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.39.
Backups were saved into the directory /root/drush-backups/civi2crm/20150916182131/drupal.                                                                           [ok]
Backups were restored successfully.                                                                                [ok]

```

And then if I immediately try the same thing again, I see that it still doesn't think it install 7.39. I can confirm that /user#overlay=admin/reports/updates tells me that I am still running 7.38

```
# drush up drupal-7.39 -y
Failed to get available update data for one project.                                                                                [error]
Update information last refreshed: Wed, 09/16/2015 - 14:21

Update status information on all installed and enabled Drupal projects:
 Name         Installed version  Proposed version  Status
 Drupal core  7.38               7.39              Specified version available

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.39.
Backups were saved into the directory /root/drush-backups/civi2crm/20150916182138/drupal.                                                                           [ok]
Backups were restored successfully.

```

Any thoughts why I can't update Drupal. And, in case it matters, I'm using Drupal to run CiviCRM. And I think that is the "project" that it failed to get update data for. But I believe I have to manually update CiviCRM by copying files and stuff, so that seems okay to me. But perhaps I'm wrong on that. But I can't see why, since I JUST want to patch the Drupal Core with the security update.

# Answer
"Backups were restored successfully" means that Drush failed at some step, and restored your old version of Drupal over the recently updated version. Try setting file ownership &/or permissions; run with --debug, and perhaps you will see more information about why the upgrade is failing.
> 1 votes

---
Tags: drush
---


# Question
Title: How to add phone number field with extension to webform component
**Theme:**

Bootstrap subtheme

**Modules:**

https://www.drupal.org/project/webform\_bt\_layout,

https://www.drupal.org/project/webform,

https://www.drupal.org/project/phone,

https://www.drupal.org/project/webform\_phone.

**Steps:**

Enter 'Phone No' in component field.

Selected 'Phone Number' as field type.

Clicked 'Add'

Country was selected as 'US/Canada' (I am accepting only US/Canada 10 digits)

Separator field has dash(-)

**Problem:**

When I visit my form, I see a one field which allows to enter more than 10 digits.

How can I make sure I can enter 10 digits numbers (separated with dashes) with upto 4 digits extension?

# Answer
You could add a phone field as you described for the phone number.

And add another field of type number for the phone extension, you can limit this field to be only numeric and 4 digits.

And even to make sure that the phone number is introduced and not only the 'phone extension', you can add a Webform conditional to display the 'phone extension' field only if the 'phone' field has been filled.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to display a message on login until a user fills out a specific Webform?
Relevant modules installed:

What I have tried:

* Rule 1: activates on user login that displays a system message.
* Rule 2: activates on Webform submission with the condition that the Webform's name is the required name. The rule executes PHP code to disable Rule 1 if true.

> ```
> /**
> * Implements hook_update_N().
> * Disables name_of_rule rule.
> */
> function hook_update_N() {
>   $rules_config = rules_config_load('name_of_rule');
>   $rules_config->active = FALSE;
>   $rules_config->save();
> }
>
> ```

However, this set of rules is NOT working at the moment.

Concerns:

* If Rule 1 was working, how do I ensure that it permanently disables Rule 1 per user, and not globally?
* Is there a better way to do this?
* For example, all I should need is one rule: On user login + if a Webform has not been filled out, display a message. However, I have not been able to find a module that adds the "If Webform has not been filled out" rule.

# Answer
Referring to your "is there a better way to do this": not sure if you'll consider it "better", but this is how I would adapt your 2 rules to actually "*display a message on login until a user fills out a Webform*" (as in the title of your question):

* in your Rule 2, I'd use an **Action** to "flag" the user, using the Flag module, with a (none-global) flag named something like "Webform OK" (and "Webform not OK" as the alternative). By the way, the nature of such flag is that it is for each user individually.
* in your Rule 1, add a **Condition** like "Is this user NOT flagged (with the Webform OK flag)".

With these 2 corrections of your 2 rules, and by adding the Flag module to your mix, you can:

* probably simplify both rules, such as removing the (potentially dangerous?) PHP code in your Rule 2.
* possibly eliminate the "Conditional rules" module.
> 0 votes

# Answer
I think the module you are looking for is 'Rules Webform Submitted'.

This module is similar to Webform Rules in that it supports integration between Webform and Rules, but different in that Webform Rules supports the Event "Webform Submitted", while Rules Webform Submitted provides a Condition which is typically triggered by a Node Event.

So, you can use the event 'On user login' and the condition that 'Rules Webform Submitted' offers to create your rule.
> 1 votes

---
Tags: rules, webforms
---


# Question
Title: How to display the data of a View in table format?
I created a view using "Table" as its format already. When I click on the title column record it shows the fields one by one.

Can I display the data of a view as table format?

# Answer
> 2 votes
yes there us absolutely a way

1. go to any view-\>FORMAT-\>Format (unformated list) click on that see below for image
2. click on table format -\>apply display

and enable label in all fields. will display it in table format

# Answer
> 1 votes
The DataTables module might help to further enhance the prior answers to this question. Here is a quote from its project page:

> The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:
>
> * Variable length pagination
> * On-the-fly filtering
> * Sorting with data type detection
> * Smart handling of column widths
> * Themeable by CSS
> * And more ...

Another feature that it offers is that you can "hide" specific columns from the default table display. But still the user has the option to do things like:

* expand the hidden columns.
* use the DataTables search feature to search for rows containing one or more strings contained in ... even those hidden columns.

So you could use an approach to only show, by default, a subset of all the columns, and leave it to the user to yes/no also display the (initially hidden) columns.

A few more links you may want to look at:

Refer to the (short) video about Create Powerful Tables with the DataTables jQuery Plugin and Views for an intro about it, and how to use it as a views style plugin. Using the "settings" link for this views style, you can specify all sorts of dataTables options/features. In the above video starting from around 3:00 you see many of them.

# Example

Below is a screenprint of such display using DataTables. It's a display created using Views (of course) with a table with:

* 8 fields in (defined in my view).
* 5 table columns for the 5 fields I have decided to always show.
* 3 table columns which I defined as "hidden and expandable" (within the DataTables settings after you select DataTables as the Views style).

Here is how the DataTables display looks like:

For each row there is a link '***Show Details***' (in its 1st column). If you click on one (or more) of them, the hidden fields of such row are shown below that row (with grey background here) and the link you clicked changes to '***Hide Details***'. Obviously, I've not done any styling for such expanded row (hence the grey background, etc). But you can see the 3 fields that were initially hidden.

**Bonus**: assume none of the rows are shown expanded, and you type "`Basic`" in the DataTables search box. It will then dynamically (in the browser, no server calls) reduce the table display to only those rows with `Basic Page` as value for "Type". But wait, there is even more: if you'd type a string like part of "`21:15`" instead (hidden in some of the rows), it will also dynamically reduce the table display to only those rows, like the expanded row shown in the screenprint. But wait, there is even (quite) a bit more: a search string like "basic 21:15" will filter the rows to a combination of both search strings. For only this one feature I often recommend the amazing DataTables module, one of Drupal's hidden gems I think. And then there are the other features like pager, sortable columns, etc.

# Remarks

* Make sure to use the 1.9.x version of the DataTables library (not 1.10.x or above), as mentioned also on the project page, which states:

> While there is work in the 7.x-2.x branch to upgrade to the latest DataTables version (1.10.x), the 7.x-1.x branch only works with DataTables \<= 1.9.x. Since it's not listed in the projects download page, you will have to download it directly.
* When creating a view, disable the pager of your view, since DataTables provides its own paging features (the video talks about that starting from 2:05).

# Answer
> 0 votes
In the Views interface, in "Format", you can select the "Table" format, instead of the default "Unformatted list".

See more about View formats.

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


# Question
Title: Drupal 7 - views blocks not displaying page field content
I have a page where a view is creating a block which loads a field.

Other blocks loaded into the region are showing up just fine but that particular one will not show. It is not because the field is empty or otherwise, I can creae labels and tables and empty conditions etc that do not get picked up at all

Is there something that has to be done to template files or otherwise to enable blocks created by views?

# Answer
A block created by view shows up as any other view, unless you have permission control for the block at views level or at block level.

Permission at views

Permission at block

1. Visibility settings - By various ways block visibility can be controlled, ensure you have appropriate configurations for this.

2. Region Settings - Ensure you are putting the block in the region of right theme you are expecting the block to see.

Few things to debug.

* Login with super admin(user id 1) see if you can see the block, if yes it will ensure you have permission issues.
> 0 votes

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


# Question
Title: How to display contents which matches the path alias of a content from URL using views contextual filters?
I have a content type "basic" and have contents with different URL alias for ex:

> www.example.com/news/newsletter/title;
>
> www.example.com/content/title;

both are same type. I need to create a view page and the path for that view page is news/newsletter, In this page I want only the content which having the path alias news/newsletter. How can we get the content?

Thanks.

# Answer
Views URL alias

> The 'Views URL alias' module allows Views to be filtered by path aliases.
>
> This module is useful if your website uses heirachical paths. It allows you to filter and sort a view by URL aliases.
> 0 votes

---
Tags: views, path-aliases
---


# Question
Title: How to disable 'Path prefix language code' for admin panel?
My sites requires the use of 'Path prefix language code' under `admin/config/regional/language/edit/en` to append the language prefix to the URL path, so if the language is English, `node/1` would become `en/node/1`

The problem is that when I am trying to translate content, the links to the translation pages contain this prefix too, and that will reach a page that is not there:

**`/tc`**`/my-node-title/edit/zh-hant` is the wrong path, the correct path is...

`/my-node-title/edit/zh-hant`

So is there a way to remove the language prefix on the admin panel?

# Answer
Have you tried to use the GlobalRedirect module? You may be able to set the option 'Language Path Checking' to true in the module configuration page and add the paths for admin pages in there.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Where does drupal determine which theme file to use for an entity field?
So I've got this problem where file\_entity is ignoring the configured video formatter despite triple-checking the GUI configuration. Instead it's being rendered by theme\_file\_entity\_file\_video(), which shouldn't be happening.

But it is. So I'm digging back into core to see where the theme function responsible was established. I'm in drupal\_render but I'm already seeing the theme function set improperly...

So my question: *Where does drupal determine which theme file/function to use for an entity field?*

*Clarification*: my question is, **"How/where does the theme registry get built for an entity?"** I want to watch it get built with a debugger.

# Answer
Everything can be overridden by one hook in any module so bear that in mind.

The theme registry is where everything is stored in terms of theming for pages/entities. It all depends on the order here in determining the theme it will use.

You can use the devel module and dpm out the theme registry:

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_get\_registry/7

It *usually* is built in this order:

1. module where entity is created
2. module where function was called to get the entity
3. your theme directory

but at any point that could have been overridden
> 1 votes

---
Tags: theming, entities
---


# Question
Title: Add interval to current date and dispay result in views
I have a field in one of my content-types that contains a interval (using the interval module). I have configure the field so that the user can select how many years a curtain certificate should be valid.

How can I add this interval to the current year and count how many results I got using views?

# Answer
> 1 votes
Have you tried the Views Calc module?

The other option would be to use the Computer Field module but that could be risky as you enter PHP code into the field.

---
Tags: 7, views, datetime
---


# Question
Title: Form with AJAX callback to query database and display info in block['content']
I have a simple select form that I want to use as a "Sort By" handler. When user chooses a different option I want it to change the query and display the new results. E.G. sort by duration ASC or sort by duration DESC.

This is my form:

```
function mortgage_multi_view_sort_form($form, &$form_state) {
     $form = array();
     $sortOptions = array(
        1 => t('Mortgage Duration: Shortest to Longest'),
        2 => t('Mortgage Duration: Longest to Shortest'),
     );

     $form['mortgage_sort'] = array(
        '#type' => 'select',
        '#title' => t('Sort By'),
        '#options' => $sortOptions,
        '#default_value' => 1,
        '#required' => TRUE,
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'ajax_select_callback',
            //'wrapper' => 'replace_model_div',
            'method' => 'replace',
            //'effect' => 'fade',
        ),
     );

     return $form;
 }

```

When they change this to Longest to Shortest I want to asynchronously display the mortgages in reverse order. Is this best to do in the callback function?

My callback function (currently):

```
 function ajax_select_callback($form, &$form_state){
 switch($form['mortgage_sort']){
    case 1:
        $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration DESC');
        displayMortgages($result);
        break;
    case 2:
        $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration ASC');
        displayMortgages($result);
        break;
 }

```

}

In my displayMortgages() function it just takes the entire query and displays it in a table. How do I get this information to block\['content'\] from my displayMortgages() now?

# Answer
You should do all the logic in the form function. However with your particular issue, I would approach it slightly differently. I would simply return the table HTML from `displayMortgages()` back to the form and display the table as part of the form. But just simply as a `#type=> 'markup'`. That way, your sort form and the results are one, and you don't need to worry about firing off another ajax command somewhere else.

So your form code would basically be:

```
function mortgage_multi_view_sort_form($form, &$form_state) {
  $form = array();

  // Default sort direction
  $sort_dir = 'DESC';

  $sortOptions = array(
    'DESC' => t('Mortgage Duration: Shortest to Longest'),
    'ASC' => t('Mortgage Duration: Longest to Shortest'),
  );

  $form['mortgage_sort'] = array(
    '#type' => 'select',
    '#title' => t('Sort By'),
    '#options' => $sortOptions,
    '#default_value' => 'DESC',
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_select_callback',
      'wrapper' => 'replace_model_div',
      'method' => 'replace',
      //'effect' => 'fade',
    ),
  );

  // Check if a selection on the form has been made, if so then update the direction
  if (isset($form_state['values']['mortgage_sort'])) {
    $sort_dir = $form_state['values']['mortgage_sort'];
  }

  $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration '.$sort_dir);

  $form['result'] = array(
    '#markup' => (count($result)) ? displayMortgages($result) : '',
    '#prefix' => '<div id="replace_model_div">',
    '#suffix' => '</div>',
  );

  return $form;
}

```

And you just need to return the part that's being replaced in your ajax callback:

```
function ajax_select_callback($form, &$form_state) {
  // Just a return of result is sufficient since it's being replaced
  return $form['result'];
}

```
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: How to insert content type fields directly into Views
I am wanting to place a view into my sidebar like yahoo answers Yahoo Answers TOP Right Sidebar. The block would display the actual fields (to be filled out) from the content type, once submitted it would create the content.

Is there a specific module for this or can it be done directly with views somehow?

Thanks!

# Answer
> 1 votes
You should use webform module for it. You can display the form to users which the users can fill and submit. You can review the form submissions by going to content/webforms link. You can display the webform as a block. You cannot display a content type to be filled in by the user, as only admins can create contents by default. You can download webform from this Link

---
Tags: views
---


title: JCarousel Views - Multiple Rows

text:
# Question
Title: JCarousel Views - Multiple Rows
My problem is related to Drupal and the use of the JCarousel module for my views. I'm having a few problems with this, namely in getting a jcarousel like view style but with 2 rows instead of one. With the following jcarousel-view.tpl.php in my theme folder, I was able to somewhat get further:

```
<?php
  /**
   * @file jcarousel-view.tpl.php
   * View template to display a list as a carousel.
   */
?>
<ul class="<?php print $jcarousel_classes; ?>">
  <?php $i=0; $rows_number=2; //you can change the number of rows ?>
  <?php foreach ($rows as $id => $row): ?>
    <?php if ($i % $rows_number == 0): ?>
      <li class="<?php print $classes[$id]; ?>">
    <?php endif; ?>
    <?php print $row; ?>
    <?php if ($i % $rows_number == ($rows_number - 1)): ?>
      </li>
    <?php endif; ?>
    <?php $i++; ?>
  <?php endforeach; ?>
  <?php if ($i % $rows_number != 0): ?>
    </li>
  <?php endif; ?>
</ul>

```

Here is the end result:

As you can see, it groups each set of fields for each item into a common column and not separated, so I cannot create a full border for each individual item.

How can I resolve this?

# Answer
> 0 votes
1) Hide all your fields (check mark exclude from display)

2) Add a **Custom Field**

3) In your custom field, put everything there using the tokens. (click on relacement patters, it will show you the tokes u can use).

For Example:

```
<div class="whatever">
    <div>[logo]</div>
    <div>[off]</div>
    <div>[download cupon]</div>
    <div>[expires]</div>
</div>

```

Then go to the jcarusel module folder and look for the css file and strip the css that you don't want (like the current borders) and use your "whatever" div to create your own borders.

---
Tags: views, theming
---


title: 404 error from node access hook

text:
# Question
Title: 404 error from node access hook
I have `node_access` hook in a module. I tried to prevent anonymous user from access unpublished node like the following:

```
function MODULE_NAME_node_access($node, $op, $account) {
   global $user;
if ($op == 'view' && $node->status == 0 ){
     return NODE_ACCESS_DENY;
  }
}

```

This is working fine and redirect to access denied custom page. However, I would like it to be redirect to the custom 404 not found page. i.e the http response to be 404. I tried to find any replacement of `NODE_ACCESS_DENY` but I could not able to find anything.

I tried to use `drupal_not_found()` but it generates Server Error on the server.

Also, I would like to know, if there a method or property of the `$user` object that determine if the user is anonymous user or not. I find that there is `user_is_anonymous()` but I could not know how to use it in this context.

# Answer
> 1 votes
You can use `drupal_goto("custom 404 page")` to redirect a user to your custom page. For your second question you can check if user is anonymous using this condition. `if($user->uid == 0)`

Thus your hook can be rewritten like this.

```
function MODULE_NAME_node_access($node, $op, $account) {
  global $user;
  if ($op == 'view' && $node->status == 0 && $user->uid == 0){
    drupal_goto("custom_404_page");
   }
}

```

See here for drupal\_goto documentation

Note: This function has been removed in Drupal 8. In Drupal 8 you can do this by this way.

```
return new RedirectResponse(\Drupal::url('user.page'));

```

or this way \`use Drupal\Core\Controller\ControllerBase;

```
class MyControllerClass extends ControllerBase {
   public function foo() {
   //...
   return $this->redirect('user.page');
  }
}`

```

See here for Drupal 8 redirect info

# Answer
> 1 votes
`hook_node_access()` is not necessarily invoked when a user is viewing a node page: It is invoked from `node_access()` which in turn is called in different circumstances.

In all those cases, the functions are calling `node_access('view')` and redirecting the logged-in user or showing a 404 page would disrupt the normal Drupal behavior and would avoid Drupal completes what it is doing.

The only way to be sure a user is going to view a node is intercepting when the page callback for node/%node is being called. You cannot rely on `node_view()` being called when a user is going to view a node, since `node_view()` is called also from cron tasks (see `_node_index_node()`, which is indirectly called from `search_cron()`; this also means `hook_node_view()` cannot be used to redirect users while they are supposedly seeing a node page, since this is not true.

This would mean to implement `hook_menu_alter()` to change the page callback and the access callback of node/%node. You need to change the access callback because the default one is `node_access()` and users would still get a 403 error if they try to access directly a URL for an unpublished node. Since you are interested in showing a 404 page instead of a 403 page just for anonymous users, you could use the following code for the access callback.

```
function mymodule_node_access($op, $node) {
  if ($GLOBALS['user']->uid == 0 && $op == 'view' && $node->status == 0) {
    // We will return a 404 error to the user.
    return TRUE;
  }

  return node_access($op, $node);
}

```

Since you are just using the access callback for node/%node, its code doesn't need to check the operation, since it is going to be *view*.

```
function mymodule_node_access($op, $node) {
  if ($GLOBALS['user']->uid == 0 && $node->status == 0) {
    // We will return a 404 error to the user.
    return TRUE;
  }

  return node_access($op, $node);
}

```

The page callback would be similar to the following one.

```
function mymodule_node_page_view($node) {
  if ($GLOBALS['user']->uid == 0 && $node->status == 0) {
    drupal_not_found();
  }

  return node_page_view($node);
}

```

### Notes

* Since the access callback is returning `TRUE` for anonymous users, any link to unpublished nodes will be shown to anonymous users. This is something it cannot be avoided, since Drupal uses an access callback for two different purposes.
* The alternative would be generally replacing a 403 error with a 404 error, but that would means it happens for every page. Checking the path being accessed would avoid making it happen for administrative pages, for example; checking for anonymous users would avoid it for authenticated users. (If I find a way to do this, I will updated my answer.)

As for `user_is_anonymous()`, it only works with the global `$user` and it is an hack for a specific case. The function you should call is `user_is_logged_in()`, which still works with the global `$user`.
Since the function has been removed from Drupal 8, I would rather check the user ID is 0, to understand if a user is anonymous user; in Drupal 8, you would change the code, but you would need to do that even when using `user_is_anonymous()` or `user_is_logged_in()`.

---
Tags: 7, nodes, hooks
---


# Question
Title: How do I reverse the order of submit and preview button?
I need to change the submit and preview button order in the node edit form in Drupal 7. By default the submit button shows first the preview button, But I need vice versa.

How can I achieve this?

# Answer
One solution is to use `hook_form_alter()` in a custom module to make the submit button heavier than the preview button:

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

  if($form_id == 'MYNODETYPE_node_form') {
    $form['actions']['preview']['#weight'] = $form['actions']['submit']['#weight']-1;
  }
}

```

Just change the module name and form id accordingly.
> 3 votes

---
Tags: nodes, forms
---


# Question
Title: display only selected terms in custom node template
How can I change the below code to display only the selected terms in the node. right now all terms which are defined in the vocabulary is displayed

```
<?php
$items = taxonomy_vocabulary_machine_name_load('test_categories');
$taxonomy = taxonomy_get_tree($items->vid);
foreach($taxonomy as $key => $items):
  print $items->name;
endforeach;
?>

```

# Answer
> 0 votes
If you want to print a selected taxonomy value in a node, try this way..

```
$node = node_load($nid);
//If you have multiple values use foreach.
$tid = $node->yourfieldname['und'][0]['tid'];//if you are using term reference.
$term = taxonomy_term_load($tid);
print $term->name;

```

# Answer
> 0 votes
For specific node you need to use **$info = node\_load($nid)** where you find your field value using $info-\>field\_name. Using that field you can use foreach something like foreach($info-\>field\_name as as $key =\> $items).

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


# Question
Title: Using date and rules to publish and unpublish content
I have two scenarios:

1. I have a *meditation* content type that need to show in a view when the date field = today's date. I want a view to show a *meditation* every year on the same date.
2. I need to create a new node of a certain content type every week where the date field has a start date of today's date and a relative end date of + 13 days.

How to create those two scenarios using rules? I am trying to understand rules scheduler. I think it can solve both scenarios.

# Answer
# Create a new node of a certain content type using rules

Use rules action "Create entity" to create a node, whereas "node" is a type of entity.

For the fields that you want to provide some value for (as part of your rules action), make sure to add a Rules conditions - "Entity has field" (with the field corresponding to each such field). Doing so will ensure they are available in the Rules action (to set a value for it).

# Repeat the creation of such new node

Use the rules scheduler as explained in the video about "Repeating scheduled events". The "clue" here is:

* as the last action of your rule, you reschedule the same rule to be executed again after +13 days from today on. Or maybe execute the rule again "weekly" (as per your details in "2.").
* the very first time (today + 13 days) you need to trigger the execution of this rule manually (from the rules UI). Since there doesn't seem to be any event in your question that you can use to trigger this rule.

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

PS: Your question seems to contain 2 questions, of which "1." is not clear to me (something about creating a view?). After you enhance your question (as suggested by Shawn also), I might enhance my answer also.
> 0 votes

---
Tags: nodes, rules
---


# Question
Title: Uploading images to CKeditor in a file field way?
## Background

I'm looking for one of the two possible solutions concerning image-uploading to Drupal, and especially to CKeditor image uploading and handling:

## Possible solution 1

A module that creates an independent image-folder to every node, uploads images to this specific directory, and then let me choose only between these images directly from CKeditor. If the node is deleted, than this folder is deleted along with it.

## Possible solution 2:

a module that uploads images into CKeditor text areas in an efficient, fast, Drupal-file-field-**like** way; It is important for me that this uploader will use the same rules like the Drupal file-field, the same mechanisms and SQL tables, so that when I delete the image I uploaded - it will be totally deleted from the site's home-folder.

So basically the uploader I'm looking for should do 2 things:

1. Upload files easy and fast, just like the Drupal file-field does.
2. Send some kind of signal when a file is deleted from that very CKeditor text area.

Please help me to find of these two possible solutions:

# Answer
Insert module is the standard way of doing this, it interfaces with ckeditor and allows you to insert images as an `<img src="">` tag but retain the file in the drupal file entity system.

**INSERT:**

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
>
> This module was previously known as FileField Insert.

An alternative way might be paragraphs module which allows you to insert one or more images alongside text fields and theme them by layout (so text on left-image on right or vice versa) It's not ideal in all circumstances but works.

**PARAGRAPHS:**

> Paragraphs is the new way of content creation! It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.
>
> Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.
>
> Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.
> 3 votes

# Answer
I'm not 100% sure but maybe insert module is a suitable solution for you.

**INSERT:**

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
>
> This module was previously known as FileField Insert.
> 4 votes

---
Tags: nodes, media, wysiwyg
---


title: problem getting hook_menu() to work

text:
# Question
Title: problem getting hook_menu() to work
I want to display a button on the front page of my website and for the first time (as beginner), I wanted the link to be configured in the administration page. I followed the tutorial on creating a module configuration and the code I wrote doesn't seem to show a textfield while visiting admin/config/content/linkpresent.

```
/**
 * fonction permettant de gérer le lien de la bannière du front
 */
function mij_page_presentation() {
  return 'hello world';
}

/**
 * function in admin pages
 */
function mij_page_admin() {
  $form = array ();
  $form ['mij_page_presentation'] = array (
      '#type'   => 'textfield',
      '#title'  => t('Lien renvoyant vers la page de présentation '),
      '#size' => '255',
      '#default_value'  => '',
      '#description' => t('Ici est renseigné le lien renvoyant vers la page de présentation '),
      '#required' =>TRUE,
  );
  return system_settings_form($form);
}

/**
 * implements hook_menu
 */
function mij_page_menu(){
  $items = array();

  $items['admin/config/content/linkpresent']=array(
      'title' => 'Lien de la page de présentation',
      'description'=>'Ici est renseigné le lien renvoyant vers la page de présentation ',
      'page callback'=> 'drupal_get_form',
      'access arguments' => array('administer mij_page settings'),
      'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mij_page_admin_validate($form, &$form_state){
  $presentation = $form_state['values']['mij_page_presentation'];
  if(is_numeric($presentation)){
    form_set_error('mij_page_presentation',t('veuillez entrer une URL relative valide'));
  }
}

```

Here is the blank page I obtain in the administration page.

Anyone has an idea on this?

# Answer
Your `page arguments` are missing, so Drupal doesn't know what form to load.

Change your hook\_menu implementation to this:

```
function mij_page_menu(){
  $items = array();

  $items['admin/config/content/linkpresent']=array(
      'title' => 'Lien de la page de présentation',
      'description'=>'Ici est renseigné le lien renvoyant vers la page de présentation ',
      'page callback'=> 'drupal_get_form',
      'page arguments' => array('mij_page_admin'),
      'access arguments' => array('administer mij_page settings'),
      'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

```

Remember to clear Drupal's caches after you make the change.
> 2 votes

---
Tags: routes
---


title: manage fields is missing

text:
# Question
Title: manage fields is missing
I created new content, but I can't see manage field. I googled the problem, all the solutions say enable Field UI module, I did enable the Field UI, but still I can't see the manage fields, any help please?

# Answer
> 1 votes
Did you flush all caches under `Performance settings`? You can do it manually too. Go to `phpmyadmin` and clear all tables with "cache" preposition. If you use `admin_menu` module, it need to be rebuild from time to time.

Try to access manage\_fields manually on path `https://www.yourdomain.com/admin/structure/types/manage/page/fields`

* `page` is name of your content type

When I'm facing strange problem I always try to reproduce it on new Drupal installation. It tells me a lot when I'm "reverse-engineering" the problem.

# Answer
> 1 votes
You may need to flush your caches. You can do this in any one of the following ways:

* Navigate to /admin/config/development/performance and click "Clear all caches"
* If you have devel installed, hover over the house icon in the toolbar and then click on "Flush all caches"
* If you have command line access and drush installed, run "drush cc all"

Failing that, are you looking in the correct part of the menu, it should be under `structure` -\> `Content types` -\> `[your content type]` -\> `Manage fields`

---
Tags: entities, nodes
---


title: How to get the current question's NID?

text:
# Question
Title: How to get the current question's NID?
When taking a quiz with multiple questions, how do I get the current question's NID? The URL only contains the quiz' NID (`node/1234`), even when I started the quiz there only this NID is available (`node/1234/take/1`). When I `node_load(arg(1))` there also is no clue of how and what questions are mapped to a quiz.

*quiz-7.x-5.0-alpha10*

# Answer
Thanks a lot @J.Reynolds for pointing me in the right direction!

```
/**
 * Helper function to get current question's NID.
 * @return string node ID
 */
function _current_question_nid() {

  // Presume a URL node/1234/take/2 meaning we are at the second question
  // of a quiz, where arg(1) is the quiz NID

  // Now let's look inside SESSION. There's our current quiz NID.
  if (array_key_exists(arg(1), $_SESSION['quiz'])) {

    // Inside there is the current result ID.
    $result_id = $_SESSION['quiz'][arg(1)]['result_id'];

  } else {

    // A little bit different to get the current result ID at last question.
    $result_id = $_SESSION['quiz']['temp']['result_id'];

  }

  // Now we can load the quiz results from that result ID.
  $result = quiz_result_load($result_id);
  // There all question NIDs are inside, nicely ordered, yay!

  // Finally let's take the question number and get its NID.
  $current = $result->layout[arg(3)];
  return $question_nid = $current['nid'];
}

```
> 1 votes

---
Tags: 7, quiz
---


# Question
Title: Is there a way to alter only the printable invoice for Ubercart 3.8?
Client would like to print order invoices from 'View Orders' page without their large logo at the top wasting ink. I do not seem to be able to isolate just the printed invoice without affecting the admin and customer invoice.

# Answer
I see 2 possible solutions:

* Create separate template called "when\_client\_prints" and link to this template from Views Orders.
* Edit current invoice template within your custom module with the logic like `if user hasn't id * then show the logo`. (`*` stands for the `UID` of client account)
> 1 votes

---
Tags: ubercart, commerce
---


# Question
Title: How to combine Image and Video fields in a views slideshow in a single carousel?
I have a content type called **Cities** and it has an **Image field**. Using the Views Slideshow module with *jquery.cycle* I am able to create a block which takes the Image from the content and creates a slideshow.

However I have a requirements to be able to add the videos also in the same slideshow. So, I added one more field in the content type as **Videos field** where I can post the Youtube video URL.

Now the Dilemma is to display this video also in the same slideshow as the image, so, the slideshow would continue with mixture of Images and Videos.

My question is how to combine these two fields `image and videos` in views slideshow, to create a single slideshow/carousel?

# Answer
> 2 votes
You should be able to simply add both fields. To help matters along you should can add a bit of logic to only show one field if both are populated. To do this follow these steps:

* First decide which field to show if both have values, for the purposes of this example I'll say that it's video but reverse everything if you want it to be the image field.
* Make sure you view has "Fields" selected next to "Show:"
* Add the image field and tick "Exclude from display"
* Add the video field
* In the settings for the video field under "Rewrite results", click on "Rewrite the output of this field" and then on "Replacement patterns"
* Copy the token that relates to your image field (including the surrounding `[` and `]`)
* untick "Rewrite the output of this field" and click "No results behavior"
* Paste the token you copied (including the `[` and `]`) into the "No results text" box.
* Save.

Then the view row will show the video unless there is no video in which case it will show the image.

# Answer
> 0 votes
Use the Media module instead of the Image field and Video fields. The dependent File Entity module provides a mime type agnostic field that Views can read. Then the Media module provides a peer type formatter that will be rendered via Views.

---
Tags: 7, views
---


title: Custom template

text:
# Question
Title: Custom template
In my theme I created my template for all my pages (page.tpl.php):

What should I do to create a template for page /services for example, and this inherit all of page.tpl.php? but only write in the content region.

# Answer
I may be misunderstanding the question, but Drupal always renders the content in the "content" block region of page.tpl.php. The page template is already for every page.

If you want *other regions* to be different on a specific page, it depends on the method the specific page is generated. You could create overriding template files, but I would recommend keeping as much as possible that stays the same on every page in your page.tpl.php file and use other templates like node.tpl.php or block.tpl.php (block--region.tpl.php) for dynamic layouts and markup.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to override a JS function in the Media Module without editing the actual module files?
```
Drupal.media.browser.validateButtons = function() {
    // The media browser runs in an IFRAME. The Drupal.media.popups.mediaBrowser()
    // function sets up the IFRAME and "OK" and "Cancel" buttons that are outside
    // of the IFRAME, so that their click handlers can destroy the IFRAME while
    // retaining information about what media items were selected. However,
    // Drupal UI convention is to place all action buttons on the same "line"
    // at the bottom of the form, so if the form within the IFRAME contains a
    // "Submit" button or other action buttons, then the "OK" and "Cancel"
    // buttons below the IFRAME break this convention and confuse the user.
    // Therefore, we add "Submit" and "Cancel" buttons inside the IFRAME, and
    // have their click action trigger the click action of the corresonding
    // "OK" and "Cancel" buttons that are outside the IFRAME. media.css contains
    // CSS rules that hide the outside buttons.
    //
    // We don't add a "Submit" button if the form already has one, since in these
    // cases, another round-trip to the server is needed before the user's
    // selection is finalized. For these cases, when the form's real Submit
    // button is clicked, the server either returns another form for the user to
    // fill out, or else a completion page that contains or sets the
    // Drupal.media.browser.selectedMedia variable. If the latter, then
    // Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad() auto-triggers the
    // "OK" button action to finalize the selection and remove the IFRAME.
    //
    // @todo An alternate, less hacky solution would be most welcome.
    if (!($('.form-submit', this).length > 0)) {
        $('<a class="button fake-ok">Submit</a>').appendTo(this).bind('click', Drupal.media.browser.submit);
        if (!($('.fake-cancel', this).length > 0)) {
            $('<a class="button fake-cancel">Cancel</a>').appendTo(this).bind('click', Drupal.media.browser.submit);
        }
    } else if (!($('.fake-cancel', this).length > 0)) {
        var parent = $('.form-actions', this);
        if (!parent.length) {
            parent = $('form > div', this);
        }
        $('<a class="button fake-cancel">Cancel</a>').appendTo(parent).bind('click', Drupal.media.browser.submit);
    }
};

```

(See also http://jsfiddle.net/S6WXc/.)

This function in the Media Modules js/media.browser.js is clashing with what I've added into the Media Select popup via Form Alter (A simple AJAX call to display thumbnails of images, that when clicked open up in a Colorbox modal window).

I've tracked the problem down to something in Media Module and Colorbox clashing, since when I click a thumb that opens the Colorbox modal popup, an event is launched that duplicates the 'fake' Submit / Cancel buttons in the Library tab, and also some of the Library thumbnails (my own thumbs are shown in the Web tab).

Not going in further detail, is there some way to override the function in the Media Module without editing the actual original .js file? I don't fancy doing edits each time I update it so to override it in my module or my own .js file would be preferable.

# Answer
> 7 votes
You can simply do it like that :

```
Drupal.media.browser.validateButtons = function(){ // Your code ... };

```

Of corse, this assignment must be after the original one.

# Answer
> 3 votes
I added this into my own JS file so that once the initial loading of the Library tab is completed, the functions handling it are overwritten and the weird bug is gone -- quick testing reveals that everything also works as expected so I think this is it!

Now I'll issue some bug reports based on my findings and hope the module developers might come up with some proper way to navigate around this. :)

```
Drupal.media.browser.validateButtons = function(){
  // Something in Colorbox is calling this function again, so we 'empty' it after loading.
  // @TODO: Come up with something less hacky.
};

Drupal.behaviors.mediaLibrary = {
  // Something in Colorbox is calling this function again, so we 'empty' it after loading.
  // @TODO: Come up with something less hacky.
}

```

# Answer
> 0 votes
Another possible way how to override a JS function is to edit original JavaScript and replace it with the `hook_js_alter` using your `custommodule`.

This is the sample code:

```
/**
 * Path to the new file.js
 */
function  custommodule_js_alter(&$javascript) {
  $javascript[drupal_get_path('module', 'altered_module') . '/path/to/file.js']['data'] = drupal_get_path('module', 'custommodule') . '/path/to/file.js';
}

```

Source with mode details.

---
Tags: javascript, media
---


# Question
Title: How do I make the file description field required?
In Drupal 7, I need users to enter a file description, how do I make this field required? Also on another note, I would love to make this field a select list, there's no clear way to do this aside writing a custom module. Any ideas?

# Answer
Code snippet for making a file's description field required:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $element_children = element_children($element, TRUE);
    foreach($element_children as $key) {
      $element[$key]['#process'][] = 'MYMODULE_file_field_description_required';
    }
  }
}

/**
 * Require description to be set.
 */
function MYMODULE_file_field_description_required($element, &$form_state, $form) {
  $element['description']['#required'] = TRUE;
  return $element;
}

```
> 1 votes

---
Tags: entities, files
---


# Question
Title: Printing an Entity Reference Field Value in a field collection in views-view-fields.tpl.php
I am overriding my view with the template **views-view-fields.tpl.php**, and have called it **views-view-fields--front-featured-blocks.tpl.php**

I wont bother putting all of my code for this block up, but the two defining lines of my code are as follows...

```
<span class="block-entity-id">
  <?php print $fields['field_link_to_content']->content; ?>
</span>

<span class="block-title">
  <?php print $fields['field_block_title']->content; ?>
</span>

```

The *field\_block\_title* span prints a value, but the *field\_link\_to\_content* does not.

The **field\_link\_to\_content** is an Entity Reference field, which is printing the Entity ID, which I need to build a link.

Can anyone tell me why this doesnt work, but I can print every other field in the same method? The entity reference field is only allowed one value, but is there a delta value involved? How would I print a list of allowed values? I have devel installed.

# Answer
> 2 votes
I found my main answer from this question here.. Calling a field in views-view-fields--view-name.tpl.php ---- Error

My problem was excluding the display of the field. I assumed that I would want the field hidden as I wanted to show it elsewhere, but as I am overriding the views.view.fields.tpl.php anyway, I could choose to declare it or not.

As soon as I set the field to display again, I could use...

```
print $fields['field_link_to_content']->content;

```

If I had wanted to keep the field hidden, I could have used something like...

```
$row->field_field_my_custom_field[0]['rendered']['#markup']

```

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


# Question
Title: Delta option of term field missing in views
So I have a view that's been working for the last year. now suddenly there is a missing broken handler.

Turns out that the missing field is a delta (field) of a term reference field, the term field is still available. Now even when creating a new view i can't add term reference delta

What could possibly be causing this. if someone could just give me a place to start that would be great.

this is the missing field from views export on the staging site.. which still works.. :/

```
$handler->display->display_options['filters']['delta']['id'] = 'delta';
$handler->display->display_options['filters']['delta']['table'] = 'field_data_field_people_reference';
$handler->display->display_options['filters']['delta']['field'] = 'delta';
$handler->display->display_options['filters']['delta']['relationship'] = 'reverse_field_people_reference_field_collection_item';
$handler->display->display_options['filters']['delta']['value']['value'] = '0';

```

# Answer
> 1 votes
If you accidentally change the amount of values this field takes to one then obviously there will be no delta... side note **I am an Idiot**

---
Tags: views, database, entities
---


title: Save pdf files in folder using TCPDF

text:
# Question
Title: Save pdf files in folder using TCPDF
I have installed Print module and also TCPDF library to generate PDF files. However, Print module can just create PDF files to download, but not to save in server folder. I have tried to change method \_print\_pdf\_tcpdf in Print module, so files can be saved in server folder. I have changed \_print\_pdf\_tcpdf function as follows:

I have changed line

```
$pdf->Output($filename, $output_dest);

```

to this line:

```
$pdf->Output($filename, 'F');

```

But this code throws error:

```
TCPDF ERROR: Unable to create output file: https://mywebsite/sites/default/files/aaa.pdf

```

I have set permissions for sites folder to write. Another modules can write into this folder, so I dont think the problem is in permissions. Can anybody help where can be problem?

# Answer
> 3 votes
I've made a couple of TCPDF implementations myself in Drupal. As Clive suggested, you shouldn't use URIs in TCPDF's `output()` method, instead you'll want to provide absolute filepaths.

This code has always worked for me:

```
// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$path = drupal_realpath('public://folder/folder2/folder3');

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

```

EDIT: As Clive mentioned in the comment, `drupal_realpath()` is deprecated. Here's an alternative:

```
// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$uri = 'public://folder/folder2/folder3';
$stream = file_stream_wrapper_get_instance_by_uri($uri);
$path = DRUPAL_ROOT . '/' . $stream->getDirectoryPath() . '/' . file_uri_target($uri);

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

```

Just make sure you're always providing an absolute path for TCPDF.

# Answer
> 2 votes
Looking at the error message

```
TCPDF ERROR: Unable to create output file: https://mywebsite/sites/default/files/aaa.pdf

```

It would appear your `$filename` variable contains a URI, instead of a path. Files can't be saved to URIs; for that to happen you'd need to make an HTTP request with an appropriate verb. So that's likely to be the problem.

I'm not that familiar with TCPDF so I don't know if it support stream wrappers or not. Either of these might therefore work:

```
$filename = 'public://aaa.pdf';

```

or

```
$filename = DRUPAL_ROOT . '/sites/default/aaa.pdf';

```

# Answer
> -1 votes
```
$pdf->Output( "myfile.pdf", "F");
TCPDF ERROR: Unable to create output file: myfile.pdf

```

In the 'include/tcpdf\_static.php' file about 2435 line in the static function 'fopenLocal' if I delete the complete 'if statement'... works fine.

```
public static function fopenLocal($filename, $mode) {

    /*if (strpos($filename, '://') === false) {
        $filename = 'file://'.$filename;
    } elseif (strpos($filename, 'file://') !== 0) {
        return false;
    }*/
    return fopen($filename, $mode);

```

---
Tags: 7, files
---


# Question
Title: Format of the JSON returned by the Services module
I have a big doubt about the JSON format the Services module (for Drupal 6) generates.

When I view the XML, all is OK.

```
<result is_array="true">
 <item>
  <nid>9</nid>
  <vid>9</vid>
  <type>producto</type>
 </item>
</result>

```

When I view the JSON, I see this:

```
[
 {
  "nid": "9",
  "vid": "9",
  "type": "producto",
 }
]

```

What I really is something like this:

```
[
 {
  "item":{
    "nid": "9",
    "vid": "9",
    "type": "producto",
  }
 }
]

```

How do I do this? Is there any configuration in the Services module that I can use to change the output, or do I need writing code?
I know the function to render JSON output.

# Answer
> 3 votes
You should implement `hook_services_request_postprocess_alter()`.

# Answer
> 1 votes
As I mentioned before, `hook_services_request_postprocess_alter()` won't provide you what type of data it's processing. It means that your code must be really hacky to catch exactly the type of data you need.

You better create your own formatter with `hook_rest_server_response_formatters_alter()` and use it to render data.

---
Tags: services
---


# Question
Title: How to send mail for every X months using rules?
In my user profile there is date of orientation(date field) from date(current date) and end date.

When user fills the date field, it should generate an Mail for every X months. example-according to screen shots i have two date field when user have given from date(current date or future date)based on that date for both date fields should trigger a mail every X months.

# Answer
**Requirements:**

Rules, Rules UI and Rules Scheduler must be installed and enabled.

**Step 1)** Create a **new component**, I named it **send mail every 2 months**

**Step 2)** Add an action of **Send Mail**, fill out the form, see picture below.

**Step 3)** Add an action (again)

This time select **Schedule Component Evaluation** and **select** your component (**send mail every 2 months**)

> Note: this will re-schedule your e-mail to be sent 2 months after its sent for the 1st time

**Step 4)** For **SCHEDULED VALIDATION DATE**, erase everything and put **+2 Months**

For **Identifier**, put something like I did (see picture) so you know who the schedule is for.

For **ACCOUNT**, put **account**

**Step 5)** Create a **new rule**, for **React on Event**, select **After saving a user account**.

**Step 6)** Add an action, select **Schedule Component Evaluation** and **select** your component (**send mail every 2 months**)

**Step 7)** Click on the **switch to data selection** button

**Step 8)** Put your field in Scheduled Evaluation Date. My user date field is called **From Date** with a **machine name of field\_from\_date** Therefore, it's **account:field-from-date**

Click on Add Offset, put 2 and select Months. (This means it will send the e-mail 2 months from the from date.

For **Identifier**, put something like I did (see picture) so you know who the schedule is for.

**ACCOUNT**, put account
> 3 votes

# Answer
Refer to my answer to the question about "Rule to store user's last post date and scheduled rule based 30 day reminder", which is a variation (though not a duplicate) of your question here. Below are some more details about the steps you need to complete to make it work for your case also.

# Step 1

Your `to date` already corresponds to `field_next_article`. Let's assume the fieldname of your `to date` is `field_to_date`.

# Step 2

Copy the Rules component example from Step 2 (in export format already) to some temporary file, and perform these changes:

* change field name `field_next_article` to `field_to_date`.
* change the eMail details (such as Subject, etc) to fit your requirements.

Then import the edited version in your own site.

# Step 3

Copy the Rules example from Step 3 (in export format already) to some temporary file, and perform these changes:

* change field name `field_next_article` to `field_to_date`.
* change 30 days to 2 months, and review (correct) the value for `date_offset` (to also make it match 2 months).
* Replace the "Rules Event" (= the line starting with "*ON*", by "some event that fits your exact requirements".

Then import the edited version in your own site.

# Step 4

To actually sent such eMail every 2 months, you need to add another action at the end of the Rules component you created in Step 2. That action is to repeat the execution of the Rules component itself (which was created in Step 2), similar to what is explained in the video about "Repeating scheduled events" (especially what is shown from about 7:00 to 8:00 in that video).

**Note**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

PS: I'm assuming this question is about D7.
> 1 votes

---
Tags: rules, emails
---


# Question
Title: Making sure the cookie path does not include language code
I'm in the process of setting up a site to support 4 languages. One of the changes I made started to redirect /user to /\[lang-code\]/user, which in turn means Drupal's session cookie path now contains the language code. With the language code in the path, authenticated users do not stay logged in when they change languages.

Is there a simple way to avoid having Drupal add the language code to the cookie session path?

# Answer
The problem in this case was solved by setting the cookie path in settings.php:

```
ini_set('session.cookie_path', '/subdir');

```

The site is running in a sub-directory (which may or may not have mattered), and the initial value used in the settings file has lacked the leading / (which mattered a great deal).
> 0 votes

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


# Question
Title: Changing background color in table when status is changed
I have table in VIEWS who stores from webform so i want to make is When user select green from webform, then those informations need to be with green background, if other user select blue, that need to be blue in my table with results.

# Answer
> 0 votes
You can add use fields as classes to table rows and then through CSS assign background color to it. Check the screen shot, in the screen shot I have used a field as Row class. You will get your field replacement pattern in "Rewrite the output of this field" for all fields.

---
Tags: webforms
---


# Question
Title: View Revision log message with display suite
In drupal 7, Is there any way, with or without Display suite, to show the revision log message at the bottom of a view node page?

# Answer
> 1 votes
You can easily do this with help of views module. Check the screen shot

**Update** Position the view block to show on node page, where view will pick the node id and show the related revision log message.

---
Tags: display-suite, nodes
---


title: Path to views in menu link

text:
# Question
Title: Path to views in menu link
I have a view that shows all the articles then I can select the year. I made this with a group filter. At this point drupal send the user to an url /noticias?created=2

and here news of 2014 are displayed

and so on.. noticias?created=3 ---\> 2013 noticias?created=4 ---\> 2012 ...

Now I want add a link in the main menu

News 2014 (path: noticias?created=2)

but it says: The path 'noticias' is either invalid or you do not have access to it.

The question is

How can I create a menu link for each year? I would not like to use absolute path...

Thanks

# Answer
> 1 votes
You could use contextual filters with the year as parameter. Your views path could be "noticias/%". "%" is a placeholder for your contextual filter. So you have to add 2 filter i think. Global: Null and your year date as second parameter. This method is more SEO friendly.

---
Tags: views, routes, path-aliases
---


# Question
Title: How to apply a distinct css class to each value of a field with multiple values?
In a similar manner to views-row classes, is it possible to add a distinct css class to each value of a field where cardinality is greater than one?

Ideally I am looking for a module that does this.

# Answer
> 3 votes
A simple approach would be to use CSS `:nth-child()` pseudo classes. Assuming some HTML output like:

```
    <div class="entity-reference-wrapper">
        <div class="entity-reference">
            [CONTENT]
        </div>
        <div class="entity-reference">
            [CONTENT]
        </div>
        <div class="entity-reference">
            [CONTENT]
        </div>
        <div class="entity-reference">
            [CONTENT]
        </div>
    </div><!--/.entity-reference-wrapper -->

```

You can target the 2nd div with css like this:

```
    .entity-reference-wrapper .entity-reference:nth-child(2) {
        color: green;
    }

```

Odd children like this:

```
    .entity-reference-wrapper .entity-reference:nth-child(odd) {
        color: green;
    }

```

There are a lot more options over at CSS tricks here: https://css-tricks.com/useful-nth-child-recipies/

---
Tags: theming, entities
---


title: Drupella form api

text:
# Question
Title: Drupella form api
I have looked everywhere but can't find the answer to this question. I am using Drupella File Manager. All is working well but I have this custom form I have made. I need to make this file field I have use the Drupella FM.

Does anyone know how this can be done?

My code is:

```
$form['site_image'] = array(
  '#type' => 'file',
  //'#default_widget' => array('dfm_filefield_on' => true),
  '#name' => 'site_image',
  '#title' => t('Site image'),
  '#size' => 40,
  '#description' => t('Select your image'),
  '#upload_location' => 'public://media'
);

```

# Answer
> 1 votes
This is a non-drupal product. But if you're using this sandbox module: https://www.drupal.org/sandbox/Drupella/2008504

Then the project directions simply say:

> Enable Drupella FM for File Field module if you want to select files from Drupella FM for your image/file fields. You must check the Allow users to select files from Drupella FM for this field option in your field's configuration page.

If you're not using this sandbox module and trying to do this yourself. I recommend you try the sandbox module.

---
Tags: entities
---


# Question
Title: How may I schedule when comments can be Opened and Closed?
I've been tasked to set up a Q&A styled project where we invite an industry leader, subject matter expert (SME) to answer questions for hopeful students in the same field. The individual requesting this project is a fan of reddit's Ask-Me-Anything styled interviews. So, yes, that is a big driver of this project.

We'll have a period of a week where the students can ask questions and two weeks where the SME can respond to those questions. In the fourth week, both can further respond with follow up questions or expanded responses. After that, the conversation will be available as read-only archive with nothing new added. I'm thinking nested comments would be sufficient.

Can I tell Drupal to open and close comments on certain dates, or even use a date field of when comments should be closed?
I'm okay with either using a contributed module (I haven't found one), Rules (I've not used very much), or custom code (My default, but there are people much smarter than me who have probably already done this better).

# Answer
That should be as simple as:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (/* Your logic to determine that comments are closed here */) {
    $node->content['comments']['#access'] = FALSE;
  }
}

```

(it'll probably need to be tweaked for your exact requirements, have a look at what else lives in `$node->content['comments']` if you want to hide the form/existing comments separately).
> 5 votes

# Answer
I'm assuming you have a content type for this, say "Question", for which you want to enable / disable comments. Refer to the steps below about how to do so.

# Step 1 - Create a list

Start with creating a VBO list of all relevant questions, whereas in your view you use any relevant filters, etc.

# Step 2 - Create a rule to enable comments

Use this VBO list to do something that is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

> * You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
> * However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
> * You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
> * The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from that VBO list of questions for which comments are to be enabled. And for each node in the list you want the rules action to be something like "enable comments", instead of "remove sticky" (as in the video).

Should you need any other rules "conditions", you can add them to the rules component you created.

# Step 3 - Trigger the rule to enable comments

The Rules component that you create as described above, should then become the action to be performed by a rule that is triggered automatically, via the Rules Scheduler. This is what is shown in the video (mentioned in Step 2), starting from 11:30. In the video the Rules component is triggered daily, though you want it to be triggered "on certain dates". As an alternative for using the scheduler (eg if these dates may vary), you can also trigger the rule by just executing the rule from the Rules UI (whenever the time is right).

# Step 4 - Create and trigger the rule to disable comments

The above is to "enable comments", but you can use a similar approach to "disable comments" also of course (via a 2nd rule).
> 2 votes

---
Tags: 7, comments
---


# Question
Title: How to programmatically display a webform in a block based on user selection
I am developing a module which generates custom blocks based on some configuration done by site admins in a module-specific config page. For each block I would like the admins to be able to nominate a webform (from a select dropdown), which would then be displayed in the block.

What I don't understand is how to match up the webform selection process with the webform display process. In the module-specific config page, I would generate the options by querying the node table for all nodes of type 'webform', display the titles of the webforms in the select element, and then save the nid of the chosen webform.

However this nid doesn't seem to be much help to me when it comes to `my_module_block_view`, where (as I understand it) in order to display a webform I need to do something like

```
$block['content'] = module_invoke('webform','block_view','client-block-N');

```

~~where N is the nid of the node to which the webform is attached, **NOT** the nid of the webform itself ?~~ **Incorrect statement - see correction below**

So I'm unsure how to request the webform that the users have selected, as all I know about it is its nid?

**What I'm seeing:**

On my test Drupal, I have a webform with nid = 1, and content items of nid 2 and 3. Whether I specify `'client-block-1'`,`'client-block-1'`, or `'client-block-3'` in my call to `module_invoke`, I am seeing no webform displayed.

Does anyone have any suggestions how I should proceed with this?

All help greatly appreciated.

**CORRECTION**

In the code example above, N should be the node id of the webform.

# Answer
> 3 votes
You're very close - the return from `hook_block_view()` is an array with keys `content` and optionally `subject`. Your current code example:

```
$block['content'] = module_invoke('webform','block_view','client-block-N');

```

Produces the equivalent of:

```
$block['content'] = array(
  'subject' => ...,
  'content' => ...,
);

```

When you put that through `drupal_render()`, it gets angry (because `subject` isn't a render array but isn't prefixed by `#`).

You're probably looking for:

```
$block = module_invoke('webform','block_view','client-block-N');

```

Or simply:

```
return module_invoke('webform','block_view','client-block-N');

```

(once `N` is substituted for the node ID of the webform).

---
Tags: webforms, blocks
---


# Question
Title: Search API Views Indexed Node Filter by Author Role
I have Search API installed, and have indexed all of my nodes.

The nodes all have a different Author, and the Authors have roles "Free user", and "Business User".

I only want the nodes belonging to Business Users showing up in search.

I created a view, the search works perfectly on indexed fields, but I cannot filter by Author:Role

I have added a relationship of Indexed Node: Author, but still no filter available.

Anyone know how I can achieve this?

# Answer
> 2 votes
You need to index the author's roles so that Search API can query that field.

Visit the fields configuration page for your node index (probably admin/config/search/search\_api/index/default\_node\_index/fields if you're using the default node index). At the bottom of the list of fields you'll see a fieldgroup called "add related fields". Expand that, choose author, click "add fields".

When the page reloads your big list of fields will now contain a bunch of new Author-related fields including `Author » User roles`. Check the box next to that one, choose how you want it indexed (integer or string are probably the only ones you'd care to use for this purpose), save your changes, and re-index your content.

I've found that with these sorts of changes I need to clear my cache twice in order for the proper data to be registered with Views and for the appropriate filters to appear in my Views.

---
Tags: views, users, search
---


# Question
Title: What is the proper URL to get flag service?
I'm running Drupal 7 with the Services module and the Flag Service modules installed but I'm having trouble trying to figure out how to Get countall for a particular post ? Can anyone please tell me what URL I should use ?

URL to get all posts : http://webaddess/rest/events

URL to get one Post : http://webaddess/rest/node/3591

# Answer
I had to implement this for DrupalGap/jDrupal:

https://github.com/dontmcyn/flag/blob/master/flag.js#L282

Essentially you make a `POST` to `?q=rest/flag/countall.json` and send along the following data:

```
var data = {
  flag_name: 'my_flag_name',
  entity_id: 123
}

```

You may have to `JSON.stringify(data)` before sending it. And you are right, pass along an `X-CSRF-Token` header in the `POST` call, the value of the token can be retrieved here: `?q=services/session/token`
> 1 votes

---
Tags: flags, 8, services
---


# Question
Title: Is it possible to change how entity reference field is displayed?
I have an entity that I has a taxonomy reference in it. it currently looks like this

and I want this

Is this one of the options in display options array? Or is it something different? How do I change this?

This is my code

```
$fields['category'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Category'))
      ->setDescription(t('Section this poll is to appear on'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setTranslatable(TRUE)
            ->setDefaultValueCallback('Drupal\poll\Entity\Poll::getMain')
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => -10,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ),
      ))
      ->setDisplayConfigurable('form', TRUE)
            ->setRequired(FALSE);

```

# Answer
You just need to set the cardinality of the field.

```
->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)

```

Note that you need to re-install (to be safe, uninstall *before* making the change) or write an update function to convert the database structure if you make this change.
> 7 votes

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


# Question
Title: I am not able to assign a group to a node while creating it
We are using Drupal 7.39 and Services 7.x-3.12 .

We are also using organic groups 7.x-2.7 and while creating a node of type attendance (which is a group content). We are not able to assign a group to it.

We are passing the following parameters:

```
{
  "type": "attendance",
  "title": "Testing Attendance",
  "field_attendance_status":{
  "und":{
    "tid":3
  }},
  "og_group_ref":{
    "target_id":16
  }
}

```

# Answer
> 0 votes
Try this:

```
{
  "type": "attendance",
  "title": "Testing Attendance",
  "field_attendance_status":{
  "und":{
    "tid":3
  }},
  "og_group_ref":{
    "und": [
      { "target_id":16 }
    ]

  }
}

```

Either way, you should be able to verify the proper JSON to use by retrieving an existing node that has an og\_group\_ref.

For example, do a `GET` request (or just visit in a browser):

`?q=[my-api-endpoint]/node/123.json`

Then use a tool like jsonlint.com to inspect the JSON.

I'd also like to point out, that the JSON data you send to Services is *sometimes* dependant on the widget you have selected for the field's form element. See here for more details: https://drupal.stackexchange.com/a/159292/10645

# Answer
> 0 votes
I have tried posting group content but didn't work in all field widgets (select, checkbox or auto complete)

I see there exist an issue with that field **og\_group\_ref** take a look at that question have an answer with a patch hope to solve the issue.

---
Tags: 7, services
---