# Question
Title: Referencing a referenced entity's fields on a form
I'm setting up a contact form and would like to implement the following functionality:

* On my form I currently have an entity reference field that references the content type 'Home Team' using a select list.
* I would like to add another field to my form that populates with a select list of field data based on the content that is selected in the above entity reference field.

To help explain, each 'Home Team' has a field called 'home games' that is a list of text in the format 'Team Name - Date'.

I'd like it to be so that when a user chooses a team from the first select list, the second select list is then populated with that team's home games.

I think that the answer might be by using the Field Reference module, however I'm not sure how to implement what I am needing to do.

# Answer
You can use DFV - Dependent Field Values. It's a great module and does exactly what you're asking

The module's page says:

> This modules enables site admins and developers to make the allowed values of a field depend on another proviously selected field's value.
>
> You can use views with arguments to let views return the allowed values for a dependent field.

I'm using it myself, it's quite simple to use: you create a view of type Dependent Field Value with a contextual filter, which in your case is the NID of the node in the first field, the team (remember to add the relevant relationship in the view's Relationships section).

Usually you'll want to add two fields to this view, e.g. the home game's NID and the home game's title. After adding the two fields, click on the settings of the dfv list format. Choose the home game's NID as the Key Field an the home game's title as the Title Field. The view is done!

You didn't explain how is your contact form made, but I suppose that you use webform. So: you just have to go to the second field's settings, check the "Enable dfv settings", choose the parent field (team) and the view you just created.
> 2 votes

---
Tags: entities
---


title: Display comment titles only

text:
# Question
Title: Display comment titles only
Is there a way in Drupal 7 to display only the titles of node comments beneath the node (hopefully threaded), thus allowing users would click on title to see the full comment? This was essentially the behaviour in Drupal 6. In Drupal 7, I only see how to list the full comment title and body, or no comments at all.

Thanks for any suggestions.

# Answer
> 1 votes
Drupal 7 does not have this feature.

All you have to do is create your own javascript/jquery (.js) file and do something along these lines.

```
(function ($) {
     $(".commentbody").hide();
          $(".commenttitle").click(function() {
          $(this).parent().find(".commentbody").slideToggle();
          });

})(jQuery);

```

Here is an example JS FIDDLE

---
Tags: comments
---


# Question
Title: Programmatically added taxonomy terms not being indexed
I'm assigning taxonomy terms to an entity (user) like this:

`$drupalUser->taxonomy_vocabulary_6 = array('und' => array(0 => array('tid' => _findorcreate_tid($eecid, $arrUser[12]))));`

`_findorcreate_tid` finds, or creates a new tid, within the supplied vocabulary. This function is working correctly. **$eecid** is the vocabulary ID. **$arrUser** is some user data imported from a CSV.

When viewing the user object, the correct term name and ID is displayed, but viewing the term's "contents" (at a URL like http://localhost/taxonomy/term/1061), I'm told there is no content.

My very amateur poking around leads me to believe that the taxonomy\_index table is not getting populated when I assign the terms in this manner.

I have tried to call `taxonomy_build_node_index($drupalUser);` after the user object is saved, but this has yielded no change (and I'm a bit unclear if that function only applies to nodes, or any entity).

**Is there a better way of assigning taxonomy terms to a user entity that would fix this?**

# Answer
You're correct. The core taxonomy module doesn't index or display entities other than nodes. `taxonomy_build_node_index()` is only for nodes.

It sounds like the solution you're looking for is Taxonomy Entity Index.

> The Taxonomy Entity Index module maintains a normalized index of all terms associated with a specific entity and revision. The core {taxonomy\_index} table only maintains its data for published nodes. This module maintains its data for all entity types (regardless of published or not) and also indexed by revision.

It also supports views integration so you should be able to create a view of users who have been tagged with your taxonomy.
> 1 votes

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


# Question
Title: User picture not removed when deleting user in Drupal 7
After creating users with a picture programmatically, and deleting them afterwards, I found out that the pictures (files) were not removed.

I started digging into this problem and found out that this problem also occurs when just adding a user by the UI, uploading a picture and deleting the user.

The picture is not being removed. Also the file remains in the file\_usage and in the file\_managed tables. They're not marked for deletion, so I guess they will stay there forever. Is this a bug? Or am I missing something?

# Answer
if you really like to delete user profile picture on user delete event use this code in hook\_user\_delete($account).

```
// Load user by using user id
$user = user_load($uid);
// Get file id of profile photo
$fid = $user->picture->fid;
// Load the file object
$file = file_load($fid);
// delete profile photo from.
file_delete($file);
// Unset the image object (my case it's 'picture')
unset($user->picture);
// Save the user
user_save($user);

```

hope works for you
> 1 votes

# Answer
Reference : #3 I'd be interested in opinions on a couple of approaches to this:

**1.** Modify user.module user\_delete function to directly call file\_usage\_delete and file\_delete if there is a profile picture attached to the user account (which would solve this individual issue)

**2.** As there would appear to be the possibility that any files which belong to the user may not be deleted when the user is deleted via user\_delete\_multiple, would a better approach be to implement hook\_user\_delete in the file module (file\_user\_delete) so that the file module will respond to the user delete by deleting any files associated with them?

As an aside - and might need a separate issue, as far as I can see the code for user\_cancel applies the same to "Delete user and all their content" and "Delete user and assign their content to anonymous". Do we need to cover this scenario too?

Hope this help you well.
> 1 votes

---
Tags: users, files
---


# Question
Title: Display the content of particular content type in side a block?
I tried to create a `block` called `contact details`. I already created a `content type` called `contact`. I wanted to add the content of each contact content type in my custom block. I researched a lo abd I'm confused.

# Answer
> 0 votes
In `block_view` of your custom block write this code

```
$nids = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->fields('n', array('type'))
    ->condition('n.type', 'contact')
    ->execute()
    ->fetchCol();
$nodes = node_load_multiple($nids);

```

Loop `$nodes` with `foreach` and get the **fields** whatever you want.

# Answer
> 1 votes
1. Install and enable the Views module.
2. Create a view with 'Block' display.
3. Filter by content type 'contact'. You can also choose sort options, etc.
4. Go to the Blocks administration page at *Administration \> Structure \> Blocks*.
5. Enable the Views block.

# Answer
> 1 votes
So you can do some custom work to the output of those fields? I hope that's right.

So this is relatively easy depending in how you want to go about this.

Follow steps:

> 1. You've created your content type and added all of the fields that you want. I'm assuming you've also created some content already to test the next part.
> 2. You need to create a view that has a block display. See screenshot for an example. https://skitch.com/therealwebguy/8ksue/block-step-1
> 3. Set up your block view appropriately. See screenshot for more specific details for this: https://skitch.com/therealwebguy/8ksw9/block-step-2
> 4. If you refer to the screenshot provided in Step 3, you'll notice in the bottom right that I have highlighted the "Information" link for the Theme layer. Clicking this link will bring up a list of all of the .tpl files you can create for this view to target what you need. It has everything from the top-level view tpl to the output of a single field being rendered by the view. Choose the one that's best for you needs, copy the HTML provided and add it the view.tpl.php file you've chosen to use.

Lets recap:

> 1. We've create a content type and added fields to it.
> 2. We've added actual nodes of the new content type for testing.
> 3. We've created a new view which will provide a block display, showing us \> the field values of our content type that we want to show.
> 4. We've created a custom tpl override for the view of our choice to do some more customization at the theme level that best fits our needs.

The only thing left to do is to head over to your blocks administration and put the block where you want it.

Hope this help to solve your problem/doubt.

# Answer
> 0 votes
Your need to use core contact form and uses contact save to save and fetch contact detail. thats it.

---
Tags: blocks, nodes
---


# Question
Title: Localize nearest store to a zip code in Drupal 7
I just want to let the user enter a ZIP code, and return the nearest store from the database. I have read and I am trying Module Location + Gmap (for visual input), but I think that this module stores all data in a database. Wouldn't it be more reliable to go through a service like Google GeoCode or something? I would appreciate insights from people who has managed this problem before, as somehow I am confused with many different options available in the contributed modules.

# Answer
> 1 votes
Need to use set proxmity in views and Dependencies modules are Geolocation Field, Views.

# Answer
> 0 votes
I have managed to get working a version with modules Location + GMap, which was very primitive, because it only used ZIP code, and later I found the fantastic Google Store Locator module, which does exactly what I needed, finding the GPS coordinates for any human readable text address and displaying the stores (or points) in the map.

The only caveat is that for a correct install, I needed to use an old version of module GeoJSON (7.x-1.0-alpha2) and I also needed to install the following library and module, respectively (I didn't find in the documentation, but in the Status report page): markerclusterer library and Contextual Range Filter module.

---
Tags: 7, google-maps
---


# Question
Title: ViewsJSON module not working with Google Store Locator
I was wondering if anyone came with a solution for this. The Google Store Locator module is not working with ViewsJSON module. There seems to be an issue

I've installed the ViewJSON Alpha 4 and applied the patch but it doesn't work on my end.

Any suggestions?

# Answer
I have managed to get it working with version 7.x-1.0-alpha2 of module GeoJSON.

Please see my question and my own answer at Localize nearest store to a zip code in Drupal 7
> 0 votes

---
Tags: 7, google-maps
---


# Question
Title: How to add a placeholder to an exposed date filter form field?
This is the structure of a date field in my exposed form:

```
<input id="edit-date-filter-value-datepicker-popup-0" class="form-text hasDatepicker date-popup-init" type="text" maxlength="200" size="20" value="" name="date_filter[value][date]">

```

I added this code under

```
function bartik_form_views_exposed_form_alter(&$form, &$form_state) {}

```

to add place holder.

```
$form['date_filter']['#attributes']['placeholder'] = t('YYYY-MM-DD');

```

But place holder is not coming. Can anyone help?

# Answer
jQuery may be a solution.

```
jQuery(document).ready(function(){
 jQuery('#edit-date-filter-value-datepicker-popup-0').attr("placeholder", "placeholder to show");
});

```
> 3 votes

---
Tags: views, datetime
---


# Question
Title: Entity operations and redirect destination (using EntityListBuilder)
I have an entity collection page that's built with my own subclass of `EntityListBuilder`. My problem is that the operations links do not set a redirect destination, so after clicking e.g. on an edit link, it is hard for the user to find their way back to the listing.

Redirect destinations work fine with simple links. But I couldn't figure out an easy way how to tell `EntityBuilder::buildOperations()` to include the `destination` query string. Any suggestions?

# Answer
> 1 votes
`buildOperations` is to change the render array for the link wrapper.

The method you are looking for is `getOperations`. Just pick the operation you want and add the query string to the url.

---
Tags: entities, 8, redirection
---


title: Help with relations in views

text:
# Question
Title: Help with relations in views
Have been struggled with this problems for days and I wonder if someone could have a look at it? I have tried me sleepless to achieve a certain table in views between three content types which has relations between them, using entity reference. The biggest issue is that I can't wrap my head around how I should set up my relations.

Since this is driving me crazy, have I made this pdf that describes what I have now and what I'm trying to achieve.

http://themesh.se/problemDesc/problemdescription.pdf

Hope some of you have some spare time and if the simple answer is "This won't work" will that also be satisfying at the moment.

# Answer
To remove the rows that you annotated with "Duplicates", you could use the Views Distinct module. From its project page:

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Assuming that would indeed remove the duplicate rows, the "*What I get*" should match with "*What I try to achieve*". So with that the setup of your relationships like you already defined them should be OK also (I can't think of any other missing piece to complete your puzzle).
> 0 votes

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


# Question
Title: Is it possible to use theme_table on each key of array?
I know theme\_table only accepts rows when `$row=array();` I have an array like: **Array( \[0\] =\> 'one',  =\> 'two', )** Is it possible to have table rows as 'one', 'two', etc... **I mean, first row will be 'one', second row will be 'two'.**

**How can I achieve this?**

# Answer
> 0 votes
After few minutes, I realized it was so simple.

```
$rows[] = array('data' => array($row));

```

where $row wasn't array, it is array key.

---
Tags: theming
---


# Question
Title: Cant create View with Many to Many Relationship
I have a situation with three content types. (Simplified)

A Person is referenced in many Transactions, and a Transaction also has a reference to a Company. I.e. `Person -< Transactions >- Company`

Here the Transaction holds the entity reference to a Person, and a reference to a Company. I need to create a view that given a value from the Company content type, returns all the Person entities.

In SQL I would do something like this, to give me Persons who have had Transactions with a specific company:

```
  SELECT P.*
    FROM Person P
    JOIN Transaction T on T.PersonId = P.Id
    JOIN Company C on C.Id = T.CompanyId
    WHERE C.Name = 'Drupal Co.'

```

# Answer
> 1 votes
It's quite simple: Create a view which shows content of type Person (or users, if for Person you mean users).

Now let's say that Transaction has an Entity Reference field named field\_person and another one named field\_company.

In the view's Advanced section click on Add relationship, search for field\_student and check "A bridge to the Content entity that is referencing Content via field\_person" if Person as a node type or "A bridge to the Content entity that is referencing User via field\_person" if Person is a user. In the configuration window that pop ups check "Require this relationship" and save. You have just configured the first join.

Add another relationship. How that you have configured the first one, you can search for field\_company and check "A bridge to the Content entity that is referenced via field\_company". In the configuration window click on "Require this relationship" and check that the Relationship combobox has the first relationship selected. Now you have configured also the second join.

Finally create a Contextual filter. Search for "Content: Nid" and check it. In the configuration window, the Relationship combobox must have the second relationship selected. Choose what to do "When the filter value is NOT available" (this depends on what you want to do).

Done!

EDIT: I noticed just now that you search Company by name, not by NID. Just change the field in the contextual filter!

---
Tags: views, 8
---


# Question
Title: Drupal Webform Select 2 options instead of unlimited
I have a list of 150 products on my select a sample list on my webform. Customers are supposed to select only 2 products, not 3, 4, etc....

I chose "Multiple" so how can I have them select only 2 products from the list instead of 3 or more?

Thanks!

# Answer
You can do client-side checking for the number of items selected, and if greater than 2, you can add your desired behavior, such as clearing the selections and/or alerting the user.

Example with jQuery:

```
var selectID = '#your-select-ID'; // change this to your selector
$(selectID).change(function () {
  if ($(selectID + " option:selected").length > 2) {
      $(selectID).val([]); // clear the selections
      // do other stuff if you want, like alert('Can only select 2 options');
  }
});

```
> 1 votes

---
Tags: webforms
---


# Question
Title: How to show the data returned via hook_views_data() in a page?
I have hook\_views\_api as follows :

```
function hook_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'faq') . '/views',
  );
}

```

and i have the hook\_views\_data() function in views folder as follows :

```
function hook_views_data() {
  // faq_questions table.
  $data['faq_questions']['table']['group'] = t('FAQ');
  $data['faq_questions']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );
  $data['faq_questions']['question'] = array(
    'title' => t('FAQ short question'),
    'help' => t('The short question text for FAQ nodes.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );
  $data['faq_questions']['detailed_question'] = array(
    'title' => t('FAQ detailed question'),
    'help' => t('The long question text for FAQ nodes.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );

  return $data;
}

```

How can i show the results returned by the hook\_views\_data() `in a page` ?

# Answer
> 0 votes
You should be able to print the output to the page using print\_r. Just add `print_r($data)` at the end of the function, before your return statement.

If you're just printing this data out so you can take a look at it for debugging purposes than you might want to use error\_log instead. For `error_log` just add `error_log(print_r($data, 1))` at the end of your function, before the return statement.

# Answer
> 0 votes
you can use handlers to theme output of data. Views is all about firing queries. As you have defined base table in hook\_view\_data(), it's easy to query the table and render results to template.

For other approaches and good understanding of API, follow these(1)(2) tutorials:

---
Tags: 6, views
---


title: How drupal handles block['content']?

text:
# Question
Title: How drupal handles block['content']?
I am trying to customize a module(quicktabs) for my need. In the *hook\_block\_view*, the `block['content']` contains an associative array of the contents. Is there an existing drupal call that renders the associative array in *block\['content'\]*?

# Answer
Yes: `drupal_render()`

> Renders HTML given a structured array tree.
>
> Recursively iterates over each of the array elements, generating HTML code.

There's much more explanation, and examples, on the docs page.

I'd advise also reading through Render Arrays in Drupal 7 to get a better idea of what that array represents.
> 1 votes

---
Tags: blocks
---


# Question
Title: How to get a node content programmatically?
I am writing a module, in which I am required to display contents from multiple nodes. Using the configs I save, I will get the node id's in `hook_block_view`. Using that is there a way to get the contents of the particular node, so that I can manipulate on that?

# Answer
Assuming by 'contents' you mean the HTML for the node in a particular view mode, you're looking for `node_view()`:

> Generates an array for rendering the given node.

e.g.

```
$node = node_load(1);
$view = node_view($node, 'full');
$rendered = drupal_render($view);

```
> 2 votes

---
Tags: nodes, users
---


title: Views and Workflow module

text:
# Question
Title: Views and Workflow module
I am attempting to create a view that displays Content by it's current Workflow state.

I cannot see how this is possible using the Views module combined with the Workflow module.

Can you advise?

# Answer
> 5 votes
Have you enabled the "Workflow Views" module (in the workflow 'module')? With it you get a example "workflow summary" view with a list of all content with its current state, title and type of the content. In views you get access to a few new fields like "current state", "previous state", ...

# Answer
> 0 votes
If you have also enabled the node access module, make sure that in the author settings per content type administration page you set the node author to be able to *view* and *edit*

Other wise it will not show in the workflow view.

---
Tags: views, workflows
---


# Question
Title: Social Field Module: Icons not showing up in options
Trying to use Social Field Module for general user Profile. Followed through module text but no icons appear to show up for the module in either the Field itself or from an End-user logged in perspective. Installed Font Icon Module also.

Anyone any ideas why this is? Module seems quite simple, but maybe I'm missing something or it's lost in translation somewhere.

# Answer
Just copy "font" and "Css" folder in your activated theme and if it ask to merge just allow them to merge and check further.

Hope this helps you.

Thanks!
> 0 votes

# Answer
I am working with an omega base theme and here is how I fixed it:

1. Copy the font folder with its files into your own theme folder, so it is located at sites/all/themes/YOURTHEME/font/
2. Create a \_fontello.scss file in one of your sass directories, I put mine in base. So your path is sites/all/themes/YOURTHEME/sass/base/\_fontello.scss
3. Copy the css code from the fontello.css located in the css folder and paste it in the \_fontello.scss file
4. Don't forget to save and clear your cache

note: You will also have to do this in your admin theme because they use separate templates and stylesheets. To make it easy, just paste the css code in a style.css file.

Hope this helps
> 0 votes

---
Tags: 7
---


# Question
Title: entity_load failure: Adding revision capability to entity with existing data and unticking "create new revision" still creates a revision
I am having trouble with entity\_load returning an empty array on an entity api custom entity which previously was fine. The only change I've made is to add revision support which apart from creating the revision table etc. has also created a revision ID column in my custom entity table and filled this with `NULL` by default.

In troubleshooting why this is and trying to pin down if the revision is causing my problem, I've come across something which seems peculiar to me: creating an Article and unchecking `"create new revision"` still creates a revision.

My custom entity revision table is currently completely empty and I've been debugging and stepping through the code within `entity_load` but I cannot see where the problem is.

Where is my problem with the entity\_load? Is the new revision being created despite unchecking the option a localised problem?

# Answer
So I experimented and contrary to what I perceived, saving a node (as an example of an entity) even without "save a new revision" checked, *still saves a revision...*

So somewhere in the confusing bowels of the entity loading procedure it was diving through Drupal-shaped rabbit holes and trying to load revision information because it noted that the custom entity was revision enabled (where I enabled it in `hook_entity_property_info`). Because I'd only added the revision capability after using the entity there was none. So I had to do some SQL work.

Firstly I selected all information in the original table into the new table. In doing so, the auto-increment setup on the revision\_id column populated the revision\_id column in the revision\_id with unique incremental values.

Secondly I did a big ol' looping thing to get all the revision\_ids from the revision table and one-by-one put them in the original table. Details of that query are here after I had a little bit of trouble, but it might help someone else out.

Now it's working.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Best way to store custom commerce pane form data as part of an order?
I have a custom checkout pane that only loads if there is a product of type 'Event' in the cart. For each product of type 'Event' in the cart, the pane prints out two custom fields: 'Ticketholder's Name' and 'Ticketholder's Email'. Further depend on the event there are upto another 8 extra fields such as 'Dietary Requirements' and 'Arrival Time'.

In the past, if I have a custom value that I want sent through with the order, I have created a custom field within the order fields, and then set the value in the following way:

```
$order->field_my_custom_field['und']['0']['value'] = 'my custom value';
commerce_order_save($order);

```

Now this seems fine for custom values that need to be set for all orders. However with this custom checkout pane, these custom fields only appear for 'events'. Further it is dynamic, so if there are 2 tickets for the same event (i.e one product of quantity 2) in the cart, it will need to store Ticketholder's Name & Email etc. for both ticket 1 and ticket 2.

So is there a more appropriate way to set the custom values and display them when you go to *Store \> Orders \> View Order*? Can I programmatically attach the custom fields to the order?

In the past I have looked at adding custom line items to checkout to store this kind of data but have been unsuccessful in getting them to display within *Store \> Orders \> View Order*. Further the same event, with quantity 2 will just be one line item in the cart so I'm not sure how you would attach the data for both ticketholders in this way.

What is the best way to store this data as part of the Order, so that it is accessible at Store \> Orders \> View Order?

Thanks for your help!

# Answer
> 1 votes
I have had the same issue for some time with field collections and simply switching the panes on and off in the order entity was not doing the trick. I ended up being able to work up a solution using order types. http://drupal.org/project/commerce\_order\_types

In addition I want to mention that we used the following patch: http://drupal.org/node/1887812 so that commerce could recognize panes from different order types. At this point your already there, its a simple process of switching order types and subsequent panes based on the order type.

# Answer
> 1 votes
I needed to receive an optional phone number during checkout, but I didn't think the phone number field really belonged in the **Billing Information** pane. As you can see in the image below, I wanted the phone number field to show up below the email address in the **Account Information** pane, which I renamed "Contact Information".

Commerce User Profile Pane, Commerce Fieldgroup Panes, and Address Field Phone were all too feature-rich for my needs. I just wanted to simply add one field to the Account Information pane, validate and save it to the order, thereby persisting it through the checkout.

In my case, the simplest solution was to save the phone number in the `$order->data` array by adding a form field to the checkout form using `hook_form_alter`. Before saving it into the `$order->data` array, I do some validation stripping and formatting on future display.

Add phone number field below email address field:

Show phone number input with invalid characters that will be stripped out:

Successfully stripped invalid characters and show the saved phone number formatted for display:

**Here's the code to make this happen:**

```
/**
 * Implements hook_form_alter
 * Alter the checkout and review forms
 */
function example_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'commerce_checkout_form_checkout') {
    //Changing some titles and adding Bootstrap wrapper classes
    $form['account']['#title'] = t('Contact Information');
    $form['account']['login']['mail']['#title'] = t('Email Address');
    $form['account']['login']['mail']['#prefix'] = '<div class="row"><div class="col-xs-12 col-sm-5">';
    $form['account']['login']['mail']['#suffix'] = '</div></div>';
    $form['account']['login']['mail_confirm']['#title'] = t('Confirm Email Address');
    $form['account']['login']['mail_confirm']['#description'] = t('<small>Please re-enter your email address.</small>');
    $form['account']['login']['mail_confirm']['#prefix'] = '<div class="row"><div class="col-xs-12 col-sm-5">';
    $form['account']['login']['mail_confirm']['#suffix'] = '</div></div>';

    //add a phone number textfield to the account login array
    $form['account']['login']['phone_number'] = array(
      '#type' => 'textfield',
      '#title' => t('Phone Number (Optional)'),
      '#size' => 15,
      '#attributes' => array('class' => array('phone-number')),
      '#prefix' => '<div class="row"><div class="col-xs-12 col-sm-5">',
      '#suffix' => '</div></div>',
    );

    //load the order from the form state
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);

      $order = $form_state['order'];

      //prefill the phone number field if it's already been set in the data array
      if (!empty($order->data['phone_number'])) {
        $form['account']['login']['phone_number']['#default_value'] = _format_phone_number($order->data['phone_number']);
      }
    }

    //add a custom submit callback function to save the phone number to the order data array
    array_unshift($form['buttons']['continue']['#submit'], "_example_commerce_order_account_pane_checkout_form_alter_submit");
  }

  //show the phone number in the account info section of the review screen
  if ($form_id == 'commerce_checkout_form_review') {
    //load the order from the form state
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);

      $order = $form_state['order'];

      //append the phone number to the account info html. there's probably a better way to do this...
      if (!empty($order->data['phone_number'])) {
        $form['checkout_review']['review']['#data']['account']['data'] .= '<div class="form-item form-type-item"><label>Phone Number: </label> '._format_phone_number($order->data['phone_number']).'</div>';
      }
    }
  }
}

/**
 * Custom Account pane: checkout form submission callback.
 */
function _example_commerce_order_account_pane_checkout_form_alter_submit($form, &$form_state) {
  if (!empty($form_state['values']['account'])) {
    $pane_values = $form_state['values']['account'];

    // If the user is editing an order, load a fresh copy to merge changes into.
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);
    }

    $order = $form_state['order'];

    if (!empty($pane_values['login']['phone_number'])) {
      $order->data['phone_number'] = _strip_chars_in_phone_number($pane_values['login']['phone_number']);
    }
    else {
      $order->data['phone_number'] = '';
    }

    //don't cut a new revision, just save phone number
    $order->revision = FALSE;
    commerce_order_save($order);
  }
}

/**
 * Custom utility function to strip invalid characters from phone number input
 * leaving only digits
 * stripping a leading 1
 * substring first 10 digits
 */
function _strip_chars_in_phone_number($phone) {
  $strPhoneDigits = '';

  if (isset($phone) && !empty($phone)) {
    $strPhoneDigits = preg_replace("/[\D]/", "", $phone);
    $strPhoneDigits = preg_replace("/^1/", "", $strPhoneDigits);
    $strPhoneDigits = substr($strPhoneDigits, 0, 10);
  }

  return $strPhoneDigits;
}

/**
 * Custom utility function to format a phone number for display
 */
function _format_phone_number($phone) {
  $strFormattedPhone = '';

  if (isset($phone) && !empty($phone)) {
    if (strlen($phone) == 7) {
      $strFormattedPhone = preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
    }
    elseif (strlen($phone) == 10) {
      $strFormattedPhone = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
    }
    else {
      $strFormattedPhone = $phone;
    }
  }

  return $strFormattedPhone;
}

```

**Now to answer the rest of your question about showing this custom data on Store \> Orders \> View Order:**

Sometimes there's data I want to quickly see on the Store \> Orders view itself without having to go into each order. To do this, I edit the view at `admin/structure/views/view/commerce_backoffice_orders/edit/admin_page`. You need Views PHP to be able to add Global: PHP fields to your view. Once you have that module enabled, you can add the following fields to your view. You don't necessarily need to add a field for the entire Order object, but it is helpful if you're going to be adding multiple fields that use the Order object. Otherwise, each field will have to call `commerce_order_load`, when you could only do it one time and reference that field from other fields later on.

There are 2 key parts to this. In the **Value code** section, you must return some value that you want to use or display. You can see that I'm using the `$row->order_id` value made available to me by an existing field on this view. In the **Output code** section, it's usually best just to print the `$value` variable made available to you. This `$value` variable contains the value of the `$phoneNumber` variable I returned in the **Value code** section.

That's it! That's all there is to it.

But to get this info to show up on Store \> Orders \> Edit Order, there are a couple different ways to do it and a couple different places you can show it. I chose to display the phone number data as an additional settings tabbed fieldset, down by the Order Status, User Information, and Order History tabs.

Here's the code to do this:

```
/**
 * Implements hook_form_alter
 */
function example_form_alter(&$form, &$form_state, $form_id) {
//Add phone number field to the additional settings tab of the admin edit order form
  if ($form_id == 'commerce_order_ui_order_form') {
    $form['phone_number'] = array(
      '#type' => 'fieldset',
      '#title' => t('Phone Number'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'additional_settings',
      '#weight' => 20,
    );
    $form['phone_number']['number'] = array(
      '#type' => 'textfield',
      '#title' => t('Phone Number'),
      '#default_value' => (isset($form['#entity']->data['phone_number']) && !empty($form['#entity']->data['phone_number'])) ? $form['#entity']->data['phone_number'] : '',
    );
  }
}

```

---
Tags: 7, commerce
---


title: Menu link Translation

text:
# Question
Title: Menu link Translation
I'm using i18n and submodules to translate an English Language site to Spanish. I'm also using Automatic path aliases.

The issue is that menu links are directly to the node: `node/42.` When in the Spanish part of the site, `/es/` the links take me to `es/node/42`, not to the aliased url.

The best answer I've seen is this "Afterwards, you can arrange your menu links as you need them. I use parent/child URL aliases based on menu hierarchy, so I make a mirror menu tree." I don't know what he means, but it sounds like what I'm trying to do.

# Answer
Your problem might be because of the "language detection" configuration.

So check this configuration via *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.
> 0 votes

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


# Question
Title: When offloading a hook implementation to another function, which function should be documented as "Implements..."?
Can a function like `_menu_block_block_configure()` be documented as *Implements hook\_block\_configure()*?

It initially threw me off to see an internal function (with underscore prefix) documented as a hook implementation, but if the actual work is being done here, then there is some sense to it.

Is this the proper way to document it?

# Answer
TL;DR: Yes, it's fine and widespread too!

It might look kind of unorthodox, but it's just offloading the bulk of the hook implementation to an include to keep the main .module file smaller.

A lot of other contributed modules do this too, for example the *Display Suite* module, the Views module, and a bunch of others too.
> 4 votes

---
Tags: 7, hooks
---


# Question
Title: Achieve single node field edit to have different values for each user?
I am trying to create lets say and activity node which allow each user to insert a different value without having to create a node. for example:

I created activity1 node, and then I will allow user a to edit activity1 and insert value "a", and user b can also edit activity1 and insert value "b", and both can see their own activity1(the same node) but with different values for each user.

is this achieveable? as I tried using uniquefields module and that is the one I want for this case.

look forward for some response!

thank you

# Answer
As you described it, it is not possible with core Drupal's field system. While you can create a node editable by many users with a multivalue field, the field (and its values) do not have property of ownership. Thus, your requirement to see different values for different users would not work.

There are alternative ways to achieve this. One path is to add 2 fields to the user profile.

* **Activity**: an entity reference to your activity node.
* **Value**: the user's field value you want to capture.

If the values are inherent single property of a user, you can add them directly to the user profile and use a Field Group to present it as combination of fields for the user to enter.

If the user can have many different **Activity** & **Value** combinations, you could use either use something like Field Collection or ECK/Inline Entity Form to present an embedded form in the user profile where users can add many different Activity/Value combinations.
> 1 votes

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


# Question
Title: Emailing a bunch of users selected from a user reference field
I have a node that lets me select multiple users in a user reference field. I also have a rules setup to email the author when someone makes a comment on that node.

Now, how do I also email the users I selected in the user reference field when someone makes a comment? Would rules work in this scenario or something else?

# Answer
> 2 votes
You should be able to add another "Send email" action to your rule, but place it inside a Rules loop so it can iterate over the multiple values in the user reference field. You may need to first add an "Entity has field" condition to get access to these values.

---
Tags: 7, rules, notifications, users
---


# Question
Title: Why Views Slideshow JCarousel plugin isn't available on view format settings?
I've installed:

* Views Slideshow
* Views Slideshow Cycle
* Views Slideshow Carousel

All required libraries are available. Status reports page is green.

I want to create slideshow view. I choose slideshow format, but on settings I have only Cycle as available slideshow type.

What can be wrong?

# Answer
> 0 votes
There is nothing wrong. jQuery Cycle is the default library used by the Views Slideshow Cycle module.

Look instead at "Widgets" on the format settings screen. The relevant configuration options will appear by selecting "Pager" under either *Top Widgets* or *Bottom widgets*.

From the Views Slideshow JCarousel project page:

> Currently provides a JCarousel **pager widget**.

and

> Under the Format heading, click "format" and select "slideshow". You should now be able to select and configure your jcarousel slideshow. Pager options are on this configuration screen, not under views "pager settings". To decide where you want your pager to go, you can tick the pager widget checkbox beneath the area you wish to show it. your choices are "top" or "bottom" of carousel.

**Note:** If using Views Slideshow Cycle, you will need to download the jQuery Cycle plugin.

---
Tags: 7, views
---


# Question
Title: How to hide Profile2 entity fron user view?
I have a few profile2 types. Profile2 entity is always rendered on standard user view page.

How can I hide this entity? I know I can hide all fields in Manage Display tab, but I wondering if there is a way quicker way.

# Answer
> 1 votes
At admin/people/permissions you can configure what user roles are allowed access to the Profile 2 profiles on a per-profile-type basis. So if you're alright with letting admin users see the profiles, you can hide them for everyone else with the permission controls.

# Answer
> 1 votes
Check out these two modules.
1. https://www.drupal.org/project/view\_profiles\_perms

> This module provides permissions to view user profiles depending on what roles the profile requested to be viewed has.
>
> Use case example: If you want all users to only be able to access profiles of users with the role 'blogger', uncheck 'access user profiles' and check 'access blogger profiles' for anonymous and authenticated users.

2. https://www.drupal.org/project/field\_permissions

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> Features
>
> Enable field permissions on any entity, not just nodes. Role-based field permissions allowing different viewing patterned based on what access the user has. Author-level permissions allow viewing and editing of fields based on who the entity owner is. Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

---
Tags: 7, users
---


# Question
Title: How to group taxonomy and node flags together?
I have 2 view block displays. One view displays flagged nodes and other displays flagged taxonomies. I need to print latest 8 flagged contents (nodes + taxonomy) in a single display sorted by title or term name, in ascending order.

Any suggestions about how to achieve this?

# Answer
> 0 votes
You could use the Views Contextual Filters OR module. Excerpt from its project page:

> ... provides a views plugin which modify query to support OR conditions for contextual filters.

Create a view using 2 contextual filters (=both of the filters you already have for your 2 views), and combine them with an **OR**.

---
Tags: views, flags
---


# Question
Title: What does the message "hook_flag_access: ignore" mean, and how do I turn it off?
I currently have the flag module enabled, and I have placed a simple flag on a node content type. The flag works fine, but I'm getting a Drupal message / notification in green that says "hook\_flag\_access: ignore" when the node is viewed.

It appears to be called by sites/all/modules/flag/tests/flagaccesstest/flagaccesstest.module

What does this message mean, and how can I fix / disable?

I'm using flag 7.x-3.1 on Drupal 7

Thanks, Steven

# Answer
Sounds like you need to disable the flagaccesstest module.

The problem is, in *flagaccesstest.info* the module declares

```
hidden = TRUE

```

So, it doesn't show up in Drupal module admin.

You could probably still disable it with Drush

```
drush dis flagaccesstest

```

or even (last resort) SQL:

```
UPDATE system SET status = 0 WHERE name = 'flagaccesstest';

```

Alternatively, in flagaccesstest you could comment out

```
;hidden = TRUE

```

and then disable the module from Drupal module admin UI.
> 1 votes

# Answer
You could use the Disable Messages module to disable that "*hook\_flag\_access: ignore*" message. Here is a quote from its project page:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

More specifically, you could use its "regular expressions" feature. But you have to make sure that you use a regular expression that "catches" the error message you want to intercept, as explained also in the Community documentation.

Below "*Tip: Keep it simple.*" on that page, there is a great sample.

So assume you want to suppress an error message containing this error:

> hook\_flag\_access: ignore

In this case a possible regular expression should look something like so:

```
.+hook_flag_access:.+ignore.+

```
> 0 votes

---
Tags: flags
---


# Question
Title: Is there a module for using Google Analytics to display popular content?
I'm actually looking to make a simplier version of the Radioactivity module.

I wonder if there are any modules out there that are using Google statistics to display content.

# Answer
> 4 votes
Google Analytics Statistics has integration with views...

Project page says

> This module provides views integration for the Google Analytics Data Export API.
>
> This allows you to use Google Analytics directly through views to do things like Most Popular, Most Read ect. You can combine the statistics to create interesting results.

# Answer
> 2 votes
You can consider using Drupal Most Popular Module

> The module is pre-packaged with several services including: Google Analytics - Most Viewed pages
>
> 1. Create any number of Most Popular widget blocks, displaying any combination of services and intervals.
> 2. Customize the maximum number of results to display for each block.
> 3. Show or hide the number of page hits for most popular items.

# Answer
> 2 votes
There's a module called Google Analytics Counter. This is from its project page:

> *Views integration with any of the storage tables. If using the module's table, to add the counter values for nodes to your view you just need to add field "Pageview Total". Sorting and filtering by the counter values works as well. **This for example allows you to show nodes sorted by their popularity!***.

Here you can learn how to configure it.

---
Tags: google-analytics
---


# Question
Title: How to find "next day date" (xx/xx/xx 00:00:00) from a given date & time value in Rules?
I'm trying to figure out how to find the next day date (xx/xx/xx 00:00:00) from the given date&time value in rules without the use of PHP filter module. Played with offset already - couldn't get the needed result.

The idea is to set up scheduled task in Rules that will take the date & time value from a node field#1 and change the field#2 on that node at midnight of the next day.

**EDITED:** To simplify: if my date field = 07/30/15 05:00:00 how do I schedule task at 07/31/15 00:00:00 without the use of PHP filter.

Any ideas are greatly appreciated.

# Answer
Let's see my example.

**First**: I created *content type* with two date fields: *date1* and *date2*

**Second**: I created *rule*

1. Create Action 'Add variable' to store first date field value in your variable
2. Create Action 'Set data value' and choose your second date field as Data and your variable name as Value
3. Create Action 'Set data value' and choose your second date field as Data and don't "Switch to data selector", simply set "+1 day midnight" as Value

What's the point: when you r creating 'Set data value' action and choosing Date type you can see next description under Value field in form:

> The date in GMT. You may enter a fixed time (like 2015-08-16 14:05:10) or any other values in GMT known by the PHP strtotime() function (like "+1 day"). Relative dates like "+1 day" or "now" relate to the evaluation time.

If you google strtotime() php function you can simply understand what goes on.

"+1 day midinight":

* "+" means add
* "day" means what to add
* "midnight" means "The time is set to 00:00:00"
> 2 votes

---
Tags: rules, datetime
---


# Question
Title: Drupal.behaviors function can't detect Views object when user is Anonymous
Goals:
1. have a button in a View that refreshes that View via AJAX on click event.
2. Load refresh script only on pages that have View named "my\_view".

I was able to achieve both of the following with the code shown below.

template.php

```
function mytheme_preprocess_views_view(&$variables) {
  $view = &$variables['view'];
  // Make sure it's the correct view
  if ($view->name == 'products_left_in_stock') {  //EDITED
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/views-refresh.js');
  }
}

```

viewsrefresh.js

```
(function ($) {
    Drupal.behaviors.myViewsRefresh = {
    attach: function( context , settings) {

        var viewName = 'products_left_in_stock';

        // View is Ajax enabled,
        // and is available as a property of the Drupal object
        // like so...
        var instances = Drupal.views.instances;
        var targetedView;

        // iterate thru the various
        // views instances name to find your views
        $.each( instances , function getInstance( index, element){
                    if(element.settings.view_name == viewName ){
                            targetedView = '.view-dom-id-' + element.settings.view_dom_id;
                    }
        });

        // Define your button click here...
        $('.viewsrefreshbtn').click( function(){
                if(typeof targetedView !== 'undefined'){
                    $(targetedView).trigger('RefreshView');
                    console.log ('Clicked refresh btn on view. View Refreshed');
                }
                else {console.log ('Can\'t find viewName on this page');}
        });
    }
}
})(jQuery);

```

refresh button added to Views footer in Global Text

```
<div class="viewsrefreshbtn">refresh</div>

```

**ISSUE IS:** Refresh button works only for logged in users. When Anonymous user clicks Refresh button - following line from viewsrefresh.js executes

```
else {console.log ('Can\'t find viewName on this page');}

```

and nothing else happens. Targeted View is present on a page and markup generated for that view is exactly the same as for logged in users. Seems like my function can not find the view when user is not logged in.

**QUESTION:** How can I make this function to detect targeted view when the user is not logged in? Am I missing something fundamental?

I understand this is a lengthy question. Greatly appreciate any insight on this if anybody has time to spare. thanks

# Answer
> 2 votes
I found that solution that works for me even under anonym. **Stars - changes**

```
(function ($) {
    Drupal.behaviors.myViewsRefresh = {
    attach: function( context , settings) {

        **var viewName = 'ajax_test';**

        // View is Ajax enabled,
        // and is available as a property of the Drupal object
        // like so...
        **var instances = settings.views.ajaxViews;**
        var targetedView;

        // iterate thru the various
        // views instances name to find your views
        $.each( instances , function getInstance( index, element){
                    if(**element.view_name** == viewName ){
                            targetedView = '.view-dom-id-' + **element.view_dom_id**;
                    }
        });

        // Define your button click here...
        $('.viewsrefreshbtn').click( function(){
                if(typeof targetedView !== 'undefined'){
                    $(targetedView).trigger('RefreshView');
                    console.log ('Clicked refresh btn on view. View Refreshed');
                }
                else {console.log ('Can\'t find viewName on this page');}
        });
    }
}
})(jQuery);

```

---
Tags: views, ajax, javascript
---


# Question
Title: How can I theme an image inside a field formatter
I'm trying to change the output of an image field so that I can display it using a Javascript image gallery. I have the basic field formatter set up, but I'm having trouble finding the correct place to override the theme that displays the `<img>` tag itself.

I'm overriding the viewElements function of the core ImageFormatter:

```
class ImageGalleryFormatter extends ImageFormatter {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = parent::viewElements($items);
    foreach ($elements as &$element) {
      $element['#theme'] = 'imagegallery_format';
    }

    $elements['#attached']['library'][] = 'imagegallery_formatter/light-gallery';
    return $elements;
  }

}

```

There I can set my custom Twig theme for each element, but that theme only writes the stuff directly around the `<img>` tag, not the tag itself. The theme provides access to an `{{ image }}` variable that renders the actual image. I tried accessing the variables inside the image like `{{ image.uri }}`, but that didn't work. I know the information I need is in there as I dumped the image variable in Twig and can see the array, but I can't access it from here.

From the Twig debug output I know that `'core/themes/classy/templates/field/image.html.twig'` is the theme I need to override, but I can't find a way to do that from my module. I read the source of the core ImageFormatter viewElements function, but I don't see the image variable there and don't understand how I can modify it.

How can I override the theme that renders the `<img>` tag of an image field in my field formatter?

# Answer
> 4 votes
I'm no expert on field formatters in D8, but are you opposed to using a preprocessor? If not, have a look at template\_preprocess\_image\_formatter. It looks like that is where you would prepare your own variables for use in the image formatter template. Cheers -

---
Tags: media, 8
---


# Question
Title: Synchronous XMLHttpRequest on the main thread is deprecated error at the end of ajax call
I'm a developer on a freelancing site (the only one actually) and I'm trying to allow anonymous users to bid on a project too. For this reason, I have the following code to check whether the username the anonymous user typed exists in the database, and show them a warning if it does. Now, everything works great, except that if the username exists in the database, I get the error at the end of the post and we can't check again because all Javascript executing is halted. What am I missing?

```
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      $form['submitted']['kullanici_adi']['#ajax'] = array(
        'wrapper' => 'webform-client-form',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'blur',
        'async' => 'false',
        'callback' => '_tubitekuz_check_username',
      );
      break;
    default:
      break;
  }
}

function _tubitekuz_check_username($form, &$form_state) {
  $parents = $form_state['triggering_element']['#array_parents'];
  array_pop($parents);
  $element = &drupal_array_get_nested_value($form, $parents);
  $exists = FALSE;
  $username = $form_state['values']['submitted']['kullanici_adi'];
  if (!empty($username)) {
    $exists = user_load_by_name($username);
  }
  if ($exists) {
    form_error($element, 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
    $error_selector = '.webform-client-form';
    $commands[] = ajax_command_replace($error_selector, theme('status_messages').drupal_render($form));
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

```

**The error**

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

# Answer
> 0 votes
I at least found a solution. What I did was add the below again to my webform's tpl file, because that was the one which had stopped working.

```
$(".messages").on("click", function() {
  $(this).hide();
});

```

---
Tags: ajax, forms
---


# Question
Title: Is this possible to copy Views fields declarations to another view?
Use case:

We have a page with a lot of complicated Views generating a lot of queries. There is a way to do it in more efficient way but this needs a lot of changes in Views or even creating different views, similar in displays field declarations.

Is there any way to copy fields declarations between those views?

# Answer
> 1 votes
Try export view and look in export's code

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


# Question
Title: How to add another filter to Scald search?
I have added new field to the Scald Image atom `admin/structure/scald`which is called description and it is text area multiple rows. Now I want to have this field in the search to be shown at the below screen shot.

I tried to edit the field by checking `MEE Enabled` but I could not get it in the search.

# Answer
The search is provided by a View called Scald Atoms. Add the filters you want to that view.
> 1 votes

---
Tags: 7, scald
---


# Question
Title: Write all PHP errors, warnings and notices to error_log
Drupal catches PHP warnings and notices to log them via dblog or syslog. As a result, there are two places to monitor for PHP errors (with the watchdog UI not well suited to cater for any large number of notices).

Is it possible to prevent this behavior and have ALL php errors be logged to the error\_log defined in the php config?

# Answer
For that, you will need to implement the hook\_watchdog to make calls to the error\_log() function.

You could as example one of the places where is implemented, that is the syslog\_watchdog. Instead of use the openlog() and syslog() function, you will use the error\_log().
> 3 votes

# Answer
Rudimentary code example for the solution provided by @gerzenstl

```
/**
 * Implements hook_watchdog()
 */
function MYMODULE_watchdog(array $log_entry) {

  if($log_entry['type'] == 'php') {

    $output = format_string($log_entry['message'], $log_entry['variables']);
    $output =  strip_tags($output);
    error_log($output);

  }

}

```
> 1 votes

# Answer
Got here when googling for the same. I want watchdogs go to webserver logging, since I use Docker. After checking @gerzenstl links, I tried again looking if someone already coded it and finally found a module: https://www.drupal.org/project/logging\_alerts

The 'errorlog' submodule does exactly this. Overall, all the modules are very complete and provide other useful goodies. Solved this without coding!
> 0 votes

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


# Question
Title: Overriding nodes of a certain type with a view
I'm using a single view to display *some* nodes on my site, and I can't figure out how to get it to only override the three content types I want (retreat, location, and teacher) but not all of them. In the contextual filter I specified validation by those types but it seems that's just making it do nothing on nodes of other content types so their content doesn't get shown at all.

I suspect the problem is either in the contextual filter settings and/or the fact that I specified the view's path as /node/% so as to override the normal display.

Attached are my view and the full contextual filter settings. Thanks for any advice!

# Answer
> 2 votes
After brainstorming with a friend, I came up with a wonderfully simple solution. I simply created a **block** display to my view, and then restricted that block to only display on nodes of the selected type.

I also changed the default display settings of those content types to not show any of the fields. I also could have hidden that content via CSS or other methods.

# Answer
> 3 votes
You cannot do this because your view has now taken over the path "node/%", which is all node pages.

This means that hitting any node page will load your view, not the default Drupal node page and when your view loads, the contextual filter will either show the node if it is one of your 3 selected types, or it will display no results found for any other node type.

You can only override like this if you want to override the same for all nodes.

There are alternatives though, like (in no particular order - an there are almost certainly more ways not listed here):

---
Tags: 7, nodes, views
---


# Question
Title: Where is source code of advanced search form?
I can't find where in Drupal 7 search module is the source code of advanced search form that appears on search result site.

Below is code of `search_form`. You can see there is `basic` key in renderable array. In output of `dpm` is even `advanced` key, but i can't find from where it comes.

It should be probably somewhere in search module, but it is not big module and i checked it last 4 hours and can't find it.

```
function search_form($form, &$form_state, $action = '', $keys = '', $module = NULL, $prompt = NULL) {
  $module_info = FALSE;
  if (!$module) {
    $module_info = search_get_default_module_info();
  }
  else {
    $info = search_get_info();
    $module_info = isset($info[$module]) ? $info[$module] : FALSE;
  }

  // Sanity check.
  if (!$module_info) {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
    return $form;
  }

  if (!$action) {
    $action = 'search/' . $module_info['path'];
  }
  if (!isset($prompt)) {
    $prompt = t('Enter your keywords');
  }

  $form['#action'] = url($action);
  // Record the $action for later use in redirecting.
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';
  $form['module'] = array('#type' => 'value', '#value' => $module);
  $form['basic'] = array('#type' => 'container', '#attributes' => array('class' => array('container-inline')));
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array('#type' => 'value', '#value' => '');
  $form['basic']['submit'] = array('#type' => 'submit', '#value' => t('Search'));

  return $form;
}

```

# Answer
The advanced form is altered in **node.module** and not in search.module. you can find the below function for advance search in node.module, Please have a look in the below hook: `function node_form_search_form_alter(&$form, $form_state)`
> 3 votes

---
Tags: forms, search
---


# Question
Title: Search API Views only displaying one result
I've just cloned a production site into a staging environment. I copied core and contribute, cloned the repo containing custom modules and themes, cloned the database and copied the solr configuration to a new core. Bringing up the database I configured a new search server pointing to the new core, repointed the index and reindexed the site.

All my old search API Views, and all new ones I create, only show one result. However the pager can tell that there are more. Jumping to other pages works. However no content is shown. If I do a search in solr admin I get many results.

I'm at a loss for where to start looking. As far as I can see all configuration is the same in the database and in the files. Google doesn't seem to think this is a thing.

Is this likely to be a Views issue, a solr issue or a search API issue?

EDIT: I've called the URL directly as @Eugene suggested. It looks to me like only one result *is* returned by Solr. However as you can see it things that a larger number has been found.

Query string: http://example.com:8983/solr/core2/select?fl=item\_id%2Cscore&start=0&rows=10&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field=sm\_field\_domains%24name&facet.field=im\_field\_regions&facet.field=im\_field\_topics&facet.field=im\_field\_sources&facet.field=im\_field\_domains&f.sm\_field\_domains%24name.facet.limit=50&f.im\_field\_regions.facet.limit=50&f.im\_field\_regions.facet.mincount=0&f.im\_field\_topics.facet.limit=50&f.im\_field\_sources.facet.limit=50&f.im\_field\_domains.facet.limit=50&f.im\_field\_domains.facet.mincount=0&group=true&group.main=true&group.field=ss\_field\_source\_url%3Aurl&wt=json&json.nl=map&q.alt=%28ss\_type%3A%22article%22%29%20%28bs\_status%3A%22true%22%29%20%28index\_id%3A%22solr\_local%22%29%20%28hash%3Agpsxif%29

Response `"response": {
 "numFound": 197180,
 "start": 0,
 "maxScore": 2.0000253,
 "docs": [
 {
 "item_id": "1646",
 "score": 2.0000253
 }
 ]
 },
...
}`

# Answer
> 1 votes
Try to remove this from your url

```
&group=true&group.main=true&group.field=ss_field_source_url

```

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


# Question
Title: Is it possible to create a template (tpl) file for comment view mode?
I created a new view mode for **comments** called "cool", as shown in the image below (click the image for full size):

I created **comment--cool.tpl.php** and added it to my theme template folder.

Based on the question about Custom tpl for view mode for all contenty type, I also need to add a pre-process to my theme. I tried:

```
  function MyThemeName_preprocess_comment(&$vars) {
  $vars['theme_hook_suggestions'][] = 'comment__' . $vars['view_mode'];
  }

```

But I get an error "Undefined index: view\_mode"

Seems like comments preprocess doesn't have view\_mode as an argument. So I guess it's not possible to create a tpl for comments? OR is there another way?

# Answer
With take look at Template Comment Preprocess You find out that you just need use `$vars['elements']['#view_mode']` instead of `$vars['view_mode']`.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How to replace large, original images used for image caching?
All of the content types on my site allow users to upload up to 10 images. Each file is around 2 to 6 mb in original size.

I don't want to add another layer of complexity to their posting experience by enforcing that they use photoshop or some other software to 'format for web.' before uploading (which would be the case if I set the max file size to, 512k, for example).

Instead, how can I do like other services where you can upload whatever size and then the backend takes care of formatting them to a much smaller size for storage as well as the be the original that image caching uses for its work?

I see two ways of handling it: write a module that understands when the file is saved and use PHP to reformat via its image functions, and then save that new file on the file system as well as be the source of any related image information needed in the database.

or, if the image data in the database is not dependent on the uploaded file size, etc, then why not just write an independed script to loop through all the images and reformat their sizes? Doesn't even have to be a module really.

Thoughts on the best way to do that?

# Answer
hook the image while finishing the upload process, then compress the size is a good Drupal approach much better than another batch job since the project can be managed in a good scope.

If it is a once-off task, script batch job is fast and efficiency but regarding the daily normal usage, a module is more preferable.

There is a module ImageAPI Optimize (or Image Optimize)

BTW, the theory could be:

Something like the following may be what you need:

```
function MYMODULE_node_insert($node) {

```

// See if a file has been added if ($file\_items = field\_get\_items('node', $node, 'field\_file')) { // Get the first file item $file\_item = array\_shift($file\_items);

```
// Load the file object from the cache/database
$file = file_load($file_item['fid']);

// The path to the file is in $file->uri
do_something_with($file->uri);

```

} }

REF: https://api.drupal.org/api/drupal/includes%21file.inc/group/file/7
> 1 votes

# Answer
Hi you can try this very helpful Module *Original image with style*

https://www.drupal.org/project/original\_image\_style
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to prepopulate a term reference field with multiple values on a new form?
I seem to struggle with a problem which has already been answered. I have a 'review' form on which there is a field that I want to prepopulate. It is a term reference field and I want it to be prepopulated with taxonomy values from another node. I have looked at this issue without success. Any help would be greatly appreciated.

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
      $nodeid=$_GET['id'];
      $node=node_load($nodeid);
      if ($form_id == 'review_node_form') {
        $form['field_revactivities']['und'][0]['value']['#default_value'] = $node->field_ad_tags['und'][0]['tid'];
      }
}

```

I know that '$node-\>field\_ad\_tags\['und'\]\[0\]\['tid'\]' returns the number of the term, but I am not sure how to get the value into the new field.

Also, if there are multiple terms for the field, should I populate the field for each term by incrementing \[0\], then \['1'\], etc...?

# Answer
Answering my own question: 1) First aspect is to feed the data correctly to the term reference field. The magic formula I found is:

```
$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);

```

where $bidule is a the string of taxonomy term (not its taxonomy id).

2) If there are multiple elements in the field\_ad\_tags, then I had to create a loop to place them all one after the other in a string. It was important to have the exact wording of each taxonomy term for the field to recognise which tag it is and to separate them with a comma. Here is my final code:

```
$bidule = '';
$i=0;
foreach ($node->field_ad_tags['und'] as $truc => $value) {
        drupal_set_message('<pre>$truc '. print_r($value, TRUE) .'</pre>');
        $term = taxonomy_term_load($node->field_ad_tags['und'][$i]['tid']);
        $name = $term->name;
        $bidule= $bidule.','.$name;
        $i++;
}
$bidule=substr($bidule, 1); // Remove the first character ','

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);

```
> 0 votes

---
Tags: forms, taxonomy-terms
---


title: Pathauto alias programmatically?

text:
# Question
Title: Pathauto alias programmatically?
My custom module enables my **custom token** that allows me to create user paths from one of 3 fields: user:name, or if exists first name + last name, or if exists pageurl field.

this token really gives me the strings like:

Katherine Resette - if page url field is not filled

Mike Nukle - if page url field is not filled

mybeautypage - if page url field is filled

This custom token is: \[user:user\_pageurl\]

and I use this token in Pathauto Patterns on User Paths: \[user:user\_pageurl\]

it does not create strings like:

example.com/katherine-resette and

example.com/mike-nukle

it use just this line as it is:

example.com/Katerine Resette

Please help me to fine my code with pathauto alias create ?

the code from my module user\_pageurl.module is this:

```
     /**
 * Implements hook_token_info().
 */
function user_pageurl_token_info() {

  // Add tokens.
  $user['user_pageurl'] = array(
    'name' => t('Page URL'),
    'description' => t('Defines string for user page address based with priorities
                        (if filled, 3 - high priority, 1 - low priority) : 1. login, 2.fields First name and Last name, 3. field Page URL'),
  );

  return array(
    'tokens' => array(
      'user' => $user,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function user_pageurl_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

 if ($type == 'user') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'user_pageurl':
          $user_pageurl = user_pageurl_token_replace($data, $options);
          $replacements[$original] = $sanitize ? check_plain($user_pageurl) : $user_pageurl;

          // pathauto clean
          module_load_include('inc', 'pathauto', 'pathauto');
          $replacements[$original] = pathauto_clean_alias($replacements[$original]);
          break;
      }
    }
  }

  // Return the replacements.
  return $replacements;
}

 /**
 * Implements hook_token_info().
 * user_pageurl token might contain 1 of 3 user fields
 * 1: user:name - login
 * 2: first name + last name - if exists any
 * 3: pageurl field - if exists - highest priority
 */
function user_pageurl_token_replace($data, $options) {
  //dpm($options);
  $language = $options['language']->language;

  //high priority pageurl token - user:field_pageurl
  //dpm($data['user']->field_pageurl);
  if (isset($data['user']->field_pageurl[$language][0]['safe_value'])) {
    $pageurl = $data['user']->field_pageurl[$language][0]['safe_value'];

    return $pageurl;
  }

  //medium priority pageurl token - user:field_first_name user:field_last_name
  if (isset($data['user']->field_first_name[$language][0]['safe_value'])) {
    $first_name = $data['user']->field_first_name[$language][0]['safe_value'];
    $pageurl = $first_name;
  }
  if (isset($data['user']->field_last_name[$language][0]['safe_value'])) {
    $last_name = $data['user']->field_last_name[$language][0]['safe_value'];
    $pageurl = $last_name;
  }

  if (isset($first_name) &&  isset($last_name)) $pageurl = $first_name . ' '. $last_name;

  //low priority pageurl token - user:name
  $pageurl=$data['user']->name;

  return $pageurl;
}

```

I do not understand why pathauto takes the string as it is and do not transform it replacing uppercases, spaces and so on...

# Answer
> 1 votes
You have to prepare the string yourself, manually. You can use the `pathauto_cleanstring()` helper function that will remove all characters you wouldn't want in the URL (e.g. spaces).

Here's an example:

```
// The function we need is in the pathauto.inc file.
module_load_include('inc', 'pathauto');
$clean_title = pathauto_cleanstring($string_you_want_to_clear);

```

Hope this is what you were asking about.

---
Tags: path-aliases
---


# Question
Title: How to add a comment using service api when uuid_service module is enabled
How to add a comment when UUID and services are enabled The url which we tried is :

http://localhost/api/comment/uuid\_of\_new\_comment (PUT request) with json raw data:

```
{
    "comment": {
        "uuid":"uuid_of_forum ",
        "subject": "testing"
    },
    "uuid":"uuid_of_new_comment ",
    "type":"comment"
}

```

I know that it is not correct. But was not able to find a proper documentation for this any where. So trying some random things !!!

It will be highly helpful if some one can suggest where to find proper documentation for uuid with services .

# Answer
We got it working finally:

URL Used : https://localhost/api/comment/0b1dd306-bbcb-410c-b991-319a3ca189c3 METHOD: PUT JSON:

```
{
    "nid": "2583",
    "name": "dsad",
    "subject": "sda",
    "language": "und",
    "node_type": "comment_node_forum",
    "date": "now",
    "status": 0,
    "is_anonymous": true,
    "op": "edit",
    "comment_body": {
        "und": [
            {
                "value": "jhkjh"
            }
        ]
    },
    "uuid": "0b1dd306-bbcb-410c-b991-319a3ca189c3"
}

```

And to allow users other than administers to add comment the patch in the following issue has to be applied: https://www.drupal.org/node/2236229
> 1 votes

# Answer
First, when creating a comment you must use *POST*. Here's an example:

**POST**: `?q=[my_endpoint]/comment.json`

```
{
  "subject":"Testing...",
  "comment_body":{"und":[{"value":"Hello world..."}]},
  "nid":"123"
}

```

Secondly, from my understanding the *uuid* will automatically be generated server side, so you should not need to send it up to Drupal. And lastly, you use the *PUT* http method to update a comment, and in that case you can send along similar JSON, but include the cid value (e.g. 456) and exclude the nid value in the JSON object, and change the URL path to `?q=[my_endpoint]/comment/456.json`

```
{
  "subject":"Updating...",
  "comment_body":{"und":[{"value":"Hello world again..."}]},
  "cid":"456"
}

```
> 1 votes

---
Tags: services, entities
---


# Question
Title: How to remove taxonomy term reference field from simplenews newsletter HTML
I have spent a week watching videos and reading tutorials on how to customize the HTML generated by Simplenews. I'm stuck on how to remove the following from my newsletter. I discovered the following using Firebug. There is a bewildering array of CSS, HTML, and php files that are involved. I'm clueless as to how to find the one that it is control.

Can you tell me how to code CSS in the new theme I created for newsletters to remove the following?

```
div class="field field-name-field-simplenews-term field-type-taxonomy-term-reference field-label-hidden view-mode-full"ul class="field-items"li class="field-item even"a datatype="" property="rdfs:label skos:prefLabel" typeof="skos:Concept" href="/newsletter/test">test</a></li></ul></div

```

# Answer
> 1 votes
Go to

> Home » Administration » Structure » Content types » Simplenews newsletter

Go to Display and customize it

There will be **Newsletter category** \- you can change it's format to **Hidden**

But first activate needed display type on that page in

Full Content fixes the node display. Email HTML fixes it on the email itself.

---
Tags: emails
---


# Question
Title: How to optionally redirect to a payment page after adding a node?
I want to add an option to the node add form so that the user who creates the node can choose if the node will be " promoted " or not. If the promoted option is selected, then I want to redirect the user to a payment page, so that the option charges can be payed.

Any suggestions about how to do so?

# Answer
# Step 1a: Optional redirect to payment page

Add a Boolean field to each content type for which you want to offer such "Promoted" option, say its allowed options are `Yes` or `No`.

Then use the Rules module like so:

* **Event**: After saving a node
* **Condition**: (both conditions must be true)

1. Entity has field "Promoted"
    2. Data Comparison "Promoted" = "Yes"
* **Action**: Perform a page Redirect to your Payment Page

# Step 1b: Limit node access while payment is not completed

To wait for the payment to be completed (and not "submit" the node yet), you could use the Content Access module, and the Content Access Rules Integrations module.

So that "After saving content" (= Event), you "Give 'authenticated user' the permission to 'view own content' for the specific node" (= Action). This additional "Action" can be added is a 2nd action to the same rumle suggested above.

This would be a variation of what is explained in this article also (within "Access Control Customized for Your Needs").

# Step 2: Promote the node (after payment)

After the payment is received, you could use that "Event" to trigger another rule, which basically consists of these actions:

* Mark the node as "Promoted".
* Remove the node access restriction, so that all appropriate roles can view the node.

# Step 3: Stop the promotion of the node

If at some point in the future the "Promoted" node no longer should be promoted, then you could use the Rules Scheduler ( a sub-module of the Rules scheduler) to trigger a rule to no longer mark the node as "Promoted.

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

---
Tags: 7, commerce, redirection
---


title: how to rewrite field in view

text:
# Question
Title: how to rewrite field in view
I have following Html code, I want to rewrite two field .1st is `[field_poster_hover_image]` and 2nd is `[field_team_image]` .This is my HTML Code.

```
 <div class="thumb thumb-type-1">

                <a href="post-page.html" data-logo="images/girls-12s.png">
                  <img src="images/project-3.jpg" alt="project 1" />                </a>           </div>

```

and I have written code like this but its not working

```
 <div class="thumb thumb-type-1">

                <a href="post-page.html" data-logo="[field_poster_hover_image]">
                  <img src="[field_team_image]" alt="project 1" />                </a>           </div>

```

# Answer
You don't want to use \[field\_team\_image\] in the src ,just put the \[field\_team\_image\] you can get the image and print $data in views custom php field to get the another image to get the url.
> 0 votes

# Answer
You can use hook\_views\_pre\_render(&$view) to rewrite the code .

```
 function hook_views_pre_render(&$view) {

      switch ($view->name) {
        case 'YOUR_VIEW_NAME':
          foreach($view->result as $key => $value) {
          $value->field_some_element[0]['rendered']['#markup'] = '<div>Your custom markup should be placed here</div>';
    }
        break;
      }

```
> 0 votes

# Answer
Using the Image URL Formatter module it is possible to display image. Here is a quote about it (from the module's project page):

> ... adds a url formatter for image field. Then you can output image url directly.
>
> I had created a content type, and added an image field instance to it. Later on I used views to export the data of this content type. And I wanted to output the data, so I could import it into another Drupal 7 site with the Feeds module. What I needed is the url of the image field, but I could not export the image url directly. That is why I created this small module.
> 0 votes

# Answer
You can alter the HTML output at the row level from inside the Views UI:

1. Add the fields to your view. Settings:

*Create a label* \- unchecked
*Exclude from display* \- checked
2. Otherwise configure each field depending on what kind of output you want. For example, with an image field you might select as your formatter "Image" (to display the rendered image tag) or "Download link" (to display the download path to the file). The latter would be most appropriate in this case.
3. Add a new field **Global: Custom text**. Add the mark-up below, only replace `[field_myfield1]` and `[field_myfield2]` with the actual tokens for each field, which can be found by expanding *Replacement patterns*.

//

```
<div class="thumb thumb-type-1">
  <a href="post-page.html" data-logo="[field_myfield1]"><img src="[field_myfield2]" alt="project 1" /></a>
</div>

```

//

**:) Bonus:** If using the node title as the text in your *alt* attribute, in the above HTML you can replace "project 1" with the `[title]` token.
> 0 votes

---
Tags: views
---


# Question
Title: Modify custom search box added in page.tpl.php
My Drupal theme (Nexus) doesn't have a search bar in the header. So added a custom header in page.tpl.php using the following code.

```
 <?php if ($search_box):?><div id="searchbar_right" style="float:right"><?php print $search_box ; ?></div><?php endif; ?>

```

I wish to modify the search-box a bit, so I added the following lines to nexus\_form\_alter function in template.php.

```
if ($form_id == 'search_block_form') {
    print $form_id;
    //$form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibility
    $form['search_block_form']['#size'] = 20;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search Site'); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit']['#attributes']['alt'] = "Search Button"; //add alt tag
    unset($form['actions']['submit']['#value']); // Remove the value attribute from the input tag, since it is not valid when input type = image

    //$form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/icon-search.png');

// Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search Site';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search Site') {this.value = '';}";
  }

```

But the above piece of code doesn't have any effect on the search box that appeared on the top. I suppose that since I have manually printed the search box at the header, hook\_form\_alter may not be of any use to me.

Can anybody suggest how to change my search-box characteristics.

# Answer
> 1 votes
I have finally resolved this one using a jquery which I have applied to the element using JS Injector Module.

```
jQuery(document).ready(function($) {
  $('#edit-keys').attr('size', '20');
  $('#edit-keys--2').attr('size', '20');
});

```

---
Tags: search
---


# Question
Title: How to create a url pattern for a specific node
I have a node with the path: http://www.example.com/test

I would like all paths that begin with /test/ to go to this node. url like these: http://www.example.com/test/a/b/c http://www.example.com/test/a?bc

all should be redirected to this node.

How can this be accomplished?

# Answer
> 0 votes
To accomplish this, you can use `Pathauto` module. To set a specific path for a specific node, go to admin/modules/pathauto/config and set the path for that specific node in the textbox as you want. For your case use `test/[node:title]` in the Pattern for all test paths text field.

---
Tags: 7, path-aliases
---


title: Overriding field.html.twig in my module

text:
# Question
Title: Overriding field.html.twig in my module
I'm writing a field formatter and I need to override the default field formatting. I've already implemented themes for the items itself, but I can't get my theme to work for the field container.

I've set #theme in the following code, and my field-image.html.twig is found by Drupal and processed:

```
class ImageGalleryFormatter extends ImageFormatter {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = parent::viewElements($items);
    foreach ($elements as &$element) {
      $element['#theme'] = 'imagegallery_format';
    }
    $elements['#theme'] = 'field_image';
    $elements['#attached']['library'][] = 'imagegallery_formatter/light-gallery';
    return $elements;
  }

}

```

But it doesn't actually work correctly, I don't get any content for {{ item.content }}. This is the core of my field-image.html.twig:

```
{% for item in items %}
   <div>{{ item.content }}</div>
{% endfor %}

```

I suspect that I didn't implement hook\_theme() correctly, I tried a few variants, but none worked.

```
function imagegallery_formatter_theme() {
  return array(
    'imagegallery_format' => array(
      'variables' => array('item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL),
    ),
    'igimage' => array(
    'variables' => array(
        'style_name' => NULL,
        'uri' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
      ),),
      'field_image' => array(
        'render element' => 'element',),
  );
}

```

The first two themes work, for those I simply copied the variables array from existing code. The third one doesn't work, and I couldn't find any existing code I could use as a template. I tried to define the variables instead of using 'render element', but I don't know how to define the `items` variable there. I tried setting it to NULL or an empty array, but nothing did work. When I put a variables array in hook\_theme, I get simply four empty divs, with the render element array I get a single empty div.

What am I doing wrong here, and how do I override this theme correctly in my module?

# Answer
I managed to track down the place in core where the code for this specific theme is located, it was in `core/includes/theme.inc` and not in the field or system module where I previously searched. Copying from there did work in the end, using `render element` in hook\_theme() is correct, but I was missing an important preprocess function.

I defined the following function and called the original preprocess function from there:

```
function template_preprocess_field_image(&$vars, $hook) {
    template_preprocess_field($vars, $hook);
}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: When to use BaseFieldDefinition instead of hook_schema
While creating a new information for Drupal 8, I came across 2 approaches to create a new column on the entity table on database: * use hook\_schema() (as I was used on Drupal 7) (https://gist.github.com/pedrorocha-net/3ed63f33b513d9c9ff86) * extends ContentEntityBase and use BaseFieldDefinition (https://gist.github.com/pedrorocha-net/70d6a84c3ddba1c5939d)

Both alternatives creates the table for me, with the data, but I think the latter already provides me more integration with other Drupal components e.g. Views module. By the other hand, being an "Entity" I believe brings some "weight" to the data, as it works with some wrappers(on Drupal 7 at least).

What i'm doing is port the Voting API module, so this question about extra weight can really impact on sites with more content.

Any thoughts?

# Answer
> 4 votes
The question that you are really asking is if you should be using the entity system or not. You only have one option depend on the answer to that.

Yes, there is considerable overhead especially when using content entities. But things like nodes and comments are entities too, and you can have hundreds of thousands of those. It doesn't really depend on how many are stored but how many are accessed and processed on typical requests. If it's common to load a large amount of them (not just calculate aggregates like how many votes but actuall load the whole thing), then entities might not be such a good match.

Drupal Core only has two primary types of entities, content and config entities. You could also define your own lightweight entity type that is completely custom, but then you again need your own storage class, table creation and so on.

But as you said yourself, being a (content) entity gives you a lot functionality, like CRUD, views integration, REST and many more that you possibly don't need for your use case.

---
Tags: 8
---


# Question
Title: How can I use different database backend for certain tables?
What do I need to do in order to serve config entities from Mongo and cache from Redis database backends?

So basically: a) how do I tell Drupal that I want to use different db backend for certain tables? b) what is needed in regard to drivers for those database backends? Are they available?

This is similar to How can I save/load my Entity from a different database in Drupal 8? but in this case I am interested in entirely different db backend + I want to include also non-entity tables so that annotation approach is not working for me.

# Answer
> 1 votes
That's actually more than one question because the answer is different.

To use redis as the cache, you can use our port on github: https://github.com/md-systems/redis

The README isn't been fully updated yet but the quickstart part tells you how to configure it (after enabling the module):

```
  $settings['redis.connection']['interface'] = 'PhpRedis'; // Can be "Predis".
  $settings['redis.connection']['host']      = '1.2.3.4';  // Your Redis instance hostname.
  $settings['cache']['default'] = 'cache.backend.redis';

```

To use redis for the cache tags checksum service, which most cache backends use, you need to override a service, for example in sites/default/services.yml, add the following:

To use the redis cache tag checksum implementation, put this in sites/default/services.yml or any other yml file that is loaded after core.services.yml:

```
services:
  cache_tags.invalidator.checksum:
    class: Drupal\redis\Cache\RedisCacheTagsChecksum
    arguments: ['@redis.factory']
    tags:
      - { name: cache_tags_invalidator }

```

In the same way, you can replace any service that is defined in the core or one of the module services.yml files with a different implementation, for example some of the mongodb service implementations provided by https://www.drupal.org/project/mongodb.

In general, you don't think in terms of tables but services and API's, and you either replace them directly or by configuration he factory service (cache/key value/queue/...)

---
Tags: 8, database
---


# Question
Title: Set allowed value of a list field depending on the URL
In the list field php code I want to set the value of a field:

1. first do a call to parse the URL.
2. take the \[3\] element (`nid` of the organic group) and use it to do a call to the db to get the node type for that `nid`.
3. set the value of the field depending on the node type.

I had all this working in D6, now have to redo for D7. Not having any luck getting it working yet.

---

```
function custom_pathnoder() {
    $pathnoder = array();
    $pathnoder = check_plain(drupal_get_path_alias($_GET['q']));
    $pathnoder = explode('/', $pathnoder);
  return $pathnoder;
}

$node = menu_get_object();
$pathnoder = custom_pathnoder();

$group_id = $pathnoder[3];

$query = db_select('node');
 $query->condition('nid', '$group_id', '=')
              ->fields('type');
$og_type = $query->execute();

if ($og_type) {
if ($og_type == 'square_group')  {
$def_value = array( 0 => array('value' => square) );
}

elseif ($og_type == 'west_group')  {
$def_value = array( 0 => array('value' => west) );
}
elseif ($og_type == 'east_group')  {
$def_value = array( 0 => array('value' => east) );
}
elseif ($og_type == 'circle_group')  {
$def_value = array( 0 => array('value' => circle) );
}
elseif ($og_type == 'north_group')  {
$def_value = array( 0 => array('value' => north) );
}
elseif ($og_type == 'south_group')  {
$def_value = array( 0 => array('value' => south) );
}
}

if (isset($def_value)) {
  return $def_value;
}
else {
  return array(0 => array('value' => null));
}
}

```

@Shawn Conn

I changed the code to reflect the suggestions above but it's still not setting the value. Can you see the reason?

```
def_value = array();
$pathnoder = array();

$pathnoder = check_plain(drupal_get_path_alias($_GET['q']));
$pathnoder = explode('/', $pathnoder);

$og_type = db_select('node','n')
    ->fields('n', array('type'))
    ->condition('nid', arg(3), '=')
    ->execute()->fetchField();

switch ($og_type) {
    case square_group:
         $def_value = array( 0 => array('value' => square) );
         break;
    case west_group:
         $def_value = array( 0 => array('value' => west) );
         break;
    case east_group:
       $def_value = array( 0 => array('value' => east) );
       break;
    case circle_group:
       $def_value = array( 0 => array('value' => circle) );
       break;
    case north_group:
       $def_value = array( 0 => array('value' => north) );
       break;
    case south_group:
       $def_value = array( 0 => array('value' => south) );
       break;
}
if (isset($def_value)) {
  return $def_value;
}
else {
  return array(0 => array('value' => null));
}

```

# Answer
You're making this a little more convoluted than it needs be; the core arg() function can parse out the path and get the 4th element; the query is also broke (`condition()` is passed a string literal instead of variable & it's missing aliasing argument); lastly you could help readability with a switch control.

```
  //fields() needs an alias argument $group_id can be pulled from arg()
  $og_type = db_select('node','n')
    ->fields('n', array('type'))
    ->condition('nid', arg(3), '=')
    ->execute()->fetchField();

```
> 1 votes

---
Tags: entities
---