# Question
Title: Running simpletest tests with clean urls on nginx
Having **Drupal 7** on nginx with enabled `clean urls.` nginx config:

```
location @drupal {
rewrite ^/(.*)$ /index.php?q=$1 last;
}

```

When trying to run tests getting message:

> You are not authorized to access this page.

Looks like Drupal cant resolve correctly /batch?op=start&id=28 path. Tests running ok if clean urls disabled.

**Any advise on nginx or drupal config to resolve this?**

# Answer
> 1 votes
You should rewrite Drupal 7 URLs using **rewrite ^ /index.php last;**. The more complete setup is (copied from my development setup):

```
server {
  listen 80;
  listen [::]:80;

  root [...];
  index index.php;
  server_name [...];

  location = /favicon.ico {
    log_not_found off;
    access_log off;
  }

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  # Deny all attempts to access hidden files
  location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
  }

  location / {
    try_files $uri $uri/ @rewrite;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^ /index.php last;
  }

  # pass the PHP scripts to FastCGI server listening on my unix socket
  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 256 16k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_read_timeout 1200;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
  }

  client_max_body_size 100M;

  location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|ttf|svg|eot)$ {
    expires max;
    log_not_found off;
  }
}

```

---
Tags: uri, testing
---


# Question
Title: Gmap won't show infobubbles when clicking markers (with View Module)
First some information:

Drupal Version - 7.41 GMap Version - 7.x-2.10 Location Version - 7.x-3.7

I'm using the gmap module on a webshop i'm creating.

I made a custom content type for this (gmap) which simply has basic fields + a location field I've added. So far so good.

I've added one of this custom content, with the locations I need added through the location tab in the options. I've made a view that displays these all of these custom contents (there's only one, but still displays it) which is working fine. The problem is that, one clicking on the marker, it doesn't show the information while I've set it up to do so.

The issues start when I go to the configuration of my GMap Location. I get these errors

`Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).`

So I'm guessing i'm giving in something which is an object instead of a string, which should be a string in fact. If I scroll down, I notice the that it says "Marker for " but doesn't give any content type after saying just that. I'm assuming that is the error? I'm also getting a few errors in my console

I really have no clue what to do, if i installed the wrong version or if I have some wrong settings somewhere?

Quick edit: using blocks in my regions, not really touching the PHP code I don't think that's a real issue.

# Answer
> 1 votes
I just found the issue myself through googling better. Sorry

https://www.drupal.org/node/2241573#comment-10493640

Some bad code at line 999 of the gmap.module file, remove this and it will work :)

---
Tags: 7, commerce, location, google-maps
---


# Question
Title: Webform response: "Illegal information. Data not submitted."
I have a very simple webform (ie. name, email, comments) that has begun giving this response to any submissions, no matter what they are:

Has anyone seen that before? The results are still saved in the webform but it causes confusion and people also enter their comments multiple times as a result.

# Answer
It seems that message is triggered by the \_webform\_submission\_spam\_check function. Looking at the code, it seems to check the following regular expression:

```
'/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers

```

Maybe some of the submissions contain "cc" or "bcc" or "content-type"?
> 7 votes

---
Tags: webforms
---


# Question
Title: Preventing user creation, but allowing edit
I have defined a role in which I'd like to grant:

1) Permission to edit users

2) Prevent from creating new users

Is this possible? I only see one permission under User called "Administer users" which looks like grants both abilities.

Thanks

# Answer
> 3 votes
You might want to use the Administer Users By Role module. The 7.0-2.x version depends on the Chain Menu Access API.

After both modules have been installed and enabled, you will be able to grant user edit but not user add permissions to certain roles within the /admin/people/permissions form.

Nice side-effect: The user editors won't be able to alter the site admin's profile, if you don't allow it, as it could cause serious problems.

---
Tags: 7, users
---


# Question
Title: How to avoid "An illegal choice has been detected" when updating select list values via ajax?
I have four entity reference fields to user entity in a form. Host form is node edit form. Three of them are select lists, last is Inline Entity Form.

After adding a user entity via IEF I'm trying to update select lists values:

```
function ebep_users_feature_users_list_ajax($form, $form_state) {

  $ief = array_shift($form_state['inline_entity_form']);
  $options = array('_node' => t('- None -'));
  $commands = array();

  foreach($ief['entities'] as $data) {
    $options[$data['entity']->uid] = $data['entity']->name;
  }

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#options'] = $options;
    $commands[] = ajax_command_replace('#'.$fieldName.'_wrapper', drupal_render($form[$fieldName]));
  }

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

```

It works, but when I try to add another user via IEF I am getting:

> An illegal choice has been detected. Please contact the site administrator.

# Answer
My solution:

```
/**
 * Implements hook_form_FORM_ID_alter()
 */
function ebep_users_feature_form_ebep_exhibitor_profile_node_form_alter(&$form, &$form_state, $form_id) {

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#prefix'] = '<div id="'.$fieldName . '_wrapper">';
    $form[$fieldName]['und']['#suffix'] = '</div>';
    $form[$fieldName]['und']['#options'] = _ebep_users_feature_getOptionsValuesFromIEFList($form_state);
  }

  $form['#attached']['css'] = array(
    drupal_get_path('module', 'ebep_users_feature') . '/assets/styles.css',
  );

  $form['#attached']['js'] = array(
    drupal_get_path('module', 'ebep_users_feature') . '/assets/scripts.js',
  );

  $form['users_refresh'] = array(
    '#type' => 'submit',
    '#value' => t('Refresh users list'),
    '#ajax' => array(
      'callback' => 'ebep_users_feature_users_list_ajax',
    ),
  );
}

function ebep_users_feature_users_list_ajax($form, $form_state) {

  $commands = array();

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#options'] = _ebep_users_feature_getOptionsValuesFromIEFList($form_state);
    $commands[] = ajax_command_replace('#'.$fieldName.'_wrapper', drupal_render($form[$fieldName]));
  }

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

function _ebep_users_feature_getOptionsValuesFromIEFList($form_state) {
  static $options = array();

  if (empty($options)) {
    $ief = array_shift($form_state['inline_entity_form']);
    $options['_node'] = t('- None -');

    foreach($ief['entities'] as $data) {
      $options[$data['entity']->uid] = $data['entity']->name;
    }
  }

  return $options;
}

```
> 2 votes

# Answer
**--- Original answer. Is wrong, check update below.**

Just set

```
$bla['#validated'] = TRUE

```

On the select that will be updated with AJAX.

Checkout "Illegal Choice has been detected"

**--- Update 17 Dec 2019 ---**

Actually that was not good advice, that was a long time ago, now I know better.

Ajax callback function is supposed to only return the piece of form that has changed or some ajax commands.

In this case form modification must be made on the form function or a form alter hook. Form building and validation functions are run each time an ajax callback is called. Just check $form\_state on your form build or alter function and adjust values accordingly.

See Resolve the error "An illegal choice has been detected..."
> 19 votes

# Answer
I have faced this problem number of times in Drupal 6, changing the values of Select list via Ajax.

Here is what you can do is

1. If possible, try to insert all the possible values in the in the Field API, you need to edit that field, and then when you change the values, you will have to make sure that only the listed values are in the list.
2. Solution that I implemented was, you can change the field type from Select list to textfield, from Field API, and ask Drupal to save the value as is. Now, on form runtime, you will have to alter the form, change the type to select list, and push in options, which you want to. While submission as well, you will have to assign the correct value required by the field, that will be saved in DB as is. Make sure your submit handler is called before the default form submit handler, for that you may use `array_merge`

If first solution works for you, you will save a lot of time coding and testing things. BUT if the list in the drop down is dynamic and you have no control over it, you might have to go with second solution.

Do post if you face any issues, I have done quite lot of work on this problem, for my project, and I did for ~50 forms, PHEW !!! :)
> 4 votes

# Answer
I have found the best way round this is to set the `#value` on the select list.

If we have the value in formstate and it is in our options then we will not get an error. If our value is not in the options then select the first option in our options and use that.

```
$form['example'] = array(
    '#type' => 'select',
    '#title' => t('Example'),
    '#options' => $options,
    '#value' => isset($form_state['values']['example']) && in_array($form_state['values']['example'],$options)?$form_state['values']['example']:key($options),
  );

```
> 4 votes

# Answer
In your ajax callback, add:

```
...

drupal_get_messages();
form_get_errors();

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

```

As a security precaution, the core `_form_validate()` function checks if an element's #options key has changed from what what was set in the original build (which they have). By calling `drupal_get_messages()` and `form_get_errors()` we basically tell Drupal to ignore any errors/messages while running our ajax request. :)
> -1 votes

---
Tags: 7, ajax, forms
---


# Question
Title: Where to write public, common, utility functions in Drupal?
At times you have to write little utility functions which will have a general scope (not restricted to the module you are working on) so that it can be called from anywhere in the project.

I know I can write it anywhere and include the php file from the caller, but **is there a convention followed in Drupal?**

For e.g. I am working on xyz.module which does xyz thing which will have a silly

```
function startsWith($haystack, $needle) // case-insensitive startsWith
{
    return strncasecmp($haystack, $needle, strlen($needle)) === 0;
}

```

Where shall I write that function?

# Answer
As many API modules do, you can place your global helper functions within a dedicated module. (I'll be using MYHELPERMODULE in the following example.)

You then should follow the naming conventions:

```
function MYHELPERMODULE_startswith($needle, $haystack) {
  // do your magic
}

```

You can call this function from within all other modules, as long as your helper module is active. To assure it's active, add your helper module as dependency to the .info file of the module that is using the helper function:

```
dependencies[] = MYHELPERMODULE

```
> 8 votes

---
Tags: 7, coding-standards
---


# Question
Title: How do I add the Arab League flag as language?
I can't find a flag of the Arab League in Drupal. How do I add this flag as language? It isn't showing in the languages' list.

# Answer
> 1 votes
You can't add a flag as a language, if you can add a new language go to `YOUR_SITE/admin/config/regional/language/`add choose the new language if your language is not listed you can add a Custom language (See at the bottom of the page the collapsed option).

And if you want to use a flag for your language you can install the Language Icons module. Then go to the folder (in your server) `YOUR_SITE/sites/all/modules/languageicons/flags` and add the flag for your new language, you need to use as a name YOUR\_LANGUAGE\_CODE.png

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


title: Field Collection vs. Paragraphs

text:
# Question
Title: Field Collection vs. Paragraphs
I used Field Collection in my previous sites and I faced some performance issue, So this time I am looking a alternative for Field Collection. I find a answer Alternative to Field Collection.

but I can't find much on how different or similar these solutions specially \[**Field Collection and Paragraphs**\].

Maybe someone can help to explain? So that I can make a good decision.

# Answer
> 17 votes
In many respects the Paragraphs module appears to be a fork of Field Collection. Functionally, the difference between the modules lies in how their respective field widgets operate. The Field Collection widget allows users to embed multiple instances of a single field collection bundle in a node, while Paragraphs allows users to select a different bundle for each instance they embed using the Paragraphs widget. Both of these methods are extremely valuable and I now find myself combining field collections and paragraphs on the same node.

Read more in the issue about "Merge with Paragraphs module?".

---
Tags: 7, database, performance, entities
---


title: Both language menus show up

text:
# Question
Title: Both language menus show up
Currently I'm working on a 6-language website and all content obviously needs to be translated, including menus. For this, I have enabled i18n\_menu and i18n\_select (as I had a little experience on the latter regarding this issue), translated the originally French node to English, and both menu items show up when I go to English translation of the node. Any ideas?

There are several discussions on drupal.SO about this, including this and this one on drupal.org; but none seemed to resolve my issue.

# Answer
I suppose you added the french menu item before you added additional languages to your Drupal. Then it is very likely that it was saved using LANGUAGE\_NEUTRAL as language and therefore will appear within all languages.

To fix this, go to the menu's item list on admin/structure and manually edit the menu item. You should find a drop down for the language within the edit form. Make sure to choose the appropriate language here and save the item.
> 0 votes

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


title: Return value on a submit handler

text:
# Question
Title: Return value on a submit handler
Below is a hook from the LinkedIn Integration module.

Then I have a hook form alter in my module and it's all setup and ready to go to call a submit handler.

When the user goes to authorize LinkedIn, and come back, I want to fire some my code.

The question is I don't know what states or values are after it comes back. I tried this

```
function my_module_form_link($form,$form_state, $uid)
{
  dpm($form_state['values']);
}

```

but it did not return anything

```
function linkedin_user_enable_form($form, $form_state, $uid) {
  $form = array();
  $form['#user'] = $uid;
  $form['#action'] = url('linkedin/token/' . $uid);
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Go to LinkedIn'),
    '#suffix' => '<p class="description">' . t('You will be taken to the LinkedIn website in order to complete the process.') . '</p>',
  );
  return $form;
}

```

# Answer
Looking at the linkedin module source code, there's some ways that can run code on the way back (but only when are logging-in, it seems).

**When they are logging-in:**

1. `hook_linkedin_external_login`: if they don't already have an account and will be asked to register.
2. `hook_linkedin_tie_external_login`: if they already have an account and will be logged-in using that account.

**When they are associating a linkedin account:**

* *I do not see any hooks or any stable way of running code in this case.*

**Here's an example on how to hook into `hook_linkedin_external_login`:**

In your `mymodule.module` file:

```
function mymodule_linkedin_external_login($uid) {
  // do something
}

```

But you'll have to be careful since `linkedin_auth_linkedin_external_login` does a `drupal_goto()` so you'll have to have your module hook called first, so that your function doesn't get skipped. See how drupal decide execution order of same hook in different modules?
> 0 votes

---
Tags: hooks
---


title: Å in form option

text:
# Question
Title: Å in form option
I have

```
$form['type'] = array(
'#title' => t('Country'),
'#type' => 'select',
'#name' => 'countrye',
'#id' => 'country',
'#options' => array(
                    'Afghanistan' => t('Afghanistan'),
                    'Åland Islands' => t('Åland Islands'),
                    'Albania' => t('Albania'),

```

etc

But `'Åland Islands' => t('Åland Islands')`, is coming out blank as it does like Å. How you you get Å to be recognised please?

# Answer
> 2 votes
Use the html\_entity\_decode function:

> html\_entity\_decode — Convert all HTML entities to their applicable characters

```
echo html_entity_decode('Åland Islands');

```

Output:

> Åland Islands

In your code:

```
$form['type'] = array(
'#title' => t('Country'),
'#type' => 'select',
'#name' => 'countrye',
'#id' => 'country',
'#options' => array(
                    'Afghanistan' => t('Afghanistan'),
                    'Åland Islands' => t(html_entity_decode('Åland Islands')),
                    'Albania' => t('Albania'),

```

---
Tags: forms
---


# Question
Title: Multiple login attempts from different IP Addresses
My website has been getting about 25 login attempts per hour for the past few days for usernames admin, administrator and our website name. The attacker seems to be using differing IP addresses and when I checked the last 3 hours worth, only two were are actually repeated. It's not much of a security issue since those are not the usernames we use for admins but it's kind of annoying that it's filling up our logs. What modules/options are available?

# Answer
> 3 votes
You can use Rename Admin Paths module to override the admin path.

> This module allows you to:
>
> ```
> rename path like '/admin/...' to '/something/...'
> rename path like '/user/..' to '/something else/..'
>
> ```
>
> It can be effective against registration spam bots or malicious people.

And using the Login Security module you can

> * limit the number of invalid login attempts before blocking accounts,
> * or deny access by IP address, temporarily or permanently.
>
> A set of notifications by email or Nagios may help the site administrator to know when something is happening with the login form of their site:
>
> * password and account guessing,
> * bruteforce login attempts or just unexpected behaviour with the login operation.
>
> For alternative controls, Login Security can disable Drupal core's login error messages, obfuscating the reason for the login failure. This could make it harder for an attacker to discover whether the account even exists.

The use of the Flood control module is another option to control variables like the login attempt limiters and any future hidden variables.

---
Tags: users, security, proxies
---


title: creating custom page template

text:
# Question
Title: creating custom page template
How do you create a custom page layout in Drupal 8? In drupal 7 you could do something like page--about.tpl or something. How do we do that in drupal 8?

# Answer
Enable twig debugging by copying default.services.yml to services.yml and following instructions in the twig.config section. The debugging comments will display template file name hints in HTML comments in the page output.
> 0 votes

---
Tags: theming, 8
---


title: How do I group items with same color

text:
# Question
Title: How do I group items with same color
We use Drupal Commerce. Products in our catalogue have various colors and we have a filter for that. I don't want to see one product in ALL colors on the product list page, but only in one; say black.

When I apply the filter to 'white', I want to see all the products in white. Ideally, without the page reload.

Our catalogue is made with the Views module.

How can I achieve this?

# Answer
Add a filter of your color field and expose the filter.

Enable ajax for your view, it's listed under Advanced.

There is a catch though: I believe this only works for **page views** only and not for block views.
> 0 votes

---
Tags: commerce
---


title: Create entity form as a table

text:
# Question
Title: Create entity form as a table
I am looking for a way to create a table entry form for an entity type. We are trying to create an invoice form. I am currently using a field collection for each invoice line.

```
Order (node)
  Invoice (node)
    Invoice line (field collection)

```

I am currently using the field\_collection module along with field\_collection\_table. I am using entity reference to connect the invoice to the order and invoice line This works great except when we have more than roughly 75 rows. At that point we are unable to add new rows to the table. Users are getting a 500 AJAX error.

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Internal Server Error
ResponseText:

```

Originally I received an error about max\_imput\_vars limit of 1000 when we got to about 50 lines. I have since changed the limit to 100000. Now nothing shows up in the server error log or the Drupal recent log messages. My PHP settings are:

```
memory_limit = 256M
max_execution_time = 120
max_imput_time = 120
post_max_size = 160M
upload_max_filesize = 128M
max_input_vars = 100000

```

My thought now is to create a custom entity for invoice line. The trouble is how to display this entity as a table and allow users to edit multiple items at once. Some invoices could have 500 rows and I need a way for users to be able to quickly move from line to line. For non-Drupal forms I have used jQuery to dynamically add new rows to a table. Not sure how this would work for Drupal since each field in the table has an id that is specific to each row (e.g. edit-field-desc-und-31-value).

Any suggestions? A separate but important issue is a need to regularly autosave. Users would not be happy if they added 300 rows and lost power, computer froze, or something else happened.

# Answer
> 0 votes
We ended up going the route of a custom field collection table module combined with batch processing. The problem was the standard Drupal way of adding rows using ajax. Instead we created the rows dynamically using Javascript to duplicate the last row and all associated features tied to each field. We then used a batch process to save the data. This resolved the issue of the server timing out with lots of rows.

---
Tags: entities
---


# Question
Title: How to download or print user profile data
I am using **Profile2** module to create user profile. I am installing the **print** module to print or download user profile data,

but when I am viewing our profile page there are not such options are displayed as like on a node or any content type.

How can I download profile page data using profile2 module.

# Answer
> 1 votes
Go to `admin/config/user-interface/print/ui`

Scroll down to `"ADVANCED LINK OPTIONS"` and enter system URL for user profiles

`user/*` \- where * is wildcard

in *"Setting this option will add a link on pages created by Drupal or the enabled modules."* field(s) as shown on the image below. This will add print icons/links to user profiles.

If you do not see any print/pdf icons after saving your settings - make sure that block "Printer, email and PDF versions" is enabled on user/\* pages in your theme. Or add it to your user profile template in some other way if you are doing custom overrides.

---
Tags: users
---


# Question
Title: db_select with subquery including conditions from 2 tables
I spent much time without success to search how to convert with db\_select the following query, running perfectly with db\_query :

```
    SELECT *
    FROM job_orders j
    WHERE j.statut = 'To do'
    AND j.job
    IN ( SELECT r.job
    FROM referential r
    WHERE r.category = j.category
    AND r.label = :label
    AND r.activity = :activity ),
    array(':label' => $label, ':activity' => $activity);

```

Here is the corresponding (?) db\_select query I wrote :

```
$subquery = db_select('referential', 'r')
    ->fields('r', array('job'))
    ->condition('r.category', 'j.category')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);

$query = db_select('job_orders', 'j')
    ->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('j.job', $subquery, 'IN');
$results = $query->execute();

```

I got no result with this db\_select query, while I got answers with the db\_query one... could somebody tell me what is wrong in my db\_select query ?

Thank you.

# Answer
> 1 votes
To achieve your desired behavior you have two options.

If you really like to filter by using a subquery, you should execute it first, parse its result set to an array and set this array as parameter to the condition method of your second queries db\_select:

```
// Run your subquery first.
$subquery = db_select('referential', 'r')
  ->fields('r', array('job'))
  ->condition('r.category', 'j.category')
  ->condition('r.label', $label)
  ->condition('r.activity', $activity);
$result = $query->execute()->fetchAllAssoc('job');

// Make sure $results is initialized for further evaluation.
$results = array();

// If we have referential results, execute the query on job orders.
if (!empty($result)) {
  $query = db_select('job_orders', 'j')
    ->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('j.job', array_keys($result), 'IN');
  $results = $query->execute();
}

```

The far more elegant and therefore suggested solution is to using an INNER JOIN on your query. The target query would look like:

```
SELECT j.*
  FROM job_orders j
  INNER JOIN referential r ON (r.job = j.job)
  WHERE j.statut = 'To do' AND r.label = :label AND r.activity = :activity

```

You can achieve this solution using db\_select by adding a join to your $query:

```
  // Run the query using an INNER JOIN.
  $query = db_select('job_orders', 'j')
    ->join('referential', 'r', 'r.job = j.job');
  $query->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);
  $results = $query->execute();

```

**Edit:** As I don't see any special reason for using db\_select in your use case, I'd also suggest on sticking to db\_query here for better performance of your application.

**Edit 2:** In the above 'solutions' I have overseen you are using two conditions between the tables. In this case, you have to add both conditions to your JOIN:

```
SELECT j.*
  FROM job_orders j
  INNER JOIN referential r ON (r.job = j.job AND r.category = j.category)
  WHERE j.statut = 'To do' AND r.label = :label AND r.activity = :activity

```

Which would need the following db\_select:

```
  $query = db_select('job_orders', 'j')
    ->join('referential', 'r', 'r.job = j.job AND r.category = j.category');
  $query->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);
  $results = $query->execute();

```

---
Tags: database
---


# Question
Title: Is it possible to do a Drush make custom installation profile?
Is is possible to make a selective Drush Make file?

For example:

The site has 3 modules, with 3 library files.

A normal drush make will give me all modules and files.

But it is possible to selectively, fetch some modules and files?

For example: fetch module 1 and file 1 but not 2 and 3?

# Answer
> 4 votes
You can use the *OPTIONAL ATTRIBUTES*

**root\_element\[first\_key\]\[next\_key\] = value**

> The 'projects' attribute is where you define the modules/themes that are to be packaged with the profile. The first key is the short name of the project (as seen in the drupal.org/project/{projectshortname} URI).
>
> These projects are defined using the short form definition. You can use this form if you only want to declare the version of the project. The version is the value to the right of the core Drupal version in a full version string. For example, if you wanted to specify Views 7.x-3.1, you would use:

```
projects[views] = 3.1

```

> For pre-releases, like CTools 7.x-1.0-rc1, use this format:

`projects[ctools] = 1.0-rc1`

> You can also specify -dev releases of projects; however, this is generally NOT recommended, since it results in end users getting different sets of files at different times that distribution is built, which can cause confusing bug reports. If you really must use a -dev release, it's better to specify a Git revision (see below).

```
projects[media] = 2.x-dev

```

**Reference**

---
Tags: drush, installation-profiles
---


# Question
Title: Dynamically create fields based on integer value
I have a requirement that I need to dynamically create x number of fields based on a supplied int value from a text box.

Example: There is a software content type. A user goes to add a new piece of software into the system. They received 11 keys/licenses with their purchase. The users enters 11 into a textbox, and then 11 license key fields display. The users enters in the 11 license keys and saves.

Hopefully that makes sense? Just looking for help deciding which fork in the road to take..

# Answer
you should look into

### Licensing

> This module is useful for people that plan on integrating a software licensing system on their site.
>
> Features Out of the box, it provides the following:
>
> * Ability to generate, edit & delete unlimited unique license keys.
> * Ability to export your keys into a CSV document, which you can mail merge and distribute with physical copies of your product.
> * Ability for users to 'register' their key when they sign up for a drupal account, or by visiting a page when logged in.
> * Users can have multiple keys registered to one account, and they are all displayed on their user page.
> * Provides views functionality for default and custom reports.
> * Brandable license keys like XXXX-BRAND-XXXX-XXXX-XXXX
> * This module does provide functionality out of the box, however - it's power is in the hooks it provides which allow you to extend this further.

### Commerce Product Key

> This module lets sites implementing the Commerce module, attach product keys to orders. Product keys / Vouchers are strings of text that are used to unlock or activate a piece of software.
> 1 votes

# Answer
It's a tricky one but my suggestion is to create a licensing field in the Software node type which has unlimited cardinality (I know you said above that approach will not work but you did not elaborate).

Then, use jQuery to control the number of the fields which display depending on the number provided in the 'count' textfield.
> 1 votes

---
Tags: 7, nodes, entities
---


title: URL-Alias for language neutral content

text:
# Question
Title: URL-Alias for language neutral content
I have a page with 8 languages. Most of the content is translated and have a language assigned. But there is one part of the page, where I need language neutral content to show in each language.

If I create a language neutral content, it generates the "Language Neutral" path from the URL-Alias settings. This looks basically like the English path. Thats Ok. But it looks now for every language like the english path. Only the language prefix changes:

```
/path/to/content
/de/path/to/content
/fr/path/to/content

```

Is there a way to generate programatically URL-Aliases to this node for each enabled language?

```
/path/to/content
/de/pfad/zum/inhalt
/fr/chemin/au/contenu

```

I have found something similar for Taxonomy Terms where it creates a URL-Alias for each term in each language (Pathauto i18n Taxonomy). But I should have this for nodes.

How can I achieve this without creating each alias manually?

# Answer
> 5 votes
You can use the Pathauto i18n module:

> This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

# Answer
> 4 votes
I think you probably want to use a block for that language-neutral bit. As an analogy - if there's a language-neutral image that should appear for all translations, then this isn't part of the content per se. The word 'content' can be confusing, particularly when you've got a multi-lingual site, and sometimes it's useful to only call it 'content' when it's something that can stand on it's own (an 'atomic unit of content').

---
Tags: 7, i18n-l10n, path-aliases
---


# Question
Title: How to use the language neutral url alias pattern in pathauto?
I want to use the following patterns in pathauto:

* myCT **All** languages: pattern1
* myCT **neutral** language: pattern2
* myCT **EN** language: pattern2

So that all neutral (UND) and EN nodes of myCT have pattern2 and all other languages have pattern1. I'm using the ALL languages pattern for all other, as I have many other languages that should have the same pattern and I do not want to repeat it.

I'm using entity translation module for myCT.

When I create a node and save it having the default language (UND) and automatic path alias, pattern1 is always generated. I have to **re-edit the node to have it get the correct pattern** (for UND/neutral language), pattern2.

First of all, the **pathauto\_pattern\_load\_by\_entity** function (pathauto.module file) is called before the node creation, so the language of the node is always UND during creation of a node.

Second, trying to debug the pathauto module I can see the following:

```
function pathauto_pattern_load_by_entity($entity, $bundle = '', $language = LANGUAGE_NONE) {
  $patterns = &drupal_static(__FUNCTION__, array());

  $pattern_id = "$entity:$bundle:$language";
  if (!isset($patterns[$pattern_id])) {
    $variables = array();
    if ($language != LANGUAGE_NONE) {
      $variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
    }
    if ($bundle) {
      $variables[] = "pathauto_{$entity}_{$bundle}_pattern";
    }
    $variables[] = "pathauto_{$entity}_pattern";

    foreach ($variables as $variable) {
      if ($pattern = trim(variable_get($variable, ''))) {
        break;
      }
    }

    $patterns[$pattern_id] = $pattern;
  }

  return $patterns[$pattern_id];
}

```

So in the following lines it seems that **it never takes into account the neutral language** path.

```
if ($language != LANGUAGE_NONE) {
   $variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
}

```

Shouldn't that if statement be removed? How is it possible to use the neutral language path otherwise?

# Answer
Good point, I was thinking the same too.

Rather then the line to be removed there should be a check for `LANGUAGE_NONE` to set a pattern in the variables array for "und"-language. Then if not set the language specific pattern in the array.

I opened an issue and posted a patch, please check out https://www.drupal.org/node/2438745
> 2 votes

# Answer
You can use the Pathauto i18n module:

> This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.
> 3 votes

---
Tags: 7, i18n-l10n, path-aliases
---


# Question
Title: How to remove dropdown items from a form?
I am trying to remove two select list items from a form using this code:

```
function module_r_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'forum-node-form') {
        unset($form['edit-taxonomy-forums-und']['#options']['_none']);
        unset($form['edit-taxonomy-forums-und']['#options']['4']);
    }
}

```

The above code is not working. I would greatly appreciate any help you can give me in working this problem.

# Answer
If the name of your field is `edit-taxonomy-forums-und` your code should be:

```
unset($form['edit-taxonomy-forums-und'][LANGUAGE_NONE]['#options']['4']);

```

Maybe you don't have the correct name of the field. Go to the Manage fields page of your content type (`YOUR_SITE/admin/structure/types/manage/YOUR_CONTENT_TYPE/fields`) and check the name of the field.

***EDIT:***

If you read the comments in the answer you will see that the problem was the change of `forum_node_form` by `forum-node-form`.
> 2 votes

---
Tags: forms
---


title: Custom fields in user's default tab

text:
# Question
Title: Custom fields in user's default tab
I'm a first-time stackexchange user, long time Drupal 6 developer.

I'm just starting playing with Drupal 8 and I know I'm going to love it when I get used to working in it but right now I'm in that frustration phase where it's unfamiliar again and I can't do even the simple things! I wonder if you can help.

I would like to add dynamic content (probably just #markup) to the user's main tab. At the moment, the user tab only contains the familiar text 'Member for xxx'.

Under Drupal 6 I just handled hook\_user, something like:

```
function mymodule_user($type, &$edit, &$user, $category = NULL) {
  switch ($type) {
    case 'view':
      $user->content['the_time'] = array(
        '#type' => 'markup',
        '#value' => 'Epoch = <b>' . time() . '</b>',
        '#weight' => 100,
      );
      break;
  }
}

```

(I've not checked the above actually runs, but it's a modified version of something I'm using on a live site).

What's the equivalent under Drupal 8? I'm looking at the following:

```
function mymodule_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  $build['the_time'] = array(
    '#type' => 'item',
    '#markup' => 'Epoch = <b>' . time() . '</b>',
  );
}

```

Although this works (after clearing the caches) I don't think this is the recommended way to do it, as I'm not seeing dynamic content, the hook is only called once and the text is cached.

I really hope someone can point me in the right direction!

# Answer
> 3 votes
The question how to put a custom field in the user tab is already answered, btw you don't need '#type', when using '#markup' in drupal 8.

As you said at the end, this is a caching issue. In general it is not a good idea to put the time in the html of every page, you better do this in javascript. If you don't care about performance, then you can disable the cache:

```
$build['#cache']['max-age'] = 0;

```

This does not work for anonymous users, because in drupal 8 there is also the page cache enabled by default. If you deliver a different page on every request, you don't need this module and you can uninstall it.

If you want to disable it only for the user default tab, then use this command:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

---
Tags: 8, users, caching
---


# Question
Title: How to call a drupal custom module function from a basic page?
*** if i will click a input button in basic page a particular function should be called from my custom module. I have already enabled my module in my instance.\***

```
<?php
$name = $_POST['name'];
$pwd = $_POST['pwd'];
homeFun($name,$pwd)
?>
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<p>Name<br> <input type="text" name="name"><br></p>

<p>Password:<br><input type="password" name="pwd"><br></p>
<input type="submit"  value="Register">
</form>

```

i am using this code...and its working but the problem is while refreshing the page, function automatically gets called without clicking button... I wrote this code in Basic Page...

> Please guys tell me the proper way to call the functioin from my basic page.

I just wanted to execute my cutome module function after clicking submit button...is there any simple way to do that...

# Answer
> 3 votes
I guess you want to create a menu callback which will call your form right? Here is how to-

Create your menu hook like bellow:

```
function mymodule_menu($node) {
  $items['my-frm'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_form'),
    'access callback' => TRUE,
  );
  return $items;
}

```

Than create your form like below:

```
function my_form() {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

```

And after that here is your form submit:

```
function my_form_submit() {
  drupal_set_message("Hello World my form submit hook is called here");
}

```

Do a clear cache and navigate to yoursite/my-frm link you should see your form.

# Answer
> 2 votes
I think you are taking all the wrong steps.

In drupal you do this by implementing hook\_form\_alter in your custom module and do something like the following:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'YOUR-FORM-ID') { // identify your form
        $form['#submit'][] = 'YOUR_CUSTOM_FORM_SUBMIT_HANDLER'; // set your form-submit handler
    }
}

function YOUR_CUSTOM_FORM_SUBMIT_HANDLER(&$form, &$form_state){
    // ALL THE SUBMITTED FORM DATA ARE IN $form_state
}

```

The YOUR\_CUSTOM\_FORM\_SUBMIT\_HANDLER is where you write code to process the submitted data however you like.

However, the form that was submitted must be one generated by Drupal's form-api.

# Answer
> 1 votes
You are trying to add a form to a page. But if you just add PHP code to your page, then this code will be executed every time you call the page.

Luckily, form building is easy in Drupal. You define one function to layout your form (hook\_form), and another function to handle the results (hook\_submit).

Have a look at the https://www.drupal.org/project/examples "Code examples for developers". You can copy&paste form building examples from there. It will also help you understand where to put code in other cases.

Specifically, do not add your homefun() function to the page itself. Put that into the hook\_submit() function.

---
Tags: hooks
---


# Question
Title: how do I open a custom module form in colorbox popup?
I am creating a form in custom module, and I need to show this form in a view. How do I show this form in a color-box popup?

I have created a custom block to render this form, but I don't understand how to show this form in a view page, inside a popup.

# Answer
> 0 votes
I am suggesting you to use chaos tools for modal popup form. Its easy to implement and integrate into Drupal 7. I already used in my several sits.

You can find a great example of Ctools modal form at here

---
Tags: 7, views, forms
---


# Question
Title: Advanced Forum - how do I delete a forum?
I'm using Advanced Forum - how can I remove the default forum created (General Discussion)?

# Answer
> 1 votes
Structure \> Forums \> You should see General Discussion listed, hit the Edit Forum link \> Scroll down and hit the delete button

# Answer
> 0 votes
To delete a forum programmatically, you can use the following code (in an update script for example):

```
// First load the terms with the name "General discussion"
$terms = taxonomy_get_term_by_name('General discussion', 'forums');
if (is_array($terms) && !empty($terms)) {
  // Since $terms is an array, we take the first (and ideally the only) item.
  $term = reset($terms);
  taxonomy_term_delete($term->tid);
}

```

---
Tags: 7, nodes
---


title: filefiles node and comment in one view

text:
# Question
Title: filefiles node and comment in one view
I have a content type called "Document" where i have a "file" field so i can upload files. I also have comments enable where another users can add a comment and also upload more files.

Whats i would like to do is have a table of all uploaded file in a single table at the bottom of the node.

In Views i am unable to get files upload from the node and comments in one views. Can anyone help with this?

using Drupal 7

Thanks

# Answer
> 0 votes
On the view that you have the files upload, under Advanced, add a relationship of comments of the node, then add Comment:Comment as a field.

# Answer
> 0 votes
I'd recommend to use File Entity module, which provides all the functionality you need.

> File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters. File entity integrates with a number of modules, exposing files to Views, Entity API, Token and more.

---
Tags: files
---


# Question
Title: For settings.php $conf, how can I tell what a variable in Drupal 7 is named in Drupal 8?
This article explains that using `$conf` in `settings.php` works differently in Drupal 8 compared to Drupal 7:

> The settings.php file could contain environment level overrides. Just remember how we disabled email sending on development servers in Drupal 7:
>
> **$conf\['mail\_system'\]\['default-system'\] = 'DevelMailLog';**
>
> That’s how it will look in Drupal 8:
>
> **$config\['system.mail'\]\['interface'\]\['default'\] = 'devel\_mail\_log';**

In Drupal 7, I used `$conf` to set different Google Analytics accounts per site environment like this:

```
  if (PANTHEON_ENVIRONMENT == 'dev') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-X';
  }
  else if (PANTHEON_ENVIRONMENT == 'test') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Y';
  }
  else if (PANTHEON_ENVIRONMENT == 'live') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Z';
  }

```

How can I determine what `$conf['googleanalytics_account']` was renamed to in Drupal 8?

# Answer
Unless the module's documentation tells you the name directly, you'll have to look for it manually.

You can search with drush:

```
drush config-list (cli)     List config names

```

Choose one of the names and display its whole content:

```
drush config-get (cget)     Display a config value, or a whole configuration object.

```

If you are using a lot of modules, that list may grow fast so you can narrow it down by inspecting the module to get an idea of how its data is structured.

Drupal 8 modules can ship with documentation in a `.yml` file in their `config/install` directory, which may include default values for configuration. It seems unlikely there would be a hardcoded default value for the equivalent of the `googleanalytics_account` variable, but you would at least be able to find the code fetching its value, something like this: `\Drupal::config('googleanalytics.account');`. *

There's also the new State API, meant to store information which could be different depending on the environment (dev vs production), or any other information you would not want to synchronize with different instances of the same system, like the last time automated jobs ran. If the module uses that, look instead for lines like this: `\Drupal::state()->get('googleanalytics_account')`. *

Once you've found what you think may be the correct key name, you can retrieve its current value using drush:

```
drush state-get key

```
* The names used here are quick guesses based on the Drupal 7 names, the real code may use entirely different names.
> 4 votes

---
Tags: 8, configuration
---


# Question
Title: Re-write output on different images on Views Slideshow
Using this - tutorial

I have a views slideshow that rotates images with a fade effect. I know you can re-write output to show images and a text field below but so far I can just add one text block - I want each image to have its own text!

# Answer
## Image Field Caption

> Adds an extra text area for captions on image fields.
>
> Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

Has views integration.
> 0 votes

---
Tags: 7, media, javascript, views
---


# Question
Title: how to depricate repeated field values from my view?
Look at my screenshot i don't need repeated employee id and name...i just want to print emloyee id and name once but i want to display the others records with blank employee id and name but not salary, month and year....I am using JOIN query in my hook view... So gyus please suggest me any trick to remove those field value...

edited question for clarity...

# Answer
> 1 votes
> You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.
>
> 1. Go and edit your view
> 2. In Advanced » OTHER section by enabling Use aggregation: Yes
> 3. In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

source: https://www.drupal.org/node/1704962

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


# Question
Title: How do you change rules settings on the fly?
I want to be able to modify a rule based on a setting choice made by a user, but I don't want to expose the form for setting the rule that you see at

```
admin/commerce/config/payment-methods/manage/<payment_method>/edit/<action_id>

```

because it contains some sensitive information such as our company's secret key for connecting to the payment gateway.

I have figured out that this UI is governed by a rule, and this particular setting is stored in the **rules\_config** entity in its data field. I want to be able to directly manipulate this field, but I am unfamiliar with the format and do not want to mess up the entire rule.

Is there a way to do a **entity\_import** and change the rule with the new settings on the fly? It seems like all of the hooks are only for when the module loads/installs.

# Answer
> 2 votes
The issue is that the settings on an action of a rule need to be changed. The settings form for when you implement `hook_settings_form($settings)` for your payment method maps to the settings of the rule `commerce_payment_<name of your payment method>`. You need to change that rules action settings and then save. Here is an example.

Lets say that you have added a form element called `txn_type` to the settings form as follows in `hook_settings_form($settings)` of your payment method.

```
  $form['txn_type'] = array(
    '#type' => 'radios',
    '#title' => t('Default credit card transaction type'),
    '#description' => t('The default will be used to process transactions during checkout.'),
    '#options' => array(
            COMMERCE_CREDIT_AUTH_CAPTURE => t('Authorization and capture'),
            COMMERCE_CREDIT_AUTH_ONLY => t('Authorization only (requires manual or automated capture after checkout)'),
    ),
    '#default_value' => isset($settings['txn_type']) ? $settings['txn_type'] : COMMERCE_CREDIT_AUTH_CAPTURE,

```

);

To make the changes to the rule outside of the settings form, you need to load that rule and make changes to the action settings. You first load the rule, then you load the action settings within the rule, then you make your settings changes. The rule action name is always `commerce_payment_enable_<name of your payment method>`

```
$rule = rules_config_load('commerce_payment_<name of your payment method>');

foreach ($rule->actions() as $action) {
if (is_callable(array($action, 'getElementName')) && $action->getElementName() == 'commerce_payment_enable_<name of your payment method>') {
  dpm('bh_market_settings: in action array');
  if (is_array($action->settings['payment_method']) && !empty($action->settings['payment_method']['settings'])) {
    $action->settings['payment_method']['settings']['txn_type']=COMMERCE_CREDIT_AUTH_ONLY;
  }
 }
}

$rule->save();

```

This example can be applied to anytime you are trying to change a rule outside of the UI. You can make changes to all aspects of the rule and then save it using `$rule->save()`

# Answer
> 3 votes
There are likely several ways of peeling the proverbial potato, depending on what you're actually trying to do:

1. See if the rule's callback function has some sort of hooks to allow you to change the data there. This is the easiest way to do anything and the least invasive.
2. Implement `hook_rules_config_execute()`. This hook gets called during the invocation of the rule and it appears to give you a chance to modify the rule before everything gets executed.

Not generally recommended but also possible:

3. Alter the rule's callback to call a new custom callback which wraps or replaces the original function and sets the configuration that you want.

---
Tags: commerce, rules
---


# Question
Title: How do I install dependencies for commerce using the Composer manager module
I installed the composer manager module and enabled it. I have tried initializing it from using drush in the command line and failed using the command `drush composer-manager-init`.

I am confused on how to add the libraries intl, address, pricing and tax to my site.

# Answer
> 6 votes
Please refer to our installation instructions for Commerce 2.x here:

http://docs.drupalcommerce.org/v2/getting-started.html

Note that we recommend the Drupal console project, not drush. However, the linked Composer Manager instructions in there may help you do it via drush.

# Answer
> 1 votes
I'm not sure you can use drush to initialize composer manager. I usually use the init script from composer manager and have had no issue with it:

This is how I typically do it.

`php modules/composer_manager/scripts/init.php` (initialize composer manager)
`composer drupal-update --no-dev` (fetch dependencies)

You can also run `composer drupal-update` without the `--no-dev` but I've found that composer sometimes can fail to update certain libraries within drupal core, as it expects to find .git files but these are not included in Drupal core builds.

---
Tags: commerce, 8, composer
---


# Question
Title: Passing current node ID to the block template
I have a module with a custom block MyCustomBlock.php that get the nid of the current page and pass the value to the block template:

```
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;
return array(
  'currentnid' => $nid,
);

```

Inside the template I print the passed value {{ currentnid }}, but it only works cleaning the cache! For example, if I load the page with nid 5 it prints 5, but if I move to page with nid 3 it prints 5. Cleaning the cache and reloading page with nid 3 I get the value 3 printed. I think it is a problem with the template caching system in D8, do you have any idea about this?

# Answer
Blocks are cached. However blocks are also context-aware in Drupal 8. Per the documentation page regarding Cache Contexts:

> Cache contexts provide a declarative way to create context-dependent variations of something that needs to be cached. By making it declarative, code that creates caches becomes easier to read, and the same logic doesn't need to be repeated in every place where the same context variations are necessary.

The Cache API documentation page is a good read for everyone.

A Block plugin should implement getCacheContexts. I think that in this case it should either be "route.name" or "url.path". You may need to delve into this a bit more for your particular use case.

```
  public function getCacheContexts() {
    return array('route.name');
  }

```
> 5 votes

# Answer
The proper way to do this would be use contexts. Plugin contexts, not cache contexts.

Similar to NodeType condition plugin, put something like this in your plugin annotation:

```
* context_definitions = {
*  "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }

```

And then get the node using $this-\>getContextValue('node').

This has two advantages:

* Your block doesn't rely on global state directly. It could for example be used also in page manager, with a different node.
* Drupal automatically understands that your block varies by whatever node is passed in. If using the current node, it will vary by route, if it would e.g. be a node from a static page manager context, it wouldn't. It will also include cache tags, in case the node is changed in a way that would affect your output.
> 8 votes

---
Tags: nodes, blocks, 8, caching
---


title: Template variable pre-process concept

text:
# Question
Title: Template variable pre-process concept
I am new to Drupal and I am trying to create a theme for it (Drupal 8). I have a few questions:

1. What does it mean to pre-process a variable?
2. Do all variables have to be pre-processed?
3. How do you figure out how to pre-process a variable? I understand some come from the Drupal config. Where else can variables come from?

I have read a few articles and searched the Internet but it seems Drupal 8 documentation is still being worked on. It's not very explanatory. Are there any articles you can suggest to learn how to theme Drupal 8 from the ground up?

Thank you

# Answer
> 2 votes
Preprocessing is just an optional step between defining a render array that will then use a twig template and the actual twig template.

It's a place where you can execute PHP code to prepare variables that you can later use in your template.

You don't have to use preprocess for you own templates but some things can only be done there or are a lot easier, as you can't execute arbitrary code in a twig template.

See `template_preprocess_image()` for an example. Note the different names of preprocess functions. There's always the one prefixed with `template`. That's reserved for the module that defines template in `hook_theme()` and is called first. And then it's called for each module and active theme, just like a hook, e.g. as `yourmodule_preprocess_image`.

That brings me to another advantage of the preprocess phase. There can only be one template that's actually used and while there are ways, modules in general shouldn't provide template unless they define it. But, every module can implement the preprocess function and influence the output of a template to a certain degree. For example to add a certain class or data attribute to a node so that some JS can then use it.

---
Tags: 8, theming
---


# Question
Title: My theme CSS uses relative paths, but Advagg or another module seems to be rewriting them to absolute paths. Core aggregation uses relative paths
* Our CSS authored in the theme uses relative paths for all references to assets
* But the CSS aggregated/processed by Advagg has absolute paths where the authored CSS uses relative paths
    + I can't see any Advagg settings where I am asking it to convert relative paths to absolute
* When Advagg is disabled, the CSS aggregated by Drupal core noes not have any absolute paths, instead the relative paths from the authored CSS are used
* If I enable Advagg but enable the `advagg_convert_absolute_to_relative_path` setting then relative paths are used, but doing this would cause problems elsewhere on the site where some CSS is used that requires absolute paths. I'd rather Advagg left our relative paths alone, rather than seemed to convert them to absolute paths, and then back to relative paths.
* I have a custom module on the site that alters the base URL to make links/URLs absolute for a small subset of the site (which is consumed and displayed on an external domain). This seems like a potential cause, but disabling this module does not resolve the issue.

## A potential cause of the issue?

I have a module that uses `hook_url_outbound_alter()` to make URLs on some pages absolute by modifying the base URL:

```
/**
 * Implements hook_url_outbound_alter().
 */
function site_absolute_paths_url_outbound_alter(&$path, &$options, $original_path) {
  if (drupal_static('_is_absolute_path_requiring_callback')) {
    $options['base_url'] = _site_absolute_paths_url_modified_base();
    $options['absolute'] = TRUE;
  }
}

```

This seems like it could be a candidate for causing the issue, but the problem persists even when the changes to the options array in this function are commented out.

I'm not sure how else to debug this? I suspect it is not an issue with Advagg, but something else on this site that is interacting badly with Advagg. That said, it is odd that the aggregated CSS produced by Drupal core has the correct paths rather than the absolute paths.

If the `advagg_convert_absolute_to_relative_path` setting seems to resolve the issue, does that suggest that something 'upstream' of Advagg is adding the absolute paths? But isn't adding them when the core aggregation process is run?

## Things I have tried

A breakpoint in the first line of `advagg_file_create_url()` gives `"/"` as the value for `$aggregate_settings['variables']['base_path']`. This is what I would expect to be working OK.

```
global $base_url;
echo $base_url;

```

In `/devel/php` gives `http://my-site.drupal.dev`

## Variables used in Advagg hash

```
Array
(
    [variables] => Array
        (
            [advagg_gzip] => 1
            [is_https] =>
            [advagg_global_counter] => 10
            [base_path] => /
            [advagg_ie_css_selector_limiter] => 1
            [advagg_ie_css_selector_limiter_value] => 3500
            [advagg_scripts_scope_anywhere] =>
            [advagg_devel] =>
            [advagg_convert_absolute_to_relative_path] => 0
            [advagg_convert_absolute_to_protocol_relative_path] => 0
            [advagg_force_https_path] => 0
        )
)

```

Is this an intended feature of Advagg? This line seems to suggest so:

```
// Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
$contents = preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);

```

# Answer
This is an intended feature of AdvAgg, see Mike (one of AdvAgg maintainer)'s issue on Drupal.org where a 'do not convert' option has been raised as a feature request.
> 0 votes

---
Tags: css-js-aggregation
---


# Question
Title: Creating views or facets search with multiple flags
So I'm categorising with flags and I will have over 20 per node so that multiple people can flag a node with their opinion... Searching for the past two weeks I have found it hard to work out how I put these flagged results on to the front end, in search, making multiple flag recipes (to show to searchers), with views?

My first question is, do I have to make a view for every single flag I have on the front end? There are over 20 of them, I don't mind doing this but can't this be put in to an exposed view or something so I can have one view with all outputs covered?

How can I mix up certain flags together/make recipes so that if I wanted three certain flags together so that people can search through that output I could, can I do this in views with flags?

My final question is, how do I put the output of a search or a view I make and make it sortable by how many times that node has been flagged with that flag or combination of different flags? If someone wants to see the nodes all flagged with 'river' and that the nodes that come to the top of the search/output/view has had it's 'river' flag flagged by more users than those below it. This will show that that node is definately more 'river' than the other ones.

# Answer
> 0 votes
I found out that if I add all of the flags (each one individually) as a relationship, so I end up with 20+ relationships, I can expose each one in a field to visitors and that way they can click through what type of flags they want to see and don't.

It's not pretty, you will end up with 20+ true/false select boxes but its working.

---
Tags: flags
---


# Question
Title: How to use drush download file plugin (drush_dlf) project page has no information
**How to use this plugin?**

https://www.drupal.org/project/drush\_dlf

> Drush Download File is a drush plugin that allows you to download files and place them in locations. This is behavior similar to what a make file can provide except you won't need to write a make file in order to get a file and put it in the right place.

This is what I am looking for, but there is not documentation, how can I do this?

I tried:

```
c:\source\sites\all\modules>drush drush_dlf
The drush command 'drush_dlf' could not be found.  Run `drush[error]

```

Not sure how to do this....

# Answer
> 1 votes
If you would like to install the Drush extension `drush_dlf`, run:

`drush dl drush_dlf`

If the module you download is a Drush extension (has a .drush.inc file but no .module file), then Drush will put it in `$HOME/.drush`, where it will be findable by Drush.

If the module you download has a .module file, then Drush will put it in the appropriate `modules` directory (`DOCROOT/modules` for Drupal 8, or `DOCROOT/sites/all/modules` for Drupal 7). In this instance, the command will only be available for that one site.

To stipulate where the downloaded extension should go, you can add `--destination=$HOME/.drush` (or some other location). Use caution when doing this with any extension that has a .module file, though, as some of these are designed such that they only work when their module is available and enabled.

Finally, note that Drush caches the location of all of the available Drush extensions. If you add a new extension, you must run `drush cc drush` before your new command will be available. Drush does this automatically if you use `drush dl` to install the extension, but you must do it manually if you copy the files into `$HOME/.drush` yourself.

Finally, with regard to `Drush Download File`, the behavior it purports to provide could also be implemented with a simple shell script that simply called `drush dl` repeatedly, as Drush dl will already place the files where they belong. Using `drush make` or `composer` is generally preferable, but just using `drush dl` directly is an option if you don't want to do that.

# Answer
> 0 votes
Looking at the plugin code, I would say it doesn't even work.

```
/**
 * Callback for the drush-demo-command command
 */
function drush_drush_dlf_drush_download_file($type = FALSE) {

  drush_download_file($url, $destination = FALSE, $cache_duration = 0);

}

```

`drush_drush_dlf_drush_download_file()` accepts a single argument (`$type`), but then passes `$url` to `drush_download_file()` without setting it, or defining it. It means `drush_download_file()` will get `NULL` as first parameter, but it is expecting the URL of the file to download.

As the comment for the callback says, it seems the plugin is just an example of what a plugin could do. It's not a constructive example, since it doesn't work at all.

---
Tags: drush
---


# Question
Title: Getting drush to install missing dependencies automatically into libraries
How to get drush to automatically install libraries ***or*** ignore dependencies?

Trying to automate enabling modules in batch with Drush

```
c:\2016\sites\all\modules>drush en views_slideshow_cycle -y
Module views_slideshow_cycle doesn't meet the requirements to be         [error]

enabled.
You need to install the jQuery cycle plugin. Create a directory in       [error]

sites/all/libraries called jquery.cycle, and then copy
jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find
the plugin at http://malsup.com/jquery/cycle. (Currently using jQuery
Cycle Library Library required for Views Slideshow Cycle)

c:\2016\sites\all\modules>

```

# Answer
It's the module that handles "libraries" dependencies - not Drush. AFAIK you can't force Drush to ignore hook\_requirements implemented by the module in (the install file). Some modules, for example Colorbox, provides a Drush command to download the missing libraries dependencies, but it's not automated.
> 1 votes

# Answer
I'm guessing that this Drupal 7, since you're installing to sites/all/modules. My guess is that you've installed Views Slideshow 7.x-3.1.

In Drupal 7, `drush en` typically will download and enable required modules automatically. But other kinds of libraries, like jQuery libraries, won't get installed automatically for you. In this kind of case, you definitely want to see if the module has a README file. And for Views Slideshow, indeed it does.

From README.txt:

```
Installation
=============

1) Assure that you are using Views 3.x. http://drupal.org/project/views
2) Upload/install the Libraries API module. http://drupal.org/project/libraries
3) Upload/install the ctools library. http://drupal.org/project/ctools
4) Create a sites/all/libraries directory on your server.
5) Create a directory within sites/all/libraries named jquery.cycle.
6) Locate/download the jQuery cycle plugin. http://malsup.com/jquery/cycle
7) Upload/install the jQuery cycle plugin: place it inside the jquery.cycle
   directory.
8) Enable the Views slideshow and Views Slideshow: Cycle modules
9) You should now see the new views style option called "Slideshow"

```

These aren't the simplest instructions, but at least they're clear.

The good news is that in Drupal 8, drush uses the Composer installation system, and this kind of requirement will get auto-installed for you. But for Drupal 7, sometimes you'll need to track down the manual instructions.
> 0 votes

---
Tags: drush
---


# Question
Title: Getting image URL and rewrite results for Views Module
I have a Content Type of only an Image field and I am using Views module to create a view for it as in follows

```
    <div style="background:url(IMAGE1_FULL_PATH.JPG)"></div>
    <div style="background:url(IMAGE2_FULL_PATH.JPG)"></div>

```

Using Image URL Formatter module I was able to get the image absolute URL, but using the following "rewrite rule" in Views

```
  <div style="background-image:url([field_banner_image]); "></div>

```

It outputs the URL wrapped in a

```
  <a></a>

```

or

```
  <span></span>

```

tags, how can I possibly get the pure text URL for this image?

# Answer
Views does reject having style attributes to any of the html elements even though the style attribute is explicitly included in rewrite results of any field in the view.

The reason and workaround maybe found here: Rewrite results strips some html attribute

My recommendation is, you can write tpl for that particular field and use the output text (which will be the url in your case) to build the div or any html element around it.
> 1 votes

# Answer
under Rewrite Results for the image field, try checking "strip HTML tags":

> If checked. all HTML tags will be stripped
> 0 votes

# Answer
Edit your image field, check "Strip HTML tags" and " Exclude from display". Uncheck "rewrite output". Then add a Global: Text area field and write your image token wrapped by your div structure

If you strip tags in your image field and use the same field to show your data, obviously, it will remove your div and styles properties, thats why we use it in another field

However, probably Views wont let you to use a Style attribute in your Rewrite output field, so yeah maybe use it's tpl is the best option
> 0 votes

---
Tags: views, 7
---


# Question
Title: Flags - show a flag marker even if user cannot modify it
I have been able to set up a flag with Advanced forum to allow users to mark comment in a thread they started as an accepted answer. It was simple to set up and works well.

However, it seems Flag only alters a comment if the user has permissions to set/unset the flag. I want a tick to appear on a comment which has been flagged which any (even anonymous) users should be able to see. How do I go about doing that?

# Answer
> 0 votes
You could add a new boolean field *Answer* to comments which has a default value of 0. Next, create a Rule that changes the boolean value of a flagged comment to 1. The rest is theming; use the following code in your comment.tpl.php file:

```
<?php if ($comment->field_answer['und'][0]['value']): ?>
  <mark>This is the answer</mark>
<?php endif; ?>

```

---
Tags: flags
---


# Question
Title: How can I add a new value to a multi-value field programmatically?
I have a multi-value textfield that stores the user agent string. I want to store the user agent every time the user logs in (this may not in fact be a good idea, but for sake of example).

The following code will save the user agent, but only in the first position. It replaces the old value instead of creating a new one.

```
function MYMODULE_user_login($account) {
  $account->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  $account->save();
}

```

How can I add a new value each time this is called?

# Answer
Using this:

```
$account->get('field_useragent')->appendItem($_SERVER['HTTP_USER_AGENT']);

```

However, that doesn't seem like a good idea to me. Over time, that list will grow big, multi-value fields don't scale that well. All values are always loaded, on save, all values are inserted again into the database.

Maybe you want a list of unique user agents, but even that is hard to control with versions and so on. If you want a log, then save it somewhere else in your own table.

http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf doesn't have this yet, would probably make sense to add it.
> 1 votes

---
Tags: entities, 8
---


# Question
Title: How do I change the image style for avatars displayed in comments
I'd like to use a custom image style for the comment avatars, but I don't know where the setting in Drupal is to change it.

I thought if I changed the user image style at `admin/config/people/accounts/display` that might work, but it doesn't. There's no image field at `admin/structure/comment/manage/comment/display`, so I can't change the style there.

I did this on a site a couple weeks ago on another site, but I can't remember for the life of me how I did it. I don't think I needed to make code modifications. Help?

# Answer
You can modify the image style used for displaying avatars in comments by editing the "compact" display mode for user accounts.

The setting can be found at */admin/config/people/accounts/display/compact*. Or by navigating the administration interface:

1. Admin -\> Configuration
2. Account Settings
3. 'Manage display' tab
4. 'Compact' sub tab.
5. On the 'Picture' row, click the edit field settings button (Cog image) located on on the right.
6. Then select your image style.
> 1 votes

---
Tags: 8, comments, media
---


# Question
Title: How to display the user email on account pages?
On the user account page all feilds are displayed except for the email. I have tried to modify the user-profile.tpl, and added

```
print $user->mail

```

but it displays the logged in user and not the account being displayed. Not a big problem since the end users usually only see their own account bit frustrating for admins. I also tried

```
print render($user_profile['mail']);

```

but that displays nothing.

# Answer
> 2 votes
You can implement the following hook in the ***template.php*** of your theme:

```
/**
 * Process variables for user-profile.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 *
 * @see user-profile.tpl.php
 */

function YOUR_THEME_preprocess_user_profile(&$variables) {
  $account = $variables['elements']['#account'];
  //Add mail to $user_profile variable
  $variables['user_profile']['mail'] = $account->mail;
  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
}

```

And in your ***user-profile.tpl*** you can use:

```
print $user_profile['mail'];

```

---
Tags: theming, users, emails
---


title: Send prefill message PrivateMsg

text:
# Question
Title: Send prefill message PrivateMsg
I need a feature for my website, I want that users can send pre-filled messages to others users.

Like in an user's profile page, they just have to click on a button and then, the pre-filled message is sent.

I'm using PrivateMsg module, I don't know if this module could do the job

(By the way I'm new to Drupal).

Thanks for your help !

# Answer
> 0 votes
You may implement this: hook\_privatemsg\_message\_presave\_alter.

> Change the message before it is stored.

The `$message` variable contains the message's body (as well as much more parameters) ready to be edited. Note that you can include html tags in your message. Here is a code sample:

```
/**
 * Implements hook_privatemsg_message_presave_alter().
 * Change the message before it is stored.
 */
function my_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $name = $message->recipients['user_1']->name; // use foreach for many recipients
  $message->body = "<i>Dear $user</i>,\n <strong>you rock!</strong>";
}

```

---
Tags: 7, users, privatemsg
---


title: html entities privatemsg token

text:
# Question
Title: html entities privatemsg token
I am using the privatemsg module to send messages and mails with questions about plants. The subject is automatically filled in with the token of a node title, which is always a plantname. They always have **2 single quotes** in their names and that is turned into ' when it comes in the subject field of the private message.

What can I do about that?

# Answer
> 0 votes
You may implement this: hook\_privatemsg\_message\_presave\_alter in you custom module and change the message's subject as you like.

Here is a code sample:

```
/**
 * Implements hook_privatemsg_message_presave_alter().
 */
function your_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $message->subject = "$message->subject"; // use single or double quotes
}

```

Tip: strip quotes from a string

---
Tags: tokens, privatemsg
---


# Question
Title: How do I show the total number of votes for "Rating" option in Fivestar?
When using the Fivestar module, I can show the result in three ways:

1) "Stars" - This has an additional setting called "Text to display under the stars". For example, it'll look like the following if I choose "Average vote":

```
*****
Average: 4.1 (235 votes)

```

2) "Rating" - There is no additional option whatsoever, so the above example will just look like the following:

```
4.1/5

```

3) "Percentage" - I don't use this, so let's just ignore it.

Is there a way to make the "Rating" option show the total number of votes like the following?

```
4.1/5 (235 votes)

```

UPDATE 1:

I have to overwrite the function `theme_fivestar_summary` on line 126, and add lines 279-301 right before `return $output;`:

```
function theme_fivestar_formatter_rating($variables) {
  $element = $variables['element'];

  if (empty($element['#item']['average'])) {
    $element['#item']['average'] = 0;
  }
  // Get number of stars.
  $stars = (empty($element['#instance_settings']['stars'])) ? 5 : $element['#instance_settings']['stars'];
  $average = $element['#item']['average'];
  // Rating is X out of Y stars.
  $rating = round(($average/100) * $stars, 1);
  $output = $rating . '/' . $stars;

  $votes = 235;
  if (isset($votes)) {
    if (!isset($user_rating) && !isset($average_rating)) {
      $div_class = 'count';
    }
    if ($votes === 0) {
      $output = '<span class="empty">'. t('No votes yet') .'</span>';
    }
    else {
      if (!empty($microdata['rating_count']['#attributes'])) {
        $rating_count_microdata = drupal_attributes($microdata['rating_count']['#attributes']);
      }
      // We don't directly substitute $votes (i.e. use '@count') in format_plural,
      // because it has a span around it which is not translatable.
      $votes_str = format_plural($votes, '!cnt vote', '!cnt votes', array(
        '!cnt' => '<span ' . $rating_count_microdata . '>' . intval($votes) . '</span>'));
      if (isset($user_rating) || isset($average_rating)) {
        $output .= ' <span class="total-votes">(' . $votes_str . ')</span>';
      }
      else {
        $output .= ' <span class="total-votes">' . $votes_str . '</span>';
      }
    }
  }

  return $output;
}

```

But the big problem is that I have no idea how to pass the $votes variable, so I hardcoded `$votes = 235;` right above `if (isset($votes)) {`, just to see if the code works so far, which it does:

```
4.1/5 235 votes

```

I know where to add the parentheses (line 298), but I'm having trouble figuring out how to pass $votes. Any help is greatly appreciated.

UPDATE 2:

The code above is far from perfect, as it produces minor error messages regarding the $microdata & $rating\_count\_microdata variables. Using the code from Jeroen, I was able to come up with better code that I posted as the final answer below.

# Answer
> 0 votes
Using the code from Jeroen, I came up with the following code that works 100% without errors in the `template.php` file:

```
function YOURTHEMENAME_fivestar_formatter_rating($variables) {
  $element = $variables['element'];
  $votes = $variables['element']['#item']['count'];
  $rating_count_microdata = NULL;

  if (empty($element['#item']['average'])) {
    $element['#item']['average'] = 0;
  }
  // Get number of stars.
  $stars = (empty($element['#instance_settings']['stars'])) ? 5 : $element['#instance_settings']['stars'];
  $average = $element['#item']['average'];
  // Rating is X out of Y stars.
  $rating = round(($average/100) * $stars, 1);
  $output = $rating . '/' . $stars;

  if (isset($votes)) {
    if (!isset($user_rating) && !isset($average_rating)) {
      $div_class = 'count';
    }
    if ($votes === 0) {
      $output = '<span class="empty">'. t('No votes yet') .'</span>';
    }
    else {
      // We don't directly substitute $votes (i.e. use '@count') in format_plural,
      // because it has a span around it which is not translatable.
      $votes_str = format_plural($votes, '!cnt vote', '!cnt votes', array(
        '!cnt' => '<span ' . $rating_count_microdata . '>' . intval($votes) . '</span>'));
      $output .= ' <span class="total-votes">(' . $votes_str . ')</span>';
    }
  }

  return $output;
}

```

I also decided to write a blog post with more details and explanations, including examples of some more simple customizations. I hope this helps some newbies having trouble customizing this awesome module.

# Answer
> 0 votes
The output for average votes is set in the fivestar.theme.inc file, which is located at fivestar/includes. You have to overwrite the function `theme_fivestar_summary` on line 248 (version 7.x-2.1). In order to do this, simply copy the whole function to your theme's `template.php` file and make the necessary adjustments. I've already done that for you in the code underneath:

```
function YOURTHEME_fivestar_summary($variables) {
  $microdata = $variables['microdata'];
  extract($variables, EXTR_SKIP);
  $output = '';
  $div_class = '';
  $average_rating_microdata = '';
  $rating_count_microdata = '';
  if (isset($user_rating)) {
    $div_class = isset($votes) ? 'user-count' : 'user';
    $user_stars = round(($user_rating * $stars) / 100, 1);
    $output .= '<span class="user-rating">' . t('Your rating: <span>!stars</span>', array('!stars' => $user_rating ? $user_stars : t('None'))) . '</span>';
  }
  if (isset($user_rating) && isset($average_rating)) {
    $output .= ' ';
  }
  if (isset($average_rating)) {
    if (isset($user_rating)) {
      $div_class = 'combo';
    }
    else {
      $div_class = isset($votes) ? 'average-count' : 'average';
    }

    $average_stars = round(($average_rating * $stars) / 100, 1);
    if (!empty($microdata['average_rating']['#attributes'])) {
      $average_rating_microdata = drupal_attributes($microdata['average_rating']['#attributes']);
    }
    $output .= '<span class="average-rating">' . t('!stars',
      array('!stars' => "<span $average_rating_microdata>$average_stars/5</span>")) . '</span>';
  }

  if (isset($votes)) {
    if (!isset($user_rating) && !isset($average_rating)) {
      $div_class = 'count';
    }
    if ($votes === 0) {
      $output = '<span class="empty">'. t('No votes yet') .'</span>';
    }
    else {
      if (!empty($microdata['rating_count']['#attributes'])) {
        $rating_count_microdata = drupal_attributes($microdata['rating_count']['#attributes']);
      }
      // We don't directly substitute $votes (i.e. use '@count') in format_plural,
      // because it has a span around it which is not translatable.
      $votes_str = format_plural($votes, '!cnt vote', '!cnt votes', array(
        '!cnt' => '<span ' . $rating_count_microdata . '>' . intval($votes) . '</span>'));
      if (isset($user_rating) || isset($average_rating)) {
        $output .= ' <span class="total-votes">(' . $votes_str . ')</span>';
      }
      else {
        $output .= ' <span class="total-votes">' . $votes_str . '</span>';
      }
    }
  }

  $output = '<div class="fivestar-summary fivestar-summary-' . $div_class . '">' . $output . '</div>';
  return $output;
}

```

---
Tags: 7, rating
---


title: How to make an attendance form

text:
# Question
Title: How to make an attendance form
I specifically hope views can solve my issue.

My views will display the list of students in a specific class and in front of each student's name, I will like to have a button to select whether a student is present or not.

Since this page will be accessed daily(monday-friday), it needs to reset to default everyday but the record must be saved in d database so that we can send the total number of days a student is present in school.

I have tried flag but the issue with the approach is that u can either flag or unflag a user which doesn't allow for daily flaggings.

Could you give me any hint as to what next to try? Do I need to write a module for this?

# Answer
Modules needed: Flag, Rules, Rules Scheduler (comes bundled with rules)

1. Create a user flag
2. Add an **integer** field to your user fields. Ex: Attendance (this will keep track of the # of days attended)
3. Create a new Rule

React on A user has been flagged

Actions: Set a data value \>\> flagged-user:field-user-attendance \>\> OFFSET : 1

> So this will +1 your field every time the user is flagged.

4. in Rules add a new component.

Component: Rule \>\> **Data Type:** User \>\> **Label:** att \>\> **Machine Name:** att \>\>

Actions: Unflag a user \>\> **USER:** att \>\> **USER ON WHOSE BEHALF TO FLAG:** att \>\> Skip permission check

5. Go back to your Rule and add action of Schedule Rule Component

Select your component \>\> **SCHEDULED EVALUATION DATE**: +5 hours \>\> Identifier: `[flagged-user:name] will be auto unflaged soon` \>\> ATT: flagged-user

> so in 5 hours all users that are flagged will be auto unflagged. (this auto resets them for you, so you are ready to flag the next day)

# Update

> A good solution but the date really needs to get recorded as well – J. Reynolds

Challenge accepted.

In users add a field called "Date Attended" type:text field. In settings Change **number of values: Unlimited**

In your rule, add Action: Add an item to a list \>\> flagged-user:field-date-attended \>\> ITEM TO ADD: click on switch to direct input mode and then put \[site:current-date\] \>\> Append item to the end.

> This will auto add a new term with a timestamp when you flag a user/student.

You can then use the Field Permissions module if you want to hide this from users so they cant see it and/or edit it.

PS: I think you might know this already, but just in case. To add a flag link to your view, first you need to add a RELATIONSHIP of flag to your view. Then the flag link option will be available to add as a field in fields.

**IMPORTANT NOTE**: The Scheduled rule will be triggered in the next cron run.
> 0 votes

---
Tags: views
---


# Question
Title: Clone nodes and change fields with Rules and VBO
I' trying to create a rule component that clones selected nodes and then changes some fields, using Rules, VBO and Node Clone.

VBO and Node clone work fine, but I can't change values of every field in the clones afterwards. After the action "Clone node", I can add a "set data to value" action to change just core node fields (like status, sticky...), but the selector doesn't show me my other fields defined in the content type (like cloned-node:field\_xyz).

I also tried to use Rules Bonus Pack instead of Node clone to duplicate nodes, but with no luck: same issue.

After some researches, I tried to force a save entity action on the cloned node and then tried to load entity from cloned-nid, but I cannot choose my content type's fields to change them.

I also added a condition on top like "Content is type | entity has a field | entity is bundle", but nothing happens.

Probably I miss something. Any idea?

Thanx in advance

# Answer
I solved using custom PHP code in my component instead of the node clone action, so I'd like to share this with you:

```
// load the original node
$node = node_load($node_parameter->nid);
$node->nid = null;
$node->vid = null;
// park the new node
node_object_prepare($node);
// reset fields
$node->uid = 1;
$node->status = 1;
$node->path = null;
$node->created = 1432072800;
$node->title = $site->current_date;
$node->field_one['und'][0]['target_id']= 11530;
$node->field_two['und'][0]['value']= 'my text';
unset($node->field_three);
// save the new node
node_save($node);
// flush
unset($node);

```

Probably the key is that when you use the action "node clone", Rules alone can't determine the cloned node type and access to its fields directly, even if you are cloning a node already verified by the condition at the beginning of the component. Probably it could if putting another condition after the clone action, but I don't know how to.

So another solution I tried is to create a component that just clones the VBO passed node. And then create a separated rule that reacts on event "after cloning a node" and put in there the condition "content is type of" and all the "set data value" actions I needed.

And it works.

Anyway I prefer the first solution, so I can keep all I need in just one place and avoid using Node Clone module. I was worried about performance executing PHP and node\_load() in Rules, but in just few minutes I successfully cloned and updated 2260 nodes.

Thanx all
> 0 votes

# Answer
@Cheope hit on the problem exactly:

> Probably the key is that when you use the action "node clone", Rules alone can't determine the cloned node type and access to its fields directly, even if you are cloning a node already verified by the condition at the beginning of the component. Probably it could if putting another condition after the clone action, but I don't know how to.

You can do that without writing custom code, using the Conditional Rules module, which lets you add conditionals into the actions section of a rule.

After the node clone action, you can add a conditional to check the node content type. When you add actions inside of the conditional, they can access the fields of the created node.
> 0 votes

---
Tags: nodes, views, rules
---


# Question
Title: Hide new topic link based on the forum topics
My goal is to create a second forum. I created a new content type called forum2 and added taxonomy\_forums term reference to it.

Drupal automatically creates links for each content type.

I would like to display links based on the forum topics. For example ,

* namesite/forum/1 - only New topic link is visible
* namesite/forum/4 - only link for forum2 is visible

and so on.

here is what I did

```
function theme_advanced_forum_node_type_create_list(&$variables) {
  $forum_id = $variables['forum_id'];

  // Get the list of node types to display links for.
  $type_list = advanced_forum_node_type_create_list($forum_id);

  $output = '';
  if ($forum_id == 1 || $forum_id == 2)  {

      $output .= '<div class="forum-add-node forum-add-forum">';
      $output .= theme('advanced_forum_l', array(
        'text' => 'Add to forum',
        'path' => $type_list['forum']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '</div>';

  }
  elseif ($forum_id == 3 || $forum_id == 4)  {
    $output .= '<div class="forum-add-node forum-add-forum2">';
      $output .= theme('advanced_forum_l', array(
        'text' => 'Add to forum2',
        'path' => $type_list['forum2']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '</div>';
    }
  else {
    // User did not have access to create any node types in this fourm so
    // we just return the denial text / login prompt.
    $output = $type_list;
  }

  return $output;
}

```

Any help would be greatly appreciated

# Answer
> 0 votes
I got it working. Here is the code

```
function theme_advanced_forum_node_type_create_list(&$variables) {
  $forum_id = $variables['forum_id'];

  // Get the list of node types to display links for.
  $type_list = advanced_forum_node_type_create_list($forum_id);

  $forum_ids = array(1,2,3,4); // Ids of forum1
  $forum2_ids = array(5,6,7,8,9,10);  // Ids of forum2

  $output = '';

    if (in_array($forum_id, $forum_ids))  {

      $output .= '<div class="forum-add-node forum-add-forum">';
      $output .= theme('advanced_forum_l', array(
        'text' => 'New topic',
        'path' => $type_list['forum']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '</div>';

  }
  elseif (in_array($forum_id, $forum2_ids))  {
    $output .= '<div class="forum-add-node forum-add-forum2">';
      $output .= theme('advanced_forum_l', array(
        'text' => 'New topic',
        'path' => $type_list['forum2']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '</div>';
    }
  else {
    // User did not have access to create any node types in this fourm so
    // we just return the denial text / login prompt.
    $output = $type_list;
  }

  return $output;
}

```

---
Tags: nodes
---


# Question
Title: Open Atrium 2 or Drupal Commons or Simple Drupal with OG
What will be the best option to build a fully functional social collaboration and community website in Drupal? Open Atrium 2 or Drupal Commons or new install of Drupal 7 with Organic groups?

I am good in Organic groups but redoing everything will be tricky though considering already existing distributions like Open Atrium and Drupal Commons.

# Answer
> 1 votes
Drupal Commons has a terrible track record or maintainability and upgrade path. I only recommend using Drupal Commons or Open Atrium when they fit your needs out-of-the-box. If you have very custom needs, definitely go with a custom D7 & OG build.

If you find that Drupal Commons or Open Atrium have features that you would like to replicate, then install them somewhere else and use them as a guide for creating your own features.

The best answer is to say you need to try them all and determine their strengths and weaknesses according to your project, but from personal experience, I have regretted every project I've used Drupal Commons on, and won't do it again.

One project I did, we started with Drupal Commons, and eventually realized that it was not a good fit. So we just copied all the features we wanted into a normal D7's sites/all/modules directory.

# Answer
> 0 votes
Have a look at the (fairly new) alternative for the Organic groups module, which is the Group module. Some more details about it (from its project page):

> **Organic Groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
>
> **Groups** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" OG module.

---
Tags: 7, distributions
---