# Question
Title: Can't get favicon/shortcut icon to show up
Despite trying multiple times various favicon location approaches:

* at theme root
* at `files` root
* uploading the file through `admin/appearance/settings`
* typing in a path of manually uploaded icon

always clearing cache afterwards, I cannot get my shortcut icon to show up.

I tried pasting into the browser's address bar the path of the ico file so to force an update, but I got a generic server error that there was no such file at this location. When I looked into the generated source code, I could not see neither my file nor the default drupal icon. So I'm completely lost.

I'm close to modifying the html.tpl.php by pasting the `link` tag manually or through `drupal_add_html_head_link` but I'm puzzled because it happened to me for the first time. Any clue what else I could double-check?

# Answer
> 3 votes
Just went through this Drupal favicon mess myself :) Hope this helps:

> When I looked into the generated source code, I could not see neither my file nor the default drupal icon.

This is the first problem to solve – getting at least the default blue Drupal drop icon to show again. For this:

1. There is both a global "Shortcut icon settings: Use the default shortcut icon." setting at `admin/appearance/settings` and an equivalent one for each theme that can be enabled on that page. In all these forms, tick this setting and save the form. If neither this box is ticked nor a valid path entered into the "Path to custom icon" field of the form whose settings "win" the overwriting, Drupal will interpret this as "do not show any favicon".
2. Make sure Drupal's default favicon is readable by your webserver user: visiting `http://example.com/misc/favicon.ico` for your domain should show that icon. If it is not accessible to the web server, Drupal will detect that and not even render a shortcut icon header entry.
3. Cache clearing should not be necessary, but who knows. If still no favicon shows up, do a `drush cc all` and check again. Check the HTML source code, not what the browser shows, to prevent issues with the browser cache.

Now that the "blue drop" Drupal default favicon shows up again, let's configure your own one. The surefire way is this:

1. Navigate to the settings screen `admin/appearance/settings/theme-name` of your "most-sub-theme" applying to the page where you want your favicon to be in effect. So if you have a theme `A`, a sub-theme of `A` called `B` and a sub-theme of `B` called `C`, go to `admin/appearance/settings/c`.
2. Click "Shortcut icon settings: Browse" and upload a custom favicon. It will end up in the `files` root directory of your default site.
3. Load your site again, and it should show your favicon now, at least in the HTML source. If not, try a full cache clear, though that never helped in my case.

Explanations:

* **Choosing the most-sub-theme.** This is necessary because the `admin/appearance/settings` form is just the global setting for all themes, and values entered here will be overwritten by each theme and sub-theme down the chain of themes. So the setting in the "most-sub-theme" will win. Plus, it seems there is no option to *not* enter a value into the "Shortcut icon settings": when you keep the "Path to custom icon" field empty, Drupal will not fall back to the theme higher up in the chain, but interpret it as "do not use any favicon".
* **Uploading, not typing in a path.** There seems to be a Drupal bug with the "Shortcut icon settings" form: it will only accept typed-in values for the "Path to custom icon" field *after* uploading an icon before. You can then *modify* the value in that field and it will modify what favicon is used, but when you delete the value, save the form, enter a new value and save again, no favicon will show up even though the same value worked before.
* **Base path when typing in a filename.** If you use the above trick to upload first, then modify the value in the "Path to custom icon" field, also remember that the base path for filenames entered here is the `files` directory of your default site. So, `sites/example.com/files/` from web document root. You can be sure it's the right one by checking that your immediately before uploaded favicon arrived in this directory. (If the referenced file exists, Drupal will also accept without form validation errors if you type in a path starting at document root (like `sites/all/themes/my_theme/favicon.png`) – but I never could get favicons referenced this way to show up.)

---
Tags: files
---


# Question
Title: How to implement a Comment Reply Form through Views and using JS?
We have a comment body, using views, where we have the name, comment, picture, and date for each of the posted comments. At the end of all comments we have a comment body, where one can add a comment.

Now this works great for a linear comment system, but we want a threaded system in place. In views, I can add a reply comment link, but that takes me to a new page.

What I want is JavaScript based action, such that the comment form, goes below the reply link when reply button is clicked. Is this possible via views?

If not, what's my best option?

**UPDATE**

I enabled a module called ajax comments. This works great with default drupal comment system, but not so much with views. I added the required classes, and got the basic thing to work but the newly added comment doesn't appear until you refresh the page. Also the message (queued for moderation) comes at the bottom of the page.

If someone has set this module up successfully with views, please let me know.

# Answer
Have you looked at Inline Ajax Comments?
> 1 votes

# Answer
Pratik,

Using AJAX comments with default settings is a good idea, but any modifications to it can really cause things to break. When I worked, it did not even provide any *hook()* for data modification.

It is better to do it in a custom way, which is much easier and flexible as per needs.
> 0 votes

# Answer
I just want to add something to your *updated portion*, may be it will help you.

If you are able to appear the message bellow you can bring it up by using the custom template of `comment-wrapper.tpl.php` and to display message without refreshing the whole page you can refresh the `<div>` on reply `submit/save` using `drupal_add_js`.
> 0 votes

# Answer
you can render your form in th template file of your view.You can include this code in your views--view-YOUR\_VIEW\_NAME.tpl

```
$build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));

print render($build);

```
> 0 votes

# Answer
For this use Entity collection module, where make comments as entity and make collection of entities, by that you can perform threaded comment system.
> 0 votes

# Answer
just add Comment: Thread (asc) to your sort criteria. It keeps all comments of same thread together
> 0 votes

---
Tags: views, javascript, comments
---


# Question
Title: "Strict warning: Only variables should be passed by reference in eval()" when concatenating several text fields
I am using Computed Field to concatenate a few text fields into one value. The text fields are pieces of a street address (the street address, the city, the state, and the zip code). When using the code below, I receive the error below.

COMPUTED CODE:

> $entity\_field\[0\]\['value'\] = array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_address'))) . ', ' . array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_city'))) . ', ' . array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_state'))) . ' ' . array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_zip\_code')));

DISPLAY CODE:

> $display\_output = $entity\_field\_item\['value'\];

ERROR:

> Strict warning: Only variables should be passed by reference in eval() (line 1 of /home/mysite/public\_html/sites/all/modules/computed\_field/computed\_field.module(468) : eval()'d code).

How can I resolve this issue?

# Answer
```
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_address')));

```

=\>

```
$items = array_pop(field_get_items($entity_type, $entity, 'field_address'));
$entity_field[0]['value'] = array_pop($items);

```

You have to store result of function in variable and pass it to another function, instead of pass function to function.

Passing by Reference
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Drupal 7 Ajax Form, add elements dynamically to a fieldset
I have the following form:

```
  $form['#tree'] = TRUE;

  $tasks = array(
    'Julia',
    'John',
  );

  foreach ($tasks as $task_key => $task) {

    $form['task_fieldset'][$task_key] = array(
      '#type' => 'fieldset',
      '#title' => $task,
      '#prefix' => '<div id="task-' . $task_key . '-fieldset-wrapper">',
      '#suffix' => '</div>',
    );

    if (empty($form_state['num_todos'][$task_key])) {
      $form_state['num_todos'][$task_key] = 1;
    }

    for ($i = 0; $i < $form_state['num_todos'][$task_key]; $i++) {
      $form['task_fieldset'][$task_key]['todo'][$i] = array(
        '#type' => 'textfield',
        '#title' => t('Todo'),
      );
    }

    $form['task_fieldset'][$task_key]['add_todo'] = array(
      '#type' => 'submit',
      '#name' => 'add_todo_' . $task_key,
      '#value' => t('Add more'),
      '#submit' => array('custom_mod_example_ajax_collection_add_todo'),
      '#ajax' => array(
        'callback' => 'custom_mod_example_ajax_collection_callback',
        'wrapper' => 'task-' . $task_key . '-fieldset-wrapper',
      ),
    );

  }

  return $form;

```

These are the callbacks:

```
function custom_mod_example_ajax_collection_callback($form, $form_state) {
  $name = $form_state['triggering_element']['#name'];

  $task_key = (int) substr($name, strpos($name, "_") + 1);

  return $form['task_fieldset'][$task_key];
}

function custom_mod_example_ajax_collection_add_todo($form, &$form_state) {
  $name = $form_state['triggering_element']['#name'];

  $task_key = (int) substr($name, strpos($name, "_") + 1);

  $form_state['num_todos'][$task_key]++;
  $form_state['rebuild'] = TRUE;
}

```

And the form looks like this: https://i.stack.imgur.com/cwShN.jpg The problem is that when I click on "Add more" on John fieldset, it changes to Julia. What have I done wrong?

It works as expected when I try Add more on Julia, however.

# Answer
> 0 votes
The problem was in the AJAX callback, and specifically the code line:

```
$task_key = (int) substr($name, strpos($name, "_") + 1);

```

The buttons are named add\_todo\_key, and the code above returns todo\_key, and not the key.

It was solved simply by using `strrpos`, which find the position of the LAST occurrence of a substring, rather than `strpos` that finds the first.

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


# Question
Title: How to restrict moderators to only access a limited set of users?
I have 2 user roles: Moderator and Company. Each Moderator has a set of companies; for example:

* Moderator A owns Company d, e, anf f
* Moderator B own Company g, h, and i

When moderator A logs in, I want that moderator can **only** see Company d, e, and f. I want to use a view.

How can I achieve this? How can I restrict each moderator to see those companies (which, I repeat, are user accounts) they own?

# Answer
Have a look at the Group module which is like a "little brother" of Organic groups. It only started in D7 and with a D8 version in the pipeline. Personally I'm more and more considering/using it as a potential alternative for the Content Access module. And since it is all Entity based, there are lots of ways it can be used in combination with the Rules module also.

Specific to your question here, I think what is going to help you a lot is the **Group member profiles** submodule, which you can use to create multiple fieldable member profiles and which can be attached to a member.

For way more details about this module, refer to:

Also, as per your comment below (= "*Can you tell me if it works with views? I would like to display in a view all the companies attached to the user (Moderator) that is logged in.*"): I suggest you have a look at comment nr 2 in the issue about "How to list groups in a view?", which even includes a view in export format you may want to have a look at.

**Note**: Your question doesn't specify which version you are using, but this answer applies for both D7 and D8.
> 1 votes

# Answer
If moderators are creating the Company nodes themselves, you will probably be best off with the Content Access module.

If Company nodes are created by administrators, you could use the Node access user reference field to reference the moderators. They would then get the necessary view permissions.

Let me know if I missed your question.
> 2 votes

---
Tags: 7, views, users
---


# Question
Title: Access denied or format unknown on field in Services Views
Installed the following modules in Drupal 7

* Services
* Services Views

When creating new services view, I am facing the following issue.

nid and title fields shown correctly, but other fields including body and custom fields showing the following error. **"Access denied or format unknown on field."**

The preview shows as below:

```
array (
  0 =>
  stdClass::__set_state(array(
     'nid' => '47',
     'title' => 'World Cup Stadiums',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
  1 =>
  stdClass::__set_state(array(
     'nid' => '49',
     'title' => 'Ladies Fencing Tournament 2014',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
  2 =>
  stdClass::__set_state(array(
     'nid' => '48',
     'title' => 'FIfa World Cup',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
  3 =>
  stdClass::__set_state(array(
     'nid' => '46',
     'title' => 'Fifa World Cup Title',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
)

```

# Answer
You just need to uncheck the "Use field template" inside the "STYLE SETTINGS" of your 'publish\_date' field.
> 0 votes

---
Tags: views, services
---


# Question
Title: When an image shows up in "page not found" in Watchdog, how to find the content containing the image link?
I disabled the countryicons\_shiny module on my site, and now I'm getting some errors in Watchdog showing that the images weren't found:

```
Details
Type    page not found
Date    April 3, 2016
User    Anonymous
Location    https://www.example.com/sites/all/modules/contrib/countryicons_shiny/images/tw.png
Referrer
Message sites/all/modules/contrib/countryicons_shiny/images/tw.png
Severity    warning
Hostname    1.1.1.1
Operations

```

I'm pretty sure this is a misconfigured view, but I have a ton of views and content types on my site, so I was hoping to find a way to identify the content (view, page, etc.) that is trying to display the icon.

I have all my views in features and I tried using `grep countryicons *` but no results are returned.

**How can I find what content is linking to the image when I only have the watchdog log "page not found entry?**

# Answer
> 0 votes
This is not the ultimate solution, but in this specific case, since I moved the icons into another module, to fix this particular error I just symlinked the folders:

```
mkdir countryicons_shiny
cd countryicons_shiny
ln -s ../mycustommodule/countryiconsdirectory images

```

---
Tags: uri, log-messages
---


# Question
Title: Cannot Add Registration to cart: SQL Error with Registration and Drupal Commerce
I have drupal site running core 7.42 and Commerce 7x-1.11 with Commerce Registration and Entity Registration. The modules all seem to be working fine as I can create registration products and product displays and add registrations to pages and such.

The problem is when a user tries to add the registration to cart it produces the following error

```
       PDOException: SQLSTATE[42000]: Syntax error or access violation:
       1064 You have an error in your SQL syntax; check the manual that
       corresponds to your MySQL server version for the right syntax to use near
        '))  LIMIT 1 OFFSET 0' at line 1: SELECT registration.registration_id
        AS entity_id, registration.type AS bundle, :entity_type AS  entity_type,
NULL AS revision_id FROM {registration} registration WHERE (registration.entity_id
         = :db_condition_placeholder_0) AND (registration.user_uid = :db_condition_placeholder_1)
     AND (registration.state IN ()) LIMIT 1 OFFSET 0; Array ( [:db_condition_placeholder_0] => 5
        [:db_condition_placeholder_1] => 1522 [:entity_type] => registration ) in EntityFieldQuery->execute()
    (line 1192 of /home/phislub9/public_html/includes/entity.inc).

```

I'm not sure what is causing the error, or how to debug it. It looks like a bad query is getting passed to the a drupal\_alter function to modify query's in entity.inc.

# Answer
So, the error was the result of missing registration states. I found the details in this post on the Entity Registration Issue Queue Pdoexception Error. I added a default "active" registration state, and this solved the problem.
> 0 votes

---
Tags: commerce, entities
---


title: Is that a way to sync Drupal databases

text:
# Question
Title: Is that a way to sync Drupal databases
I'm working on an existing website. So before I started I copied all files and database to my local environment. So far so good. To port the changes over I'd planned on using features. For a number of reasons the project got slightly off track I can't no longer migrate the features using the `features` module. Other than trying to fix why I can't port the features to the live site, I've been wondering whether is there a way to sync the two databases (*effectively moving all the content - nodes, taxonomies and users - from the live site to the local site*). I've tried **Migrate Drupal to Drupal** but the content wasn't imported. (I'm also looking at why it didn't work) but my question now is:

Are there any options to do it ? How ? (Other than Migrate Drupal to Drupal or using Features to migrate the features over)?

# Answer
> 0 votes
There are a couple of other options you can explore, apart from the ones you have already mentioned:

drupal sync The present module allows synchronizing content among multiple websites. Supported entity types: node and taxomony, menu items.

deploy The Deploy module is designed to allow users to easily stage and preview content for a Drupal site. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.

---
Tags: 7, migrations
---


# Question
Title: Load custom form into contents of a specific content type
I have created a custom form through Drupal form API. Also i have added various content pages of a Content Type called "Search Pages". Those pages contain only Metadata which they are hidden. What i actually want is to show my custom form into those pages (Search Pages). How can i implement that programmaticaly?

# Answer
> 1 votes
You can output form as block, then output this block in region and set block's visibility options to show only on specific content types:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('Block with form'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = drupal_get_form('mymodule_custom_form');
      break;
  }
  return $block;
}
/**
 * Form example.
 */
function mymodule_custom_form($form, &$form_state) {
  $form = array();
  $form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Place your form fields here'),
  );
  return $form;
}

```

Clear cache, go to blocks page (/admin/structure/block), assign your block to region. Go to your block configuration page and define Visibility settings on `Content types` tab.

---
Tags: nodes, forms
---


# Question
Title: Drupal Views Search: Creating an Exposed Filter with Checkbox Options
Using basic search module and Views to make a search interface.

When I create an exposed filter for a field with multiple options I only have the option to choose 'dropdown' or 'autocomplete' for the filter settings.

Is there a way to make the filter display the options to users with checkboxes rather than a dropdown menu?

# Answer
> 3 votes
Better Exposed Filters module should help you.

---

---

---
Tags: views, search
---


# Question
Title: Allow authenticated users to fill out fields in nodes that only they can see
Is it possible in Drupal 7 to allow users to fill out their OWN values for particular fields in a content type?

For example, we want our authenticated users to be able to save nodes to a dashboard. For each node they save there are 5-7 fields we want to make available for the user to enter data into...but ONLY that user should be able to see the notes.

On their dashboard, using Views, they will then see a list of their saved nodes in tabular format with columns that include the data they filled out for each of those fields, as well as the other information that comes from the nodes that the authenticated user can't edit (ie. the title, etc.).

Is this possible?

# Answer
> 1 votes
you can use field permission to set limit to each field https://www.drupal.org/project/field\_permissions

In field permission, You can set fields that can edit by an authenticated user and can only edit by an admin role, etc.

---
Tags: nodes, users
---


# Question
Title: User permission to edit only nodes with taxonomy term
I want to let my customers only edit nodes that have a specific taxonomy term.

For example i have user TimCook from company Apple. He got the role "customer" and i want to give him the right to edit nodes only with the taxonomy term "apple" of the vocabulary "company".

I didn't find any module for this. Maybe there is one, or someone has a hint where i should start to make an own module.

# Answer
> 1 votes
Taxonomy Access Control Lite module should help you.

> This node\_access module governs access to nodes based on the taxonomy terms applied to the nodes. A simple scheme based on taxonomy, roles and users controls which content is visible.

# Answer
> 0 votes
Taxonomy Access Control

You may set permission to allow users in role "apple" have the right to view, update or delete nodes with an "apple" term.

---
Tags: users
---


# Question
Title: webform + form builder: how to clone an existing form
I am using webform + form builder to manage some forms on my site.

I can't find a way to clone the form (with all its elements) to a new form? I know that I can clone elements inside the same form, but I can't export them to another form (and I can't export the form itself).

There is a way to do it?

Thanks

# Answer
> 0 votes
Use node clone module to clone that webform node. Then, you will have a new node with webform fields.

---
Tags: forms, webforms
---


# Question
Title: How can I submit a form into a node and save it in the database?
I installed drupal 8 in local and i have created a content type named 'Formulaire' and also i've created a FormulaireForm and i want to submit this form into that node .how can i do this ? and i also want to storage this values into the database.

# Answer
Your FormulaireForm is made by webform? Under this case, you can use rules to create node automatically.
> 0 votes

---
Tags: nodes
---


# Question
Title: Making columns into sort asc/desc in search api-based view
I've created a search page using Views and 'search api'. I've got my results showing in tabular format with the labels in a above the results returned.

But I can't figure out how to make each label/column header a sort. I want the user to be able to click the label in the column header to then sort that column by ascending/descending.

Anyone know how to make that possible?

# Answer
I figured this one out. I have to set the field to 'string' in Search API configuration \> index \> edit. The default is 'fulltext', which sounds right, but isn't for this usage.

Then you have to change the settings for the format: table to make the field sortable.
> 1 votes

---
Tags: views, search
---


# Question
Title: Print date and timestamp in views-view-field--blog--block-1--image.html.twig
How to print date and timestamp in views-view-field.html.twig ?

This is my html code

```
<span class="date"><span>27 <em>Mar</em></span></span>

```

And this is code for timestamp

```
<span class="timestamp">
        <i class="fa fa-clock-o"></i>
        6 mins ago
</span>

```

To look like this. This is html look.

Date and timestamp need to be add in

views-view-field--blog--block-1--image.html.twig

# Answer
> 1 votes
I am assuming that the template is for a date field and you want to display the date field in the format that you specified above.

Here is the article that might help http://twig.sensiolabs.org/doc/filters/date.html

For PHP date formats you may refer to http://php.net/manual/en/datetime.formats.date.php

Similar question : https://stackoverflow.com/questions/8318914/how-to-render-a-datetime-object-in-a-twig-template

---
Tags: views, 8
---


# Question
Title: How can I set up RNG Conflict with a multi day event
I'm loving the RNG module and the conflict functionality, but I'm a little confused regarding how to set up my seminars and events.

My current use case is I have a simple four-day event with one optional seminar every day.

Initially, I created one registration type "spring seminars", and one event type "Registration". Then I created the four seminars as content, and couldn't figure out how to allow people to register for more than one, as conflict made the other three days unavailable as soon as a registrant registered for one day.

Then I went back and created four different event types, "spring seminar day 1, spring seminar day 2, etc." Then I recreated the four seminars, one per event type, and it allows registrants to register separately. This allowed registrants to register for more than one, but doesn't allow me to keep all sessions under the same seminar \[event type\] and doesn't work well with calendar if I decide to have more than one seminar per event per day \[when I would like to keep them all under the same event type\]. It also seems like I was missing a simple "no conflict" option when all four seminars were under the same event type.

Here's the basic layout of the two seminar \[registration type?\] & session \[event?\] types the Kobe Education Commission puts on;

* 3-5 day seminar \> 1 timeslot per day \> 1 session per timeslot Registrants can register for any of the events as there is no conflict with either timing or with having specific topics for different groups of registrants. I'd like these to be the same registration type "spring seminar" if possible.
* 1 day seminar \> 5 timeslots per day \> 3-5 sessions per timeslot Registrants can only register for one seminar per timeslot, and there may be specific sessions that a group of registrants isn't eligible for.

# Answer
This is my interpretation of your multi day seminars:

I think for your first scenario where there is no conflicting sessions, there is no need to enable RNG Conflict.

For the second scenario where you have multiple (3-5) sessions potentially running at the same time. You should have some field on the event nodes that uniquely identify each. You could do this by:

1. Adding a integer field representing the timeslot number (timeslot 1, 2, 3 etc). Or,
2. Add a date field on each event with the start datetime for each session. Then set RNG Conflict to use one of these options.

You may also want to add a field representing the overarching seminar. Resulting in something along the lines of:

Your site only needs a single event type (a node type, etc), and a single registration type no matter how many seminars you have. If you are customising your registration form then you may want to add more registration types, but this would be unusual.
> 1 votes

---
Tags: 8, rng
---


# Question
Title: Hide language settings on user account form (alternative to "dul")
The user account form has settings for "Language" and "Regional settings" (to choose a timezone).

A common use case is that a site is only built for one language (e.g. German), but the admin user still wants to see it in English.

So the two settings need to be removed from the admin page.

There used to be a module for this, DUL. But it is now tagged as "obsolete" and "unsupported".

If someone finds a solution, this would be a place to share it :) (this someone could be me.. we'll see)

And please no dirty js or css solutions.. I am sure there are better ways!

# Answer
Administration » Configuration » Regional and language » Regional settings

```
/admin/config/regional/settings

```
> 1 votes

---
Tags: 7
---


title: Exclude node title in bulk

text:
# Question
Title: Exclude node title in bulk
Is there a way to exclude titles in bulk? I want to exclude title of several nodes all at once.

I'm using Exclude Node Title to remove node titles to the display. However, I can only edit it one by one by opening and editing each nodes.

What I want is to update nodes by bulk if possible.

Thanks!

# Answer
> 0 votes
override the node template and remove title from there.

# Answer
> 0 votes
What @Mohammad AlQanneh means is the following:

a. Go to your theme / subtheme directory

b. create a file named node--MACHINE-NAME-OF-CONTENT-TYPE.tpl.php (example node--article.tpl.php) and paste the contents of the original node.tpl.php inside it

c. edit the file and remove the HTML / PHP code that prints the title, for example, remove or comment out this:

```
<a href="<?php print $node_url; ?>"><?php print $title; ?></a>

```

d. clear the caches, that is all.

# Answer
> 0 votes
Hope this solves your problem

```
function theme_preprocess_page(&$vars) {
  if ($vars['node']->nid == 'your node id' && $vars['node']->type == 'your-content-type') {
    unset($vars['node']->title);
  }
}

```

Add this code in your template.php and clear the cache

# Answer
> 0 votes
Now I understand well what you need and here is the way to do it:

a. create a custom Integer field called *field\_show\_title* with two possible values 1 or 0

b. use VBO to bulk update the desired nodes to set the custom field's value to 1 or 0

c. in the node--???.tpl.php file use PHP's if or switch & case statements to determine if the title should be shown or not based on the value of *field\_show\_title*

---
Tags: nodes
---


# Question
Title: How to add flag on each field in a node in Drupal?
I have created a membership based website in Drupal 7. I want the user should create his portfolio and upload his work images. So i created a content type called portfolio having image field with unlimited upload option and gave access to that role. Also i want the user to like other user's images. So i created a View in which all portfolio images displays. For like button, i used Flag module.

Now problem is, there is only option Node Flag in views that shows flag only on 1st image in that node. I want flag on each image field in views like Facebook. So technically user should create multiple nodes if flag need to appear on each image. But its very much complex. Is there any way to add flag on each field in content in views?

# Answer
> 2 votes
I am gonna say something different than @Volker, hopefully correct.

Important: You need to install the File Entity module to allow flags on your image field's multiple values.

Just tried this and it works for me, using:

* A multivalued Image field; setting its display "Format" to "Rendered file" and the "View mode" to "Teaser", here is a screenshot of my configuration:
* A new Flag for File entities; selecting the respective "Display in entity links" view modes. Selecting is optional, it should work out of the box.

And there is what I get:

Hope this helps!

# Answer
> 0 votes
AFAIK at the moment with flag module and views this isn't possible (see https://www.drupal.org/node/1024536) because multivalue-fields aren't identifiable with an ID. There's probably a workaround using the Field-Collection module for this as individual field-items are entities. For easy upload you could use Field Collection Bulkupload.

# Answer
> 0 votes
In views you can create a filter for the flagged images:

1. add a relation to the image:fid
2. add a relation to the flag: image
3. add a flag filter

---
Tags: 7, views, flags
---


title: How to override menu Item?

text:
# Question
Title: How to override menu Item?
I am using entity\_translation module for translating node titles. And with this Translate tab appears on node view like in screenshot.

I am trying to override titles and access permissions for this menu tab and found that its coded in **/sites/all/modules/entity\_translation/entity\_translation.node.inc** like below:

```
/**
 * Node-specific menu alterations.
 */
function entity_translation_node_menu_alter(&$items, $backup) {
  if (isset($backup['node'])) {
    $item = $backup['node'];
    // Preserve the menu router item defined by other modules.
    $callback['page callback'] = $item['page callback'];
    $callback['file'] = $item['file'];
    $callback['module'] = $item['module'];
    $access_arguments = array_merge(array(1, $item['access callback']), $item['access arguments']);
  }
  else {
    $callback = FALSE;
    $access_arguments = array(1);
  }

  $items['node/%node/translate']['page callback'] = 'entity_translation_overview';
  $items['node/%node/translate']['page arguments'] = array('node', 1, $callback);
  $items['node/%node/translate']['access arguments'] = $access_arguments;
  $items['node/%node/translate']['access callback'] = 'entity_translation_node_tab_access';
  $items['node/%node/translate']['file'] = 'entity_translation.admin.inc';
  $items['node/%node/translate']['module'] = 'entity_translation';
}

```

In my custom module I tried overriding like this:

```
function my_module_node_menu_alter(&$items, $backup) {
  $items['node/%node/translate']['title'] = "My New Title";
  $items['node/%node/translate']['access callback'] = 'my_module_transaltion_access';

}

function my_module_transaltion_access(){
   // code for my permissions according to user roles.
}

```

But I am not able to alter this menu item. Please suggest what is right way to do this ?

**UPDATE:**

```
function my_module_menu_alter(&$menu,&$items) {

   $items['node/%node/translate']['access callback'] = "my_module_transaltion_access";
}

function my_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {
    case 'menu_alter':

      // Move some of our hook implementations to the end of the list.
      $group = $implementations['my_module'];
      unset($implementations['my_module']);
      $implementations['my_module'] = $group;
      break;
  }
}

```

Thanks!

# Answer
> 0 votes
```
function my_module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  global $user;

  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && in_array($router_item['page_arguments'][$key]->type, array('link'))) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == 'node/%/translate') {
          if (add condition according to requirement) {
            unset($data['tabs'][0]['output'][$key]);
          }
        }
      }
    }
  }
}

```

With this code I am able to unset Translate tab according to user roles. NOTE: "link" is my content type.

# Answer
> 0 votes
Try hook\_menu\_alter() to alter the menu, https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu\_alter/7.

Moreover, entity\_translation\_node\_menu\_alter() is not a hook and it is a function called from entity\_translation\_menu\_alter().

---
Tags: 7, routes
---


# Question
Title: What to do for "Login attempt failed for admin." and "Access denied" to path admin?
In Watchdog, I started seeing several entries like this:

> Login attempt failed for admin.

And

> access denied 2016/04/04 - 15:06 admin

These are generating a fair number of log entries. The IP address is different for each request; they all geolocate to Russia.

Obviously, this is not me, and there doesn't appear to be any particular danger to my site, but is there a way to minimize such requests?

# Answer
> 1 votes
As an option you can rename path to login page, you can try Rename Admin Paths module to do it.

---
Tags: security, log-messages
---


# Question
Title: Custom Drupal breadcrumbs - how to disable the last item
I have a D8 custom module providing its own breadcrumbs. The breadcrumbs are shown perfectly, but the current page (last item) is shown as a link. I want to change Change this but as I see it, the ::build method requires the $links to be returned as an array of Link.

```
use ...

class BreadcrumbsBuilder implements BreadcrumbBuilderInterface {

  public function __construct() {
    ...
  }

  public function applies(RouteMatchInterface $route_match) {

    $result = // calculate logic
    return $result;
  }

  public function build(RouteMatchInterface $route_match) {
    $crumbs = new Breadcrumb();
    // prepare the data
    $links = $this->buildLinks($prepared_data);

    $crumbs->buildLinks($links);
      return $crumbs;
  }

  private function buildLinks($prepared_data) {
    $links = [
      Link::createFromRoute(t('Home'), '<front>'),
      Link::createFromRoute($title, 'entity.node.canonical', ['node' => $this->node->id()]),
    ];

    foreach($prepared_data as $data) {
      $links[] = Link::fromTextAndUrl($page_title, Url::fromUserInput($dummy_data));
    }
    return $links;
  }

}

```

The crumbs are shown properly as:

```
home >> My Title >> page_1 >> page_2

```

But page\_2 is the current page, so it should not show as a link

# Answer
> 1 votes
To answer my own question: The last link should point to route name `'<none>'` and that removes the href attribute from the item. So after all super easy.

```
// untested
foreach($prepared_data as $data) {
  $links[] = $is_last_link($data)
     ? Link::createFromRoute($page_title, '<none>')
     : Link::fromTextAndUrl($page_title, Url::fromUserInput());
  }

```

Related: It appears Drupal 8 core does not provide the current page in the breadcrumbs. The contributed module Easy Breadcrumbs does this for D7. The D8 version is in still in sandbox. Reference: Blog post.

---
Tags: navigation, breadcrumbs
---


title: Wrong $language_content variable

text:
# Question
Title: Wrong $language_content variable
I'm using entity translation module for node localization and `dpm($language_content)` always gives english, which is my default language. This outcome is for all languages, I don't understand what is the problem.

# Answer
The `$language_content` variable is not set to the language used for the currently shown node, but it contains the value set by the language negotiation providers.

See `language_initialize()`, which is the function that initialize that and other variables, and that is called from the following code.

```
  // Ensure the language is correctly returned, even without multilanguage
  // support. Also make sure we have a $language fallback, in case a language
  // negotiation callback needs to do a full bootstrap.
  // Useful for eg. XML/HTML 'lang' attributes.
  $default = language_default();
  foreach ($types as $type) {
    $GLOBALS[$type] = $default;
  }
  if (drupal_multilingual()) {
    include_once DRUPAL_ROOT . '/includes/language.inc';
    foreach ($types as $type) {
      $GLOBALS[$type] = language_initialize($type);
    }
    // Allow modules to react on language system initialization in multilingual
    // environments.
    bootstrap_invoke_all('language_init');
  }

```

The language negotiation providers are the ones you set in admin/config/regional/language/configure.

>

If none of the provider is enabled, which what happens by default, that variable will be set with an object for English language.
> 2 votes

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


# Question
Title: How to move the edit tab in user-profile.tpl.php
I would want to reorganize the profile of the users, in the following way:

1. Name (h1),
2. Custom field 1,
3. Custom field 2,
4. Edit tab ($tab),
5. Block.

I tried to delete the $tab variable in page--user.tpl.php, and add it in user--profile.tpl.php, but it does not work.

How to move the edit tab in user-profile.tpl.php ?

# Answer
> 0 votes
Ok, i find the answer :

```
function THEME_preprocess_user_profile(&$variables) {
  $variables['tabs'] = menu_local_tabs();
}

```

---
Tags: 7, theming
---


# Question
Title: Print view field direct in views-view-fields.html.twig
Is it posible to print all view field direct in views-view-fields.html.twig and sciping to use views-view-field.html.twig?

In my blog view I have a lot views-view-field.html.twig for every field type and this is just one view.

So is this posible and is this recomend?

# Answer
> 1 votes
Yes, that is possible, this is the most basic fields twig:

```
{% for field in fields -%}
    {{ field.content }}
{%- endfor %}

```

Then you loose most field configuration from views and can put in your own html structure.

You don't need to skip the field twigs for single fields, simply delete you own twigs and let the core twigs take over again.

---
Tags: views, 8
---


# Question
Title: How to delete files when the node that displayed them is deleted?
Is there a way to delete files/images from the server automatically when the main node is deleted?

How do I implement this?

# Answer
It's a revisions thing. I guess it makes sense. If you have revisions enabled for that content type, it keeps all your old files on the server (associated with old revisions), so replacing a file definitely is harder. If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question. Since a file with that name is kept on the server and there is a name duplication, it adds those "\_0", "\_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace. Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!
> 2 votes

# Answer
When a node is deleted. the images and other files uploaded in the node edit form are automatically deleted during cron tasks; the files are deleted if they have been uploaded more than 6 hours ago.

If, for any reason, you need to delete them faster, and before 6 hours are passed, you could use the following code. Put it in a file (e.g. delete-files.php) in the directory where Drupal is installed (which is the same directory where you find the cron.php file).

```
  /**
   * Root directory of Drupal installation.
   */
  define('DRUPAL_ROOT', getcwd());

  include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  // Delete 100 files at time.
  $result = db_query_range('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - 60 * 60
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {
        file_delete($file);
      }
    }
  }

```
> 0 votes

---
Tags: 7, nodes, media, files
---


# Question
Title: How to add a profile field in page--user.tpl.php
I need to put a profile field in page--user.tpl.php.

I try this :

```
function THEME_preprocess_page(&$variables) {
  global $user;
  $user_fields = user_load($user->uid);
  $variables['myfield'] = '';
  $myfield = $user->field_myfield;
  if($myfield) {
    $variables['myfield'] = $myfield['und'][0]['safe_value'];
  }
}

```

But i have an error :

```
Notice : Undefined property: stdClass::$field_myfield dans THEME_preprocess_page()

```

Do you know where should come the problem ?

# Answer
> 0 votes
try using field\_get\_items()

```
$field_myfield = field_get_items('user', $user, 'field_myfield');
$myfield_value = field_view_value('user', $user, 'field_myfield', $field_myfield[0]);
$variables['myfield'] = render($myfield_value);

```

More info here and here

# Answer
> 0 votes
```
  global $user;
  $user_full = user_load($user->uid);

  // option 1
  $field_items = field_get_items("user", $user_full, 'field_myfield');
  if ($field_items) {
    $variables['myfield_value'] = $field_items[0]['safe_value'];
  }

  // option 2
  $variables['my_renderable_field'] = field_view_field("user", $user_full, 'field_myfield');

```

**EDIT:**

If you are going with option 2 it can be printed in your tpl file like this:

```
<?php print render($my_renderable_field); ?>

```

Also note that field\_view\_field can take a view mode as parameter which is helpful if you want to display it in the tpl file in a manner different to what you specified in the user display settings for the default view mode.

---
Tags: 7, theming
---


# Question
Title: What does the votingapi_set_votes function in the votingapi module actually do?
I am trying to use the Voting API module to add a vote through a menu item. Meaning that when someone visits a menu item \[`the/menu/item`\] a vote is added to the database.

There is already the Voting API functions that does that. I don't understand what the `votingapi_set_votes` function in the Voting API module does.

I have read the website documentation however I don't understand what it does and how can I use it. And couldn't find an example of usage either.

I have tried the follwing to add a vote:

```
  $items['the/menu/path/1'] = array
  (
  'title' => 'Some title',
  'page callback' => 'my_page',
  'access callback' => TRUE
);

return $items;
}

function my_page(){

  $votes = array();
  $votes[] = array(
    'content_type' => 'news',
    'content_id' => 1025,
    'value_type' => 'points',
    'value' => '1',
  );

  $criteria = array(
    'content_type' => 'news',
    'content_id' => 1025,
    'function' => 'sum',
    'value_type' => 'points',
  );

  if (TRUE) {
    if (module_exists('votingapi')) {
      // die("test");
      votingapi_set_votes($votes);
      die();
      $result = (votingapi_select_results($criteria));
      print 'result is: '.$result[0][value];
      $result = '';
    }
  }
  return "true";
}

```

But it gives me an SQL error like so:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'content\_type' in 'where clause': SELECT votingapi\_vote.\* FROM {votingapi\_vote} votingapi\_vote WHERE (content\_type = :db\_condition\_placeholder\_0) AND (content\_id = :db\_condition\_placeholder\_1) AND (value\_type = :db\_condition\_placeholder\_2) AND (uid = :db\_condition\_placeholder\_3) ; Array ( \[:db\_condition\_placeholder\_0\] =\> news \[:db\_condition\_placeholder\_1\] =\> 1025 \[:db\_condition\_placeholder\_2\] =\> points \[:db\_condition\_placeholder\_3\] =\> 130 ) in votingapi\_votingapi\_storage\_select\_votes() (line 225 of C:\Users\tarek.ismail\public\egyptinnovate\sites\all\modules\contrib\votingapi\votingapi.module).

# Answer
> 0 votes
Here is a working example:

```
function YourModule_menu(){
  $items = array();
  $items['the/menu/path/1'] = array
    (
    'title' => 'Voting button',
    'page callback' => '_YourModule_voting',
    'access callback' => TRUE
    'type' => MENU_CALLBACK,

    );
  return $items;
}

function _YourModule_voting(){
  $nid=arg(3);
  $votes = array(
    'entity_type' => 'node',
    'entity_id' => $nid,
    'value_type' => "points",
    'value' => 1,
    'tag' => "like",
    );

  $criteria = NULL;

  if (module_exists('votingapi')) {
      votingapi_set_votes($votes);
  }

  return "true";
}

```

---
Tags: 7, rating
---


# Question
Title: Customizing taxonomy Term page with sticky articles
I am trying to create an educational website. I have created terms as

History, Science, Biology, Mathematics and Mathematics term, sub-term as Algebra, Trigonometry

I want to create a separate page like frontpage for each term with few posts sticky at top. For example When someone clicks on History then a page with teaser view of Articles like "About history", "Books for history", " Preparation Guide" will be top on that page list and all other nodes tagged with History term will come below these three posts.

And how can I set no of total posts of History term page as 10?

I am new to drupal and not able to find right modules. Stuck in this issue for 2 days, any help will be appreciated.

# Answer
You can create a custom module and implement `hook_menu_alter` for taxonomy terms.

In your custom callback you then filter by your taxonomy and intercept the ones you want and pass the rest to the default handler.

On the ones that you intercept you then render a custom view for that taxonomy. That view will just be a normal default view (no page) with an attachment as well. You set the attachment to the top of the other view and show teasers. The other view will show links only with an offset to not show the teaser nodes as well. Your view will be constructed with appropriate contextual filters that you will pass.

Your `MODULE.module` file:

```
function MODULE_menu_alter(&$items){
  // change taxonomy view path for certain vocabularies
  $items['taxonomy/term/%taxonomy_term']['page arguments'][] =   $items['taxonomy/term/%taxonomy_term']['page callback'];
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'MODULE_taxonomy_term_callback';
  $items['taxonomy/term/%taxonomy_term']['file path'] = drupal_get_path('module', 'MODULE') . '/includes';
  $items['taxonomy/term/%taxonomy_term']['file'] = 'MODULE_callbacks.inc';
}

```

Your `MODULE_callbacks.inc` file (located at `MODULE/includes`):

```
function MODULE_taxonomy_term_callback($term, $callback) {
  $function = __FUNCTION__ . '_' . $term->vocabulary_machine_name;
  if (function_exists($function)) {
    return $function($term);
  }

  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return $callback($term);
}

// one for each vocabulary
function MODULE_taxonomy_term_callback_TAXONOMYVOCABULARYMACHINENAME($term){
  $view = views_get_view('VIEW_MACHINE_NAME');
  $view->set_display('default');
  $view->set_arguments(array($term->tid));
  $view->pre_execute();
  $view->execute();
  return $view->render();
}

```

**You View(s) will be as follows:**

**Contextual filter**: Content (taxonomy in question)

**When the filter value is not available**

* Provide default value: Taxonomy term ID from URL
* Load default filter from term page.
> 0 votes

---
Tags: taxonomy-terms
---


title: Bakery doesn't pre-sync accounts

text:
# Question
Title: Bakery doesn't pre-sync accounts
I want to use the Bakery module to login and synchronize users, but I am not able to synchronize existing accounts. Users that exist only on slave cannot login confirms Bakery doesn't provide pre-sync facility.

May someone help me to synchronize existing user accounts, possibly at database level, for example with `drush rsync` or `sql sync`?

# Answer
I would go with the migrate module, it's no syncing but export and import in two steps. But i cannot tell you if existing users will be replaced, skipped or doubled ..

Maybe account\_sync does what you want.

Also have a look here How to sync users profiles and user tables in 2 drupal sites.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: PrePopulate a Node URL from Previous Node via Rules Link to Add Content Form
### Scenario

A Content Node's URL needs to be incorporated into an Application (Node Add) for a future reference so the users can view their Applications made. The user clicks on a Rules Link (i.e.'Contact User') button and the user is taken to a Form (which for my purposes creates a new content Node 'Application',so the entity is Prepopulated with the referring Node URL (or a linked Title) so the user can later view it in a list and for backend managment purposes, the Application Nodes will be CRON purged once in a while as required.

I have installed https://www.drupal.org/project/entityreference\_prepopulate module along with Tokens but it doesn't included the previous Node URL as expected although it does add the 'current' mydomain.com URL, so it's working to some degree. And yes, I have looked at online Youtube etc videos, but they don't seem to cover my requirements.

I'm at a loss understanding how the process is working backend in Drupal. I'm not sure if in the Rules Link Component if I need to add the URL first then move to the Form page next (using Rules), or if that is completely an incorrect approach on my part and I need to use an API or whatever.

Any advice is very much appreciated. Thanks.

# Answer
> 1 votes
You need to have an entity reference field in your form and set it to reference nodes.

Normally, you would then build your link with the current node's **Nid** to fill the entity reference field on the next page.

```
http://example.com/node/add/article?field_previous_page=123

```

However, because you are using rules link, I guess you have to create a redirect to the form based on the current node replacement pattern available.

***Or below is a solution if that doesn't work out.***

> If you really must use rules link and can't get normal methods to work, then Rules Session Variables would be an easy solution. It will give you actions to let you add the node's id into $\_session.
>
> Then when you the user saves the form, have another rule that checks if $\_session exists and if so, take the Nid, fetch the node and then set the entity reference field with it.

So yeah, do you need to use rules link?

---
Tags: rules, entities
---


title: Get referenced node fields in twig

text:
# Question
Title: Get referenced node fields in twig
In Drupal 8, I have a content type, that has an "entity\_reference" field and I wish to access the referenced node's fields in twig template. the kint() output for the field is:

In this list I can't find the referenced node's field values. How can I (if at all possible) load the node or node fields/values in twig?

Best,

Alari

# Answer
The referenced nodes are inside the list and you can get the first list item with `.0`, the referenced node with `.entity` and then the first field value:

For example if you are in a page or node template:

```
{{ node.field_reference.0.entity.field_in_referenced_node.0.value }}

```

You can ommit `.0` in both cases, when you only want to get the first value.

Other examples could look like this, but your question is unclear exactly where you are:

```
{{ item.content['#item'].entity.field_in_referenced_node.value }}
{{ elements['#items'].0.entity.field_in_referenced_node.value }}

```

**Edit: Counting the items in multivalue fields**

```
{{ node.field_reference.getvalue|length }}

```

You can't use `count()` in twig, because this is not on the whitelist for allowed methods. This uses `getvalue()` to get the array of the field and then counts the array keys.
> 17 votes

---
Tags: theming, 8, entities
---


# Question
Title: Use swipe to switch blocks for mobile screen
In the mobile version of my site I would like to use swipe to cycle through different blocks. E.g. a certain block (view) is displayed and swiping the screen would show the next one in the same region. Is it possible to achieve this? Thanks!

# Answer
Work with a views - slideshow, like owl or slick, where you show these blocks using views\_block\_area.

Show this view by css-media-queries, in which you hide the normal content .. like:

```
.my-view {display: block;}
.my-block {display: none;}
@media(min-width:34em){}
@media(min-width:48em){
  .my-view {display: none;}
  .my-block {display: block;}
}
@media(min-width:62em){}
@media(min-width:75em){}

```

more info on the web or here https://stackoverflow.com/questions/18424798/twitter-bootstrap-3-how-to-use-media-queries
> 1 votes

---
Tags: blocks, theming
---


title: Views header with custom summary

text:
# Question
Title: Views header with custom summary
Drupal 7 I have a content type called "Question" with a Answered/Not\_answered field for editors. I want to create a view of all questions which has a header of answered and unanswered questions. Something like this:

Answered questions: 10 Unanswered questions: 2

with links to answered and unanswered questions.

Can anyone please help me to create this view?

Many thanks, Alice

# Answer
In order to accomplish this task you need to create two attachments and tie them to your page. First attachment should display 'Global: Result summary' result with all answered questions. Second attachment should display Global: Result summary' result with all unanswered questions.
> 0 votes

---
Tags: 7, views
---


title: How does block page whitelisting work?

text:
# Question
Title: How does block page whitelisting work?
I've created a custom entity which only should to be displayed on pages provided by the user.

To handle multiple pages, I've created a textarea where the user can enter a page per line. Just like the blocks module.

My problem here is that I don't know how to make the query that loads the correct entity by page.

My guess is that it should be something like this:

`SELECT * FROM {my_entity} WHERE pages LIKE :path`

However, that leads to the problem that 'node/1/edit' also loads the entity when the user has entered 'node/1'.

I know this functionality already exists somewhere in Drupal because it is used for blocks, but I can't find it in the code...

# Answer
> 1 votes
The related code is found in `block_block_list_alter()` function, inside `/modules/block/block.module` file.

Here's how you would perform a similar check in your code:

```
// Get the pages to check. This should be in the same format as what Drupal
// core uses - meaning one path per line and you can use placeholders.
//
// Variable below is just as an example.
$pages_to_check = 'page1' . PHP_EOL . 'page2' . PHP_EOL . 'page3/*';
// This is a good practice, because it will make sure that paths are always
// checked consistently and won't depend on the case.
$pages = drupal_strtolower($pages_to_check);
// Compare the lowercase internal and lowercase path alias (if any).
$page_match = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
  $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
}
// Now you can do whatever you want based on whether or not the current path
// matches the pattern. For example:
if ($page_match) {
  // You are on one of the listed pages.
}
else {
  // You are not on one of the listed pages.
}

```

Hope this helps.

# Answer
> 0 votes
Aram Boyajyan answered my question correctly. This solution, however, is not usable by me. The 'block-approach' does a page check on every block, I want to load a number of entities with a given page (or pages) from the database without preloading all entities.

I have a custom entity with a multiline textfield `path`. In my save function I make sure the path always ends with a newline, also if there is only one line.

I wrote the following function to load all entities by path(s):

```
function load_entities_by_page($paths = array()) {
  // Create a where array with placeholders.
  $where = array();
  $where_tokens = array();
  foreach ($paths as $key => $path) {
    $where[] = 'path LIKE :path' . $key;
    // Every path must end with a newline.
    $where_tokens[':path' . $key] = '%' . str_replace('%', '*', $path) . "\n" . '%';
  }

  // Retrieve all entity IDs.
  $ids = db_query('SELECT id from {entity_name} WHERE ' . implode(' OR ', $where), $where_tokens)->fetchAllAssoc('id');

  return $ids;
}

```

---
Tags: 7, blocks
---


# Question
Title: How I get the name of the taxonomy term reference of the content type
I created a content type. One of the field of the content type is entity term reference. Now I want to fetch the term of the particular content type and load the nodes that contain the term.I used the following code. But does not get the answer. Any error in my concept?

```
$aupl_node_query = new EntityFieldQuery();
$aupl_referrence = $aupl_node_query
->entityCondition('entity_type',  'taxonomy_term')
->execute();
dpm($aupl_referrence);
$aupl_node = node_load_multiple(array(), $aupl_referrence, true);

```

# Answer
You can refer to this article having detailed information about entity queries.

You should use `->entityCondition('entity_type', 'node')` rather than using `->entityCondition('entity_type', 'taxonomy_term')`
> 1 votes

# Answer
You need to add condition by taxonomy term ID in your query

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'YOUR_CONTENT_TYPE')
  ->propertyCondition('status', 1)
  ->fieldCondition('YOUR_FIELD_REFERENCE_NAME', 'tid', $YOUR_TAXONOMY_TERM_ID);
$query = $query->execute();

```
> 0 votes

---
Tags: entities
---


title: form_alter: Inline entity Form

text:
# Question
Title: form_alter: Inline entity Form
I am using IEF and all is well...until I try ad implement hook\_form\_alter() and when I access the form via IEF UI (as opposed to directly modifying the entity) none of the changes I make appear to take effect.

I see everything is posted to a ajax/system as well as pulled from when assembling the form...

Is it not possible to hide form elements from the IEF as I would when directly hooking?

Any ideas?

Each line item has a price field which I need to iterate and sum and the apply to the root node. Figured as this module was used in commerce this would be standard practice.

# Answer
> 29 votes
IEF has a hook as outlined in the inline\_entity\_form.api.php file.

```
/**
 * Perform alterations before an entity form is included in the IEF widget.
 *
 * @param $entity_form
 *   Nested array of form elements that comprise the entity form.
 * @param $form_state
 *   The form state of the parent form.
 */
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_line_item') {
    $entity_form['quantity']['#description'] = t('New quantity description.');
  }
}

```

Check the inline\_entity\_form.api.php file as there are a few hooks that you may be able to use.

# Answer
> 6 votes
Also check out hook\_field\_widget\_WIDGET\_TYPE\_form\_alter()

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function MY_MODULE_field_widget_inline_entity_form_form_alter(&$element, &$form_state, $context) {
  // Move the Add Existing button to the left of the Add New button.
  if (isset($element['actions']['ief_add_existing'])) {
    $element['actions']['ief_add_existing']['#weight'] = -50;
  }
}

```

---
Tags: forms, entities
---


# Question
Title: Menu does not set active trail when generating tree in theme file
I want to display the whole menu tree in my Drupal 8 theme to be able to show/hide submenus using javascript. To accomplish that, I added the following code to my theme file:

```
function pspartner_preprocess_page(&$variables) {

  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);

  // Make menus available in templates
  $variables['main_menu_tree'] = $tree;
  $variables['main_menu'] = $menu;
}

```

This works, but the active trail is not set.

# Answer
Set the active trail in the MenuTreeParameter object per MenuTreeParameters::setActivityTrail. This requires knowing the menu link plugin ids, which can be retrieved using MenuActiveTrail::GetActiveTrailIds (linked from the previous API page).

```
  $active_trail = \Drupal::service('menu.active_trail');

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();
  $parameters->setActiveTrail($active_trail->getActiveTrailIds($menu_name));

```
> 0 votes

---
Tags: theming, 8, navigation
---


title: Empty search redirect to Home page

text:
# Question
Title: Empty search redirect to Home page
I am using Drupal 7 and my `search functionality` is not working properly.

When I click on search button without enter any `keyword` it redirects to `home page` with showing the message `Please enter some keywords`. and same thing happens when there is `no result` found for the respective `search keyword`.

So can anyone please guide me how can I redirect the empty search to search page?

Thanks in advance...

# Answer
> 0 votes
Something like this should work:

```
/**
 * Implements template_preprocess_search_results.
 */
function YOUR_THEME_preprocess_search_results(&$variables){
  $results = $variables['results'];
  if(count($results) == 0){
    drupal_goto('<front>');
  }
}

```

---
Tags: search, views
---


# Question
Title: SQL query to access a field collection's data? At them moment, I'm only getting field_collection_item returned
In the below example, I am trying to return the value of a field from all the field collections in the database but only get *field\_collection\_item*. This example is just the most basic field collection sql possible.

```
SELECT field_collection_item.item_id AS item_id, 'field_collection_item' AS field_data_field_grade_decimal_field_collection_item_entity_
FROM
field_collection_item field_collection_item

```

What do I need to change in this example? My SQL is terrible unfortunately. I just can't return any values from field collections using sql. I need to be able to do this for Forena Reports. I'm getting the above code from views which returns the field collection values.

# Answer
You can use the field\_collection\_field\_get\_entity() function to obtain the desired result without writing SQL, like this:

`$node = node_load(12);
$items = field_get_items('node', $node, 'field_fc_field');
foreach ($items as $item) {
$fc = field_collection_field_get_entity($item);
// Do something with $fc
dpm($fc);
}`
> 0 votes

---
Tags: entities, database
---


# Question
Title: Content Migrate throwing `MediaInternetNoHandlerException` errors for embedded video fields
I am getting the following error on multiple nodes when using the content migrate module on a Drupal 6 to 7 upgrade.

```
Requesting rollback of field "field_video" due to failure to convert record:array (                                                                                [error]
  'entity_id' => '5703',
  'revision_id' => '36928',
  'field_video_embed' => 'https://www2.City.urbana.il.us/_Video/_Boards_-_Commissions/Community_Development_Commission/2016/03-22-16.flv',
  'field_video_value' => 'https://www2.City.urbana.il.us/_Video/_Boards_-_Commissions/Community_Development_Commission/2016/03-22-16.flv',
  'field_video_provider' => 'zzz_custom_url',
  'field_video_data' =>
'a:5:{s:35:"emvideo_zzz_custom_url_data_version";i:1;s:3:"url";s:110:"https://www2.City.urbana.il.us/_Video/_Boards_-_Commissions/Community_Development_Commission/2016/03-22-16.flv";s:4:"size";s:9:"416649450";s:4:"mime";s:11:"video/x-flv";s:4:"type";s:3:"flv";}',
  'field_video_status' => '1',
  'field_video_version' => '0',
  'field_video_title' => NULL,
  'field_video_description' => NULL,
  'field_video_duration' => '0',
  'delta' => '0',
  'entity_type' => 'node',
  'language' => 'und',
  'bundle' => 'meeting',
)  Cause: exception 'MediaInternetNoHandlerException' with message 'Unable to handle the provided embed string or URL.' in
/Users/cwahlfeldt/Sites/dev.urbanaillinois.us_D7/sites/all/modules/media/modules/media_internet/media_internet.module:119
Stack trace:
#0 /Users/cwahlfeldt/Sites/dev.urbanaillinois.us_D7/sites/all/modules/emfield/emfield.module(143): media_internet_get_provider('https://www2.Ci...')
#1 /Users/cwahlfeldt/Sites/dev.urbanaillinois.us_D7/includes/module.inc(1157): emfield_content_migrate_data_record_alter(Array, Array, Array, NULL)
#2 /Users/cwahlfeldt/Sites/dev.urbanaillinois.us_D7/sites/all/modules/cck/modules/content_migrate/includes/content_migrate.admin.inc(410): drupal_alter('content_migrate...', Array, Array, Array)
#3 [internal function]: _content_migrate_batch_process_migrate_data('field_video', Object(DrushBatchContext))
#4 /Users/cwahlfeldt/.composer/vendor/drush/drush/commands/core/drupal/batch.inc(149): call_user_func_array('_content_migrat...', Array)
#5 /Users/cwahlfeldt/.composer/vendor/drush/drush/commands/core/drupal/batch.inc(99): _drush_batch_worker()
#6 /Users/cwahlfeldt/.composer/vendor/drush/drush/includes/batch.inc(93): _drush_batch_command('360')
#7 /Users/cwahlfeldt/.composer/vendor/drush/drush/commands/core/core.drush.inc(1145): drush_batch_command('360')
#8 [internal function]: drush_core_batch_process('360', '360')
#9 /Users/cwahlfeldt/.composer/vendor/drush/drush/includes/command.inc(362): call_user_func_array('drush_core_batc...', Array)
#10 /Users/cwahlfeldt/.composer/vendor/drush/drush/includes/command.inc(214): _drush_invoke_hooks(Array, Array)
#11 [internal function]: drush_command('360', '360')
#12 /Users/cwahlfeldt/.composer/vendor/drush/drush/includes/command.inc(182): call_user_func_array('drush_command', Array)
#13 /Users/cwahlfeldt/.composer/vendor/drush/drush/drush.php(92): drush_dispatch(Array)
#14 /Users/cwahlfeldt/.composer/vendor/drush/drush/drush.php(61): _drush_bootstrap_and_dispatch()
#15 /Users/cwahlfeldt/.composer/vendor/drush/drush/drush.php(16): drush_main()
#16 {main}

```

This happens for hundreds of nodes on the site and they all seem to be using a custom url to a video on a secure server somewhere else. The media module isn't liking the custom urls. I know the videos exist because I can plug the URL (https://www2.City.urbana.il.us/\_Video/*Boards*-\_Commissions/Community\_Development\_Commission/2016/03-22-16.flv) in and the video will download (using chrome).

p.s. I am attempting the migration locally if that has anything to do with it.

# Answer
Is the target field set up to handle urls that end in .flv (flash video format)?

Is this a GUI only migration and what hard and soft dependencies are set up?

I know you can migrate video urls I did thousands of them last year with no issues at all. But I was using coded migration classes not simply relying on the drupal to drupal migration built in classes. I was not doing Drupal to Drupal but some Proprietary CMS to drupal.

So first check that the target field takes the url from the source and makes sense of it. If that works make sure the .flv video format is accepted by the media field and then if all else fails you will have to write code to handle that migration.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Is there a way to restrict some pages like node/add, /user/login and more?
Can we restrict some page like

* node/add
* /user
* /user/register - as I dont have login/registration page at all
* /user/login
* node/200 or node/500 - so that may be of any content type

and it should be unlimited. I need to show Access denied page when somebody accessed those pages.

Though I can use programmatically `drupal_access_denied()` function, do we have any other option on this.

# Answer
You can use the Rules module to restrict access to those selected pages. Here is a rule (in Rules export format) which should be pretty close to implement such access restrictions as you're asking for:

```
{ "rules_limit_access_to_some_urls_" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "node\/add",
                  "user",
                  "user\/register",
                  "user\/login",
                  "node\/200",
                  "node\/500"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "Access to the content located at the path you tried to use is not allowed.\r\n\u003Cbr \/\u003E\r\nIf you think this is an error, please contact us.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

Check the paths in the above rule to ensure it fits your own needs. Also note that I include an extra path that corresponds to "`node/*/something`" (in case you'd also want to limit access to any such URL. Replace the `something` in it to fit your needs. Or if you don't have such URLs then just remove that entire Rules Conditions (with the `regex` in it).

And indicate the correct path of the redirect to be perform (= change the "`no_access`" make it fit your "no access" page). Possibly you may also want to adapt the roles for which these validations should be applied.

For more details/background about using such rule, refer to my answer to the question "How to make the permissions of a module more granular?".
> 1 votes

---
Tags: 7, users
---


title: How to see if the test works?

text:
# Question
Title: How to see if the test works?
There is a way to see if the Drupal tests are working? I wanted to test the **FileSystemTest**, but when I type `phpunit` command on the test folder this error appears:

```
1) Drupal\Tests\Core\File\FileSystemTest::testChmodFile
Argument 1 passed to Drupal\Core\File\FileSystem::__construct() must be an instance of Drupal\Core\File\StreamWrapperManagerInterface, instance of Mock_StreamWrapperManagerInterface_428d696c given, called in /var/www/html/drupal-8.0.5/core/lib/tests/FileSystemTest.php on line 43 and defined

/var/www/html/drupal-8.0.5/core/lib/Drupal/Core/File/FileSystem.php:62
/var/www/html/drupal-8.0.5/core/lib/tests/FileSystemTest.php:43
/home/bianca/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:153
/home/bianca/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:105

```

Someone know how to make the test work with phpunit?

# Answer
> 1 votes
See https://www.drupal.org/node/2116263.

You either need to run it inside the core folder, or (easier IMHO), you need to pass the -c core argument, so it finds the phpunit documentation.

Also note that only a part of Drupal's tests are phpunit, others are based on our own test framework and you need to run them with run-tests.sh or through the UI.

That said, you only need to run core tests if you work patches for Drupal core. Drupal's tests always path, nothing is added unless it is passing all tests.

---
Tags: 8, testing
---


# Question
Title: How to disable/enable a context programmatically
I want to disable contexts programmatically (for automated updates, where a new release of a website needs a context to be disabled).

I manage contexts using Features, but Features doesn't hold the enabled/disabled status of the context.

I can't find a function to change context status programmatically. There's a support request but the snippet is not working (nothing happens, context remains the same status).

After some investigation I came across the context\_status variable. It seems to hold an array with context names as key and TRUE as value: each of these contexts is disabled. If you edit that variable by unsetting one context, the context becomes enabled.

So it seems the only way to disable/enable a context programmatically is to edit this conext\_status.

Is there a better way to do it?

# Answer
> 5 votes
Use the context\_status to enable/disable contexts.

This variable is an array with context names as key and TRUE as value: each of this context is disabled.

To disable a context: add a new pair to the array like this:

```
$contexts = variable_get('context_status', array());
$contexts['context_name'] = TRUE;
variable_set('context_status', $contexts);

```

To enable a context: unset the context name from context\_status.

```
$contexts = variable_get('context_status', array());
unset($contexts['context_name']);
variable_set('context_status', $contexts);

```

Also you can use Features, exporting the context\_status to a feature.

# Answer
> 0 votes
You may also find Context Disable Context to be useful. It is a Context plugin that adds a reaction which allows you to disable a context.

---
Tags: 7
---


# Question
Title: Custom prefix for each value of a multi-value field
I have a number field where a user needs to enter two values. Each value should have a custom prefix but that isn't possible within the field settings.

Does anybody know how this can be done? Thanks.

# Answer
> 1 votes
That's how you can add prefixes to node output (replace view\_mode and field\_name to yours):

```
/**
 * Implements hook_preprocess_field().
 */
function mymodule_preprocess_field(&$vars) {
  if ($vars['element']['#entity_type'] == 'node' &&
      $vars['element']['#view_mode'] == 'full' &&
      $vars['element']['#field_name'] == 'field_number') {

    $vars['items'][0]['#markup'] = '<span>$</span>' . $vars['items'][0]['#markup'];
    $vars['items'][1]['#markup'] = '<span>€</span>' . $vars['items'][1]['#markup'];
  }
}

```

# Answer
> 1 votes
You can use form\_alter function to do it:

```
/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_number'][LANGUAGE_NONE][0]['value']['#prefix'] = '$';
    $form['field_number'][LANGUAGE_NONE][1]['value']['#prefix'] = '€';
  }
}

```

---
Tags: entities
---


title: How do I theme the user profile?

text:
# Question
Title: How do I theme the user profile?
I would like to create a custom template for the user profile view. With the help of "Theme debug" I figured out that I need to create a template named html--user.html.twig, but even if I copy all content of page.html.twig to my new template, I do get a blank page for any user profile now. Can anyone tell me what I'm doing wrong? I cleared all caches though.

Which content do I have to copy to a custom template (suggested file name)?

# Answer
> 4 votes
html--user.html.twig would be the template file used instead of html.html.twig when viewing a user profile (for example, for http://example.com/user/1). It is not the template file that shows the content of a user profile, but it's the template file that contains the basic structure of a Drupal page; in fact, its default content is the following one.

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes }}>
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

```

page.html.twig is the template file for a generic page; that is why you are getting a white page for user profile pages.

The template file for a user profile is user.html.twig, and its default content is the following one.

```
<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

```

As you see the variable it receives are completely different from the ones the other two template files (html.html.twig and page.html.twig) receive. That is why using the wrong template gives you a blank page.

---
Tags: 8, theming
---


# Question
Title: How do I make ugly URLs such as "/index.php?main_page=about_us"?
I'm converting a Zen Cart site to Ubercart and need to keep Zen Cart’s ugly URLs for SEO purposes. The site is top ranking on Google Search for their keywords and I’ve been advised that changing the URLs to something cleaner could potentially hurt rankings.

I wonder if there is any way to give a node a URL like `http://example.com/index.php?main_page=about_us`?

By default Drupal encodes special characters, so it tries to make my URL `/index.php%3Fmain_page%3Dabout_us` and I also get a 403 error.

# Answer
My advice would be to keep Drupal's URL handling as is and simply configure a set of redirects with code 301 in your .htaccess.
That way your URLs will maintain their google ranking.

A useful quote:

> "Be aware that when moving a page from one URL to another, the search engines will take some time to discover the 301, recognize it, and credit the new page with the rankings and trust of its predecessor. This process can be lengthier if search engine spiders rarely visit the given web page, or if the new URL doesn't properly resolve."

This is an excerpt from https://moz.com/learn/seo/redirection, I would recommend reading that whole article, it's quite useful.

And an example of such a redirect:

```
RewriteCond %{QUERY_STRING}     ^main_page=about_us$     [NC]
RewriteRule ^.*$             /node/1234     [NC,L,R=301]

```

Hope this helps!
> 6 votes

# Answer
I agree with one of the comments below the question like "***Drupal would not let you set something like `index.php?main_page=about_us` as path alias ...***". However, you could use the the Rules module to get this to work, together with the Rules URL Argument module. It will make the value of the URL argument available as new variable to Rules. Here is a quote about the Rules URL Argument module (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 1 votes

# Answer
You can disable clean URL's of your Drupal website on the following link:

http://example.com/admin/config/search/clean-urls

Further if you want some help you can go through the community documentation about Disabling clean URLs.

Besides that for the SEO purpose you should use your content with keywords and meta tags, there are several modules available for SEO under https://www.drupal.org.

One of the most popular modules for SEO is Metatag module.
> 0 votes

---
Tags: .htaccess, uri
---


# Question
Title: Strip HTML tags from Field Collections in Services Views
I'm trying to strip the HTML tags from a JSON response I generated using Services Views, but I'm not having any luck so far. I have a content type with a Field Collections field in it that is outputting HTML tags no matter what I do. I've tried the following:

* Check Strip HTML tags in the field settings in the view
* Set customize field HTML to 'None'
* Set Customize field and label wrapper HTML to 'None'
* All combinations of the above
* Making sure to turn of all 'Provide default field wrapper elements' options

Am I missing anything? My output still looks like this in my json:

```
"Animals": [
            "<div class=\"entity entity-field-collection-item field-collection-item-field-product-animals clearfix\">\n  <div class=\"content\">\n    <div class=\"field field-name-field-product-animal field-type-taxonomy-term-reference field-label-above\"><div class=\"field-label\">Animal: </div><div class=\"field-items\"><div class=\"field-item even\">Big</div></div></div><div class=\"field field-name-field-product-withdrawal-time field-type-text field-label-above\"><div class=\"field-label\">Withdrawal time: </div><div class=\"field-items\"><div class=\"field-item even\">25 dg</div></div></div>  </div>\n</div>\n",
            "<div class=\"entity entity-field-collection-item field-collection-item-field-product-animals clearfix\">\n  <div class=\"content\">\n    <div class=\"field field-name-field-product-animal field-type-taxonomy-term-reference field-label-above\"><div class=\"field-label\">Animal: </div><div class=\"field-items\"><div class=\"field-item even\">Rund vlees</div></div></div><div class=\"field field-name-field-product-withdrawal-time field-type-text field-label-above\"><div class=\"field-label\">Withdrawal time: </div><div class=\"field-items\"><div class=\"field-item even\">21 dg</div></div></div>  </div>\n</div>\n",
            "<div class=\"entity entity-field-collection-item field-collection-item-field-product-animals clearfix\">\n  <div class=\"content\">\n    <div class=\"field field-name-field-product-animal field-type-taxonomy-term-reference field-label-above\"><div class=\"field-label\">Animal: </div><div class=\"field-items\"><div class=\"field-item even\">Pluimvee ei</div></div></div><div class=\"field field-name-field-product-withdrawal-time field-type-text field-label-above\"><div class=\"field-label\">Withdrawal time: </div><div class=\"field-items\"><div class=\"field-item even\">6 dg</div></div></div>  </div>\n</div>\n"

```

Any help on this is greatly appreciated.

# Answer
> 0 votes
*You have to tell use what you have done so far.*

To strip tags use strip\_tags php code. This function takes two parameters:

```
string strip_tags ( string $str , [string $allowable_tags ] )

```

The first argument is the string and the optional second parameter is to specify tags which should not be stripped. For example

```
<?php
    echo strip_tags("Hello <b><i>world!</i></b>","<b>");
?>

```

Will output this

> Hello **world!**

Not

> Hello ***world!***

---

I guess you have to use views\_datasource module to generate JSON. I have already used this module and no default HTML tag were inserted by the View.

**Did you try preprocess functions to strip the tags from the view?**

# Answer
> 0 votes
You can override the output using `hook_preprocess_HOOK` and expose it into the variable, for example:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_views_view_field(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'my_view':
      // @see: views-view-field--my-view--page--field-foo.tpl.php
      $node = entity_metadata_wrapper('node', $vars['row']->nid);
      $vars['value']  = '';

      foreach ($node->field_foo_collection->getIterator() as $item) {
        foreach ($item->field_multivalued as $value) {
          $vars['value'] .= '[ ' . $value . ' ], ';
        }
      }
    break;
  }
}

```

Then print the `$value` in your template file (e.g. `views-view-field--my-view--page--field-foo.tpl.php`), e.g.

```
<?= $value ?>

```

---
Tags: views, entities, services
---


# Question
Title: Get field_collection values in field template
I have installed field\_collection and have a collection called **field\_contact**, each entry of which has a field called **field\_contact\_url**

I'm trying to customise the display of that field by overriding the view template, using the file **views-view-field--field-contact.tpl.php**

The template is being used, if I put a simple **print 'hello'** I can see the hello come up, but I cannot figure out how to access the field\_collection properties. I've gone through every answer and example I can find on google, but all of them seem to rely on a variable that is not there.

* `$content` is not present
* `$node` is not present
* `$field` is present, but `$field->field->id` is empty
* `$items` is not present

I tried using this example, but the $rows is not showing up (perhaps because I put the functions in the wrong file... I put them both in the template.php file.

I have spent 6 hours trawling through Drupal docs, would really appreciate if someone could help me figure out what variables I need or where I need to put the template file so the right variables become available.

# Answer
This is the solution I came up with. The first line is a bit of a hack and I think is not very robust.

Also, I think i'm not using the entity\_metadata "way" of accessing the contact fields - but it works for now.

Would welcome suggested improvements.

```
$candidate_node = node_load($row->node_node_nid);
$survey_node = node_load($row->{$field->field_alias});

$candidate_wrapper = entity_metadata_wrapper('node', $candidate_node);
$survey_wrapper = entity_metadata_wrapper('node', $survey_node);

foreach ($candidate_wrapper->field_contact->value() as $contact) {
    if (array_key_exists('und', $contact->field_type)) {
            $key = $contact->field_type['und'][0]['value'];
            $value = $contact->field_contact_url['und'][0]['safe_value'];
            print sprintf($format[$key], $key, $value, ucfirst($key), $score);
    }
}

```
> 0 votes

# Answer
Theming field collections is more like theming a node than a field since they are custom entities. I haven't tried to render a field collection as a views field, but I'm assuming it's similar to rendering it on a field level.

It'll probably give you a list of entity ID's instead handy field arrays. You'll have to load the entities from there and then render all the fields inside.

I preprocess the crap out of field collections instead of trying to handle everything in TPL's.

```
$fcIDs = /* array of Field Collection ID's */;
$fcRaw = entity_load('field_collection_item', $fcIDs);
// Reset array to start at 0 instead of using ID as index
  $fcData = array_values($fcRaw);

  // Figure out what fields the FC has and normalize them for optimal theming
  $fcFieldsInfo = field_info_instances('field_collection_item', $fieldName);
  $fcFieldNames = array_keys($fcFieldsInfo);
  foreach($fcData as $i => $fcDataInstance){
    foreach($fcFieldNames as $fcFieldName){
      $fcData[$i]->$fcFieldName =
        field_get_items(
          'field_collection_item',
          $fcDataInstance,
          $fcFieldName);
    }
  }

```

Field collections are powerful, but a bit unwieldly. I wrote myself a number of helper functions to help work with them. Hopefully this helps!
> 0 votes

# Answer
Define the preprocess hook (`hook_preprocess_HOOK`) for your view, so you can write a logic there and expose it into the variable, e.g.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_views_view_field(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'my_view':
      $node = entity_metadata_wrapper('node', $vars['row']->nid);
      // For single valued field.
      $field = $node->field_contact->field_contact_url->value();
      // For multi valued field.
      foreach ($node->field_contact->getIterator() as $item) {
        $vars['value'][] = $item->field_contact_url->value();
      }
    break;
  }
}

```

Then print your value in the template file (`views-view-field--field-contact.tpl.php`), e.g.

```
<?= $value ?>

```
> 0 votes

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


title: Hiding tab request new password

text:
# Question
Title: Hiding tab request new password
I want to remove the option of request new password from admin section. I have Drupal 8.

# Answer
> 0 votes
```
/**
 *Implements hook_form_FORM_ID_alter().
 */

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  unset($form['account']['pass']);
}

```

Hope it works.

---
Tags: users
---


# Question
Title: entity translation access permission alter
I'm using Entity Translation for node translations.

I would like to modify access to edit form for this translation language based on roles and node properties. I've a field in the node entity with a select list of languages, translator should only access translate nodes in languages that are checked in that list.

Which is the best option to modify the access to the **node/{NID}/edit/{LANGUAGE}** ?

* `hook_menu_alter` ?
* `hook_node_access()`: this hook is called but how can I get the language? (`$_GET` could be problematic I think).
* Extending the `EntityTranslation` class?
* Other?

# Answer
> 0 votes
This is how its working for me, with args() we can get path ie english or any other language node is there :

> Example Paths in my case:
>
> node/\[nid\]/edit/add/sv/en
>
> node/\[nid\]/edit/add/en/sv
>
> node/\[nid\]/edit/sv
>
> node/\[nid\]/edit/en

```
define('ROLE_EDITOR',4); // role ID 4
define('ROLE_EDITOR_ENGLISH',10); // role ID 10

function my_module_node_access($node,$op,$account) {
  global $user;

  if (in_array(ROLE_EDITOR, array_keys($user->roles)) && !in_array(ROLE_EDITOR_ENGLISH, array_keys($user->roles))) {
    if(arg(3)== "en"){
      return NODE_ACCESS_DENY;
    }
    if(arg(3) == "add" && arg(4) == "sv"){
      return NODE_ACCESS_DENY;
    }
  }

  if (!in_array(ROLE_EDITOR, array_keys($user->roles)) && in_array(ROLE_EDITOR_ENGLISH, array_keys($user->roles))) {
    if(arg(3)== "sv" || arg(3)== NULL){  // Null is need to add as edit and edit/sv is same in my case because sv is defult language
      return NODE_ACCESS_DENY;
    }
    if(arg(3) == "add" && arg(4) == "en"){
      return NODE_ACCESS_DENY;
    }
  }

}

```

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


# Question
Title: How to force entity translations to load in a certain language with user_view() or entity_view()
I have a custom view mode that uses a template to print out user profiles.

I am saving the HTML from this view mode in the Solr search index using Search API Solr.

In `user--my-view-mode.tpl.php`, I print out the various fields of the user profile, including one that is a *taxonomy term* that has been translated by the **Entity Reference** and **Title** modules:

```
  $agegroup = $user_profile['field_acc_age_group'][1]['#markup'];

```

In the Search API callback, I call this view mode like this:

```
$render = user_view($item, 'my-view-mode', 'ja');

```

Here's the problem-- the profile is rendered in Japanese except the taxonomy term, which has been translated by Entity Reference/Title.

When I make a view that shows output of *Rendered User* and set the view mode to *my-view-mode*, and access the view with a user who has the language set to Japanese, then the taxonomy term is translated correctly.

So how do I get `user_view()` or `entity_view()` to show translated entity translations along with the rest of the translated output?

# Answer
> 0 votes
So one workaround is to force it manually like this:

```
$agegroup = $user_profile['field_acc_age_group']['#items'][1]['taxonomy_term']->name_field[$lang][0]['value'];

```

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


# Question
Title: How to create a statistics dashboard of my users using Views?
I'm working on a Drupal website based on its users. They can login, pay their debts, set and update their personal and contact information, etc.

I would like to create a Dashboard showing statistics of these users, based on my user's fields, something like:

* **GENDER:** Male 54% - 46% Female
* **ACTIVE USERS:** 67%
* **AGES:** 20% KIDS - 56% Young - 16% Old - 8% Other

I even have a design for it, I´m just trying to figure it out technically using the Views module. Any idea?

# Answer
> 6 votes
Use the Charts module and its integration with the Views module. A straight forward cloning of the delivered views example would do what you are asking for. Have a look at this online example to get a first impression.

Some more examples of the Charts integration with Views, using data contained in "nodes" (so not using any Views aggregation facilities):

Disclosure: I'm a (co-)maintainer of Charts.

# Answer
> 4 votes
You can also do just normal (the Views) blocks, maybe a **charts view** using any of the charting modules mentioned in the Comparison of charting modules. And place the block(s) on the default drupal dashboard.

# Answer
> 1 votes
Assuming you wish to create an Admin dashboard with no coding:

You will need more than one view. You either have multiple views or a single view with attachments. If it is multiple views you will have to find a way of embedding them on one page, probably using Panels.

Your view(s) will use aggregation as you are accumulating stats by grouping.

**Modules that might assist:**

Page Manager (part of CTools)

Contextual Administration which is a nice module to assist in creating admin path dashboards:

> Contextual Administration is an administration tool based on CTools Page Manager module. It allows for the deployment of custom administrative pages through a typical database driven mechanism or can take advantage of the typical page\_manager exports through custom modules + exports or features module.

Tutorial for using Contextual Administration:

https://www.youtube.com/watch?v=Luc-bGGxa6c&list=PLEFD8FDE69D61DCA3

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


# Question
Title: Set value of field based on GET param for anonymous users
I ran into a strange problem. All forms are cached for anonymous users even if there is a token present in the url. But I need that token to store a "value" field type on a form. Because the form is stored in cache, it does not verify for that get param and set the value accordingly.

I tried using an "after\_build" function but that is also not triggered.

Is there a way I can use the GET param in my code? Or is there a way I can disable caching only for this form?

Thanks.

# Answer
Have a look at this module Cache Exclude, it might help you.

And even have look at this link, it is having more details about your problem.
> 1 votes

# Answer
I found my answer. My form was part of a block that was being cached by Drupal. I had to add `"cache" = DRUPAL_NO_CACHE` to the block info function to stop the block from being cached. After that, everything worked as expected.
> 1 votes

---
Tags: 7, forms
---