# Question
Title: ajax_command_invoke adding a new item in a field collection
I'm using the field\_collection module. A collection has a "custom field" I've created, which rely on a jQuery plugin. When I add another item in my collection, the jQuery plugin is no more invoked, and the field doesn't work anymore.

At the first load, all is working, it's only after adding a new item.

I don't know how to invoke the jQuery plugin initialization, there is probably something with the ajax command "field\_add\_more\_js", but I can't figure out which hook or which solution I can use :(

Do you have any idea ? many thanks

# Answer
Actually, it was quite simple... I use **Drupal.behaviors** to attach my jQuery plugin initialization to the form, and it's now called on ajax callback as well, when a part of the form is updated by this ajax call. So it's fixed !

The drupal documentation helped me, and the Lullabot article as well !
> 0 votes

---
Tags: ajax, entities
---


# Question
Title: How can I trace the source of a redirect error listed in Administration -> Reports?
Under `Reports -> Recent log messages`, I have a large number of errors such as the following:

I have a multilingual site (English `en` and Japanese `ja`), so I assume that somewhere there is a bad link or a module is outputting a bad link to the registration page. How can I find out where? The only clue I have is this entry in the recent error log.

When I visit the link (`http://mysite.com/ja/user/en/user/register`), I get a "The page isn't redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

# Answer
If you know the name of the failing redirect URI (such as `user/register`), the best is to scan through your database and look for redirect entries, e.g. using `drush`:

```
drush sql-dump --ordered-dump | grep "user/register"

```

---

Alternatively add `dd()` (from Devel) into `drupal_goto()` and log the backtrace of each call into the file, e.g.

```
dd(debug_backtrace(FALSE, 5));

```

and check `drupal_debug.txt` in your `tmp` folder.

---

Another trick include using DTrace and hook into static probes (if your PHP supports that: `php -i | grep dtrace`), for example (after running the script):

```
sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

```

then you may grep it and look for specific functions such as `drupal_goto`, so you may append to above:

```
| grep -B5 drupal_goto > trace.txt

```

so this will log into file all calls to `drupal_goto` with 5 function calls before.

See also: How to generate the function stack trace of the last request made?
> 2 votes

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


# Question
Title: I need to use hooks without using theme and module
I'm in a project that needs to add features to Drupal Core without using themes niether modules.

I have implemented a class that makes different things, but I need to use hooks or something similar. Maybe I'm mistaken, but hooks must be implemented throught a module or a theme. Can I do this kind of paranoia?

Thanks!!

# Answer
> 0 votes
Yes, hooks must be implemented in a module or theme.

The only other options would be:

1. Hack at the core functionality until it does what you want. This is bad for many reasons.
2. Use the PHP filter module, and hope that it's compatible with the place(s) you need to inject your custom code. This is even worse than the first method.

Moral of the story:

Drupal provides hooks in themes and/or modules to extend its functionality.

If you need to extend Drupal's functionalality, use hooks in themes and/or modules.

---
Tags: hooks
---


title: Why can my node not be found

text:
# Question
Title: Why can my node not be found
I've created node with the following php code and I'm getting the error "The requested page "/node/xx" could not be found where xx is the nid.

```
//Code to add a new pmissue to the drupal7 database
$tmpTitle = "A test PM Issue Insert";
$tmpDescription = "<p>A test PM Issue Body Insertion</p>";
$tmpCallID = '002';
$InsTime = time();
$tmpTime = date("Y-m-d H:i:s", $InsTime);

$result = db_query("SELECT field_callid_value FROM field_data_field_callid WHERE field_callid_value='$tmpCallID'");
$num_rows = $result->rowCount();
db_close();

if ($num_rows < 1) {

//Create new node
$result = db_query("INSERT INTO node (type, title, uid, status, comment, created, changed, language) VALUES ('pmissue', '$tmpTitle', 1, 1, 2, $InsTime , $InsTime, 'und')");

//Assign the new Node ID to $tmpNID
$tmpNID = db_query("SELECT nid FROM node WHERE created = $InsTime")->fetchField();

//set node VID to NID
$result = db_query("update node set vid='$tmpNID' where nid='$tmpNID'");

//Create Node Revision Record
$result = db_query("INSERT INTO `node_revision` (`nid`, `vid`, `uid`, `title`, `log`, `timestamp`, `status`, `comment`, `promote`, `sticky`) VALUES ('$tmpNID', '92', '1', 'A test PM Issue ', '', '$InsTime', '1', '2', '1', '0')");

//Create comment count record
$result = db_query("INSERT INTO `node_comment_statistics` (`nid`, `cid`, `last_comment_timestamp`, `last_comment_name`, `last_comment_uid`, `comment_count`) VALUES ('$tmpNID', '0', '$InsTime', NULL, '1', '0')");

//Insert Tracker_node record
$result = db_query("INSERT INTO `tracker_node` (`nid`, `published`, `changed`) VALUES ('$tmpNID', '1', '$InsTime')");

//assign permissions to NODE (there are 9 of this to execute)
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '0', 'pmpermission_pmissue_update_all', '0', '1', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '1', 'pmpermission_pmissue_update_own', '0', '1', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '56', 'pmpermission_pmissue_update_belonged_organization', '0', '1', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '0', 'pmpermission_pmissue_delete_all', '0', '0', '1')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '1', 'pmpermission_pmissue_delete_own', '0', '0', '1')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '56', 'pmpermission_pmissue_delete_belonged_organization', '0', '0', '1')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '0', 'pmpermission_pmissue_view_all', '1', '0', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '1', 'pmpermission_pmissue_view_own', '1', '0', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '56', 'pmpermission_pmissue_view_belonged_organization', '1', '0', '0')");

//Create body data
$result = db_query("INSERT INTO field_data_body (entity_type, bundle, entity_id, revision_id, body_value, body_format, delta, language, body_summary) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, '$tmpDescription', 'full_html', 0, 'und', '')");

//Create body revision data
$result = db_query("INSERT INTO `field_revision_body` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `body_value`, `body_summary`, `body_format`) VALUES ('node', 'pmissue', '0', '$tmpNID', '$tmpNID', 'und', '0', '$tmpDescription', '', 'full_html')");

//Create CallID field data
$result = db_query("INSERT INTO field_data_field_callid (entity_type, bundle, deleted, entity_id, revision_id, field_callid_value, delta, language) VALUES ('node', 'pmissue', 0, $tmpNID, $tmpNID, '$tmpCallID', 0, 'und')");

//Create pm category reference
$result = db_query("INSERT INTO field_data_pm_category (entity_type, bundle, entity_id, revision_id, pm_category_value, delta, language) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, 'Support', 0, 'und')");

//Create CallID revision data
$result = db_query("INSERT INTO `field_revision_pm_category` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `pm_category_value`) VALUES ('node', 'pmissue', '0', '$tmpNID', '$tmpNID', 'und', '0', 'support')");

//Create pm date reference
$result = db_query("INSERT INTO field_data_pm_date (entity_type, bundle, entity_id, revision_id, pm_date_value, pm_date_value2, delta, language) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, '$tmpTime', '$tmpTime', 0, 'und')");

//Add revision date record
$result = db_query("INSERT INTO `field_revision_pm_date` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `pm_date_value`, `pm_date_value2`) VALUES ('node', 'pmissue', '0', '$tmpNID', '$tmpNID', 'und', '0', '$tmpTime', '$tmpTime')");

//Create pm status reference
$result = db_query("INSERT INTO field_data_pm_status (entity_type, bundle, entity_id, revision_id, pm_status_value, delta, language) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, 'inserted', 0, 'und')");

print $tmpNID;
} else {
print "CallID " . $tmpCallID . " already exists";
}

```

# Answer
> 4 votes
You should follow Drupal 7 - Create a Node in Code to properly create a node programmatically.

1. Create an object of StdClass, and populate its properties with the required properties for a node per the documentation page.
2. Call `node_submit()` and `node_save()` to handle all necessary database operations for you.

---
Tags: 7, nodes
---


title: Anynomus posts in my website drupal

text:
# Question
Title: Anynomus posts in my website drupal
im just new on drupal, i noticed that some posts in my content of my website are submitted by anynomus ( not verified ) user , it came with no type or author . is it hacked ?? or how can i stop these posts on my website. the role at my website required to be verified before publishing BUT these posts came published already

plz help here is a screenshot with the black rectangle arround the posts which i mean.

# Answer
with the Permissions you can deny anything to anonymous (not registered) users you don't want them to do. Also this may help.
> 0 votes

---
Tags: users
---


title: Views Grouping by Field

text:
# Question
Title: Views Grouping by Field
I'm looking to display a list of staff grouped by department. I've figured out how to do this just fine with one exception.

I have a few staff who's time is split between 2 departments. However, when I edit their department field and enter more than one department, they show up in a new section. For example.

> Outreach
>
> > Joe Smith
> >
> > jane Smith
>
> Technical Services
>
> > Joe Johnson
>
> Outreach, Technical Services
>
> > Jane Johnson

Instead of having this separate display, I want Jane Johnson to be listed twice, under both Outreach and Technical Services.

Any ideas?

# Answer
> 1 votes
I'm not sure if you've had this answered yet, but in Drupal 7 and the latest version of Views, this is possible by doing the following:

Under Fields, click the one you want to configure, in your case it probably looks something like: Content: Departments

Select Multiple Field Settings and it will drop-down to where you see a check mark in the box labelled: Display all values in the same row

Uncheck this box and it should list your members twice, once in each department they are specified under.

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


# Question
Title: How to convert field labels to search boxes in views
I have a requirement where I need to convert the labels of specific/all fields of a view to search boxes on user click. The search box will be an autocomplete field. Here, say for eg. the label TITLE gets converted to a search box on user click and provides suggestions(from the title field) as the user types characters

# Answer
> 1 votes
Since these are completely different things you may want to add the autocomplete fields as exposed filters from the view and then add them to the label using javascript. You could use jQuery .append into the label tag with a click listener.

---
Tags: views
---


# Question
Title: How to display another message instead of 403 when trying to open a display of an unpublished product?
When somebody tries to open the product display page for the product which is unpublished, it results in the access denied 403 page being shown.

I want to display a message ("***This product is not available as of now, check other products.***") instead of showing 403 page.

# Answer
> 4 votes
You could add a view as the error page.

Add the view with page (with appropriate path) and attachment as your error page. Filter it on your Product display, pass in the nid as contextual filter and be as creative as you want. The attachment can show the details for the Product that is no longer available, the actual page view can show similar products as alternatives etc. The not found for the contextual filter can be the generic 403 for anything other than products.

Then add the path of the view to the 403 error page setting at `admin/config/system/site-information`

# Answer
> 1 votes
Have a look at my answer to the question about "How to make the permissions of a module more granular?". It uses (only) the Rules module, for which this is the summary of the included rule:

* **Rules Event**: Drupal is initializing.
* **Rules Conditions**: Check if it is an anonymous user and verify if they try to visit some URLs they do NOT have access to.
* **Rules Action**: Redirect those who meet the Rules Conditions to "some other URL instead", and display some informational message about it.

Start with adapting the URLs used in these Rules Conditions and Actions, and remove the 1st Rules Condition (about anonymous users). Then change the message to be displayed to your "***This product is not available as of now, check other products.***". With that, you might be close to what you're looking for.

**Note**: you might be able to further enhance this Rules Condition using some more appropriate Rules Condition that indicates "Product is unpublished" (though I don't know (yet) which one that would be).

# Answer
> 1 votes
If I were you, I'd create a menu item in a custom module for the site that you used as your custom 403 page. (You can configure this in your *Site information* settings form.) This menu item would look at the request path to determine if the user is seeing a 403 error because of an unpublished product display and return the product specific message based on that. Otherwise I'd fall back to the standard text (or perhaps a redirect to login).

This is the least intrusive way to manage your request without involving slower modules, unnecessary queries / render times, etc.

---
Tags: 7, commerce, users
---


title: Rdirected site folder doesn't work

text:
# Question
Title: Rdirected site folder doesn't work
My web host directs traffic to the main *public\_html* folder on the site for my main site. However, I want my main site to redirect to a subfolder for organizational reasons, so I can easily manage just the main site files within that folder. Therefore I want to redirect to *public\_html\mysite.com*.

I created a .htaccess file in the *public\_html* folder that does redirect properly when I just point it to a test index.html file. However, when I try to point to index.php file used from Drupal, I get the following error.

> The server encountered an internal error or misconfiguration and was unable to complete your request.
>
> Please contact the server administrator, webmaster@mysite.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
>
> More information about this error may be available in the server error log.
>
> Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

This is the content of the .htaccess file which lives in the *public\_html* directory.

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?<mysite>.com$
RewriteCond %{REQUEST_URI} !^/<mysite>.com/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /<mysite>.com/$1
RewriteCond %{HTTP_HOST} ^(www.)?<mysite>.com$
RewriteRule ^(/)?$ <mysite>.com/production/dev-code/index.php [L]

```

Do I need to modify the .htaccess in public\_html\mysite.com? I don't have access to the server error log.

# Answer
> 2 votes
Just add a rewriteBase to your .htaccess file

```
RewriteBase /subdirectory

```

Note that this goes into the .htaccess file in the “subdirectory”, not your website root .htaccess file!

# Answer
> 0 votes
I ultimately did not have to use RewriteBase. I changed the .htaccess in `public_html` and change the `$base_url` in my settings.php

My setup was such that I needed to redirect to a subdirectory(yourdomain.com) within a subdirectory(subdirectory) from the main `public_html` folder. This is because for organizational purposes, I wanted everything to live under subdirectories. So the drupal installation was at `public_html\mydomain.com\subdirectory`

I modified the .htaccess at the `public_html` level to redirect to the subdirectory where drupal was installed.

yourdomain.com=the directory where you want your site to redirect to instead of the main `public_html`folder.

subdirectory = If you have an additional subdirectory structure to where your drupal installation goes. I did this so that the drupal install would not live directly under the yourdomain.com because I wanted to keep my private directory there.

```
RewriteRule ^$ yourdomain.com/subdirectory/index.php [L]
RewriteCond %{DOCUMENT_ROOT}/yourdomain.com/subdirectory%{REQUEST_URI} -f
RewriteRule .* yourdomain.com/subdirectory/$0 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* yourdomain.com/subdirectory/index.php?q=$0 [QSA]

```

The `RewriteCond %{DOCUMENT_ROOT}/yourdomain.com/subdirectory%{REQUEST_URI} -f` and corresponding rule were necessary because otherwise when you start clicking on links in your site, it will show http://yourdomain.com/subdirectory

Finally, you need to change the `$base_url` in settings.php to `http://yourdomain.com`

---
Tags: .htaccess
---


# Question
Title: Node Add / Edit Options Vertical Tab Problem
For just one of my content types -- the built-in Article content type -- the node option vertical tabs at the bottom of the add / edit form are not displaying correctly.

As shown in the attached screenshot, the first node option for whether to create a menu link for the node is displayed as a tab. All other node option fieldsets are displayed WITHIN the first vertical tab as collapsible fieldsets, not as additional tabs. This only happens for the Article content type.

I cannot figure out why this is happening. Clearly, some module is form\_altering the node add / edit form, but I have no idea which one or why only for Article.

# Answer
> 0 votes
Here is a series of things I would try. Check tabs after each test.

1. Try with a different browser.
2. Flush all caches (that one often solves a lot of problems).
3. Put your site in maintenance mode and Run updates (update.php).
4. Disable the Overlay module.
5. Disable all modules. Flush all caches. Re-enable all modules.
6. Update to the latest version of core if you can (currently 7.22).

Number 5 is a bit time consuming but it has solved issues for me in the past. First, make a list of all enabled modules. I do this with screen captures. Second, start disabling modules (except maybe Admin menu). You won't be able to disable all modules at once. It may take half a dozen **Save configuration** to completely disable all modules. When done, Flush all caches and while you're at it, clear your browser's cache too. Finally, re-enable all required modules. Run updates. Run cron. Flush all caches.

Hope this helps.

# Answer
> 0 votes
On the content type's configuration page (eg: yoursite.org/blog/admin/structure/types/manage/article/fields), make sure you have nested your tabs correctly. Each vertical tab should be within a **vertical tab group**. Drupal treats the administrative tabs (like menu items, authoring, etc.) as a tab group, but if your other tabs are free-floating, they'll all go together.

On your Manage Fields tab, scroll to the bottom and create a new group, selecting Vertical tabs group option. See screenshot below. Then put your node's fields inside the group. The admin tabs will be outside it and will go into their own group.

---
Tags: 7, nodes, forms
---


title: Vertical Tabs for node Content?

text:
# Question
Title: Vertical Tabs for node Content?
I would like to basically make a node with some tabs on the left that switch what's being viewed on the right. I can structure the content however I'd like since it's a node; is there a way to simply make the content display inside vertical tabs, like on the node editing forms, but when viewing the form?

Does the Render API allow rendering content in vertical tabs in a node?

# Answer
> 1 votes
I've upvoted both of the other answers, because they're both helpful, but not exactly what I'm requesting. I want to display tabs inside a node, with content from the body field. I found that I can add in jQuery UI tabs by adding the appropriate js library and javascript to a particular node.

See: http://dansilvercentral.com/jquery-ui-tabs-drupal-7-tutorial for an example.

Also, to facilitate easier implementation of this on a node-by-node basis, I have a custom module to add an on-site admin interface to choose which pages should get the library added to them, and I'm using Code per Node to be able to simply add the JS right on the page in the node edit form. I'd rather not have to keep adding to a custom module to support content being added and maintained on the site.

# Answer
> 5 votes
See the Quicktabs Module.

# Answer
> 4 votes
If I'm not mistaken, Field Group module offers that.

# Answer
> 0 votes
I would recommend Display Suite, which does precisely this (among many other things) with custom view modes for your content type.

---
Tags: nodes
---


title: Default values in tableselect

text:
# Question
Title: Default values in tableselect
I have a custom module that, among other things, shows the user of a certain role. I want some of the users in this tableselect, do already be checked and I have and arry with these uids.

Now, how do I chedk default values in my list? See code below:

```
$companies = 'mail1@test.org,test2@test.org';
$uids = array();
$comp_mail = explode(',', $companies);
foreach ($comp_mail as $mail) {
    $uids[] = db_query("SELECT uid FROM {users} WHERE mail = '$mail'")->fetchField();
}

$form['msg']['accounts'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => in_array($uids),
    '#empty' => 'no companies',
);

```

# Answer
> 4 votes
Thanks to Clive, this is how it now looks, and works:

```
    $uids = array();
    $comp_mail = explode(',', $companies);
    foreach ($comp_mail as $mail) {
        $uid = db_query("SELECT uid FROM {users} WHERE mail = '$mail'")->fetchField();
        $uids[$uid] = TRUE;
    }

//      drupal_set_message('<pre>' . print_r($uids, TRUE)); // Debug

    $form['msg']['accounts'] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $options,
        '#default_value' => $uids,
        '#empty' => 'No companies',
    );

```

# Answer
> 8 votes
`in_array()` returns a boolean (and takes two arguments), whereas Drupal is expecting an array to be passed for the default value.

The default value array needs to be keyed by the same key used for the options array, so in this case `uid`. The value for each array element should be `TRUE` or `FALSE`, to mark the element as checked or unchecked respectively.

```
$uids[1] = TRUE;
$uids[2] = FALSE;
$uids[3] = TRUE;
// etc.

$form['msg']['accounts'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $uids,
  '#empty' => 'no companies',
);

```

**EDIT**

I haven't tested the following, but since your `$uids` array contains only the array keys you want checked, and a positive number is automatically cast to a boolean `TRUE` in PHP, you might get away converting your array in one step:

```
$uids = drupal_map_assoc($uids);

```

# Answer
> 0 votes
Option and default array need to have the same keys; change `$uids[] =` to `$uids['same_key_as_in_option_array'] =` and remove `in_array()`.

I also use 0 for `FALSE`, and 1 for `TRUE`, but I am not sure if this needs to be like this.

For '#empty', I would use a `t()`'d value.

# Answer
> -1 votes
In looking at the code, the form api expects the default to be set with '#value', not '#default\_value'. I hope this helps someone else avoid the frustration I have experienced!

form.inc: line 3458

```
  if ($element['#multiple']) {
    $value = is_array($element['#value']) ? $element['#value'] : array();
  }

```

form.inc: line 3486

```
  $element[$key] = array(
    '#type' => 'checkbox',
    '#title' => $title,
    '#title_display' => 'invisible',
    '#return_value' => $key,
    '#default_value' => isset($value[$key]) ? $key : NULL,
    '#attributes' => $element['#attributes'],
  );

```

---
Tags: 7, forms
---


# Question
Title: How to show multiple Series of line charts in Views with the Charts module?
I need to create multiple line charts in the same chart. I have a year column, a product column, and a consumer column. I can plot product and year or consumer and year, but when I use all three columns I get a chart that puts both product and consumer data on the same line.

I am using the Charts module, with the Highcharts library as its charting engine and its views integration.

How can I get a product and consumer line to appear on the same graph? I was hoping for the chart to look like Preview 6 here: https://www.drupal.org/node/2426177#preview6

Here is what my chart looks like.

### Data:

### Products:

### Consumer:

### Both:

# Answer
The way to get this to work (to put those charts together), is to work with what's called "parent charts" and "child charts", as explained within Steps to create charts using the views UI. More specifically what's detailed within the paragraph "Creating Multiple Series and Combo Charts in the UI". Here is a quote from it:

> ... you can combine multiple charts on top of each other. The "parent" chart provides the global information, such as the height, width, title, and other properties. Charts that are "children" provide only data and (optionally) a secondary axis. After you've assembled the first series of data in your chart according to the instructions in the Creating Charts using the Views UI section, add a new display to the same view of the type "Chart Add-on". The "Chart Add-on" type is added the same way you would add a new Page or Block display, from the "+ Add" menu at the top of the view configuration.
>
> After this new display has been added, find the setting for "Combine with parent chart" and change this value to point at the parent chart you have already assembled. Then adjust the settings for the child chart to pull in different data (often by overriding the filter settings). Now you can go back to your parent display, and see that the results from the child chart have been merged into the results from the parent chart. You can even use this approach to combine different types of charts, such as a line chart over the top of a column chart. Note that not all chart types can be combined together and invalid combinations may cause your chart to throw errors.

Refer to "Combination chart without aggregation" for an online demo of such chart. Here is a quote from it:

> The chart below (created using the "charts" module) shows a combination chart about all nodes of content type "Article", which has these fields with these "machine names" (+ values):
>
> * "`field_optionlist`" (with some select list values, such as the "year")
> * "`field_free_format_text`" (assumed to contain some numeric values), with Y-axis left, is used in the parent chart.
> * "`field_free_format_nr`" (assumed to contain some numeric values), with Y-axis right, is used in the child chart.

This online demo consists of a combination of 2 "***Area charts***". If you only change the "settings" for each of the 2 charts to "***Line chart***" (within "format" of each view), you'd get a similar set of combined charts but shown as line charts instead. Here is the view (in views export format) that created that chart (using "Line chart" as the format for both charts):

```
$view = new view();
$view->name = 'combination_chart_without_using_aggregation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Combination chart without using aggregation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Combination chart without aggregation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'body';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'body' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'body' => '#2f7ed8',
  'field_free_format_text' => '#233a99',
);
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'The chart below (created using the "charts" module) shows a combination chart about all nodes of content type "Article", which has these fields with these "machine names" (+ values):

- "field_optionlist" (with some select list values, such as the "year")
- "field_free_format_text" (assumed to contain some numeric values), with Y-axis left, is used in the parent chart.
- "field_free_format_nr" (assumed to contain some numeric values), with Y-axis right, is used in the child chart.';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
/* Field: Content: Free Format Text */
$handler->display->display_options['fields']['field_free_format_text']['id'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['table'] = 'field_data_field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['field'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['label'] = 'Products';
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);
/* Filter criterion: Content: OptionList (field_optionlist) */
$handler->display->display_options['filters']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['filters']['field_optionlist_value']['field'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['value'] = array(
  13 => '13',
  14 => '14',
  15 => '15',
);

/* Display: Chart */
$handler = $view->new_display('page', 'Chart', 'page');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['xaxis_title'] = 'Year';
$handler->display->display_options['style_options']['yaxis_title'] = 'Nr of Products';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_free_format_text' => '#7b0d49',
  'field_optionlist' => '#8bbc21',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['path'] = 'combinatuion_chart_with_no_aggregation';

/* Display: Chart add-on */
$handler = $view->new_display('chart', 'Chart add-on', 'chart_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart_extension';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_nr' => 'field_free_format_nr',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_optionlist' => '#2f7ed8',
  'field_free_format_nr' => '#006d1a',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Field: Content: Free Format Nr */
$handler->display->display_options['fields']['field_free_format_nr']['id'] = 'field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['table'] = 'field_data_field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['field'] = 'field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['label'] = 'Enduser Price';
$handler->display->display_options['fields']['field_free_format_nr']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
$handler->display->display_options['parent_display'] = 'page';
$handler->display->display_options['inherit_yaxis'] = '0';

```
> 2 votes

---
Tags: 7, views, charts
---


title: D6 to D8 migrate new content

text:
# Question
Title: D6 to D8 migrate new content
I did a D6 to D8 migration in 10/2015 and I recreated the blocks and views not migrated. But in the mean time 6 month later my D6 original site has been getting more content.

What is the best way to bring all of that content from the last 6 month from my D6 to my migrated D8?

# Answer
You should use migrate module, it's in drupal8's core.

You can define migrations for blocks, nodes, comments, users ... and launch then when you need.

You can select "update" option to syncronize imported content on your new site with changed content on old site.

Here's the offical doc of migrate: https://www.drupal.org/migrate
> 0 votes

# Answer
@user551799 - presumably you used either the UI or the drush migrate-upgrade command provided by migrate\_upgrade, correct? As long as you haven't upgraded your D8 site to the 8.1.x branch, you should be able to simply run it again, and it will import your content on top of the old content.
> 0 votes

---
Tags: migrations
---


# Question
Title: How to insert conditions into Global Custom Text?
I am new to drupal and getting hang of it. I have a custom text in one of my view and I need to display the title based on a condition. This is what I have right now,

```
 <h1>[title] | [field_annual_number] </h1>

```

But I need to display this only if the title doesn't contains the work "multi". So basically, the pseudo code is like this,

```
if([title].contains('multi')) then <h1> [title] </h1> else <h1> [title] | [ Field_annual_number] </h1>

```

Any help would be appreciated. TIA. Srividhya

# Answer
> 2 votes
Add the following code to the bottom of your **template.php** file (located in `/sites/all/themes/yourtheme/` folder)

```
function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){

        if (strpos($vars['fields']['title']->content, 'multi') !== false) {
          $vars['fields']['title']->content = "<h1>" . $vars['fields']['title']->content . "</h1>";
        } else {
          $vars['fields']['title']->content = "<h1>" . $vars['fields']['title']->raw . "|" . $vars['fields']['field_annual_number']->raw . "</h1>";
       }

      }

    }

```
* replace **themename** with your theme name
* replace **view\_name** with your view name
* replace **block\_1** with your machine name

Once you update your template.php file, don't forget to clear/flush your cache in Drupal to see changes.

---
Tags: 7, views
---


# Question
Title: Passing a node field as a contextual filter to a view pane
I am trying to pass an contextual filter to a views content pane from a field in my node and have followed the procedure described in this question without success. I see that the OP of that question eventually resorted to a PHP contextual filter as well.

The only difference is that I am using Panelizer rather than Panels. My field is called `field_organization_contact_recor`. My view works if I test it with legal values for that field in the views UI and gives the correct results in the preview.

I have chosen "from context" and checked that I am passing the correct field in the "Argument input" settings for the views pane. I checked by using firebug to check the field name of the selected option was correct. I get "no results" for my view.

I have also tried setting it up as "Input on pane config". If I do that and pass in a hard-coded value in the pane settings I also get the correct view results in my panels page. On that settings popup there is a prompt "You may use keywords for substitutions." **What is the required format of these keywords to pass a field value?** I have tried the format shown on the list of built-in contexts on the contexts tab "%node:field\_organization\_contact\_recor". This format doesn't work in my case.

Additional info: This field is CiviCRM contact reference field. Perhaps there is a particular hook that this field type doesn't implement?

# Answer
I have found that the format shown on the contexts tab (in Panelizer) which displays as "%node:field\_organization\_contact\_recor" is indeed correct. The reason that it didn't work in my case is that the default value that gets passed by this token is the fully formatted value passed through the field's default formatter. My view needed the un-themed/un-formatted raw value of the field. For now I have implemented a workaround using this method of:

1. Setting up a custom Token display mode
2. Writing a field formatter that outputs the raw value and using it in this display mode.

This is a good solution until we DO want to use the fully themed/formatted value as a token somewhere else on the site. I could not find a better solution despite all the interesting reading in these two relevant threads: Field Tokens and Entity tokens duplicates field tokens created by token module
> 1 votes

# Answer
I found a straightforward solution for this in a comment in the issue queues:

> Basically there is a Display Mode on each content type for Tokens that can be used to control exactly what is rendered by tokens that are used.
>
> To enable it per content type, do the following:
>
> * In the actual Content Type itself, got to the "Manage Display" tab.
> * Scroll down to the end of the field listing and click the "Custom Display Settings" link.
> * Enable (Check) and Save the Token option to enable the Token Display mode.
> * Go to that display mode (Grey display mode tabs near the top) and any field settings you do here effect what the tokens render (which is the same ones Panels uses).
> 10 votes

# Answer
For the "Input on pane config" field, here is a solution without the Token display mode. In your case, set the parameter to:

```
%node:field-organization-contact-recor:cid

```

Explanation: CTools context keywords can be chained like Drupal `[tokens]`. At least the versions with dashes for underscores, but apparently not the versions with underscores. In your case `%node:field-organization-contact-recor` refers to a CiviCRM Contact Record, which apparently has its raw ID stored in a `cid` field. So we use that for chaining.

I could chain entity reference fields referring to nodes with `%node:field-name:nid` successfully and assume the above will be the equivalent for your case, but I did not test it in CiviCRM.
> 0 votes

---
Tags: 7, views, panels
---


# Question
Title: How to get custom field labels translated
I want to get the labels and descriptions of custom fields translated in Dutch, but no matter what I try they always remain in English (the language I use for creating them). I hope my steps below makes sense because I don't understand why it isn't working.

What I do is I create a field (with the site language set to English) in either a profile (using the Profile 2 module) or directly in the account.

Then I edit the field and use the translate button (provided by Field translation in i18n) to add a Dutch translation. But if I then switch the site language to Dutch, the field label and description are still in English.

If I edit the field again (with the site language still set to Dutch), the translate tab now shows the Dutch translation with status original and English as "niet vertaald" or not translated. If I edit the Dutch translation, I'm presented with the English version.

I can change that again to the Dutch text and it will show correctly (in Dutch). Nice, but when I switch the site back to English the field remains Dutch! When I edit the field, the translate tab shows the Dutch text in the English language, but the status for English is back to original.

I cannot make heads or tails of this. Am I completely missing something or is this perhaps a bug? I'm using Drupal 7.

# Answer
You shouldn't change the default language to Dutch to test it, since then it sets that your field names (and all other things in website) are in Dutch.

Instead I suggest to use 'Detection and Selection' options, and enable Browser or User, then test it in other Browser in Dutch, or with another User whose language is set to Dutch.

The better and more comfortable way would be using Language Switcher block, enabling URL or Session under Detection and Selection settings.

So that, the default language of website still stays English and the fields are translated if someone is using the website in Dutch.
> 6 votes

# Answer
Last days, I got the same issue to translate labels and descriptions of custom. here is what i did to solve it.

* Enable i18n's i18\_field "Field translation" submodule
* Go to `admin/config/regional/translate/i18n_string`
* Checked 'fields' (properly check all) and Click on "Refresh strings".
* Go to `admin/config/regional/translate/translate`
* Search desired string and translated it to other lang.
> 12 votes

# Answer
I print translated field labels this way (using i18n\_field.module):

```
$instance = field_info_instance('node', $my_field_name, $my_node_type);
$my_translated_label = i18n_field_translate_property($instance, 'label');

```

Hope it helps.
> 10 votes

# Answer
I think you could have kept Dutch as default language and set English as source language at admin/config/regional/i18n/strings.
> 2 votes

# Answer
the easiest way to do this, is by installing Localize field module.

it provides translations for the following thing:

* title and description of all core fields, date fields and field
* collections prefix, suffix and decimal separator
* option labels of list types

you can use it even if you installed i18n\_field (Field translation)
> 1 votes

---
Tags: 7, entities, i18n-l10n
---


# Question
Title: How to an Add to cart Button to a Content Type?
Is there a possibility to show add to cart button in node page.

**Requirment:**

1. Node will be created along with price
2. Add to cart button needed in that content type
3. Users can click on "Add to cart" button
4. Then ask for the payment like credit card, paypal.

I dont want a huge functionality like Drupal Commerce does. No products, products sku.

Any suggestions or any ideas about how to get this to work?

# Answer
Below are 2 possible alternatives for setting up a simple shopping cart without using the Drupal Commerce or Ubercart modules (as in your "*I don't want a huge functionality like Drupal commerce does. No products, products sku.*").

# Option 1: A lightweight e-shop

If you're only looking for a simple and lightweight e-commerce solution, have a looking at the Light Shop module (for D7, not for D6, not (yet?) for D8). Here is a quote from its project page:

> * Session-stored basket.
> * Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
> * Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
> * Orders history. For each order will be created a separate node.
> * There is no dependence on other modules.
> * Full support for working with anonymous users
> * Integration with Views.

# Option 2: A simple shopping cart

If you're only looking for a shopping cart, have a looking at the Basic Cart module (for D7, not for D6, not (yet?) for D8). Here is a quote from its project page:

> Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
>
> **Main difference from Ubercart and Commerce:**
>
> The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
>
> **Features:**
>
> * The possibility of choosing the content types that can be added to the cart.
> * The possibility of sending, or not, an email to the customer once an order is placed.
> * Custom email messages for both the site administrator and the customer, along with the order details.
> * Order registration and listing in the administration area using Views module.
> * Integration with Rules module.
> * A block with the contents of your shopping cart.

Here is a screenshot of it (note the "**Checkout**" button also ...):

**Note**: According to "Payment/Basic Cart integration" it *should be possible* to integrate this module with the Payment module. Though that integration is still outstanding. So while waiting for that to ever get delivered, it looks like you'll have to investigate yourself to what extend this Payment module is usable in your case without that integration. As an alternative: contact the module owner to see what kind of sponsorship may get it delivered soom.
> 3 votes

# Answer
SO, if you actually use drupal commerce, it separates products from product displays and it's really easy to add the 'add to cart form' to your product displays.

So, if you install the Drupal commerce module you will be able to define product type nodes. However, these will not automatically display, you need to create product display nodes. To these, you can add an add to cart form "out of box." There's a few reasons for doing it this way, but more than anything it gives you more control over presentation, product variations and so on.

So, you need to 1) install Drupal commerce; 2) add some products and create their product displays; 3) and your "add to cart form" to the product displays.

From there you can build views of your product displays for a catalogue, just remember to add the relationship back to the products themselves. There's a lot of good YouTube tutorials on how to get started with Drupal commerce
> 0 votes

# Answer
Perhaps MoneySuite **Pay per view** might do.

> Sell Access to Individual Nodes and Content.

Since MoneySuite is a fork of MoneyScripts. Here are more details:

> This module allows you to sell access to individual nodes, so that users will have to pay before they can see the full node. This allows you to easily monetize any content without having to worry about memberships or roles. Users can purchase access to as few or as many nodes as they want. **You can specify what should be shown to users who do not have access, using custom text and node tokens.** You can set default prices for a content-type, and then override them in the individual node settings. The whole setup is very flexible, and is a great way to monetize your site. Think 'Pay Per View', and you're on the right track. Some possible uses for Premium Nodes include 'Pay to View Complete Answer', 'Pay for Access to this Video', etc. Also, you can charge for access to individual Fields in a node with the new Drupal 7 Fields system. This allows for a very powerful and very flexible system. Get it to work just how you need.
> 0 votes

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


# Question
Title: How do I pass an organic groups GID to a view in a pane?
I have a drupal 7 site using Organic Groups, for each group I have list pages - so for instance if i have the group mygroup I have a page which lists all posts - (www.mysite.com/groups/mygroup/posts). This page has a groups audiance field (og\_group\_ref) which has the correct gid..

I have the list page set up with panes one of which is a view showing all posts with the contextual filter set to GID.

The view works on its own if I pass in the GID of the group I want, however, I cannot get this to cooperate with the list page, probably something to do with the pane, or panels, or a relationship I need to add to the view?

I've tried inserting the view into the pane as a content pane and as a block, but I'm having no joy...

What do I need to do to get this to work?

I have since found this post:

How do you display a pane in an organic group?

this seems to be the answer to what I'm looking to do, however, the settings shown in that post are not available to me. Maybe because panels/views/og have been updated and the settings are a little different now? Either way I still don't have this working. Does anyone have any pointers?

# Answer
**Solved it like this:**

1. Create a "Content pane" view mode of your view, and set "Argument input: Input on pane config".
2. Create a contextual filter in your view that expects a group ID value.
3. Enable the "Tokens" display mode for content type with the `og_group_ref` field. According to here:
    1. Go to "Structure → Content Types → \[your content type\] → Manage Display".
    2. Click "Custom Display Settings" below the field list, enable the "Token" option and save.
    3. Go to the new "Token" display mode in the horizontal tabs on the top.
    4. For your`og_group_ref` field, set "Format: Entity id" and save.
4. In the Panels configuration of your list, insert your View pane.
5. In the View pane config form, there will be a single input field expecting a gid value and saying "You may use keywords for substitutions." below. Enter `%node:og_group_ref`.

**How I think it works:** Panels allows CTools context keywords when supplying arguments to panels. These context keywords are automatically available for all fields (`%node:nid` works out of the box) and all defined tokens (examples). But for fields, they evaluate to the formatted field value, such as your group's name. We could change this behavior by defining a token of the same name, and choosing a formatter that outputs the raw value (the number) when that token is evaluated.

**References:**
> 0 votes

# Answer
**Simpler solution that works without Token display mode:**

1. Create a "Content pane" view mode of your view, and set "Argument input: Input on pane config".
2. Create a contextual filter in your view that expects a group ID value.
3. In the Panels configuration of your list, insert your View pane.
4. In the View pane config form, there will be a single input field expecting a gid value and saying "You may use keywords for substitutions." below. Enter `%node:og_group_ref:nid`.

**How it works:** Panels allows CTools context keywords when supplying arguments to panels. They are automatically available for all fields, and they are chainable like Drupal `[tokens]`. This is not obvious, since it's not included in the context keywords list (shown after creating a Panel variant, in the panel's content section, after unfolding "Substitutions").

Since a group ID is the node ID of the node functioning as group, `%node:og_group_ref:nid` will supply the required ID. If your groups are not node entities, they might use a different field for the ID. For example, CiviCRM contact records use `cid`, so you would supply `%node:og_group_ref:nid`.
> 0 votes

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


# Question
Title: Is there a way to programmatically add questions to a webform grid?
I have seen hooks to use to alter webform options, but not the questions that appear on the left side of a grid.

I would like those questions to be a node titles actually of a content type that I have already defined.

For example, the content type titles will appear on the left and the options are already defined as first choice, second choice, and third choice radio buttons above in the header for each node title.

Here's the grid I would like to produce:

Node Title -- First Choice -- Second Choice -- Third Choice

Title One -- Radio Button -- Radio Button -- Radio Button

Title Two -- Radio Button -- Radio Button -- Radio Button

Title Three -- Radio Button -- Radio Button -- Radio Button

Title n -- Radio Button -- Radio Button -- Radio Button

Essentially I just need a way to import questions that are node titles of another content type into the webform Questions field that requires them to be inputted as pairs ex.

"safe\_key|Some readable option"

"safe\_key|Some readable option"

"safe\_key|Some readable option"

Thank you very much.

# Answer
Sure enough there is a way, a very neat one, just found it out myself!

In the following example I use a View's result to get the list of nodes I will use as the questions in the webform grid. This allows even easier management of the questions you want to display in your grid, by setting for example specific filters on your view.

You need to implement the hook\_webform\_component\_render\_alter hook. Here is the code you need:

```
function yourmodule_webform_component_render_alter (&$element, &$component) {
  // Select the right webform component
  if( $element['#type'] == 'webform_grid' &&
      $element['#title'] == 'Title of Webform Component' ) {

    // Override the title of the grid component
    $element['#title'] = "Node Title";
    // and use it as the label of the questions' column
    $element['#title_display'] = "internal";
    $new_grid_questions = array();
    // This is a standard content view that contains at least a nid and a node title field
    foreach( views_get_view_result('my_view', 'my_display') as $res ) {
      $new_grid_questions[$res->nid] = $res->node_title;
    }
    $element['#grid_questions'] = $new_grid_questions;
  }
}

```

And here is a screenshot of the end result:

Hope this helps!
> 1 votes

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


title: Do blocks replace custom content panes?

text:
# Question
Title: Do blocks replace custom content panes?
In Drupal 7 I use the ctools\_custom\_content (Custom content panes) module to create exportable panel panes to drop into my panel pages. This module doesn't exist for Drupal 8, nor do I see any other way to create panes with the Panels, Page Manager and ctools modules installed.

Have blocks, which are now entities, effectively replaced custom content panes in Drupal 8? Or is there a different core feature or contributed module that I should look to for similar functionality?

# Answer
> 1 votes
There are 3 different things called "block" in Drupal 8. plugins, config entities and content blocks. See Adding custom block problems for an explanation.

But yes, to answer your question, content blocks are exposed as block plugins and can then be used not only for placing blocks in regions but also with page\_manager/panels. You don't need anything else.

One limitation is that they can't be exported easily into config, since they are content. If you don't need extensible structure but only a text or a reference, then you could build your own block plugin or wait for a contrib module to do that (I recently saw a module that did basically that in 7.x with its own plugin system, would be very easy to make the same for 8.x as core provides 90% of what's needed. Can't remember the name right now.)

---
Tags: 8, panels
---


# Question
Title: pathauto_clean_string and accents from a bootstrap PHP file
I have a single PHP file which makes a bootstrap of Drupal 7. The code is below. When I try to use pathauto\_clean\_string in a spanish string with accents (á é ... , etc.) it deletes the character instead of removing the accent using transliteration module (also affects other special chars, obviously). I have included also this module in the bootstrap but cannot have the PHP script to behave exactly as the Drupal site, which is doing properly the transliteration in file names and also from my own custom module.

```
define('DRUPAL_ROOT','/home/example.com/public_html');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '/sites/all/modules/transliteration/transliteration.inc';
 require_once DRUPAL_ROOT . '/sites/all/modules/pathauto/pathauto.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if(isset($_GET['string'])) echo pathauto_cleanstring(urldecode($_GET['string']));

```

Result with www.example.com?string=está-cañón : est-can

Result with the same string and module, same function and correct, expected, result: esta-canon

# Answer
After having a look at the code from the pathauto\_cleanstring function, I would suggest testing the following:

1. Checking the value of pathauto\_transliterate prior to calling the pathauto\_cleanstring function

variable\_get('pathauto\_transliterate', FALSE)
2. If that value is FALSE, you probably found the reason. Try setting that variable to TRUE to force use of transliteration inside the pathauto\_cleanstring function. N.B.: You only need to set this value once.

variable\_set('pathauto\_transliterate', TRUE), or
drush vset pathauto\_transliterate TRUE
3. Try your code again. Fingers crossed!

I suspect that your code never actually uses the transliterate function, but that is something that you can check by dumping the 'pathauto\_transliterate' variable in the various scenarios where your code is executed (in-module, custom script, etc.)
> 0 votes

---
Tags: 7, bootstrapping, transliteration
---


title: How did the ransomware get in?

text:
# Question
Title: How did the ransomware get in?
A site where the site owner put off having updates done has been compromised with ransomware. This situation brings up a lot of questions. A Google search has not produced any answers. The server is on a university system where they lock things down pretty tight.

1. Are there any stats on the ransomware infection rates for Drupal sites, esp. compared to other systems?
2. What is the most common part of a Drupal site to be the hole for a ransomware compromise, ie. specific module, Drupal core, login function, Apache server function?

# Answer
> 1 votes
> How did the ransomware get in?

The website most likely got hacked.

> What is the most likely reason for a Drupal site to be infected with ransomware?

1) Well, doing exactly what that site owner did, putting off security updates which will leave you vulnerable.

2) Leaving the front door open: Allowing scripts, javascript/jQuery or PHP to be executed by regular users.

3) Not using **Secure Login**

> For sites that are available via both HTTP and HTTPS, **Secure Login module ensures that the user login and other forms are submitted securely via HTTPS, thus preventing passwords and other private user data from being transmitted in the clear.** Secure Login module locks down not just the user/login page but also any page containing the user login block, and any other forms that you configure to be secured.

---

### Hacked!

> **This module does not and will not prevent your site from being 'hacked'.**
>
> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.

## Your Drupal site got hacked. Now what?

---
Tags: updating, security
---


# Question
Title: how do I use hook_services_request_postprocess_alter() to wrap field with CDATA?
May i know how to use "hook\_services\_request\_postprocess\_alter" .I have field called 'body' in $result ,I want to wrap it with `CDATA`.Any idea how to do it? `&$result[0]->body` is my variable.

```
function hook_services_request_postprocess_alter($controller, $args, &$result) {

watchdog("custom_forms", '<pre>' . print_r(&$result[0]->body, true) . '</pre>');
}

```

I created a view of service display and body is one of the field,which i want to wrap it with cdata,in order to avoid encoding problem,can anybody help me in this? OR **Which other hook function I need to use in order to avoid encoding problem with body field,when i view page source of service url?** In view page source of service url `&lt &gt` are coming instead of `><` for body field.

# Answer
> 0 votes
This code work for you to over right body result.

```
function hook_services_request_postprocess_alter($controller, $args, &$result) {
  if (is_object($result)){
    //Single value
    $tmpSArray = (array) $result;
    if (!empty($tmpSArray)){
      foreach ($tmpSArray as $skey => $sval){
        $result->body = t('<![CDATA['.$result->body.']]>');
      }
    }
  }

```

---
Tags: 7, views, services
---


# Question
Title: How to get a drupal path in a modal form?
I would like to have a specific path in a modal form. I tried several things but cannot get i work.

**Modal\_form**

I installed the module, clear cached and added into a body tekst the example of the module:

```
<a class="ctools-use-modal ctools-modal-modal-popup-large" href="node/2">Link to click</a>

```

When I click on this link I will get ajax error 200.

**Colorbox** and **Colorbox Node**

Maybe it is working with this module...installed module. After installation I Enabled the Colorbox load option and clear cache.Put the below link in a body text.

```
<p><a class="colorbox-load" href="node/2?width=500& height=500">colorbox test</a></p>

```

After clicking the link I will see node/2 in the browser but not in a modal form. The filters in the editor is full html

**Ctools automodal module**

Installed the module. Put node/2 into the extra modal links box. Pushed the submit button but it is not saved

So probable I do something not good but what? Any suggestion? Using chrome.

Console errors: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ with jquery

Any investigation says that this is a ajax call but I'n not sure.

set jquery update to 1.9 for front end. But no luck :-(

Any suggestion?

# Answer
> 0 votes
you want to display node on popup I guess. The modal form itself does not provide node to display on popup. You need create custom module for it and set its template page.

If you are using colorbox there is one module colorbox node which provides you built in setting to display node on popup.

only need to set `class="colorbox-node"`.

---
Tags: chaos-tool-suite, javascript
---


title: Drupal Settings for PHPStorm

text:
# Question
Title: Drupal Settings for PHPStorm
I want to try to work with PHPStorm Debug.

I already installed debug on my Mac and changed the php.ini File. Furthermore, I installed the Debug Helper for Chrome and created a Projekt on PHPStorm.

If I start Debug, my PHPStorm will find a connection, but I had the Problem that PHPStorm always jumps into my "index.php" file no matter where I set my breakpoint.

I always have to push the "play" button, but again, it runs always through the "index.php" file and my site (I work with VM) will not load before I push "play".

What do I have to do so PHPStorm only jumps to my breakpoint?

**Updated**

Attached my PHPStorm Settings:

# Answer
> 5 votes
Relevant for PHPStorm 10:

Disable the **Force break at the first line when a script is outside the project** setting. This is accessible under Settings:

> Languages & Frameworks \> PHP \> Debug \> Xdebug

I also disable **Force break at the first line when no path mappings specified**.

# Answer
> 1 votes
In addition to @mradcliffe's answer above, and as you work in a VM I guess you may have your browser open in the host OS, hence you need to enable these settings in php.ini (and assuming you use xdebug):

```
zend_extension="..path to xdebug extension/ext/php_xdebug.dll"

xdebug.remote_enable=1

xdebug.remote_port="9000"

```

You furthermore need to set the `IDE key` to `PHPStorm` in your chosen debug extension in the browser. You can also consult the PHP Storm documentation to set it up as an environment variable if you wish, or you can add a bookmarklet.

And just to cover all the bases, you need to listen for incoming connections in PHP Storm here:

---
Tags: debugging, virtual-machine
---


# Question
Title: Access to core comment preprocess variables in a custom comment layout twig template?
In Drupal 8 I have a custom comment type and when I use the default core comment.html.twig to render the comments then variables like 'new\_indicator\_timestamp' and 'parent' get rendered as expected. But if I switch to using a custom layout (via layout\_plugin and display suite) and copy across the relevant twig template code for those core comment preprocess variables into my own custom layout then they don't work.

What do I need to do to ensure that the comment.module `template_preprocess_comment()` variables are available to my custom comment layout?

# Answer
Probably the twig changed, layout modules usually bring their own templates. You have to check which templates are used. To find this out use twig debug:

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

After you found the right twig you have to use the corresponding preprocess hook, which you find in the comments of the twig template.
> 0 votes

---
Tags: 8, comments, theming
---


# Question
Title: How to set multiple entity references as default values using the hook_form_alter()
I have a node which when renders an adds an entityform to the page.

The node has a entity ref field which references multiple other nodes. (eg: Products A, Product B, Product C, etc)

What I need is a rating from each user for each product who views the node.

Eg : Node 1 | User 1 Product A : rating1 Product B : rating2 Product C : rating3

Node 1 | User 2 Product A : rating4 Product B : rating5 Product C : rating6

How could i establish such a thing?

# Answer
You can use Fivestar and Voting API for rating the product

The Fivestar voting module adds a clean, attractive voting widget to nodes and comments and any entity
> 1 votes

---
Tags: forms, entities
---


# Question
Title: How to make mail messages use the UTF8 character encoding?
I am sending mails to users about products, using the SMTP Authentication Support and Mime Mail modules. I set UTF8 as charset in the mail header, but the header is changed from UTF8 to multipart on this line in the mail.inc file:

```
$message = $system->format($message);

```

It actually changes the Swedish characters to some strange characters. So that's the problem: I can't display them correctly.

Any suggestions to correctly display them?

# Answer
> 1 votes
`Content-Type: multipart/alternative;` means that there are parts that can have their own encoding set. If your mail sending modules decide they need multipart, mail should be formatted like that:

```
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=boundary

--boundary
Content-Type: text/plain; charset=utf-8

This part uses UTF-8.
--boundary
Content-Type: text/plain; charset=iso-8859-1

This part uses ISO 8859-1.
--boundary--

```

code sample source here

If you called everything the way module docs tells you to, and UTF-8 data is not in the UTF-8 part, then you just found a bug in one of your modules.

# Answer
> -1 votes
Hi you can also create this functionality using custom hooks.

```
function add_newsletter() {
 $news_query = db_insert('news_letter')
        ->fields(array(
            'email_id' => $_POST['email'],
            'created' => REQUEST_TIME))
        ->execute();
if($news_query) {
    echo '1';
}else {
    echo '0';
}

$to = "abc_example@gmail.com";
$subject  = 'Mail coming from Subscribe';
$message  = "Hi, please check the below email coming from User Subscribers. User Email Id is : ".$_POST['email'];
$headers  = 'From: '.$_POST['email'] . "\r\n" .
            'MIME-Version: 1.0' . "\r\n" .
            'Content-type: text/html; charset=utf-8';
mail($to, $subject, $message, $headers);
if(mail($to, $subject, $message, $headers))
    echo "Email sent successfully";
else
    echo "Email sending failed";
}

```

---
Tags: 7, emails
---


# Question
Title: how can i get path vocabulary based taxonomy term with node title using views?
I have created vocabulary called **Category** and it contains below hierarchy

```
term1
  term 1.1
     term 1.1.1
     term 1.1.2
     term 1.1.3
  term 1.2
term2

```

and i have assigned to this **category** to content type called **Product** after that i have displayed those product items based on category using views with panels it's working fine.when i click product title the url goes like this

http://www.example.com/content/prodcut-title

but i want path like this

http://www.example.com/category/term1/term1.1/term1.1.1/product-title category with term based product title using views.

Please suggest possible ways,

Thanks.

# Answer
Try to change alias pattern for products. Install Entity Token + Pathauto, and on Pattern tab in alias settings (admin/config/search/path/patterns) try to use something like:

```
[node:field-category:parents:join:/]/[node:field-category:name]/[node:title]
```
> 0 votes

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: How to edit comment reply link for specific content type in Drupal 7
Is there a way I can programmatically edit comment reply links for a specific content type in Drupal 7?

So I need to check for the content type before changing the links:

```
<?php
if ($node->type == 'book') {
  // change comment reply links here
}
?>

```

Does anyone know how this can be achieved? Is there some sort of hook I need to implement?

# Answer
> 0 votes
You can try to use preprocess comment function:

```

function MYTHEME_preprocess_comment(&$vars) {
  unset($vars['content']['links']['comment']['#links']['comment-reply']);
}

```

Also check https://www.drupal.org/node/319298

---
Tags: comments, navigation
---


# Question
Title: Permissions not working with Tabs menus?
I have Menus with Tab structure Working from my custom module. But When I built permissions for each Tab It does not work according to assigned user roles in permissions, also it just made those url's not accessible. Please suggest what I am doing wrong, Thanks!

```
function my_module_permission() {
  $arr = array();
  $arr['access one_type_titles'] = array(
    'title' => t('Access First Type Titles'),
    'description' => t('Allow users to First Type Titles page.')
  );

  $arr['access second_type_titles'] = array(
    'title' => t('Access Second type Title page'),
    'description' => t('Allow users to access Second type Title page.')
  );

  return $arr;
}

function my_module_menu() {

  $items['type'] = array(

    'description' => t('Page for translation'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_list'),
    'access arguments' => array('access one_type_titles content'),

  );

  $items['type/fr'] = array(
    'title' => t('French Links'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
    'page arguments' => array('custom_list'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access one_type_titles content'),
  );

  $items['type/en'] = array(
    'title' => t('English Links'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'page arguments' => array('custom_list'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access second_type_titles content'),

  );

  return $items;
}

```

Using `'access callback' => can_the_user_see_this_item,` and then coding access according to user role make it works but not with above method.

```
function can_the_user_see_this_item(){
 if (condition....) ) {
    return TRUE;
  }else{
    return FALSE;
  }
}

```

# Answer
> 1 votes
Try to remove 'content' word from 'access arguments' in hook\_menu, because you custom permissions don't contain it. Clear cache.

```

'access arguments' => array('access one_type_titles'),

```

---
Tags: 7, routes, users
---


# Question
Title: How to insert field value programmatically after node is created?
Let's say user creates a `node` of `article` type.There is a `field` called `my_field` which can be added `multiple` times to that `node`.If user **creates** or **edits** the `node` leaving `my_field` blank, a default value something like **NA** should be created in database and should be visible inside the `my_field` when user **edits** `node` next time.

**Tried so far:**

Inside page.tpl.php

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

  foreach ($nids as $nid) {

    $node = node_load($nid);

   if(empty($node->field_my_field))
   {
     $field_language = field_language('node', $node, 'field_my_field');
     $node->field_my_field['LANGUAGE_NONE'][0]['value'] = 'NA';

      field_attach_insert('node', $node);
   }
  }
 }

```

**Note:** I don't want to create default value inside **field settings** as `my_field` can be added multiple times which can go upto more than 20.

I am using drupal `7.41`.

# Answer
> 1 votes
I suppose it is due to your `field_attach_insert()`. Usually one should save the entire node using `node_save()`. However it is a lot easier if you install the entity API module and utilize its Entity Metadata Wrappers.

And I'd really recommend creating a custom module. You will need something similar to this:

```
function mymodule_node_insert($node) {
  if ($node->type == 'article') {
    mymodule_update_empty_value($node);
  }
}

function mymodule_node_update($node) {
  if ($node->type == 'article') {
    mymodule_update_empty_value($node);
  }
}

function mymodule_update_empty_value($node) {
  $wrapper = entity_metadata_wrapper('node', $node);
  // No value?
  if  (empty($wrapper->field_myfield->value())) {
    $wrapper->field_myfield->set('NA');
    $wrapper->save();
  }
}

```

---
Tags: nodes, entities
---


# Question
Title: Webform Radio buttons are not getting "radio-checked" class when clicked on
I've developed webforms before where I set a component to "Select options" and the design has required these options to look like buttons, so with a bit of simple CSS, we can achieve this:

```
form .form-radios label{background-color:#bebebe; border-radius:3px; margin-right:5px; border: 1px solid #b6b6b6; padding: 10px; text-align: center; color:#232323;}
form .form-radios label{float: left; width:200px;}
form .form-radios label .form-radio {xposition: absolute; xleft: -99em;}

```

(the prefix "x" added to the last 2 styles are obviously removed before deployment, it's just so I can see the radio buttons)

Now, when I click on the pretend buttons, they usually gain the class "radio-checked" as per this example on a previous site I've built https://www.feelthepulse.co.uk/request-callback

However, it doesn't work on my current build (you click the button, but no extra classes are added). I've looked for any modules I might have forgotten about, and I can't see any options for the webform regarding ajax or anything.

Has anyone else had this problem, or know what I'm missing ?

# Answer
> 0 votes
After a bit more digging, it appears it's my memory that has failed me. This functionality is provided by Javascript.
So I'm placing my solution here in case anyone would like to make their select options look like buttons.

You have my CSS above. Next you need to add a javascript folder & file in your sites\> all \>themes \> \[theme\_name\] directory.

I've placed a new folder and file in the above path : js \> webform\_tweaks.js

Inside the webform\_tweaks.js file, place this code:

`(function($) {
 // DOM ready
 $(function(){
 // add a radio-checked additional CSS class to the parent label
 $(".webform-client-form .form-radios input").click(function(){
 $(this.parentNode.parentNode.parentNode).find('.form-item .control-label').removeClass('radio-checked');
 $(this.parentNode).addClass('radio-checked');
 });
 });
})(jQuery);`

You need to reference this javascript file in your \[theme\_name\].info file (found in the root of your sites\> all \>themes \> \[theme\_name\] directory.)

Open that file and add:

```
scripts[] = js/webform_tweaks.js

```

You will also need to flush your CSS & Javascript caches before you see the change.

Hopefully, now you should be able to click on your "pretend" button and apply a style to it using this new "radio-checked" class and make the button looked clicked by adding a background colour or something to it.

---
Tags: webforms
---


title: Drupal not connecting to Solr Server

text:
# Question
Title: Drupal not connecting to Solr Server
I have setup Apache Solr version 5.5 and it runs fine when I test through my browser at `http://localhost:8983/solr/` but when I try to connect Drupal to this it throws the error:

I am getting some 404's in my logs also:

I don't know what is going wrong here, My Solr set up is fine so I just can't figure out why it doesn't connect to the Apache Solr Server.

# Answer
> 1 votes
There can be two things which I can think of.

1. Most SOLR installation guides advise you to edit `IPAccessHandler` in `server/etc/jetty.xml` to whitelist certain IP addresses. Often this is `127.0.0.1`, but that would prevent access from localhost via IPv6. So you maybe should also white label the IPv6 localhost address `::1`, or connect explicitly via IPv4 `127.0.0.1`.
2. Since SOLR 4.x you should also include your core name in the url. `Search API Solr` clearly states this. It might apply to Apache Solr module as well. This would mean your should enter a URL like: `http://localhost:8983/solr/<core name>`.

# Answer
> 0 votes
I found the solution.

I had to add my core name on the end of the path so like this:

```
http://localhost:8983/solr/core_name

```

It then connected to my Solr Server.

You also have to of-course ensure you have added a core from the Apache Solr interface by browsing to `http://localhost:8983/solr` \> Core Admin \> Add Core.

---
Tags: search
---


title: Views: Add class to body based on Views

text:
# Question
Title: Views: Add class to body based on Views
In Drupal, every Views page has a class that is stored in `$css_name` (inside `views-view.tpl.php`).

Is there are any way to get this class to appear in the body class of the page?

Ideally, I would like to prefix it with `page-` (So `views-index`, would become `page-views-index`). I would also like to do it without install extra modules.

# Answer
Two simple ways I might approach this:

1. Context Module
2. jQuery

1) Context Module: create a new context where Condition is "Views" (select the appropriate view) and the Reaction is "Theme HTML" (add the class you want to display in the body there).

Cons: the class is not dynamic, unfortunately. Or at least I have not investigated any way to make dynamically name the class (i.e. page-\[node:field\_field\_yourfieldvalue\]). Because of this, you will most likely need to create a new context for each variation if you choose this approach.

2) jQuery: if you want to get the classes in views and add an altered version of these classes to the body tag, then you could use some javascript to pull that off. Something to the effect of this might work:

```
var myClasses = $(.view-name).attr('class');

$('body').addClass(myClasses);

```

Something like that, just cleaned up. Hope that helps :)
> 4 votes

# Answer
You can do something like that:

```
function THEMENAME_preprocess_html(&$vars) {
  if ($the_view = views_get_page_view()) {
   $vars['classes_array'][] = 'views-' . $the_view->name;
  }
}

```
> 1 votes

---
Tags: views, theming
---


# Question
Title: Create Bundle Product link - Not found, missing
I have done a basic install of Drupal v7.43 with Commerce Kickstart (commerce\_kickstart-7.x-2.34) Both Commerce Bundle modules are enabled.

In "Add Product" actions I cannot find the "Bundle Product" link in order to create a new Bundle Product with some of the existing (previous added) Bundle Groups.

Also, the "Create Bundle Group" link is missing but I found it in the page: /admin/commerce/products/add.

Why are they missing?

# Answer
> 0 votes
They are missing because of how Kickstart manages it's menus.

The easiest way to fix this is to just disable the Commerce Kickstart Menus (commerce\_kickstart\_menus) module. You may need to clear all of your caches, but you should see the other items start to show up again.

---
Tags: commerce
---


title: Drupal Commerce Payment Confirmation

text:
# Question
Title: Drupal Commerce Payment Confirmation
I'm using the Drupal Commerce module (http://www.drupal.org/project/commerce) along with the touchnet upay module (http://www.drupal.org/project/commerce\_touchnet\_upay). I've been able to set it up so when a user clicks checkout, they are redirected to the touchnet site and are successfully able to pay. However, there's nothing on the Orders page that shows that the Order is complete, they still say Checkout:Payment under Order Status. This is the status of the orders that have gone to the payment site but did not pay as well as the ones that actually paid.

Does anyone have experience with using Touchnet and Commerce and can tell me how I can get this to change to Payment:Complete or what Touchnet sends to my site and how I can capture that so I know that the order was actually paid for?

Thanks for the help!

# Answer
So this became an automatic completion once the Touchnet account was setup correctly. The three things that I found that need to happen to ensure it works successfully are:

1. Ensure that the postback site is www.example.com/touchnet (replace example.com with your website)
2. Ensure that the firewall is open on both your server and touchnet's server to allow traffic to each other
3. Ensure that the touchnet postback is using SSL

This made the completion of the payment become automatic without having to add a separate rule.
> 0 votes

# Answer
I believe you have to use the Rules module and create a new rule.

Use react on: after payment is received/complete (or something along those lines)

Then use add action \>\> set a data value \>\> (find your order status field token)
> 0 votes

---
Tags: commerce
---


title: SQL query cck fields

text:
# Question
Title: SQL query cck fields
I want to query if a specific content type has a photo in a custom cck field. I could probably create a View to find this? My mock up query is below. the photo is inside the table 'content\_field\_photo' in the row 'field\_photo\_data' inside this table is another row called 'nid' and this nid value should be present in the content type table called 'content\_type\_contenttype'

```
 SELECT * from content_field_photo WHERE
content_field_photo.field_photo_data IS NOT NULL AND nid is in
content_type_contenttype.nid

```

# Answer
You could use the Forena module to create a report using the data block that matches your "*mock up query*". While doing so, you could also use the WYSIWYG query writing facilities to further tune your query if needed (think of it as using PhpMyAdmin integrated within your Drupal site).

Visit the demo site samples for more details, and/or refer to 2 types of documentation that's available:

**Disclosure**: I'm a (co-)maintainer of Forena.
> 0 votes

---
Tags: database
---


# Question
Title: Custom language switcher block, returning urls problem
In Drupal 8, i am trying to create a custom language switcher block. So, I created a custom module, where I created a new class that extends the "LanguageBlock" class of the core language module. I utilize the `build()` method, that builds alright my custom block. The problem though, is that the resulting links of my custom block, return a pattern like this in the url:

and the language does not change, whereas the default language switcher block works fine. This problem occurs even if the `build()` method is copy/paste from the parent class, and/or even if I just return `parent::build()`, with no editing whatsoever. Does anybody have a clue why this is happening, and maybe a possible solution? Thank you.

PS: The code of the `build()` method.

```
public function build() {
    $build = array();
    $route_name = $this->pathMatcher->isFrontPage() ? '<front>' : '<current>';
    $type = $this->getDerivativeId();
    $links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));

    if (isset($links->links)) {
      $build = array(
        '#theme' => 'links__language_block',
        '#links' => $links->links,
        '#attributes' => array(
          'class' => array(
            "language-switcher-{$links->method_id}",
          ),
        ),
        '#set_active_class' => TRUE,
      );
    }
    return $build;
  }

```

# Answer
I finally found what the problem was. This code "`$type = $this->getDerivativeId();`" was null, and, as a result, this code "`$links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));`" could not build the following part of the $links array:

```
"[language] => Drupal\language\Entity\ConfigurableLanguage Object
                    (
                        [id:protected] => en
                        [label:protected] => English
                        [direction:protected] => ltr
                        [weight:protected] => -10
                        [locked:protected] =>
                        [preSaveMultilingual:protected] =>
                        [originalId:protected] => en
                        [status:protected] => 1
                        [uuid:protected] => 6c14f789-dcf3-4149-883f-63c29df3e544
                        [isSyncing:Drupal\Core\Config\Entity\ConfigEntityBase:private] =>
                        [isUninstalling:Drupal\Core\Config\Entity\ConfigEntityBase:private] =>
                        [langcode:protected] => en
                        [third_party_settings:protected] => Array
                            (
                            )

                        [_core:protected] => Array
                            (
                                [default_config_hash] => HolYKYAaiuzaHd7bV6FOM0HVbmmEMd3Zq4JAcgW55_4
                            )

                        [trustedData:protected] =>
                        [entityTypeId:protected] => configurable_language
                        [enforceIsNew:protected] =>
                        [typedData:protected] =>
                        [cacheContexts:protected] => Array
                            (
                                [0] => languages:language_interface
                                [1] => url.site
                            )

                        [cacheTags:protected] => Array
                            (
                            )

                        [cacheMaxAge:protected] => -1
                        [_serviceIds:protected] => Array
                            (
                            )

                        [dependencies:protected] => Array
                            (
                            )

                    )"

```

All the above was missing, so the url could not be properly build. The solution was to add "Derivative" php file for my class, just like the core language module includes both the "`core/modules/language/src/Plugin/Block/LanguageBlock.php`" and the "`core/modules/language/src/Plugin/Derivative/LanguageBlock.php`". Of course, you have to fix the machine names and namespaces if you do something similar.
> 1 votes

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


# Question
Title: Change front page url by keeping its content
I would like to change front page url to some string, e.g. http://example.com/pattern and need all `url('<front>')` links to be changed to the new url and 301 redirect to new url after openening the site directly as well.

# Answer
You simple need to configure that in your website settings:

Configuration \>\> System \>\> Site information

There you will find the "Front page" panel where you can enter your new front page URL.

Cheers!
> 1 votes

# Answer
A different answer:

You can use the Front Page module to do this, for both setting the frontpage URL as well as getting url('') to work as you want.

After you install the module, navigate to Configuration \>\> Front Page \>\> Home links and enter the pattern you want to use.

Curious to see if that worked for you!
> 1 votes

---
Tags: 7
---


title: How to get the base path in JS

text:
# Question
Title: How to get the base path in JS
I need the base path in my `custom.js` file. I have added this `custom.js` file in my `MYTHEME.info` file.

In `custom.js` file I'm trying to print

```
var baseUrl = Drupal.settings.basePath;
console.log(baseUrl);

```

Gives me empty value.

# Answer
This variable Drupal.settings.basePath is provided by drupal.js, just make sure the page includes this js file.(right click view source code to check)

If this did not work, you can create your own variable and use it on the client side:

* You can add your custom.js file into your file .info `scripts[] = custom.js` or `drupal_add_js(drupal_get_path('module','my_module'). '/custom.js');`
* Use preprocess function in a custom module

```
    function moduleName_preprocess(&$vars){
             global $base_url;
             global $user;
          drupal_add_js(array('moduleName' =>
      array(
        'basepath'=> $base_url,
        'another_variable' => $user->uid
           ),'setting');
        }

```
* access the variable into your js file :

```
  var basepath = settings.moduleName.basepath;

```
* that should be it!
> 1 votes

# Answer
Drupal.settings.basePath use value from base\_path(). Check in php what value returns base\_path(). If needed set it up in settings.php
> 0 votes

---
Tags: 7, javascript
---


title: Field Collection fields not displaying

text:
# Question
Title: Field Collection fields not displaying
I have been running into some trouble with displaying Field Collections. I have a content type (products) that has a field collection called packages. Randomly I would notice that sometimes the field collection fields wouldn't display. Today they have stopped displaying and aren't coming back.

I can't seem to figure out what the issue is. All the fields are set to display in the field collection display settings. Even when I just look at the node view page they aren't displayed there.

I was curious if anyone can help with this issue?

EDIT: It appears that enabling and disabling modules (doesn't matter which one) fixes this and the fields display. Not sure what triggers it to break again though.

# Answer
You can at least start debugging the issue using the devel module: it can tell you if the field collection entity is loaded (so, a render problem) or not. Also it can gives you the id of the entity for further debugging.
> 0 votes

# Answer
Try to load the field collection item, if you get the expected result that means there is nothing wrong with your field collection. Just make sure the field collection field/entity is not hidden in the view mode setting of the node.
> 0 votes

---
Tags: entities
---


title: Setting secure cookies

text:
# Question
Title: Setting secure cookies
In scanning a Drupal 7 site with Qualys, we're getting the issue

> 150122 Cookie Does Not Contain The "secure" Attribute

Is there a way to systematically add the Secure vs HTTPOnly flag to cookies? Would Secure Cookie Data serve this? If so, how do I test that Cookies are secure?

Moreover, this site automatically forwards to https. The user spends no time over port 80 but instead is directly shuttled to 443. We have an administrator who wants nothing but to see this test passed; regardless of the previous fact.

**The Cookie in Question:**

`has_js=1`

Would the following in settings.php be sufficient:

```
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);

```

# Answer
> 2 votes
It appears I can tell Apache to do this for me:

```
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure

```

# Answer
> 2 votes
Which cookie is this? All of Drupal 8's cookies are secure.

The exception is BigPipe's no-JS cookie, see https://www.drupal.org/node/2678628 — but there are no security consequences there.

If that's the one that is triggering this alert, then the problem is clear: your security testing tool is making blanket statements that don't make sense.

---
Tags: 7, cookies
---


# Question
Title: Can I use sub-directories in the "templates" directory?
I created a module that contains a large number of custom templates. They are only used for the module's output; they don't override any existing template file.

I would like to place these templates in sub-directories inside the *templates* directory.

If I place a template in a sub-directory and set a block's `#theme` to `'account/list_block'`, for example, the block isn't rendered, but I don't get errors.

When I keep the template in the sub-directory but set `#theme` to `'list_block'`, I get the following error.

> Template "modules/contrib/mymodule/templates/list-block.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/contrib/mymodule/templates/list-block.html.twig" in the Drupal theme registry.).

From the first example, it seems that Drupal knows the template exists and where to find it, but it doesn't render it.

Is using sub-directories in the "templates" directory possible?

# Answer
You just need to specify the path to the template in `hook_theme()`, eg

```
function MYMODULE_theme() {
  return [
    'list_block' => [
      'variables' => [],
      // Underscores are not converted to dashes automatically in this case.
      'template' => 'account/list-block',
    ],
  ];
}

```
> 5 votes

---
Tags: 8
---