title: Printing date with custom format

text:
# Question
Title: Printing date with custom format
I want to **print "event\_info\_date" Date (Unix timestamp) field with custom format** in **node.tpl.php**.

I'm using this code:

```
<?php print date("Y/m/d h:i:s", $node->event_info_date['und'][0]['value']); ?>

```

And it prints: **1970/01/01 01:00:00**, but it isn't value from my field.

I've also tried this:

```
<?php print format_date($node->event_info_date['und'][0]['value'], 'custom', 'Y/m/d h:i:s'); ?>

```

But it doesn't print anything. **Any ideas?**

# Answer
> 0 votes
Try this:

**print date("Y/m/d h:i:s", strtotime($node-\>event\_info\_date\['und'\]\[0\]\['value'\]));**

Hope this will help you.

---
Tags: entities, datetime
---


# Question
Title: How to alter Core's user login final function
In user.module, I need to alter the message that is displayed if the username/password is not recognized. I'm using the email registration module so I don't use usernames at all. I want the last form error message in the code below to show email/password instead, as well as add a custom redirect to it.

I've googled for quite some time, but cannot find how to hook onto this function. Any help would be appreciated!

```
function user_login_final_validate($form, &$form_state) {
  if (empty($form_state['uid'])) {
  // Always register an IP-based failed login event.
  flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
  // Register a per-user failed login event.
  if (isset($form_state['flood_control_user_identifier'])) {
  flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
}

if (isset($form_state['flood_control_triggered'])) {
  if ($form_state['flood_control_triggered'] == 'user') {
    form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
  }
  else {
    // We did not find a uid, so the limit is IP-based.
    form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
  }
}
else {
  // Fix password reset messages
  form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));
  watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
}

```

}

# Answer
To change the validation function then you need to add it to the `#validate` part of the form array in `hook_form_alter`:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#validate'][] = 'MY_user_login_final_validate';
  }
}

```

You will need to examine the `$form['#validate']` array to remove the current user module validation and possibly adjust the weight of the module in the `system` table.

To redirect you add something like the following to hook\_form\_alter:

```
$form['#submit'][] = 'my_redirect_node_form_submit';

```

Again bearing in mind you might need to alter/re-order the current contents of `$form['#submit']` and the system table weight.

OR if you want to simply change the string then you could do it in a number of ways.

1. The string overrides module: https://www.drupal.org/project/stringoverrides
2. Put the overrides in the settings.php file:

```
$conf['locale_custom_strings_en'][''] = array(
  'Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>' => 'YOUR MESSAGE HERE',
);

```
3. Put this in `hook_boot()` :

```
global $conf;
$conf['locale_custom_strings_en'][''] = array(
  'Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>' => 'YOUR MESSAGE HERE',
);

```

The trick is to replicate exactly what is in the string surrounded by \`t('') in the user module (currently this is line 2228).

```
      form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));

```

Then you can let the Drupal string translation system take care of it for you. See here for a reference on Drupal.org
> 0 votes

# Answer
Override login form with hook\_form\_alter()

You need to replace validation function with your custom function.
> 0 votes

---
Tags: 7, hooks, users
---


# Question
Title: t() function doesn't translate strings inside node fields
I built a rule using rules module to create a node of a certain content type which inserts a text of `full_html` format inside a `body` field when `follow` flag is flagged. This is the rule

```
$values = array(
        'type' => 'notification',
        'uid' => UID_OF_A_USER,
        'status' => 0,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'en'
);
$entity = entity_create ('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$url = "PROFILE_URL_OF_A_USER";
$uname = "USERNAME_OF_A_USER";
$link = l("$uname","$url");
$body_content = t("!link started following you.",array('!link' => $link));
$ewrapper->field_body->set(array('value' => $my_body_content ,'format'=>'full_html') );
$ewrapper->save();

```

When a user uses `Follow` flag to follow another user, a message is sent to the followed user which says, `!link started following you.`

This rule works perfectly but the problem is with translation of the `!link started following you.`. My website supports three languages. **This is the problem:**

If a user (flagging user) flags another user using `Follow` flag and he is in a certain language, say french, The above message in french language will be sent to the followed user, no matter in what language the followed user is viewing his profile, he will see this message in french language and by switching language it will not be translated.

I need this message to be translated in the current language of flagged user when he is viewing its profile but the message is sent in the language of the flagging user and in the profile page of the followed user will not be translated even if he switches the language.

How can I make this message translatable?

# Answer
Have a look at the options you can pass on to the t() function. You can explicitly say which language you want.

So you might do something like this to handle you message content :

```
$to_user = get_destination_user(); // whichever way you do that...
$body_content = t("!link started following you.",
                  array('!link' => $link),
                  array('langcode' => $to_user->language ));

```

In essence something like the above should do it.

Also make sure that the user language is set and valid. For this you might do something like :

```
$to_user = get_destination_user(); // whichever way you do that...

// get destination user language if set
$message_lang = !empty($to_user->language) ? $to_user->language : '';

// check if language is defined on our site
$languages = language_list();
if (!isset($languages[$message_lang])) {
    $message_lang = '';
}
// check if the language is enabled
if (!$languages[$message_lang]->enabled) {
    $message_lang = '';
}

$body_content = t("!link started following you.",
                  array('!link' => $link),
                  array('langcode' => $message_lang ));

```
> 1 votes

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


# Question
Title: Is there any possibility to create services to achievement module in Drupal?
I have using the Achievements module in my site, it's working fine.

* I have one doubt, I'm using the Services module to consuming user nodes and user details.

But is there any possibility to perform services CRUD operations to **achievements** module by using services module?

# Answer
> 1 votes
There isn't an existing integration between Achievements and Services (not one that Google is up for divulging, at least), so you would need to code that yourself. But yes, it's very possible, as both modules are well written.

For full details, check out the Services API docs and the Achievements API docs.

---
Tags: services
---


# Question
Title: How to send an email once every 6 months using the Rules module?
How to send an email once in every 6 months at `12:00 am` for a date field about user renewal which is there in user profile using the Rules module?

Its mail should send in cyclic form every once in 6 months to notify user, repeating the mail once in 6 months.

So far I followed the tutorial "How to Send Follow-Up Emails Using Rules Scheduler in Drupal 7", and I have created a Rules Component, I then created a Rule like so:

* Rules Event: After saving a new user account
* Rules Conditions: None
* Rules Action: schedule the Rules component (which I created before), with Scheduled evaluation date:+6 month and User \> Data Selector: account.

So this is what I have done so far and this email I want to send every 6 months once repeatedly same email

# Answer
The Rules module together with `Rules Scheduler` (a sub-module of it), can be used for sending such eMails, as explained in the steps below.

### Step 1: Create a field to store the "next renewal" date

Add a field to the "user" entity with machine name (say) `field_next_renewal`. Allow only 1 date (to store the "next" renewal date).

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Reminder about your next renewal",
          "message" : "This is a reminder about your next renewal on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_email_user_every_6_months" : {
    "LABEL" : "eMail user every 6 months",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-next-renewal" ], "value" : "+6 month" } },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 15552000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

```

The above rule refers to the *Rules Component* from the previous step.

Note that the `15552000` is the equivalent of 6 months in seconds. You may want to reduce that a bit, e.g. with a number of seconds equivalent to a few days (or a week or so). That way the eMail will be triggered a few days before the actual renewal.
> 1 votes

---
Tags: 7, rules, emails
---


title: Session variables on custom modules

text:
# Question
Title: Session variables on custom modules
I have two modules. The first module is for custom login form and the other is for custom user pages. I want to store a session variable from the first module and later to call on the second module. Let's say my field from the first module is:

```
<?php
function custom_login_form($form, &$form_state) {

    $form['custom_field'] = array(
       '#type' => 'textfield',
       '#title' => 'Custom field',
    );

   return $form
}

```

and this is the callback from my second module:

```
    <?php
    function custom_user_pages() {
       $The_session_stored_field = 'some_value';

    }

```

How can I store the custom\_field with session and how to call it on the second module?

EDIT: My custom modules are connecting with web service and all the information I'm passing with `XML`. With `simplexml_load_string()` I'm getting all the data. Now I've used `$_SESSION`, but I have some error:

> "Exception:Serialization of "SimpleXMLElement" is not allowed in session\_write\_close()...

EDIT2:In my first module I've set `SESSION` like this:

```
$_SESSION['custom_field'] = $custom_field;

```

On the other module I've set `$custom_field = $_SESSION['custom_field'];`

Is this a right approach?

Yes, I've got an error that's not related with session, because simplexmlelement cannot be serialized like that. Maybe I should open a new thread for that.

# Answer
In submit of form store your data in session variable $sid with `_drupal_session_write('mysession', $value);` and in every where you want read it with `_drupal_session_read('mysession');`

you shold start session before you write or read session variable like php.

```
drupal_session_start();
_drupal_session_write($sid, $value);
_drupal_session_read($sid);

```
> 1 votes

# Answer
There is a workaround to make SimpleXMLElement object serialized by encoding it into JSON format (as posted here):

```
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

```

This is especially useful for caching which usually fails, so the workaround is to do:

```
cache_set($cid, json_encode($data));

```

Alternatively find out if your service supports JSON format.
> 0 votes

---
Tags: forms, sessions
---


# Question
Title: How to hide options in the second select before choosing option in first select
i have taxonomy : Cities and taxonomy Towns.

* cities have : Sousse and Tunis
* Town have Elzahra (related to Tunis (taxonomy cities) and Sahlool (realted to Sousse (taxonomy cities)).

i have installed the module "reference\_option\_limit" and i created in the content a field named city and an other field named Town , in Town field i have coched :  and i created a view for this content :  but the problem in the page it shows me all the options: for the second select:

# Answer
If I am not mistaken, you want to show in the second filter only the towns (villages) related to the selected city (ville) in the first filter. That means, the content of the second filter depends on the selection in the first filter. Am I right?

In that case, you might try something like the Views Dependent Filters module. See below its description:

> Suppose you had a view showing several kinds of products, such as cake, bicycles, and books, and an exposed filter on product type that lets the user refine the listing to one or more types.
>
> With this module you could add the following filters:
>
> ```
> cake flavour, such as lemon, chocolate, coffee
> bicycle size
> book genre
>
> ```
>
> Each filter will only show when the type it relates to is selected in the filter for product type.
> 0 votes

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


# Question
Title: Where is name defined in image_effect_info_alter(&$effects)?
```
function my_module_name_image_effect_info_alter(&$effects) {
    $effects += array(
        'whatever' => array(
            'label' => t('blabla'),
            'help' => t('Everything you need to know about this effect'),
            'effect callback'=> 'function_I_wrote',
            'dimensions callback'=> 'another_function_I_wrote',
            'form callback'=> 'image_resize_form', //This one is sufficient
            'summary theme'=> 'image_resize_summary', //No need for own summary
            'module'=> 'image', //dunno?
            'name'=> 'image_rotate', //this is where my question is about
            'data'=> []
        )
    );
}

```

So I was looking at https://api.drupal.org/api/drupal/modules!image!image.api.php/function/hook\_image\_effect\_info/7

They don't even mention name, but without it I get error:

> PDOException: SQLSTATE\[HY000\]: General error: 1364 Field 'name' doesn't have a default value

And if I specify my own name it doen't show up under the Image styles effect section after adding. Using an existing one gives it that name. So my guess it's some kind of constant. Where does it come from?

# Answer
First of all: I think the alter method should not exist if this is the easier way.

Call `hook_image_effect_info()` and just pass

> label, help, effect callback, dimension callback and form callback

this way it won't ask for

> name
> 0 votes

---
Tags: 7, hooks, media
---


title: Split Webform Items into two rows

text:
# Question
Title: Split Webform Items into two rows
i'm working on a problem for a while and still found no answer. I'm using the Webform Plugin to show a contact form on my site.

The current structure is:

```
<form>
 <div class="form-item">...</div>
 <div class="form-item">...</div>
 <div class="form-item">...</div>
 <div class="form-item">...</div>
</form>

```

Is it possible, maybe with a hook because i want to apply it to a special form, to get this HTML structure:

```
<form>
  <div class="pull-left">
     <div class="form-item">...</div>
     <div class="form-item">...</div>
  </div>
  <div class="pull-right">
     <div class="form-item">...</div>
     <div class="form-item">...</div>
  </div>
</form>

```

I want to split the form items into two rows.

Thanks for hints and tips!

# Answer
Last version of webforms lets you do this outofdabox (put fields in a fieldset though)

You can also achive this using a hook\_form\_alter implementation (Have not tested this but i think that should work) and using the FAPI #type container element, for example:

```
$form['left'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array(
      'left',
      drupal_html_class($class_left),
    ),
    'id' => array('lefttoleft'),
  ),
);

```

Create as many container as you want and then move all fields FAPI element inside the container
> 0 votes

---
Tags: webforms
---


# Question
Title: Getting password hashes and salts from Drupal 7
I need to get user accounts' password hashes and salts from a Drupal 7 app, so as to migrate these accounts into Stormpath. Could you please help me to figure out where this data is stored and how to get it from the DB?

# Answer
> 1 votes
The password hashes & salts are stored in the `pass` column in the `users` table with the first 4 bytes being settings, the next 8 bytes being the salt, and the remaining the password. See the `user_hash_password()` & `_password_generate_salt()` docs for how salts are generated.

---
Tags: database, security, users
---


title: Working of Views module in Drupal 7

text:
# Question
Title: Working of Views module in Drupal 7
I am very new to Drupal. I would like to know how Views module work. I need clarification on my following understanding about the use of Views module,

"Views are not for creating new content or inputting data, I need to create content with page/article/field collection etc. then I have to provide views module to display those contents using views module."

# Answer
If you want to become familiar with Views (cfr. your "*know how Views module works*"), checkout the (free) set of 30 video tutorials about the Views module. These tutorials elaborate on all sorts of Views related topics, such as:

* Basic settings, fields, sorting.
* Contextual filters.
* Relationships.
* Grouping fields, rewriting fields.
* Other modules typically used in conjunction with Views.
> 1 votes

# Answer
To keep it simple,
Content types, Feeds, Webforms are like data input.
Views is like data output.

* Views are specifically used to display the content nodes, feeds, etc. in various formats and can generate reports and exports. But You may also embed views in content types for example to keep track of previous data while entering new data.
* Content types are used to input the data and we may also use feeds to import bulk data from csv or other file formats.
> 2 votes

---
Tags: views
---


# Question
Title: How to force a field to allow unlimited number of values using Field API?
How do I force an unlimited number of values using code for a field I created using the Field API in Drupal 7? In this case it doesn't make sense to have any other setting so every time I create an instance of this field I have to set the number of values from 1 to unlimited.

# Answer
> 5 votes
You mean for a field type that you created yourself?

There is no real API to declare that, the only thing you can do is alter the add/edit field form.

I've already done this myself for the Properties module; here is the code (source):

```
function properties_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  if ($form['#field']['type'] == 'properties') {
    // Hide the cardinality setting on the field settings for properties fields.
    $form['field']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
    $form['field']['#access'] = FALSE;
  }
}

```

(Don't forget to flush the cache after changing form\_alter hooks and, if it's an instance setting, delete and recreate the instance to remove the previous default)

# Answer
> 1 votes
The answer using hook\_form\_field\_ui\_field\_edit\_form\_alter() works, but it hides the Field visibility and permissions as well as the cardinality. I prefer to just disable the cardinality:

```
$form['field']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
$form['field']['cardinality']['#disabled'] = TRUE;

```

---
Tags: entities
---


# Question
Title: Site installation fails with "No database to operate on."
I am having some problems running drush site install through Puppet. When it comes for puppet to execute the following command I get an error. It appears as though the database URL is being truncated and then some non-verbose error tells me SQL cannot execute? If I try to install the site via the web-UI it works without any issues. I can connect from this machine using the MySQL client with username/password.

The output of `/usr/bin/php /var/webdeploy/src/composer/vendor/drush/drush/drush.php site-install -y -r /var/www/html/drupal --db-url=data.rds.awsdomain.com/dbname --db-su=user --db-su-pw=password --account-name=admin --account-pass=admin --account-mail=mail@example.com --site-name="site name" minimal` is the following.

> You are about to CREATE the 'ata.rds.awsdomain.com/dbname' database. Do you want to continue? (y/n): y
> Unable to generate CREATE DATABASE sql for
> No database to operate on.

# Answer
> 2 votes
Your --db-url is not in the correct format. Use this instead:

`--db-url=mysql://USER@data.rds.awsdomain.com/dbname`

Replace USER with the account used to access the database. If this is the same user that you have specified with --db-su, then the --db-su option is not necessary. Drush will not go the other way (fill in the "ordinary" user from the privileged user specified via --db-su), though.

---
Tags: drush
---


title: Order nodes in multiple views

text:
# Question
Title: Order nodes in multiple views
I have a site where there are multiple staff profiles, each of which are in a specific department; some times more than one. Parts of these profiles are then displayed in a grid view for each department.

What I need to do is have a method of setting their ordering in the grid view. My original plan was to just have a text field where they can enter the profiles position number & have the view order by that. The problem is they can be part of multiple departments so the numbers entered could conflict between departments.

Does anyone have any ideas on a way around this?

The other idea that has been suggested is to add a weighting to each profile and that would dictate its position, still kind of has the same problem as the text field though. If I was to use the weighting system what is the best way to add it? I assuming just creating a select field with the options -50 through to +50 isn't the best way?

# Answer
> 3 votes
With the module Draggable Views, you can set up an administrative view to set the order (with the standard drag and drop interface), and then you can create other views that display the contents following that order.

There is a comparison of node/entity ordering modules here

**Draggable Views:**

> DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
>
> Have you ever rearranged Blocks?, sorted Taxonomy terms? or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
>
> With DraggableViews you can apply this `tabledrag.js` to any Views-generated table.
>
> **Features:**
>
> * Order any type of entity.
> * Set different order for different set of arguments.
> * Create one view that sets the order, and create as many views as you like that shows that order.
> * Use core tabledrag.js or jQuery UI draggable javascripts to set the order.

# Answer
> 0 votes
There is a module for that:

Entityqueue

> A rewrite of Nodequeue for Drupal 7 based on entities.
>
> The Entityqueue module allows users to create queues of any entity type. Each queue is implemented as an Entityreference field, that can hold a single entity type.
>
> For instance you can create a queue of:
>
> * Nodes
> * Users
> * Taxonomy Terms
>
> Entityqueue provides Views integration, by adding an Entityqueue relationship to your view, and adding a sort for Entityqueue position.

# Answer
> 0 votes
Assuming the "profiles" are implemented as "nodes" (as your question title suggests), you should have a look at the Nodequeue module. Some more details about it (from its project page):

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> * A block listing teasers for the five top news stories on a site
> * A user’s favorite music albums
> * A group of favorite from which one is randomly displayed
>
> Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.

Here is a screenprint about it:

**Note**: The Entityqueue module is a rewrite of Nodequeue for Drupal 7 based on entities, and allows users to create queues of any entity type.

---
Tags: 7, views
---


title: Multiple attribute selection sets

text:
# Question
Title: Multiple attribute selection sets
Can we implement multiple attribute selection sets such as color, size and quantity multiple times for a single product.

Suppose i have a product display that renders 4 products with colors red and blue, sizes XL and L.

So in this case, i can add 4 different selection sets. red-XL-quantity, red-L-quantity, blue-XL-quantity and blue-L-quantity.

Pls check the image for clarification.

I implemented commerce extras with views but it dsnt match my requirement.

I need a link to add multiple sets if necessary.

Thanks :)

# Answer
> 1 votes
I figured this out myself..

So the basic idea is that we build the form based on the setting of $form\_state\['num\_names'\]. The custom submit functions for the "add more" button increment and decrement $form\_state\['num\_names'\] and then force a rebuild of the form. We then iterate over the fields for the product and search for entity reference fields to a commerce option set. (This takes into account that the commerce\_product\_option module has been properly configured and option sets have been set.) We create a new blank option set each time and add a quantity field with an extra key to attach it with the current option set.

For the submit callback,i had to dig deeper into the module and tweaked a bit for these specific attributes.

```
<?php

 function multiple_option_sets_form_alter(&$form, &$form_state, $form_id) {
if ((strpos($form_id, 'commerce_cart_add_to_cart_form_') > -1)) {
    multiple_option_sets_add_more_form($form, $form_state, $form_id);
    $form['#submit'][] = 'multiple_option_sets_add_more_submit';
}

}

function multiple_option_sets_add_more_form(&$form, &$form_state, $form_id) {

$form['field_extra_attributes']['#prefix'] = '<div id="ajax-attributes-wrapper">';
$form['field_extra_attributes']['#suffix']= '</div>';

// Build the fieldset with the proper number of names. We'll use
// $form_state['num_names'] to determine the number of textfields to build.
if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 0;
}

for ($i = 0; $i < $form_state['num_names']; $i++) {

    //lets add all the fields we want in the set
    // Because we have many fields with the same values, we have to set
    // #tree to be able to access them.
    $form['#tree'] = TRUE;

    // Get the current product. Is added in the cart module.
    if (isset($form_state['default_product'])) {
        $product_id = $form_state['default_product']->product_id;
    }
    elseif (isset($form_state['default_product_id'])) {
        $product_id = $form_state['default_product_id'];
    }
    elseif (isset($form_state['products'])) {
        $current_product = reset($form_state['products']);
        $product_id = $current_product->product_id;
    }
    else {
        return;
    }

    $current_product = commerce_product_load($product_id);

    $someFieldIsAdded = FALSE;

    // Iterates the fields of this product. We search for entity reference fields
    // to a commerce option set.
    foreach ($current_product as $field_name => $field) {
        $field_info = field_info_field($field_name);

        if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
            continue;
        }

        // Do not display our options if this field has been marked as an attribute field.
        $field_instance_info = field_info_instance('commerce_product', $field_name, $current_product->type);
        if ($field_instance_info['commerce_cart_settings']['attribute_field']) {
            return;
        }

        $lang_code = field_language('commerce_product', $current_product, $field_name);
        if (!isset($field[$lang_code])) {
            continue;
        }

        // Create a new blank option set.

        foreach($field[$lang_code] as $key => $data) {

            $option_set = commerce_option_set_load($data['target_id']);

            $values = array(
            'set_id' => $option_set->set_id,
            );

            $option = commerce_option_new($values);

            $form_state['commerce_option'][$field_name][$key+1+$i]['option'] = $option;

            $form[$field_name][$key+1+$i] = array(
            '#parents' => array($field_name, $key+1+$i),
            );

            field_attach_form('commerce_option', $option, $form[$field_name][$key+1+$i], $form_state);
            $someFieldIsAdded = TRUE;

        }
    }

    $form['field_extra_attributes'][$i+1]['quantity'] = array(
    '#type' => 'textfield',
    '#title' => t('Quantity'),
    '#prefix' => '<div class="col2">',
    '#suffix' => '</div>'
    );

}

$form['actions']['add_more'] = array(
'#type' => 'submit',
'#value' => t('Add more'),
'#weight' => 50,
'#submit' => array('multiple_option_sets_add_more_add_one'),
'#ajax' => array(
'callback' => 'multiple_option_sets_add_more_callback',
'wrapper' => 'ajax-attributes-wrapper',
),
);

return $form;

}

/**
* Callback for both ajax-enabled buttons.
*
* Selects and returns the fieldset with the names in it.
*/
function multiple_option_sets_add_more_callback($form, $form_state) {
return $form['field_extra_attributes'];
}

/**
* Submit handler for the "add-one-more" button.
*
* Increments the max counter and causes a rebuild.
*/
function multiple_option_sets_add_more_add_one($form, &$form_state) {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;
}

/**
* Submit handler for the "remove one" button.
*
* Decrements the max counter and causes a form rebuild.
*/
function multiple_option_sets_add_more_remove_one($form, &$form_state) {
if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
}
$form_state['rebuild'] = TRUE;
}

function multiple_option_sets_commerce_cart_product_comparison_properties_alter(&$comparison_properties) {
// Force separate line items when the same product is added to the cart from
// different display paths.
$comparison_properties[] = 'field_color';
}

/**
* Cart submit callback function. This is required to create / update
* the option related to the line item.
*
* @param $form Form array
* @param $form_state The form state array.
* @return void
*/
function multiple_option_sets_add_more_submit($form, $form_state){

// Get current product, taking into account different Commerce versions behavior.
if (isset($form_state['default_product'])) {
    $product_id = $form_state['default_product']->product_id;
}
elseif (isset($form_state['default_product_id'])) {
    $product_id = $form_state['default_product_id'];
}
elseif (isset($form_state['products'])) {
    $current_product = reset($form_state['products']);
    $product_id = $current_product->product_id;
}
else {
    return;
}

$current_product = commerce_product_load($product_id);

// Iterates the fields of this product. We search for entity reference fields
// to a commerce option set.
foreach ($current_product as $field_name => $field) {
    $field_info = field_info_field($field_name);

    if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
        continue;
    }

    $lang_code = field_language('commerce_product', $current_product, $field_name);
    if (!isset($field[$lang_code])) {
        continue;
    }

    foreach ($form_state['values']['field_extra_attributes'] as $delta => $set_id) {

        $option = $form_state['commerce_option'][$field_name][$delta]['option'];

        // Notify field widgets and populate option with values.
        field_attach_submit('commerce_option', $option, $form[$field_name][$delta], $form_state);

        // Check if our option is empty. If yes we shouldn't save anything.
        // Cannot use field_get_items() because it calls field_language().
        $option_extracted = commerce_option_get_valuables($option);
        $ow = entity_metadata_wrapper('commerce_option', $option);
        $empty = TRUE;

        foreach (array_keys($option_extracted) as $option_field) {
            $value = $ow->$option_field->value();
            if (!empty($value)) {
                $empty = FALSE;
                break;
            }
        }

        if ($empty) {
            continue;
        }
        global $user;
        if($delta != 0) {
            $new_line_item = commerce_product_line_item_new($current_product, $form_state['values']['field_extra_attributes'][$delta]['quantity'], $form_state['line_item']->order_id, $form_state['line_item']->data, $form_state['line_item']->type);
            $new_line_item = commerce_cart_product_add($user->uid, $new_line_item);
            //var_dump($form_state['line_item']);
            //var_dump($new_line_item);
            //die();
            $line_item_id = $new_line_item->line_item_id;
        }
        else {
            $line_item_id = $form_state['line_item']->line_item_id;
        }
        $product_id = $current_product->product_id;
        $match = FALSE;

        // Check if the newly created options exist on this line item already.
        // If yes we needn't save anything, commerce will just increase the
        // quantity.
        $query = db_select('commerce_option', 'co')
        ->fields('co', array('option_id'))
        ->condition('line_item_id', $line_item_id, '=')
        ->condition('product_id', $product_id, '=');

        $result = $query->execute()->fetchCol();

        if (!empty($result)) {
            $commerce_option_entities = commerce_option_load_multiple($result);
            $option_extracted = serialize($option_extracted);

            foreach ($commerce_option_entities as $commerce_option) {
                $commerce_option_extracted = commerce_option_get_valuables($commerce_option);
                $commerce_option_extracted = serialize($commerce_option_extracted);
                if ($commerce_option_extracted == $option_extracted) {
                    $match = TRUE;
                    break;
                }
            }
        }

        if ($match) {
            continue;
        }

        $option->line_item_id = $line_item_id;
        $option->product_id = $product_id;

        // Save the option.
        commerce_option_save($option);

    }
}
}
?>

```

---
Tags: commerce
---


# Question
Title: How to patch core via drush-make when using a stub make file?
When using a stub make file based profile workflow as suggested in Drush Make theory for happy profile development I notice that patches to core are no longer applied.

I've tested this by reverting to a single make file workflow - core patches get applied just fine that way.

Has anyone else found a fix/workaround for this?

---

UPDATE with details...

---

Here's what my stub make file looks like:

```
api = 2
core = 7.x

projects[] = drupal

projects[example_profile][download][type] = "git"
projects[example_profile][download][url] = "git@github.com:danohea/example-profile.git"
projects[example_profile][type] = "profile"

```

Which as you can see is designed to go grab a custom profile. I should mention that that is not the real path to the profile (which is a private repo anyway).

The profile contains a further make file that looks a bit like this (shortened for convenience):

```
api = 2
core = 7.x

; Contrib modules (not in dev)

; Specify common subdir of "contrib"
defaults[projects][subdir] = "contrib"

projects[admin_menu][version] = 3
projects[ctools][version] = 1
projects[diff][version] = 3
projects[eck][version] = 2
projects[entity][version] = 1
projects[jquery_update][version] = 3
projects[libraries][version] = 2
projects[link][version] = 1
projects[module_filter][version] = 2
projects[pathauto][version] = 1
projects[token][version] = 1
projects[transliteration][version] = 3
projects[views][version] = 3

; Contrib modules (in dev)

projects[wysiwyg][version] = 2.x-dev
; Keep in dev until this issue makes it to stable:
; https://drupal.org/node/1956778

; Themes

projects[omega][version] = 4
projects[omega][subdir] = "contrib"

; Libraries

; ckeditor
libraries[ckeditor][download][type] = file
libraries[ckeditor][download][url] = http://ckeditor.com/builder/download/a63002d0b001ab7841c8e29bb8081e57

; Patches

; drupal
; Ignore front end vendor folders to improve directory search performance
projects[drupal][patch][2329453] = https://www.drupal.org/files/issues/optimize_scan-2329453-84-do-not-test.patch

; pathauto
; Merge in pathauto_persist module functionality to prevent losing manual aliases with node_save() calls
projects[pathauto][patch][936222] = https://www.drupal.org/files/issues/merge_in-936222-299.patch

```

The stub make file is run with a command that looks a bit like this:

```
drush make --prepare-install path/to/stub.make -y

```

I'm running Drush version 7.0.0.

Note that there are 2 patches, one for drupal core and one for pathauto. The pathauto one is applied as expected, the drupal one doesn't seem to even run.

If I download & run the profile's make file directly (i.e. not via the stub) then the core patch is applied as expected.

If I move the drupal core patch to the stub make file, it still doesn't run.

# Answer
> 1 votes
Include the core patch in the core stub makefile. Here is mine straight out of buildkit.

```
api = 2
core = 7.x

projects[drupal][type] = core
projects[drupal][version] = "7.39"

; Use vocabulary machine name for permissions
; http://drupal.org/node/995156
projects[drupal][patch][995156] = http://drupal.org/files/issues/995156-5_portable_taxonomy_permissions.patch

projects[example][type] = profile
projects[example][download][type] = git
projects[example][download][url] = git@github.com:Laudanum/example.git

```

---
Tags: drush
---


title: Override user registration function

text:
# Question
Title: Override user registration function
The default behavior for user registration is that if a user tries to register with an email that already exists, it lets them know and asks if they have forgotten their password.

We have a custom link to our product download in the email the user receives, and what we'd like to do if a user tries to re-register with the same email is to just resend the email, without notifying them that they already have an account.

I can't seem to find a way to do this. Any ideas? I'm not super-experienced with Drupal anymore.

**CODE**

```
function create_vector_user_form_user_register_form_alter(&$form, &$form_state) {
    error_log("form alter"); // this logs
    $form_state['values']['pass']['pass1'] = 'password';
    $form_state['values']['pass']['pass2'] = 'password';
    $form_state['values']['op'] = t('Create new account');
    $form['#submit'] []= "create_vector_user_user_register_submit";
}

function create_vector_user_user_register_submit($form, &$form_state) {
    error_log("submit handler"); // this does not log
  $form_state['build_info']['args'] = array(&$object);
  drupal_form_submit('create_vector_user_form', $form_state);
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}

```

# Answer
```
 /**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  array_unshift($form['#validate'],'my_first_custom_validation' );
  $form['#validate'][] = 'my_last_custom_validation';

}

function my_first_custom_validation(&$form, &$form_state){
  if(isset($form_state['values']['mail'])){
    if($user = user_load_by_mail($form_state['values']['mail'])){
      rules_invoke_component('rules_send_email_to_user', $user);
    }
  }
}

```
1. Hook into register form using hook form alter
2. Add custom validation handler to the top of submit handlers (must execute first before any other submit handler )
3. In the handler function try to load user by email using user\_load\_by\_mail If true send the email using drupal\_mail or rules then redirect to same page or any page to stop the execution.

The only problem with this code that the validation error still showing , I could not find way to stop drupal from execute the rest of validation handlers
> 1 votes

---
Tags: users
---


# Question
Title: Drupal 7 multisite domain without www. not working
I have moved a site (www.example.com) to a multisite installation. The path is 'sites/www.example.com'. I am reading that adding the 'www' to the sites folder is a no-no.

www.example.com - Works but..

example.com - Doesn't.

I tried creating a symlink 'example.com -\> /home1/username/public\_html/sites/www.example.com/

also, tried adding "$sites\['example.com'\] = 'www.example.com';" to my sites.php, but..nothing.

If I rename the folder to 'example.com' all of the paths in the database will be broken. Any ideas?

# Answer
> 0 votes
Rename the folder to example.com, create a 'sites.php' file in /sites, then add the following:

```
<?php
$sites = array (
  'www.example.com' => 'example.com',
);

```

---
Tags: 7, database, multi-sites
---


# Question
Title: Is there a way to track text-bytes changes Drupal nodes?
**A Drupal security question:**

Assuming some people have admin access to your site. How could you know **if and how much** text they changed in any of the nodes of your site? I'm not talking about going to admin/content and see if some nodes are "Updated" but I'm asking about a way to see change in the **number of text bytes**; A good example to such tracking would be the Wikipedia article tracking system --- Each time a Wikipedian article changes, you could see the number of bytes changed in it --- If someone adds 219 bytes of text to it, it will be seen in green in the famous "View history" tab. If someone deletes 12 bytes of text from it, it will be seen in red (See attached image from the "View history" tab of a typical wikipedian article to understand me better).

I try to understand if there is a similar mechanism in Drupal that I could use to track byte changes in the nodes of my site, in case someone else enters as admin and change the text of some pages.

---

# Answer
Yes, all one needs to do is look at the `field_data_body` table and compare the byte count of `body_value` between revisions to get this information.

In fact, this would probably make a good patch for the Diff module which alters the node *Revisions* tab to an interface pretty similar to MediaWiki. The only thing missing is the core of your question, a comparison of byte count between revisions.
> 3 votes

---
Tags: nodes
---


title: Various forms of overrides

text:
# Question
Title: Various forms of overrides
**Hi, my friends!**

Sometimes, making an override of a contributed module consists only of: in template.php, copy the function we want to modify and change its prefix "theme" for "my\_theme". But this is not enough.

Speaking of the Quiz module:

**1.** I need to modify the multichoice-alternative.tpl.php file. This file contains functions. But, there is only one **foreach**, and within it is what I want to change. How do I override it?

**2.** I need to modify the multichoice.classes.inc file. This file has functions without the prefix "theme". So, I can not replace "theme" for "my\_theme" in order to make the override.

Help me!

# Answer
Copy `multichoice-alternative.tpl.php` to your theme's `templates` folder. Make your changes in this file.

In your theme's `template.php` file you are also allowed to create process and preprocess functions for any theme function. So, you could create

`function THEME_preprocess_multichoice_alternative(&$variables) {`,

wherein you could add/subtract/alter any variable within `$variables`. This would allow you to pass such variables through to the `multichoice-alternative.tpl.php` file, which in your case now resides in your own theme's `templates` folder.

As to overriding the class, first see if what you need done can be done in the theme layer. If that fails you can always create your own class to inherit from class MultichoiceQuestion, make your changes, then look for the code instantiating instances of the parent class and replace with your own class. And if you do make a note so that when you upgrade the module you can make the changes again.

BTW, it is the norm in Drupal to put more complex processing (PHP) in the default template process and preprocess functions instead of the template file, and to just put enough processing in the template file to print out the variables and do some conditional logic to assist with that.
> 0 votes

---
Tags: quiz
---


title: Stock market module or configuration?

text:
# Question
Title: Stock market module or configuration?
I am researching a project and am interested in learning if there is a way or module to configure Drupal Commerce to act essentially as a stock exchange. Where multiple sellers would be able to post prices for a limited number of products (like ticker symbols on an exchange) and buyers would be able to purchase X number of said products, which would be filled from lowest to highest price?

If there is not such a configuration and/or module that implements this functionality, how complicated would it be to develop one for the Drupal Commerce stack?

The purpose of this is to trade units of quota allocation (think carbon offset trading or commodities trading) so there is no physical delivery necessary. Just a limited number of quota types, seller's prices, and purchaser orders that would be filled from low to high.

Amazon has a similar feature where multiple merchants sell the same product on the Amazon Marketplace. I am looking to implement something like that.

If Drupal Commerce is not the best platform to build this project, if someone has any idea/or experience with something similar, I'd appreciate the advice.

# Answer
I think you would have to write your own inventory system as this is not the kind of use-case Commerce is usually used for.

Commerce does have a number of hooks you can use to control the cart and checkout, but I'm pretty sure that user-ownership of stock is not something that has been tackled successfully, yet.
> 0 votes

---
Tags: commerce
---


# Question
Title: Wysiwyg (ckeditor) disappeared after drush rr
I was restructuring the modules directory (moving modules from /sites/all/modules/ to /sites/default/modules/) because we are adding a multi-site and do not want to share all the modules. After moving them I ran `drush rr` in the /sites/default/ directory and then `drush cc all` for good measure.

Everything went fine except that now on all of the content editor forms the rich text editors are all gone. I can click "switch to plain text editor" and it works fine, but CKEditor is now completely gone.

I tried doing `drush pmu ckeditor` and then `drush en ckeditor -y` and cleared cache again but for some reason the rich text editors still appear completely blank.

I checked the chrome inspector console for errors and found that the site is still looking in the /sites/all/ sub-directories for the module.

```
/sites/all/modules/custom/custom_cke_plugin/ckeditor/custom_cke_plugin/plugin.js?t=DAED Failed to load resource: the server responded with a status of 404 (Not Found)

ckeditor.js?nviice:219 Uncaught [CKEDITOR.resourceManager.load] Resource name "nyuslink" was not found at "/sites/all/modules/custom/custom_cke_plugin/ckeditor/custom_cke_plugin/plugin.js?t=DAED".

```

Has anyone had issues with moving CKEditor module and found any resolution?

# Answer
Go to `yourwebsite.com/admin/config/content/ckeditor/editg`

In there you probably need to change the path to ckeditor. As you can see from the screen shot the `%m` stands for `/sites/all/modules/ckeditor`

so you need to erase `%m/ckeditor` and instead put `/sites/default/modules/ckeditor/ckeditor`

**Click image to enlarge**
> 1 votes

---
Tags: drush, wysiwyg
---


# Question
Title: How to make relation between user term and nodes terms?
I'm newbie to Drupal. I'm in a process to restrict the user based on the node taxonomy term, and the user taxonomy term. For the user's I have attached a custom field of type **Term Reference**. I have a Taxonomy Vocabulary called **Company**. Inside that vocabulary I have created two terms **Tata**, **Infos**. There are totally 100 nodes, out of these 60 were belongs to **Tata** and the 40 belongs **Infos**.

Now these terms would be reflect to the user profile page as radio button. When admin select **Tata** for particular user, then that user might be able to see only the **Tata** tagged nodes and vice versa. I have tried tac\_lite and content\_access module before adding custom fields to user profile page, but not my requirement is getting finished. Is there any way to achieve this!!!

Thanks!!

# Answer
> 0 votes
You can do it by using view :

1. add field in views
2. add relationship of user
3. add expose filter against term id or term name
4. if you want show on user profile page add contextual filter against user id

---
Tags: users, taxonomy-terms
---


# Question
Title: How to send an email to an author on a specific date using date field specified in a node?
In my content I have one date field which is entered by the author, who fills that as future estimate date like tomorrow or after 1 month. Depending on that estimated date, on that day mail should trigger.

Example: my date field is "weaning date" which the author will fill at as after one month on that day should trigger a mail.

# Answer
You might use the Rules Scheduler module (included with Rules) for this. The following tutorial explains a case similar to yours: http://www.webwash.net/tutorials/how-send-follow-emails-using-rules-scheduler-drupal-7

In short, you would need to:

* create a "send email" component that sends an email with a user as parameter
* create a rule triggered when a node of your content type is modified
* set the action for that rule to an "scheduled component evaluation" that uses the "send email" component you created.
* in the "scheduled evaluation date" of the action you need to press the "switch to data selection" button, and then to select the date field of your node from the dropdown menu.

Note that the scheduled component evaluation is triggered by cron. You need to make sure that cron is configured correctly in your site.

Hope that helps,
> 1 votes

# Answer
Use the Rules module together with `Rules Scheduler` (a sub-module of it) for sending such eMails, as explained in the steps below.

### Step 1: Create a field to store the "weaning" date

Assume your weaning date field has a machine name (say) `field_weaning_date`, for which only 1 date is allowed.

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Reminder you requested",
          "message" : "This is a reminder that you asked for ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_send_email_on_a_scheduled_date" : {
    "LABEL" : "Send eMail on a scheduled date",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_weaning_date" } }
    ],
    "DO" : [
      { "schedule_delete" : { "component" : "rules_send_email_notification", "task" : "[node:nid]" } },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : [ "node:field-weaning-date" ],
          "identifier" : "[node:nid]",
          "param_user_to_notify" : [ "node:author" ]
        }
      }
    ]
  }
}

```

The above rule refers to the *Rules Component* from the previous step.

The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recently entered date).

**Attention**: as per your specs in your question, if anybody different from the "author" ever updates that weaning date, the effect of doing so will be that:

1. no eMail will be send on the previously requested "weaning date" (if that is not what you want, then remove the `schedule_delete` part in the rules action in Step 3).
2. the "author" will receive another eMail, on the updated weaning date (if that is not what you want, then add a rules condition in Step 3 to verify that the editor's userid matches the author's userid).
> 0 votes

---
Tags: datetime, emails
---


# Question
Title: How to add where condition in hook_views_query_alter with a join
I have a files listing view which I need to filter on the basis of current logged in user's roles. Since one user can have multiple roles I want to filter data on the basis of all the roles those are assigned to current logged in user. I used following code but it didn't work.

How do I achieve this?

here is the code that I wrote:

```
function ModuleName_views_query_alter(&$view, &$query){
  global $user;
  if ($view->name == 'my_view_name'){
    $user_roles = $user->roles;
    $view->query->add_where($user->roles,$user_roles,'IN');
  }
}

```

# Answer
You can use something like this.

```
function ModuleName_views_query_alter(&$view, &$query){
  if ($view->name == "my_view_name") {
     $join = new views_join;
     $join->construct('TABLE NAME', 'NODE', 'nid', 'entity_id', '', 'LEFT');

     $view->query->add_relationship('TABLE NAME', $join, 'node');
     $query->add_where('TABLE NAME', 'TABLE NAME.FIELD NAME', FILTER VALUE, 'IN');
  }

```

You Can Use your entity type in this function, i used NODE here. I hope this helps you.

Don't forget to mark it right if this help you ;)
> 2 votes

---
Tags: views
---


# Question
Title: Grouping fields into Drupal block to appear in its node
I have a content type with several fields. I need to group some fields of each node into a block. The block will contain the fields values of that particular node only.

In this layout, AAA is a photo slider displaying some photos of that node. On the right, BBB is a block containing some fields. I am trying to create this BBB as a block.

Initially I thought this could be done with the fieldgroup module, just only a matter of configuring the fieldgroup setting for \< div \>? And in that form, this question is similar to earlier ones, and has also been well answered.

But on further research, this doesn't work. In the diagram, AAA and BBB are siblings. If the fields in BBB have a \< div \> but still under the larger container and not in their own block, then it can't float with the other AAA block since they are not siblings.

Therefore, I need not only to group with \< div \> for the fields but indeed must wrap these fields into a Drupal block. How to do that? Thanks.

# Answer
I have solved this problem by using Display Suite (DS) module. Initial research cleares lingering doubt on performance and it turns out that the solution is quite simple.

DS divides the Content type display into several *panels (Left, Right, Top, etc)* and fields can be moved accordingly. Each panel is a `<div>` \- exactly what I need. But how to put the slider there? Cannot just set it up like a block, which will put it outside of the DS area and thus not sibling to Right panel.

Found out that DS can make a block into a field and as such it can be moved into the Left panel. And thus solving the problem.
> 0 votes

# Answer
Go to display settings for your content type and select div under format and save it. The contents are then wrapped in a div.

see here in firebug

Note: You can also use a template (.tpl) file for your content type and there you can wrap your desired contents inside a div.
> 1 votes

# Answer
See this module this will help you to fashion group of specific fields in views itself Views Fieldset
> 0 votes

---
Tags: views, entities
---


title: Core image module not found

text:
# Question
Title: Core image module not found
Some how it seems like the `core image module` is missing from the module list.

Here is the screenshot of the module list:

Also I tried fetching the list using drush.

```
$ drush pml | grep image
 Image                                Image Attach (image_attach)                                                          Module  Not installed  7.x-1.x-dev
 Image                                Image Gallery (image_gallery)                                                        Module  Not installed  7.x-1.x-dev
 Image                                Image Import (image_import)                                                          Module  Not installed  7.x-1.x-dev
 Image                                Image legacy (image_legacy)                                                          Module  Not installed  7.x-1.x-dev
 Image                                ImageMagick Advanced Options (image_im_advanced)                                     Module  Not installed  7.x-1.x-dev
 ImageAPI                             ImageAPI (imageapi)                                                                  Module  Enabled        7.x-1.x-dev
 ImageAPI                             ImageAPI GD2 (imageapi_gd)                                                           Module  Enabled        7.x-1.x-dev
 ImageAPI                             ImageAPI ImageMagick (imageapi_imagemagick)                                          Module  Enabled        7.x-1.x-dev
 Other                                Image crop (imagefield_crop)                                                         Module  Not installed  7.x-1.1
 Spam control                         Image CAPTCHA (image_captcha)                                                        Module  Enabled        7.x-1.0-beta2

```

But the list shows up on the database system table. All the images on my site are not showing up because of this.

I fixed this issue by manual enabling the module from the database and also had to set `bootstrap = 1` for it work properly, without it won't work.

so for image row I have to make this changes on system table.

`status = 1 and bootstrap = 1`

This is bit weird but some how the image module gets disable after some time ( days ). Not sure what is causing it. Every time I have this issue, I have to go to database and make the same changes as above. Can some one guide me what might be causing this issue or how do I debug this.

Note: this is multi site installation.

> Update: Rregistry rebuild using `drush rr` also fixes the issue, but doesn't seem to be permanent.

# Answer
Missing Image module from the list suggest that it disappeared somehow from the `system` table which have the list of all modules.

To confirm that, double check that directly using the query, e.g.:

```
drush sqlq "SELECT * FROM system WHERE name='image'"

```

It's difficult to answer what causing that without actually debugging it. It depends what kind of modules you've installed, custom code and the environment it-self (e.g. caching).

To track the problem, you can try:

* temporary disable external caches (memcached/redis),
* temporary disable PHP caches (OPCache/APC/XCache/eAccelerator) or its settings which could interfere with Drupal internals,
* disable any automated QA testing (such as Simpletests or Selenium) for affected environment,
* disable useless non-stable modules,
* temporary disable further modules which you can,
* check if this is specific to environment (dev, stage, live),
* if happens on all, could be some bug in the code, so follow the section below.

### Debugging

This could be a tricky part to find out, so you probably need some tricky tools to debug it.

Here are my ideas:

* watch the module lists and check when it's missing:

```
watch 'drush pml | grep -w image || echo Missing'

```

for example by sending your-self e-mail with the recent logs:

```
watch 'drush pml | grep -w image || { drush watchdog-show | mail -s missing-image drupal@niepodam.pl && killall watch; } '

```
* run debuggers attached to MySQL which monitor everything to do with`system` table or `image` entry (note: it could be overwhelming for the system):

```
sudo strace -e recvfrom -s999 -fp $(pgrep mysqld) | grep -w image >> sql.log

```
* run debuggers attached to PHP:

```
sudo strace -e sendto -s999 -fp $(pgrep -fn php) 2>&1 | egrep "system|image" >> php.log

```

Or simply enable log queries in MySQL configuration file.

Above is more useful if you've Devel installed, so there is an option to prepend a function name before the query (so you know exactly which function caused it).
* install XDebug and enable tracing for the part which you suspect the most by adding `xdebug_start_trace();` and `xdebug_stop_trace();` in appropriate places (see sample ini config), suggested places would be:

+ `system_list()`
    + `system_list_reset()`

then analyse the trace files.
> 0 votes

---
Tags: 7, drush, media
---


title: Quiz permissions per user

text:
# Question
Title: Quiz permissions per user
I have installed the quiz module in drupal 7 and I know that there is a permission to allow roles participate in all quizzes. I want that a specific role can participate in specific quiz, not in all quizzes, and other roles can participate in their own quizzes.

Is there anyway to accomplish this through the interface? If not, I would like to know how to solve it by coding.

# Answer
It seems there is a module for this: OG Quiz. According to its description:

> This modules creates permissions similar to the core Quiz ones on the group level. This allows site builders to give Quiz creation/correction/taking permissions at the group level instead of globally.
> 0 votes

---
Tags: quiz
---


# Question
Title: I want to PROGRAMMATICALLY change the roles that can view a block
What I really want is that I have a block and I want it to be shown only for authenticated users.

Can anyone help me?

**Note**: I want to do it programmatically without an extra module.

# Answer
> 1 votes
hook\_block\_list\_alter()

`global $user;`

check `$user->roles` and `unset` your block:

```
function modulename_block_list_alter(&$blocks){
  global $user;
  $roles = $user->roles;
  if(!in_array('authenticated user', $roles)){
    unset($blocks[6]);
  }
  // 6 is actually a block id witch is
  //an array key from $blocks
}

```

I have just tested it with simpletest and it works. You need to check the user roles also.

# Answer
> 2 votes
Check out this module block access

# Answer
> 2 votes
there is the option of assigning a role in the block settings under the `Visibility settings`.

# Answer
> 1 votes
If you looking it through grammatically so follow this.

```
function hook_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'demo_block1':
      if (in_array('Admin', array_values($user->roles))) {
        $block['content'] = t('Hello Admin');
      }
      break;

    case 'demo_block2':
      if ($user->uid) {
        $block['content'] = t('Hello Authenticated User');
      }
      break;
  }

  return $block;
}

```

---
Tags: users, blocks
---


title: Failed to load the AWSSDK

text:
# Question
Title: Failed to load the AWSSDK
I'm trying to get Drupal to work with the S3 File System module.

I downloaded the AWS SDK files and put them in the libraries folder. I don't know why I'm getting the failed to load error.

I tried using the `https://github.com/aws/aws-sdk-php/releases/download/2.6.3/aws.zip` as suggested. It fixed 1 of the 2 errors, but it fails to load the AWSSDK.

* I tried to clear the cache, but it didn't help
* I checked the admin/reports/dblog page, in the case the errors were related to file permissions on the SDK files), but nothing shows up

# Answer
Check the README.txt of the S3 File System module. Contains a couple of instructions that are helpful.

> In the unlikely circumstance that the version of the SDK you downloaded causes errors with S3 File System, you can download this version instead, which is known to work: https://github.com/aws/aws-sdk-php/releases/download/2.6.3/aws.zip
>
> IN CASE OF TROUBLE DETECTING THE AWS SDK LIBRARY:
> Ensure that theawssdk2 folder itself, and all the files within it, can be read by your webserver. Usually this means that the user apache (or \_www on OSX) must have read permissions for the files, and read+execute permissions for all the folders in the path leading to the awssdk2 files.

The link to the aws-sdk-php on the AWS installation page will allow you to download the latest version (3.4.1).

On my case, I had to download the 2.6.3 version of the SDK that is mentioned on the README.txt.

You might want to check at admin/reports/dblog if there are any errors related to loading the SDK.

I found that sometimes the libraries info gets hard cached and that is why this module has the `_s3fs_load_awssdk2_library()`. Take a look of this:

> This function is a replacement for calling `libraries_load('awsdsk2')`. It's needed because `libraries_load()` caches failures to load the library, meaning that temporarily having a bad setup (e.g. nonexistent or unreadable files in the awssdk2 folder) can lead to the library being permanently unable to be loaded, even after the bad setup is repaired. This can only be remedied by clearing the full site cache.

TD;LR: sometimes you will need to refresh the libraries cache for the SDK, if that is the case, the `_s3fs_load_awssdk2_library()` can be invoked by going to `admin/config/media/s3fs/actions` and use the "Refresh file metadata cache" button option. Or also you can use the Drush command `drush s3fs-refresh-cache`.
> 2 votes

---
Tags: 7
---


# Question
Title: How to disabled Statistics module for role or anonym users?
I use Statistics module (Drupal core modules) on my site to get node's view count. How to disabled this function for role or anonym users?

Like that in `template.php`:

```
function MYTHEME_preprocess_page(&$vars) {
  if (!$logged_in) {
    // Code for disable Statistics module
  }
}

```

# Answer
> 0 votes
I'm assuming you are looking for a way to "ignore" views by some roles or anonymous users, and not for "disable of the statistics module" for those roles/users (there is no way in Drupal to enable/disable a module for selected roles).

Below are some suggestions about contributed modules. In case none of them are an actual fit for what you're looking for, you may want to look at them to get inspiration that you could use in a custom module.

# Node view count

You may want to use the Node view count module for this. Here is a quote about it (from its project page):

> ... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
>
> This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

Specific to the D7 version of it, this is what is included also on the project page:

> Also now we count node views for anonymous users.

# Statistics Advanced

The Statistics Advanced **(\*)** module is another option to consider. Here is a quote about it (from its project page):

> Provides a few advanced options to the core Statistics module.

Be aware however of the issue "Port Statistics Advanced Settings to D7", with current status = needs review.

My "recommendation" for anybody looking for a D7 version of it, is to ***review*** what is attached to Comment # 55 in that issue. And report any potential deficiencies in that same issue (confirmations that it works fine would be appreciated too, also via that same issue).

# Statistics Filter

Yet another module is the Statistics Filter module. Here is a quote about it (from its project page):

> This module allows customizable filtering of hits from particular user roles or from crawlers.
>
> Benefits:
>
> For sites with light traffic (i.e., most sites), a large percentage of the gross hits recorded by statistics.module are either from the site administrator or from search engines. Filtering out these hits makes the collected statistics more accurately reflect traffic from real, human visitors.

# Other modules to consider

If none of the above modules fit your needs, then you may want to consider reviewing this shortlist of possible alternatives (quotes are from their project pages).

* Visitors **(\*)**:

> Displays information about visitors, and integrates with the WhoIs Lookup module
* Better Statistics:

> introduces a Statistics API, which allows for a way to collect, limit, and route custom access statistics and data.
* Counter

> ... counts how many visitors on your website. This module provides real time counting. All data saved to database.
* User Visits (with related User Visits Advanced).

> ... tracks visits and referrer from other users on a user's profile page. It displays the latest visitors on a user's profile page and provides two blocks one with the latest visitors on a user's profile page and one with the latest visitors on own profile page.
>
> See User Visits Advanced for additional functionality.
* Piwik Web Analytics:

> Adds the Piwik web statistics tracking system (free open source) to your website.
>
> Related module: Piwik Reports, which provides graphical reporting of your site's tracking data inside Drupal.

**Disclosure**: I'm the maintainer of the modules marked with **(\*)**.

# Answer
> 2 votes
The statistics module doesn't provide that option, or an easy way to inject that logic at first glance.

If you're using the AJAX counting method, you can implement `hook_js_alter()` to change the settings that the module adds, specifically altering the path it sends the tracking AJAX request to. You can change that to a file controlled by your own module, and you can make the decision whether or not to save the record based on the current user in there (after copying the code from the stats module's own statistics.php file).

If you're not using the AJAX method, there are a few different ways you could attack it, but each are more of a pain than it's probably worth. If the AJAX version isn't an option, I'd recommend writing your own custom module that incorporates the existing logic from Statistics that you need, plus your new logic.

The other options are doing things like trying to remove the Stats module's implementations of `hook_exit()` and/or `hook_node_view()` from your own module, and re-implementing them. This is never a great approach as you have to re-visit your module every time there's a core update to make sure nothing's changed.

Or, you could maintain a patch to the core module. Usual caveats apply if you go down that route obviously.

---
Tags: nodes
---


title: Restrict Profile2 Profile Type on Role

text:
# Question
Title: Restrict Profile2 Profile Type on Role
I would like to do a few things:

1. Limit the profile type a user has based on their role. When/if they change roles, their profile type would change and any fields that were the same are brought forward.
2. When accessing a user's profile page, the relevant profile type displays (one URL).
3. Allow users to display some of the fields in their core profile in the profile2 page that people see. (eg. birthday in core displayed as age in profile2 page).

Or am I thinking about this all wrong? Should I just think of profile types as different pages of the same profile that happen to have different fields?

# Answer
You can use permissions to assign profile(s) to roles.

about:

> When/if they change roles, their profile type would change and any fields that were the same are brought forward.

Remember each profile form is independent, so what you want could be done with code. Or you can use only one profile form and use the field permissions module to assign role(s) per field (even if this is the case, maybe you don't need profile2).

Using only profile 2 (and turning off profile2 page), you would see your core profile fields and the profile2 fields together.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to implement POST request in custom services module?
I want to send the `POST` parameters from my PHP client library, for that how to make my custom services module?

```
function module_rest_services_resources() {
  return array(
   'new_note' => array(
         'retrieve' => array(
           'help' => 'Retrieves a note',
           'file' => array('file' => 'inc', 'module' => 'module_rest'),
           'callback' => '_module_rest_retrieve',
           'access callback' => '_module_rest_access',
           'access arguments' => array('view'),
           'access arguments append' => TRUE,
           'args' => array(
             array(
               'name' => 'id',
               'type' => 'int',
               'description' => 'The id of the note to get',
               'source' => array('path' => '0'),
               'optional' => FALSE,
             ),
           ),
         ),
     ),
  );
}

```

Its working with `GET` request, what i have to change here to process the `POST`?

# Answer
> 2 votes
In order to change into the POST request. You just change the source of resource from **path** to **data**. For example:

```
function module_rest_services_resources() {
  return array(
  'new_note' => array(
     'actions' => array(
       'retrieve' => array(
         'help' => 'Retrieves a note',
         'file' => array('file' => 'inc', 'module' => 'module_rest'),
         'callback' => '_module_rest_retrieve',
         'access callback' => '_module_rest_access',
         'access arguments' => array('view'),
         'access arguments append' => TRUE,
         'args' => array(
           array(
             'name' => 'id',
             'type' => 'int',
             'description' => 'The id of the note to get',
             'source' => array('data' => 'id'),
             'optional' => FALSE,
            ),
          ),
        ),
      ),
    ),
  );
}

```

# Answer
> 0 votes
You need to use 'action' for post request. For example:

```
<?php
/*
* Implementation of hook_services_resources()
*/
function custom_services_services_resources(){
    return array(
    'new_note' => array(
    'actions' => array(
    'note' => array(
    'help' => 'Retrieves a note',
             'file' => array('file' => 'inc', 'module' => 'custom_services'),
             'callback' => 'custom_services_rest_retrieve',
             'access callback' => 'custom_services_custom_access',
             'access arguments' => array('view'),
             'access arguments append' => TRUE,
             'args' => array(
               array(
                 'name' => 'id',
                 'type' => 'int',
                 'description' => 'The id of the note to get',
                 'source' => array('data' => 'id'),
                 'optional' => FALSE,
                ),
              ),
    ),
    ),
    )

    );

    }

```

In this,Then you need to enable that action in your rest service at backend. you need to call your service as like below http://YOURSITE/SERVICE-END-POINT/new\_note/note Please check this post for more information

---
Tags: hooks, commerce
---


# Question
Title: Making an Entityform field required using jQuery
I have an Entityform and defined dependencies to where if a particular value is selected from one of the drop downs, the resume field (file upload) should be required.

I don't know why, but it's currently not working. It marks the resume field as required, but still lets the application submitted with no error.

I noticed all the required fields (that do work) have a class of `required` in their markup. Is it possible I can do this in jQuery? Meaning that I check that dropdown and if a certain value is selected, I'll add the `required` class to the file upload (resume) field.

# Answer
Javascript can only handle soft (client-side) validation, unless you start looking into AJAX validation.

You need to alter the form on the server side to ensure that the data is validated properly - never rely on JS validation, it should only be used for UI/display purposes, and form data can easily be overridden by the user.
> 0 votes

---
Tags: forms, entities
---


# Question
Title: jQuery UI filter, Full HTML and hook_block_view_VIEW_NAME_alter
I have installed jQuery UI Filter and jQuery plugins to get text with accordion effect. It works perfectly when the content is inserted in a node, with a special tags language. However, when I try to get the text rendered in a block with **hook\_block\_view\_VIEW\_NAME\_alter**, as I am just the **$data\["content"\]\["#markup"\]** property, it is not working and it is displaying the special tags without rendering them: \[accordion\], etc.

Must I get the effect by using clean jQuery instead of the modules? Is there a way of saying that I want to apply the "Full HTML" properties to the content-markup text of the block?

# Answer
I was able to make it work with the modules installed ( jQuery plugins , jQuery UI filter and jQuery UI filter accordion). The trick was to include the following Javascript in the template **yourtheme\_preprocess\_page()** and in the HTML use the div with id="accordion" of the official example ( https://jqueryui.com/accordion/ ).

```
drupal_add_js(' jQuery(function() {
var icons = {
  header: "ui-icon-circle-arrow-e",
  activeHeader: "ui-icon-circle-arrow-s"
};
jQuery( "#accordion" ).accordion({
  icons: icons
});
jQuery( "#toggle" ).button().click(function() {
  if ( jQuery( "#accordion" ).accordion( "option", "icons" ) ) {
    jQuery( "#accordion" ).accordion( "option", "icons", null );
  } else {
    jQuery( "#accordion" ).accordion( "option", "icons", icons );
  }
});
  });', array('type' => 'inline'));

```
> 0 votes

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


# Question
Title: Only show first entity reference in views
In my situation :
I have 2 content types **content type A and B**
In **content type B** add entity reference field of **content type A**
In views, I want to display some values of **content type A**,but I also want to show some values of the first **content Type B** which has entity reference field to **content type A**.
How can i show only its first value ?

edit: **Content Type B** has an entity reference field to **Content Type A**. In the view I list all of the nodes of **Content Type A**.
But I also want to show some field of the first node that is referenced in **Content Type B**.

For example:
**Content Type A** has fields: title and logo.
**Content Type B** has fields: body and entity reference to **Content Type A**.
Multiple entities of **Content Type B** can be referenced to an entity of **Content Type A**.

What I want to show is:
**Content Type A** \- Title
**Content Type A** \- Logo
**Content Type B**\[0\] - Body

Thanks in advance!

# Answer
> 0 votes
This is how i did it :

1. In Views, under **Advanced**, add **Entity Reference:Referencing entity** relationship via your reference field id.
2. In Views, under fields add the field(in this case - Body) and add the above relationship .

**Note**: *If there are nodes of content type B that reference same nodes of content type A, those same nodes of content type A will be duplicated in the views with different values of the fields of content type B that is referencing them*.

**Update**: To remove such duplicates, you can use **Views Distinct** module and then in Views under fields, select Title field(Content Type A) and under **Views Distinct Settings**, change to **'Filter Repeats'** for **Filter/Aggregate this field** and save.

---
Tags: views, entities
---


# Question
Title: How to specify a Rules condition related to select list values?
I'm now thoroughly confused about trying to set a Rules Condition on a select list. There are two things I want to do:

(a) On a new node of my content type I want to trigger when a certain checkbox in the select list is checked

(b) When a node of the same content type is edited I want to trigger when the state of the checkbox has changed.

For (a) I start out with a Data Comparison and put the name of the select list (node:field-pbxq-stock-status) in Data Selector. On the next page I choose "Is one of" for the Operator and then my list of Data Values disappears, so I cannot select the one I want. It won't allow "node:field-pbxq-stock-status:In stock" or "node:field-pbxq-stock-status:3" (3 is it's index) in that Data Value/Data Selector field.

**Update**:

These are two more comparisons I've tried.
Both are: After saving new content of type PBX Quote

Text Comparison
Data selector: node:field-pbxq-stock-status:3
Matching text: In stock
Value: contains

List contains item
Selected list: node:field-pbxq-stock-status
Data selector: node:field-pbxq-stock-status:3

In both of those cases I'm using the '3' because I -think- thats suppose to be the list offset? I'd much rather compare without dependency on offset, eg:
Some type of comparison
Selected list: node:field-pbxq-stock-status
Matching text: In stock
Value: contains

# Answer
Below is a sample of a rule (in Rules export format) that should allow you to specify a Rules condition relation to a specific value selected via a selection list (and when a new node is created):

```
{ "rules_new_node_with_special_optionlist_value" : {
    "LABEL" : "New node with special optionlist value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value = Custom" } }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event I'm using is "After saving new content".
* In my case I have a selection list field with machine name `field_optionlist`.
* This field actually has 3 possible values, like so:
    + A (=Advanced).
    + B (=Basic).
    + C (=Custom).
* As a sample, I decided to use as condition "The selected value must be `Custom`".
* If that value is selected, then (as Rules action), a message is shown like `A new node got created with option list value = Custom` (feel free to change that to whatever Rules action, this is how I often "unit test" new rules I write).

The "clue" to make this rule work is the condition `Entity has field`. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". I wouldn't be surprised if that is what you are missing in the rules conditions you tried so far ...

Note that I've not added a Rules condition here about selected content types, that's probably an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the `Entity has field` condition should be sufficient already.

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.
> 2 votes

# Answer
React on "after saving new content"

**use TEXT COMPARISON** instead of Data Comparison

Under Matching Text put the name of the "a certain checkbox" that your talking about.
> 1 votes

# Answer
Data Types and Data Selection

* How to use data selection to explore available data and drill down to selected properties
* Using the data comparison condition
* Using the set a data value action
* That Rules recognizes different types of data,and verifies when necessary
* That Rules knows that not all data is writable, and verifies when necessary
* How to create composite tokens, extending the tokens listed in the replacement patterns
* Making field values accessible to Rules
* Using reference fields to access new data, such as tags on an article or nodes in a node reference field
> 1 votes

---
Tags: rules
---


title: 2 websites under one domain

text:
# Question
Title: 2 websites under one domain
In one domain I want 2 drupal it as follows: www.example.com/index.php (not necessarily drupal), just a landing page On the index page people have to chose between 2 Drupal Sites

www.example.com/salloon1/index.php or www.example.com/salloon2/index.php

Can I do this ass follow? **Step 1** Uploading all drupal files to www.example.com/saloon1/ Create Database saloon1\_DB settings.php pointing to saloon1\_DB **Step 2** Uploading all drupal files to www.example.com/saloon2/ Create Database saloon2\_DB settings.php pointing to saloon2\_DB

index.php 2 images: image 1 pointing to www.example.com/saloon1/index.php image 2 pointing to www.example.com/saloon2/index.php

Is this right or is there another solution?

Thanks guys in advance!! Best regards, Pieter-Jan Derks

# Answer
One way to create multiple sites within one drupal instance is to use the domain access module.

https://www.drupal.org/project/domain

Using this you can create different sites with different domains on the same instance. You won't be able to do www.example.com/saloon1 and www.example.com/saloon2 (unless you use the subfolder domain module that extends domain access. Though I'm having trouble getting that module to work) But you could do saloon1.example.com or saloon2.example.com or you could do saloon1.com and saloon2.com

On all content and blocks you'd be able to specify whether it's available to one domain, the other, or both. You could also restrict user privileges to one domain. You could also apply different themes to each domain.
> 0 votes

---
Tags: database, multi-sites
---


# Question
Title: Use twig to style a specific block (unformated list)
I have a block showing a unformated List of fields. Now I would like to use twig to style that block.

I am able to use `block--views-block--blockname-block.html.twig` to do the outer styling. But I could not get the fields out of the content.

# Answer
Not sure to understand what you mean...

Do you want to customize the fields that appear in your block?? If so, Drupal normally provides you with available twig hooks you could use. Yours would probably be *field.html.twig*.

Exemple : you can customize a menu with *menu.html.twig* and then customize the links in that menu with *links.html.twig*
> 0 votes

# Answer
Ok I got it. I've already overwritten form templates to add a template suggestion that included the form id. Here's the code :

```
function hugo_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    if (isset($variables['element']) && isset($variables['element']['#type']) && $variables['element']['#type'] == 'form') {
        $original_theme_hook = $variables['theme_hook_original'];
        $suggestions[] = $original_theme_hook . '__' . str_replace('-', '_', $variables['element']['#id']);
    }
}

```

Maybe you could reuse this piece of code changing the form by the view, something like `YOURTHEME_theme_suggestions_view_alter`
> 0 votes

---
Tags: blocks, 8, theming
---


title: Top Author of the week

text:
# Question
Title: Top Author of the week
How to get the Top Author of the week based on user points? I have tried http://drupal.org/project/userpoints\_ranking but it has no such options. I am using drupal 7
I have vote up/down module and user-points module enabled and a Rules to add user points for every vote automatically, based on that vote i want to have Top Author of the week.

# Answer
> 1 votes
The Userpoints module has Views integration to make this happen:

1. Create a new view using *Userpoints Transactions* as the base table.
2. Add a **Relationship**, *Userpoints Transactions: User*.
3. Select your **fields**: *User: uid* & *Userpoints Transactions: Points*.
4. **Filter** on *Userpoints Transactions: Timestamp* with the **Value Type** set to *An offset from the current time...* so you can input your `strtotime()` offset (e.g. by rolling week, "-7 day").
5. Enable the **Use aggregation** option.
6. Lastly, for the **Aggregation Settings** on *Userpoints Transactions: Points*, set the **Aggregation Type** to *Sum*.

---
Tags: users, userpoints
---


# Question
Title: How to count the node of content type for corresponding entity reference field
I am creating a report. I want to count the nodes of a content type saved for particular entity reference field.

So far I have worked with Views Aggregator and Forena Reports.

But I am not able find it. Can anyone help me on this please?

# Answer
In Views, under **Advanced**, **Use Aggregation - Yes**.

Suppose you have content type A and B. B has entity reference field which refers A. Now you have already created a view for content type A and added its relationship to B.

Now under Fields, Add a new field of the content type B(suppose body), change the label to Count set its **aggregation settings** to **count**.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Drupal 8 entities inheritance and bundles
I have 2 questions about entities inheritance and bundles in Drupal 8.

* Let's assume that I have a content entity called "foo" (entity type) and "foo" as its bundle, and now I want to create the content entity "bar" with the bundle "foo", and add new properties to it. Is it possibile?
* Is it possible to use inheritance with content entities, something like the following inheritance (and if so, is that considered to be a bad practice?) :

`class foo extends ContentEntityBase {}`

`class bar extends foo{}`

`class baz extends bar{}`

# Answer
> 3 votes
Drupal Core uses that itself for test entity types:

So yes, this works. However, it only works as far as it is covered by PHP. You can inherit base field definitions for example if you call the parent method and use the return value, see those classes.

Annotations for example are however not inherited, each subclass needs to re-define everything.

There is the plan to provide a default content entity that will a default set of base field definitions and other things that you probably want to have on custom entity types, likely that will live in the 8.x version of the entity.module.

On what you want to use, that depends on your use case. The common use case for bundles is so that users/site builders can create them and add configurable fields. If you need that, use them.

Keep in mind that not everything is generic, various things are still node specific, like the whole revision handling (the storage is generic, but all the user interfaces require a ton of custom code at the moment), the node preview functionality is also custom and other things. We plan to improve that situation in the mentioned entity.module until we can improve it in core.

---
Tags: 8, entities
---


# Question
Title: Which Drupal log file is available to proof when exactly some content was deleted and by whom?
Somebody claimed that content has disappeared from their site. Of course like magically. No one has deleted it, they said.

How can I find out if content was deleted and by whom? Do I have to set up rules to notify me? Or is there a log that I'm overlooking? I already looked into admin/reports/dblog without success.

# Answer
> 7 votes
Check out their http://example.com/admin/reports/dblog. You should have messages like this one:

```
Type        content
Date        Wednesday, June 5, 2013 - 09:11
User        admin
Location    http://localhost/node/1/delete
Referrer    http://localhost/node/1/delete
Message     page: deleted test.

```

For future, you can use hook\_watchdog()

> This hook allows modules to route log events to custom destinations, such as SMS, **Email**, pager, syslog, ...etc.

# Answer
> 3 votes
You can probably use https://drupal.org/documentation/modules/notify. I have not used it but it seems that it might do what want. If you can use code you could also consider implementing

```
hook_node_delete();

```

Described here. This is invoked on every node deletion.

As for the logs, I don't have any hint.

# Answer
> 1 votes
Here is another approach that might help to address the "is there a log that I'm overlooking" in the question ...

Start from a "Crosstab table" containing statistics (summary info) of the Watchdog Statistics, as in this sample:

This sample does not actually include any info about "deleted content" (because no such records were found in the specific situation). But it should be clear that you get 1 row for each flavour of Watchdog entries. Note those red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found").

How did I create such drill-down report? Rather straight forward ... I created a custom report using module Forena. More details about this specific case can be found in comment #2 of issue 2337327. Obvious, I didn't really do any effort to beef up the look-and-feel of that report, like background, etc. I'd be happy to share the "source code" of that custom report, e.g. by adding it as an attachment to the same issue. Note that at the time that comment was added, it was rather a work-in-progress version of that report. And in the meantime forena has evolved to make such crosstab tables easier to develop. Today it even allows for charting with drill down links.

Be aware: I'm a co-maintainer of forena.

# Answer
> 1 votes
The Entity Delete Log module handles this by permanently tracking the following information when an entity is deleted:

```
Entity ID
Entity Type
Entity Bundle
Entity Author
Entity Title
Number of Revisions
Created Date
Deleted Date
User Who Deleted Entity

```

It works for core entity types in Drupal:

```
Comments
Files
Nodes
Taxonomy Terms
Taxonomy Vocabularies
Users

```

It has built in support for Views, so it's easy to build custom reports.

---
Tags: 7, nodes, log-messages
---