# Question
Title: How to change the blog page title with specific user's only blog posts?
There is a team page of the company and there are few links to social accounts which every user have, including the link to their blog posts. This link redirects you to blog page, but only with this user blog articles. The address shows blog/user\_id and the title of the page is "Blog". I want the title to be different depending on what user's blog you've entered. Something like this: "John Doe's blog posts". Should I edit blog template? I use Drupal 8.

# Answer
Tryout this one Reference

```
class CustomController extends ControllerBase implements ContainerInjectionInterface
  public function getBlockContent() {
    if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
      $route->setDefault('_title', $some_title);
    }
  }

```

}
> 0 votes

---
Tags: theming, users, nodes
---


title: Dynamic page title

text:
# Question
Title: Dynamic page title
I use panels to output my taxonomy term structure. So instead of having one static title for all taxonomies, I need the page title to be the "taxonomy\_term\_context:title".

In D7 there were modules. How to deal with dynamic title for panels in Drupal 8? Are there any hooks? The panels ui does not seem to handle title from context features.

Thanks

# Answer
Couldn't find anything useful in the web. I have written a custom module with this hook:

```
/**
 * Implements hook_panels_build_alter().
 */
function shop_list_page_panels_build_alter(array &$build, PanelsDisplayVariant $panels_display) {
  // Check for panel variant.
  if ("shop_category_list-panels_variant-0" === $panels_display->getConfiguration()['storage_id']) {
    // Set page title.
    $build['#title'] = $build['#title']->create($contexts['taxonomy_term']->getContextData()->getString());
  }
}

```
> 1 votes

---
Tags: panels
---


# Question
Title: Move "Items per page" selector to the top of the content
This is my problem of the day. I would like to display the Items per page at the top of the content block.

I'm working on a View Block, this is an Exposed Filter with "Better Exposed Filter". For now, I'm doing this the dirty way with jQuery and a unstable DOMSubtreeModified bind. I have a twig with {{ exposed }}, but Drupal doesn't suggest me any deeper twig and if I had one, it wouldn't access the Content div I guess. So I have no idea about how to do this.

Here is the div organisation :

* div.exposed-block
+ form.views-exposed-form
- Filter-1
- Filter-2
- **Items-per-page** (select)

* **div.view-block** (with my content)

So, the idea is to move **Items-per-page** to **div.view-block**. Or into another that I can create, here is the twig part :

```
<div class="exposed-block">
    {{ exposed }}
</div>

<div class="bmcp-view-block">
    {{ rows }}
</div>

```

How would you do this ?

Thanks in advance.

# Answer
> 0 votes
This is the answer I got from a forum.

```
<div class="exposed-block">
    {{ exposed | without ('items_per_page') }}
</div>

<div class="view-block">
    {{ exposed | without('my_first_other_filter', 'my_second_other_filter') }}
    {{ rows }}
</div>

```

---
Tags: views
---


title: db_delete rows older than 5 minutes

text:
# Question
Title: db_delete rows older than 5 minutes
I have a table with a date column and I'd like to delete rows that are older than 5 minutes than "now".

I tried with db\_delete conditions but it doesn't work.

I tried this query:

```
$deleteOldRows = db_delete('reserves')
    ->condition('entityId', -1)
    ->condition('dataReg + 5 MINUTES', 'NOW()')
    ->execute();

```

# Answer
The problem is with the condition syntax; it looks like below and performs a binary comparison:

```
$query->condition($field, $value = NULL, $operator = '=')

```

There are several issues, there is no field `dataReg + 5 MINUTES` and it likely won't have the literal value `NOW()` either. Besides, since you omitted the operator, the query would (if it had worked) only select items that are exactly 5 minutes old.

You are looking for a way to execute SQL in the query instead, which is provided by the `where` clause:

```
$query->where($snippet, $args = array())

```

In your case, it would probably look like this:

```
$deleteOldRows = db_delete('reserves')
  ->condition('entityId', -1)
  ->where('`dataReg` + 5 MINUTES < :time', array(':time' => 'NOW()'))
  ->execute();

```

You can find some good information on conditional clauses here: https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses

**UPDATE**

It appears I was wrong and this can be done with conditions after all, you should just reverse the logic. Rather than adding 5 minutes to the date, subtract 5 minutes from now.

```
$query->condition('dataReg', $adjusted_date, '<=')

```

Where `$adjusted_date` for timestamps would be `time() - (5*60)`. And for DATE types something like `date('Y-m-t H:i:s', time() - (5*60))`.
> 1 votes

---
Tags: database
---


# Question
Title: How can i fix broken link of an image being viewed in Drupalgap after being uploaded with Drupalgap also
By using Drupalgap i create an article and attach/upload an image to that article. Image of name: `myimage.jpg` has the actual absolute path in website: `http://www.example.com/sites/default/files/myimage.jpg`. In `View`(and also in `Edit`) menu tab inside Drupalgap the image seems to be broken. By debugging i get that in the View it tries to show an image with absolute path of `http://www.example.com/sites/default/files/styles/medium/public/myimage.jpg` which doesn't exist. What exists in that specific folder is a renamed clone of my image with absolute path `http://www.example.com/sites/default/files/styles/medium/public/1495486688801.jpg` .
To make things weirder, yesterday's articles created with the same method, which appeared also to be broken yesterday, today are shown just fine. Just fine means that the link of the image being shown points to the correct cloned image: `http://www.example.com/sites/default/files/styles/medium/public/1495486688801.jpg` .
`?q=drupalgap/node/55.json` is today's article `json` with broken links `?q=drupalgap/node/53.json` is yesterdays's article `json` which shows image as expected. Both get `200 OK` response. In the 2nd json references the image `(...)"filename":"1495486688801.jpg","uri":"public://1495486688801.jpg"(...)`
and the 1st as

```
(...)""filename":"IMG-8a92960d1864691a4e03c9cfe9ee8516-V.jpg","uri":"public://IMG-8a92960d1864691a4e03c9cfe9ee8516-V.jpg"(...).

```

Default Display in site uses `Large` image style and Drupalgap display uses `Medium` image style for the article node.
I have to mention that the same warning as the issue 776 appears to my log file.
`WARNING: drupalgap_remove_page_from_dom() - not removing the current page (node_add_article) from the DOM!`
Maybe medium style is not created as per need of my mobile's request.

**UPDATE**

I installed the imageinfo\_cache module and now (confirmed after 3 newly created articles nodes with images) images are not broken in the `View` menu tab in Drupalgap. But in the `Edit` menu tab is still broken.

# Answer
It sounds like you need to add this to your `settings.php` file:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```
> 0 votes

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


title: Check if current page == a link

text:
# Question
Title: Check if current page == a link
I'm working with a content type `skills`, where i made a view with the titles(as links). This generates a kind of menu. Which is what i'm aiming for. Now i need it to check if you are on one of the pages in this so called menu. Because ofcourse. if the link is active it needs different markup.

note: I can't solve this with an `onclick` because there are multiple ways of getting on the skill pages.

I wrote the following code. but it doesn't seem to work:

```
function (themename)_preprocess_views_view_fields__our_skills(&$variables) {
    $variables['active_class'] = '';
    $current_uri = \Drupal::request()->getRequestUri();

    foreach ($variables['fields'] as $fieldname => $fieldvalue) {
        if ($fieldname == "path" $$ $fieldvalue == $current_uri){
            $variables['active_class'] = ' active';
        }
    }
}

```

The code above returns `The website encountered an unexpected error. Please try again later.`

thanks in advance.

# Answer
> -1 votes
CSS is enough assuming that you just want the color of link to change when active,

CSS for links within said view

```
.view-name > .view-content > .view-grouping > .view-grouping-header > a { color: blue; }

```

CSS for active links

```
.view-name > .view-content > .view-grouping > .view-grouping-header > a.active { background-color: white; text-decoration: none; border-left: #95e5d4 10px solid; color: black; }

```

---
Tags: views, theming, navigation
---


title: Webform Filter Component Roles

text:
# Question
Title: Webform Filter Component Roles
How may I be able to limit a webform component visibility by logged user role? In Drupal 7, this was possible with webform\_component\_roles module but there is no version for Drupal 8.

Thank you.

# Answer
> 1 votes
When creating/editing a field, scroll down to ELEMENT ACCESS. There you can set all the limitations based on roles.

If you use YML you can use something like:

```
'#access_create_roles':
    - administrator
'#access_update_roles':
    - authenticated
'#access_view_roles':
    - authenticated

```

Finally, if you want to change the accessibility of the webform, check the Access tab (admin/structure/webform/manage/FORM\_NAME/access).

---
Tags: 8, webforms
---


# Question
Title: Drupal 7 Trying to create a "Today in History" view
I'm sure there's an easy way to do the following but I've not come up with a safe Drupal way to do so:

My current front page has a view which generates a list of the most recent three articles on my site using the date stored in field\_published attached to each article. The SQL which the view generates looks like this:

`SELECT field_data_field_published.field_published_value AS field_data_field_published_field_published_value, node.nid AS nid FROM node node LEFT JOIN field_data_field_published field_data_field_published ON node.nid = field_data_field_published.entity_id AND (field_data_field_published.entity_type = 'node' AND field_data_field_published.deleted = '0') WHERE (( (node.status = '1') )) ORDER BY field_data_field_published_field_published_value DESC LIMIT 3 OFFSET 0;`

( You can see what this looks like live on my website )

Running the query on mysql CLI generates this:

`+--------------------------------------------------+-----+
| field_data_field_published_field_published_value | nid |
+--------------------------------------------------+-----+
| 2017-01-23 00:00:00 | 427 |
| 2017-01-01 00:00:00 | 426 |
| 2016-08-07 00:00:00 | 424 |
+--------------------------------------------------+-----+`

I want to now create a similar view that searches only the month and day field of every article in the DB, matches the month and day against 'today', and generates a list of article nid. The SQL for this is:

`SELECT field_data_field_published.field_published_value AS field_data_field_published_field_published_value, node.nid AS nid FROM node node LEFT JOIN field_data_field_published field_data_field_published ON node.nid = field_data_field_published.entity_id AND field_data_field_published.entity_type = 'node' WHERE (( (field_data_field_published.field_published_value LIKE (select date_format(curdate(),'____-%m-%d%'))) )) AND (( (node.status = '1') ))
ORDER BY field_data_field_published_field_published_value DESC LIMIT 3 OFFSET 0;`

This correctly generates a list of article nid on the CLI:

`+--------------------------------------------------+-----+
| field_data_field_published_field_published_value | nid |
+--------------------------------------------------+-----+
| 2015-05-24 00:00:00 | 369 |
| 1999-05-24 00:00:00 | 222 |
| 1997-05-24 00:00:00 | 150 |
+--------------------------------------------------+-----+`

My question is, how do I get my functional SQL statement into a view?

I have tried using Views Contextual Filters and Granularity, but that does not allow me to omit the year when filtering dates.

I have tried to use hook views\_pre\_execute in a module but it barfs on my query: Something like

`<?php
// TMG 3-21-09
// call to hook_views_pre_execute to override the query for the groups browser
function views_views_pre_execute(&$view) {
 if($view->name=="future_front_page2") {
 $kp_tih = date('____-m-d%');
 $view->build_info['query']="SELECT field_data_field_published.field_pub
lished_value AS field_data_field_published_field_published_value, node.nid AS ni
d FROM node node LEFT JOIN field_data_field_published field_data_field_published
 ON node.nid = field_data_field_published.entity_id AND field_data_field_publish
ed.entity_type = 'node' WHERE (( (field_data_field_published.field_published_val
ue LIKE (select date_format(curdate(),'____-%m-%d%'))) )) AND (( (node.status =
'1') )) ORDER BY field_data_field_published_field_published_value DESC LIMIT 3 O
FFSET 0";
 $query = db_select('node','n')->addTag('node_access');
 drupal_set_message(t($query));`

Any suggestions?

Thanks in advance for any advice.

# Answer
> 0 votes
Try to use hook\_views\_query\_alter.

Even though, I think you can do it using only views without altering the query. Maybe using Date Views module would help.

---
Tags: views, database
---


title: Canvas support for IE

text:
# Question
Title: Canvas support for IE
I am trying to add canvas support for IE 9 and below for a drupal 8 site. Can anyone suggest an approach for this? I am planning on using Modernizr and Explorer Canvas polyfill to achieve this.

# Answer
> 0 votes
Sure, there are plenty of choices:

1. If there are CDNs available you can add the library directly through your theme or module's library.yml file.

`https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }`

2. If you use a build system like Gulp you could add the libraries as dependencies in the package.json and from there require them when building the JavaScript file that you later include in Drupal.
3. Use Libraries API: https://www.drupal.org/node/2605130

---
Tags: 8
---


# Question
Title: Div and problem locating their CSS files
I'm making my first website with drupal 8 for a university project.

I currently have 2 problems unresolved, the first one is that using the geolocation module to add a google map location is giving me problems, the width is setted at 50% and i can't find the way to change it to 100%, since I can't find the .css file that generate the style from the location page. The code from website that I think responsible is:

```
<div class="geolocation-google-map geolocation-processed" style="height: 400px; width: 50%; position: relative; overflow: hidden;>

```

but I don´t know how to change it.

The second problem I have is that just over, it generate a div ("\<"div"\>" Location "\<"/div"\>") with the label title, and I would like to add a .css class to hide, or simply remove it.

PS: I don't know if it's important, but I'm also using drupal 8 zymphonies theme.

Thank you very much.

# Answer
1) Assuming you already have sub-themed Zymphonies theme, just add this in your sub-theme's stylesheet-

```
.geolocation-google-map {
width: 100% !important; }

```

If not, read this documentation on sub-theming and do the above. Same goes for (2)

2) You can target your div (without class or id) using :nth-child() selector

Being a title, it usually is 1st or 2nd child of the view wrapper.If so

```
.view-name > div:nth-child(1) {
  //styles for a div that is the first child
}

.view-name > div:nth-child(2) {
  //styles for a div that is the second child
}`

```

Note that the div you're targeting has to be the direct child of its predecessor
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: Trigger submission via Javascript when exposed filters are changed on a block display in Views
I have a View showing a list of nodes that has a block display, with AJAX enabled. It seems that that is required when you using exposed filters on a block display in 8.

What I want to do is autosubmit the form (where did this option go?) when a filter is changed. This is the jQuery I have tried:

```
    $('select[data-drupal-selector="edit-field-article-category"]', context).change(function() {
      $('input[name="sort_by"]').attr('value', 'created');
      $('form#views-exposed-form-blog-blog-listing input[data-drupal-selector="edit-submit-blog"]').trigger('click');
    });

    $('select[data-drupal-selector="edit-field-article-category"]', context).change(function() {
      $('input[name="sort_by"]').attr('value', 'created');
      $('form#views-exposed-form-blog-blog-listing').trigger('submit');
    });

    $('select[data-drupal-selector="edit-field-article-category"]', context).change(function() {
      $('input[name="sort_by"]').attr('value', 'created');
      $('form#views-exposed-form-blog-blog-listing').submit();
    });

```

In the first case, nothing happens. In the latter cases, the page reloads with the query string attached. Nothing in the view is filtered.

What am I missing?

# Answer
> 1 votes
Was there a while ago, still don't understand why they'd scrap-off such an essential feature. Thanks to this thread @ drupal , found a solution.

Download the module at #5

---
Tags: views, 8
---


title: View scanning wrong template file

text:
# Question
Title: View scanning wrong template file
I've inherited a Drupal 7 site that's having an issue. The field "date" appears on the test site, but not on prod, and the field "title" is linked on test, but not prod. On both sites, the "date" field shows up in views "preview."

Update: I've figured out as much as the view is scanning the wrong template file. There is a file with an identical name `learning/views-view-fields--block.tpl` that is being used in the view instead of `news/views-view-field--block`.

How does this happen and how can it be fixed (I'm new to Drupal view templates, so I apologize if there's a simple solution).

# Answer
I fixed this by going into structure-\>views-\>the-specific-view-causing-the-issue(News)-\>advanced-\>theme information, and found a more specific name for "Row style output," in this case `views-view-fields--news--block.tpl.php`.
> 0 votes

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


# Question
Title: How do I set/get third party settings on a content block?
I have a content block type, and I'd like to add a couple of simple configuration options to it without setting up "real" fields. I primarily used this for instructions:

https://www.webomelette.com/drupal-8-custom-data-configuration-entities-using-thirdpartysettingsinterface

My module code:

```
use Drupal\block_content\Entity\BlockContent;
use Drupal\Core\Form\FormStateInterface;

function oa_blocks_form_block_content_slider_images_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $block = $form_state->getFormObject()->getEntity();

  $form['autostart'] = [
    '#type' => 'checkbox',
    '#title' => t('Autostart'),
    '#default' => $block->getThirdPartySetting('oa_blocks', 'autostart'),
  ];
  $form['#entity_builders'][] = 'oa_blocks_block_content_slider_images_form_add_form_builder';
}

function oa_blocks_block_content_slider_images_form_add_form_builder($entity_type, BlockContent $block, &$form, FormStateInterface $form_state) {
  if ($form_state->getValue('autostart')) {
    $block->setThirdPartySetting('oa_blocks', 'autostart', $form_state->getValue('autostart'));
    return;
  }
  $block->unsetThirdPartySetting('oa_blocks', 'autostart');
}

```

I have the following in config/schema/oa\_blocks.schema.yml:

```
block_content.type.slider_block.third_party.oa_blocks:
  type: mapping
  label: 'Slider Block'
  mapping:
    autostart:
      type: boolean
      label: 'Autostart'

```

I get the following error when I try to edit the block:

```
Fatal error: Call to undefined method Drupal\block_content\Entity\BlockContent::getThirdPartySetting() in /Users/dicksb/Sites/devdesktop/drupal8/docroot/profiles/mogov/modules/mogov/mogov_blocks/mogov_blocks.module on line 17

```

What am I doing wrong?

# Answer
> 4 votes
ThirdPartySettingsInterface is used by **config** entitiy types:

> Interface for configuration entities to store third party information.
>
> A third party is a module that needs to store tightly coupled information to the configuration entity. For example, a module alters the node type form can use this to store its configuration so that it will be deployed with the node type.

BlockContent is a **content** entity type, and doesn't implement the interface, hence the error.

---
Tags: 8, forms, blocks
---


# Question
Title: How do I get the submitted value for a field?
I have a custom submit handler:

```
function submituserform(array $form, FormStateInterface $form_state) {
  $email = $form_state->getValue('field_email');
  drupal_set_message('Thank you for for submitting your application. You will receive a confirmation at ' . $email . ');

  $redirect_path = "/confirmation";
  $url = url::fromUserInput($redirect_path);
  $form_state->setRedirectUrl($url);

```

}

I get `Array` as value for the email. How do I get the email from field\_email?

# Answer
You can also do this in following way:

```
function submituserform(array $form, FormStateInterface $form_state) {
  $element = $form['field_email'];
  $email = $form_state->getValue($element['#parents']);

```
> 1 votes

---
Tags: forms
---


title: How do I add cross symbol in textbox?

text:
# Question
Title: How do I add cross symbol in textbox?
I have a view with an exposed filter for the node titles. I want to add *X* in that exposed filter.

I know html5 provides feature to have cross symbol when the input type is *search*. I tried changing `#type` in `hook_form_alter()` for the text-field to *search*, but it doesn't work.

Is it possible in Drupal 7?

# Answer
You can do something like below:

write below code in any module

```
function modulename_theme() {
  $themes = array (
      'search_input' => array(
      'render element' => 'element',
    ),
  );
  return $themes;
}

/**
 * Implementation of hook_element_info()
 */
function modulename_element_info(){
  $types['search_input'] = array
  (
    '#input' => TRUE,
    '#theme' => 'search_input',
    '#theme_wrappers' => array('form_element'),
  );

  return $types;
}

```

write below code in template.php:

```
function themename_search_input($variables){ //echo "<pre>";print_r($variables);exit;
  $element = $variables['element'];
  $element['#attributes']['type'] = 'search';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-number'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input']))
  {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

```

In cs file:

```
input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

```

and use `#type = search_input`. It may help you
> 1 votes

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


# Question
Title: Is the Admin role different than a role with all permissions enabled?
Is the default Admin role inherently different than other roles? Does Drupal extend privileges to the Admin role that are not configurable/available to other roles?

To be clear, I am not referring to `user/1` on the site, but rather the official Administrator role as has been assigned here: `admin/config/people/accounts`.

Here's why I'm asking:

I've been having trouble with a Data Export View where a non-Admin user runs the export and the resulting output is incomplete. When running the export logged in as an Admin, the resulting output is complete.

I spent some time futzing with the permissions of the non-Admin role with no good results. So, as an experiment, I made a new role and enabled every permission… which, presumable would make this role equivalent to the Admin role. I logged in as a user with that new role, ran the data export, and still got the same incomplete dataset. What gives?

---

*As a bonus question: any idea why is my Data Export view outputting incomplete data for the non-Admin roles?*

# Answer
> 1 votes
Yes, the user 1 is different in Drupal:

> The Drupal account created during installation (i.e. with user ID or UID=1) behaves differently from others. Primarily, it can bypass all access callbacks: it has permission to do everything by default. Failing to secure this account could result in potential security risks. Treat the UID=1 account as you would with root on Linux systems.

Source: https://www.drupal.org/node/947312

---
Tags: views, users, importing-exporting
---


# Question
Title: How to create a custom text input filter?
I am using plain text format. I want to create an input filter for when a user enters #15, it should be converted to a link pointing to the post #15. I want to do this for the Statuses (Social Microblog) module. The link of an individual status is like this: `https://www.example.com/statuses/15`.

Just for your reference, I found a snippet. It is specifically for nodes though, which was meant to be used with custom filter module.

**My question**: How to create such filter for statuses?

# Answer
> 2 votes
Take a look at the Custom Filter module.

> This module allows you to create content filter using regular expressions. Instead of creating a new module for each filter you need, now you can easily create and organize your own filters. Your filter will appear in the input format configuration page.

If you want to do it yourself in a custom module, you can implement `hook_filter_info`

# Answer
> 0 votes
The Linkit module almost does what you want:

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

handbook:

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

The user starts typing the title and gets the link. No need to remember any number or internal path structure.

# Answer
> 0 votes
The Examples module has code for how to implement your own drupal "filters" (in your own module).

https://api.drupal.org/api/examples/filter\_example%21filter\_example.module/group/filter\_example/7.x-1.x

Use them in a custom "text format" for your statuses.

---
Tags: 7, navigation, input-formats
---


# Question
Title: Core patching and version controlling across multiple versions of the same site
**How can I propagate core updates from an installation of a Drupal site to other installations of the same site?**

I maintain a private Drupal site which the owners now want to make public. As a result, there are concerns about hacking due to lapses in the core.

In addition, there is a DEV, STAGING and a LIVE version of this site. Nothing makes it to the LIVE site without having being tested in staging and those changes always initiate in the DEV site.

Code changes are only made within the **sites/all** directory, nothing in Drupal core is tampered with. The changes are version controlled via **GIT**. So I push up changes to the **sites/all** files and subdirectories to STAGING and then the LIVE sites.

This is where my problem begins: how can I patch the core code for the DEV site and propagate those changes to my STAGING and LIVE sites?

I am aware, I can of course apply the patches directly on STAGING and LIVE but those two sites are very tightly controlled by firewalls so they don't have unrestricted access to the Internet like DEV does.

Can I only accomplish this by using more version control and push up core OR *is there another way?*

# Answer
Drupal has a good guide for this. A general summary for updating would be:

1. Delete everything except `sites`
2. Unpack the latest Drupal in the same place
3. Run the updater via `update.php`.
4. Check for breakage.
5. Update modules if necessary. They'll most likely be outdated too.

When all is good, commit all the updated code. Ideally you'd have separate commits for the core update, and for each module you updated. Then push up your code to your remote repo.

Now over to your environments, you simply do a `git pull`. If your remote repo *is* the filesystem of the remote environment (i.e. Acquia, Pantheon), then pulling isn't required. Set the site to maintenance mode, and run the updater. Ideally, you'll have this automated. If you use Drush, then it's just the following commands:

```
drush vset maintenance_mode 1 # enable maintenance mode
git pull                      # pull in the latest code
drush updb                    # perform updates
drush vset maintenance_mode 0 # disable maintenance mode

```
> 1 votes

---
Tags: 7, version-control
---


# Question
Title: Custom access callbacks for user entities not being called
I'm trying to implement some custom access control for user entities, in Drupal 7.

I've used `hook_entity_info_alter` to set

```
$entity_info['user']['access callback'] = 'MYMODULE_user_access_callback';

```

and when I call `entity_get_info` at a later point, I can see that this is still successfully set.

But `MYMODULE_user_access_callback` never ever seems to get called when I try to display users directly, or load Views of users.

It looks like the custom access callbacks are normally called from the `entity_access` function in **entity.module**. But the `user_access` function in **user.module** doesn't ever call them.

`user_load` in the user module calls `entity_load`, which calls `entity_get_controller($entity_type)->load(...)`

but this still doesn't seem to invoke `entity_access`.

So is setting `'access callback'` for the user entity a wrong way to go about trying to implement custom user access control? Do I need to override `UserController` perhaps?

# Answer
The problem might be the execution order of the modules

> How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)
> 0 votes

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


# Question
Title: Access custom user field from a different account
The following works so far:

1. I can set a custom user field e.g. 'full\_name' in Drupal Account Settings
2. The logged in user has access to this field using the following code.

global $user; $user = user\_load($user-\>uid); // Fully load the user object $custom\_vars\['full\_name'\] = $user-\>field\_full\_name\[LANGUAGE\_NONE\]\[0\]\['value'\]; echo "My full name is : $custom\_vars\['full\_name'\]";

This is what I want to do:

* I want to log in as an admin account and for a specific group of
users who's unique IDs know I want to display this field.
* So perhaps for userID = (1234, 1175, 14532) I want to see this value for `'full_name'`, how do I do it?

I am hoping for a PHP solution that uses code similar to the above rather than a SQL DB call, but if I need to directly access the DB so be it.

# Answer
This seems a bit dirty, but using your exact code as a base, something like the following may work:

```
$uids = array(
  // Here is the list of user ID's that you know.
);

$full_names = array();

foreach ($uids AS $uid){
  $account = user_load($uid);
  $full_names[$uid] = $account->field_full_name[LANGUAGE_NONE][0]['value'];
}

unset($account);

return $full_names;

```

This will give you an array of full usernames keyed by the UID.

Also to bear in mind, this performs no access checking or permission checking.

For further reading, you might want to try taking a look at something like `field_get_items()` as well.
> 1 votes

# Answer
I would investigate the user\_load\_multiple() function, which would allow you to do something like this:

```
$user_ids = array(1234, 1175, 14532);

$accounts = user_load_multiple($user_ids);

```

which would return an array of user objects keyed by their user id, so you would now have access to the field as:

```
$accounts[UID]->field_name_etc_etc_etc

```

If you want to simply it further, that's up to you as the rest is just PHP.
> 0 votes

# Answer
3 years later this is my analysis:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
    //    ->propertyCondition('uid', array(21,22,23,24), 'IN')
    ->propertyCondition('status', 1);

  $result = $query->execute();
  if (isset($result['user'])) {
    $news_items_nids = array_keys($result['user']);
    $news_items = entity_load('user', $news_items_nids);
  }

```

Time: 6.16s

```
$total_users = entity_load('user', FALSE, array('status' => 1));

```

Time: 6.00s

```
$local_user = db_query('SELECT u.uid, u.name, fn.field_last_name_value FROM users as u INNER JOIN field_data_field_last_name  as fn ON u.uid = fn.entity_id WHERE u.status = 1')->fetchAll();

```

Time: 3.63s

Total users: 1184
> 0 votes

---
Tags: users
---


# Question
Title: How to use different mail interfaces (Mail System)?
I have a newsletter (simplenews) being used from time to time and it uses SMTP server to send mail. All other emails from my site should be sent using default interface. How do I do this?

I thought Mail System module could help me with this, but seems I'm doing that wrong thus I can only **switch** between interfaces, but not **assign SMTP to simplenews only** and left other using default one. How can I do that?

# Answer
> 1 votes
For D7 you can define a custom mail system using the `$conf['mail_system']`

```
$conf['mail_system'] = array('mycustom_module_thekey' => 'MyCustomEmailSystem');

```

Then you can use the `drupal_mail` function

```
drupal_mail('mycustom_module', 'thekey', $email, language_default(), $params, $from);

```

---
Tags: emails
---


# Question
Title: Overriding an entity add/edit form through alterroute
I want to create my own version of the add/edit form for an entity defined in contrib module (drupal\_commerce). I assumed i'd be able to adapt the example here http://www.foreach.be/blog/how-manipulate-forms-drupal-8 to alter route for entity forms. However i am getting the following when i try to load edit

> Fatal error: Call to a member function getEntityTypeId() on a non-object in C:\xampp\htdocs\tocyn\core\lib\Drupal\Core\Entity\EntityForm.php on line 82

My route subscriber looks like:

```
    if ($route = $collection->get('entity.commerce_product.edit_form') ) {
        $defs = $route->getDefaults();
        $route->setDefault('_form', '\Drupal\mymod\Form\EventForm');
    }

```

And my new form:

```
class EventForm extends Drupal\commerce_product\Form\ProductForm
{
   public function buildForm(array $form, FormStateInterface $form_state)
   {

      // doing nothing much here
      return $form;
   }
}

```

Do i need to do something with \_entity\_form also?? Grateful for any feedback Mathew

# Answer
Alternatively, you can use hook\_entity\_type\_alter() to override the default form handler classes. It would be something like:

```
/**
 * Implements hook_entity_type_alter().
 */
function mymod_entity_type_alter(array &$entity_types){
  $entity_types['commerce_product']->setHandlerClass('form', array(
    'edit' => 'Drupal\mymod\Form\EventForm'
  ));
}

```
> 4 votes

# Answer
You need to change

```
$route->setDefault('_form', '\Drupal\mymod\Form\EventForm');

```

To

```
$route->setDefault('_entity_form', '\Drupal\mymod\Form\EventForm');

```

Otherwise the upcasting and other magical things are broken. See `\Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider::getEditFormRoute` where it gets defined initially.
> 0 votes

---
Tags: commerce, entities, routes
---


# Question
Title: How to position javascript file as the last one to load?
In Drupal 8 the weight for javascript files in libraries is not supported, or at least only negative values are allowed, which means I am only able to position them at the top of the list (i.e. load it first) but not at the end of the list.

I have a library for the Zurb Foundation and its initialization has to be loaded last. It is a requirement for my theme and I don't want to override a template to fix this problem.

How is one supposed to do this?

# Answer
> 2 votes
I was surprised hear that "only negative values are allowed" as JS weights, so I had to hunt that down. And it's true... https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Asset%21LibraryDiscoveryParser.php/function/LibraryDiscoveryParser%3A%3AbuildByExtension/8.2.x There is an exception error message that says, "The $extension/$id library defines a positive weight for '$source'. Only negative weights are allowed (but should be avoided). Instead of a positive weight, specify accurate dependencies for this library."

This of course reminded me that, yes indeed, dependencies were added/improved in Drupal 8 so that we didn't have to worry about this. Oddly enough, there are several core JS files that define weight, so I guess we are only part way there.

So, this is just a long-winded way of saying, what scripts does the Zurb Foudation depend on? And can you list those dependencies in your libraries file under the Zurb script? See https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module for more info.

---
Tags: 8, javascript
---


title: Query with join doesn't work

text:
# Question
Title: Query with join doesn't work
I have custom tables and want to execute this query.

```
select displayname from foolzz_users_profile
join foolzz_user_has_user on (fk_user1=1 or fk_user2=1)
where fk_users_uid != 1;

```

The "1" numbers will be replaced with the users uid. This is my query in the module.

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$uid = $user->get('uid')->value;

$query = \Drupal::database()->select('foolzz_users_profile', 'e');
$query->fields('e', array('fk_users_uid,displayname'));
$query->join('foolzz_user_has_user','d','d.fk_user1=:uid OR d.fk_user2=:uid',array(':uid' => $uid));
$query->condition('e.fk_users_uid', $uid, '<>');

$friendlist = $query->execute()->fetchAssoc();

```

I'm searching for hours and still couldn't get it to work.

# Answer
> 5 votes
A couple of things...firstly

```
$query->condition('data.fk_users_uid', !$uid);

```

`!$uid` returns `false` when used on a positive non-zero integer in PHP (and `true` for zero, the anonymous user).

You probably meant:

```
$query->condition('data.fk_users_uid', $uid, '<>');

```

Secondly, you're using the same alias for both tables. That'll never work. Change the one in the join to `data2` or something:

```
$query->join('foolzz_user_has_user', 'data2', 'data2.fk_user1=:uid OR data2.fk_user2=:uid', array(':uid' => $uid));

```

---
Tags: database
---


# Question
Title: Getting exception 1003 when importing images via feeds module
I'm importing images via the feeds module from a csv file. In the field for images, I've added the `public` url like so:

```
public://path/to/my/image.jpg

```

I've verified that the image exists and is available. When I try importing the feed, everything imports fine but I get the following two db errors for every image:

First error:

> exception 'Exception' with message 'Download of public://path/to/my/image.jpg failed with code -1003.' in /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsParser.inc:424 Stack trace:
>
> # 0 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsParser.inc(483):
>
> FeedsEnclosure-\>getContent()
>
> # 1 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/mappers/file.inc(127):
>
> FeedsEnclosure-\>getFile('public://images...')
>
> # 2 \[internal function\]: file\_feeds\_set\_target(Object(FeedsSource), Object(stdClass), 'field\_y1\_rankin...', Array, Array)
>
> # 3 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsProcessor.inc(800):
>
> call\_user\_func('file\_feeds\_set\_...', Object(FeedsSource), Object(stdClass), 'field\_y1\_rankin...', Array, Array)
>
> # 4 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsProcessor.inc(746):
>
> FeedsProcessor-\>mapToTarget(Object(FeedsSource), 'field\_y1\_rankin...', Object(stdClass), 'public://images...', Array)
>
> # 5 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsProcessor.inc(296):
>
> FeedsProcessor-\>map(Object(FeedsSource), Object(FeedsParserResult), Object(stdClass))
>
> # 6 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/includes/FeedsSource.inc(399):
>
> FeedsProcessor-\>process(Object(FeedsSource), Object(FeedsParserResult))
>
> # 7 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/feeds.module(191):
>
> FeedsSource-\>import()
>
> # 8 \[internal function\]: feeds\_batch('import', 'y1\_rankings\_pro...', '109600', Array)
>
> # 9 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/batch.inc(284):
>
> call\_user\_func\_array('feeds\_batch', Array)
>
> # 10 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/batch.inc(161):
>
> \_batch\_process()
>
> # 11 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/batch.inc(80):
>
> \_batch\_do()
>
> # 12 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/modules/system/system.admin.inc(2384):
>
> \_batch\_page()
>
> # 13 \[internal function\]: system\_batch\_page()
>
> # 14 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/menu.inc(527):
>
> call\_user\_func\_array('system\_batch\_pa...', Array)
>
> # 15 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/index.php(21): menu\_execute\_active\_handler()
>
> # 16 {main}

Second error:

> Invalid enclosure public://path/to/my/image.jpg

The feed *used* to work, and I don't think I've changed anything to break the import. What could be going wrong?

# Answer
> 0 votes
The answer was that the image wasn't found, because my `path/to/my/image.jpg` was incorrect on my spreadsheet, `path/my/to/image.jpg`.

---
Tags: 7, feeds
---


# Question
Title: What's the use of the new Star button in the project pages?
If you go to a Drupal project page (for example, Views) you will see a new button with a Star, like this:

Logged-in users can Star and Unstar a project.

But what is the real use of this button?

I can't find all the users that have starred a project.

# Answer
> 3 votes
Consider this "Star"-facility as a way to "bookmark" specific contributed modules as your "favorites". Some more details about it (from What’s new on Drupal.org? - April 2017):

> Users on Drupal.org may now star their favorite projects \- making it easier to find favorite modules and themes for future projects, and giving maintainers a new dimension of feedback to judge their project's popularity. Users can find a list of the projects they've starred on the user profile. Over time we'll begin to factor the number of star's into a project's ranking in search results.

**Notes**:

* Projects that you star-ed are shown to others also. E.g here are your current star-ed projects.
* When I look at the views page (without being logged in to D.O), I don't see that "star" (as in your image), I only see the star itself, and the "35". After I log in, I do get a similar Star-image like your question here.

# Answer
> 0 votes
For the moment the only thing that I can remark is a list with your starred projects, this is available in your profile:

And you can access trough https://www.drupal.org/user/YOUR\_USERNAME/starred

---
Tags: community-official-site
---


title: How to use Field Collection in Webform?

text:
# Question
Title: How to use Field Collection in Webform?
I want to use field collection module in Webform Component, How can I do that?

# Answer
> 2 votes
I did by using entity form + field collection.

# Answer
> 2 votes
The answer is to NOT use the Webform module but instead use the Entityform module and the Field Collection module.

# Answer
> 0 votes
https://www.drupal.org/project/webform\_addmore provides in certain cases a similar functionality to field collection for Webforms.

# Answer
> 0 votes
Well, yes, entity collection is better, but can't clone dependancies...can't clone field collections

---
Tags: webforms, entities
---


# Question
Title: Drupal 7 check all solution for 2017, is it possible?
I looked online, tried the checkall module, nothing works, found info from posts in 2013...

Is there a way to provide a Select All / Check All checkbox for a field that displays multiple checkboxes in Drupal 7?

Nothing conclusive, just half baked hacks that might or might not work.

Any solution that works for 2017?

Even the Google chrome check all extensions are buggy...only thing that works in older versions of firefox for this...

Any suggestions?

# Answer
You want to create a custom module for this

**my\_module.module**

```
function my_module_form_node_form_alter(&$form,&$form_state,$form_id) {
     if($form['#node']->type == "my_content_type") {
        $form['#attached']['js'][] = array(
          'data' => drupal_get_path('module', 'my_module') . '/js/example.js',
          'type' => 'file',
        );
     }
}

```
* Change all `my_module` to the actual name of your module
* Change `my_content_type` to the actual name of your content type.

**my\_module/js/example.js** (using code from the link you gave)

```
(function ($) {
    Drupal.behaviors.selectAll = {
      attach: function (context, settings) {
        $('body.page-node .form-type-checkboxes > label').click(function() {
            $(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');
        });
      }
    };
}(jQuery));

```

If it doesn't work, try changing the line

`$(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');`

to

```
$(this).nextAll('input:checkbox').trigger('click');

```
> 0 votes

---
Tags: theming
---


title: Services add several nodes at once

text:
# Question
Title: Services add several nodes at once
I am using Drupal 7 with Services module (version 3.x). I want to add several nodes at once. When i try one it is okay.

```
{"type":"article","title":"Test article 1","body":{"und":[{"value":"test body!"}]},"language" :"und"}

```

But when I try something like this i can't

```
{"type":"article","title":"Test article 1","body":{"und":[{"value":"test body!"}]},"language" :"und"},{"type":"article","title":"Test article 2","body":{"und":[{"value":"test body!"}

```

Is there a way to make this happend?

# Answer
Services default functionality for node creation is one by one. If you want to create multiple node at once then you should write your custom service using `hook_services_resources()`. You can find some example about how to write custom service Click Here
> 0 votes

---
Tags: services
---


# Question
Title: How change user form mode programmatically?
i create 2 custom user register form mode :

When i go to mysite/user/register

Drupal show me the last form mode i create :

> S'inscrire

But when i go in the admin mode, for add a user, it show me the same form. i try to display "Affichage Admin" form mode with more field.

So i try to alter the form mode programmatically.

Any idea how can i change form mode before it render ?

# Answer
> 1 votes
something like this:

```
/**
 * Implements hook_entity_type_alter().
 */
function YOUR_MODULE_entity_type_alter(array &$entity_types) {
  // We get all form modes, for all entities, and loop through them.
  $form_modes = \Drupal::service('entity_display.repository')->getAllFormModes();
  foreach ($form_modes as $entity_type => $display_modes) {
    if ($entity_type !== 'user') {
      // We are only interested in adding a handler to the Node entity.
      continue;
    }

    $user_entity = $entity_types[$entity_type];
    foreach ($display_modes as $machine_name => $form_display) {
      if ($machine_name !== 'sinscrire') {
        // We are only interested in adding this form mode to the definition.
        continue;
      }
      // We get the default handler class. It will be enough for us.
      $default_handler_class = $user_entity->getHandlerClasses()['form']['default'];
      // We set the form class, keyed by the machine name of our custom form mode.
      $user_entity->setFormClass($machine_name, $default_handler_class);
    }
  }
}

```

Credit goes here: https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8

---
Tags: 8, forms
---


# Question
Title: How to override prepareTranslation method in Drupal\content_translation\Controller in drupal 8?
I want to override prepareTranslation method using my custom module in drupal 8. You can find this function here(Drupal\core\modules\content\_translation\src\Controller\ContentTranslationController.php).

# Answer
> 1 votes
You can use `hook_entity_prepare_form()` to override the values from `prepareTranslation()` on `$form_state`.

---
Tags: 8
---


title: hook_user_delete not being called

text:
# Question
Title: hook_user_delete not being called
I'm trying to invoke hook\_user\_delete and for some reason it isn't getting called. I have essentially the same function in hook\_user\_cancel and that gets called correctly. Basically, I go into the user edit form, then down to the bottom to "Cancel Account". From the next page, if I click "Disable the account and keep its content.", the hook\_user\_cancel function gets called, but if I pick "Delete the account and its content.", neither the hook\_user\_cancel or the hook\_user\_delete functions get called. I checked this by placing a dpm at the beginning of each function. My code looks like the following:

```
function carrier_pigeon_user_delete($account){
$num_deleted = 0;

if(is_numeric($account->uid)) {
  $num_deleted = db_delete('carrier_pigeon_subscription')
      ->condition('uid',account->uid)
      ->execute();
}
dpm($num_deleted);
}

function carrier_pigeon_user_cancel($edit, $account, $method) {
$num_deleted = 0;

if(is_numeric($account->uid)) {
    $num_deleted = db_delete('carrier_pigeon_subscription')
            ->condition('uid', $account->uid)
            ->execute();
}
dpm($num_deleted);
}

```

Sorry about the formatting. Is there something I'm doing wrong here? My impression is that I need both of these to cover my bases, but I can't seem to get the first one to get called.

# Answer
> 1 votes
I followed below steps and it is working when I cancel account by "delete user and its content"

```
/**
 * Implements hook_user_delete().
 */
function MYMODULE_user_delete($account) {
  watchdog('MYMODULE', 'hello, user: !username, user id: !uid, has been deleted', array(
    '!username' => $account->name,
    '!uid' => $account->uid
  ));
}

```

Go to `admin/reports/dblog` check if the message displayed there. Mine is showing.

# Answer
> 0 votes
I have just fixed the problem. Your code works, however I had to **disable and enable** the module in order to Drupal calls my user\_delete hook.

I hope this helps others with the same problem.

---
Tags: hooks, users
---


title: How to get term alias in twig templates

text:
# Question
Title: How to get term alias in twig templates
I have created a block to show the sibling terms of the term being viewed. In the twig template I am looping through the terms to display the names linked to their respective pages.

Now I unable to figure out how to get path alias.

Can any one of you please guide me how to get the path alias of a term?

Thanks

# Answer
A bit late, but just figured this one out in case it helps someone else:

```
{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': tid}) }}

```
> 9 votes

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


# Question
Title: How to fined the fields biggest weight in form
I have made a content type in /admin/structure/types/add and then, created for this content type extra fields from /admin/structure/types/manage/CONTENT TYPE\_NAME/fields/add-field. After i created a module that will alter this content type by hook\_form\_BASE\_FORM\_ID\_alter() in .MODULE file, and after i reset the default button that has content type that is SAVE button, and added new button:

```
    $form['register'] = array
  (
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('NAME_OF_A_FUNCTION'),
    '#weight' => '?',
  );

```

But when I do this the button is rendered first and after comes the content type fields. How to change the button row weight so that the button will always will show at the last plaice. In aver words how to get from all fields that has content type form and search for the biggest weight that has field and put this 'value + 1' in my new submit button '#weight' =\> '?'. Dose anyone has solution for that... Thanks in advance

# Answer
> 1 votes
the solution is in this code:

```
  $elements = Element::getVisibleChildren($form);
  $weight = 0;
  foreach ($elements as $el) {
    $check = strpos($el, 'field_');
    if ($check !== FALSE && $form[$el]['#weight'] >= $weight) {
      $weight = $form[$el]['#weight'];
    }
  }

  $form['register'] = [
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('NAME_OF_A_FUNCTION'),
    '#weight' => $weight + 1,
  ];

```

---
Tags: 8, nodes, forms
---


# Question
Title: Creating a ticketing system in Drupal 8. How to change a node's field value without going to the edit page?
I'm creating a simple ticketing system in Drupal 8 to log my daily tasks. The content type contains title, body, and ticket status. The status field can be new, in progress, or completed. When I create a new ticket, the status is set as new by default. I also have commenting enabled on this content type.

The issue I'm having now is the UX of this setup. I can comment on the ticket fine, but if I were to change the **status** of the ticket to **in progress** or **completed**, I'd have to goto the edit page of the node and make this change. How can I change the status value without going to the edit page? Is there a ajax field update feature?

I wan't to be able to make my comment and also change the status of the ticket all at once vs making a comment, then click edit to change the status.

# Answer
> 2 votes
You could build an ajax form that would update the node's "Ticket Status" field, embed that in a custom block and place that block on the page for that node or embed it in the node. Instead of in a block, you could also create a field formatter plugin that embeds the ajax form into the display for that field.

# Answer
> 0 votes
There a thousands of ways you can place a minified node edit form, see your last question Creating a ticket system with core only. How to modify fields on full\_content view without reloading? or the great answer from @oknate Creating a ticketing system in Drupal 8. How to change a node's field value without going to the edit page?

But what is new in this question is, that you want to do this together with the comment form. The comment form has already a submit that posts data to drupal. Then you don't need a second form. You could extend the comment form in a form alter hook with two submit buttons, which each execute not only the default submit from the comment form, but also a custom submit which changes the status of the parent node either to **progress** or **completed**.

---
Tags: 8, entities, ajax
---


# Question
Title: How to implement second level menu for bootstrap theme
i am using bootstrap theme for my drupal site, it has menus like menu 1 & menu 2 in header region. when i click on menu 1 it has to display it's sub menus like sub menu 1, sub menu 2, submenu3 ... for this requirement, i used **menu block** module. but it does not slove my problem.

Any help or suggestions are appreciated. Thank you.

# Answer
No need to use menu block. Just check the checkbox "Show as expanded".
> 0 votes

---
Tags: 7, theming, navigation, bootstrap-theme
---


# Question
Title: How do I change the temporary directory without using any administrative pages provided by Drupal?
I've moved my live Drupal website to Windows localhost (XAMPP), but I'm getting lots of "The file could not be created" errors. If I log in to the site as an administrator, it fails to return any more pages at all. I can view it with errors if I don't log in.

Is there a way to change the temporary file location without logging in through the interface, or using any administrative page?

# Answer
> 29 votes
In Drupal 7 the temporary path is stored in the variable `file_temporary_path`, so you can either update the entry in the `variables` table with a SQL-query. Or you can use Drush:

`drush vset file_temporary_path [some_new_path]`.

# Answer
> 8 votes
For Drupal 8 using Drush:

```
drush config-set system.file path.temporary /tmp

```

# Answer
> 7 votes
Variables can be overwritten within `settings.php`. An entry like the following will do it in D7:

```
$conf['file_temporary_path'] = '/tmp';

```

Replace `'/tmp'` with your specific path. You might also need to set the variable `file_private_path`.

---
Tags: files
---


# Question
Title: How do I create a nested tree with terms & nodes with Views 3?
I need to create something similar like this:

Colors (Vocabulary)

* Red (term)
    + Dark (term)
        - Node 1
        - Node 2
    + Light (term)
        - Node 3
        - Node 4
* Blue (term)
    + Node 5
    + Node 6
* Green (term)
    + Node 7
    + Node 8

(Bullet points are indents.)
Is there a way to do this with Drupal 7 and views 3? If not, is there another way to do this?

# Answer
Thanks to refino, I found a nice solution using the following modules:

Below you find the explanation:

1. First create a new Taxonomy (let's call it "Folder")
2. Then, create a new content type (let's call it "Element") with a term reference field to the "Folder" taxonomy
3. Create a new "Content" View (let's call it "Element View")
4. Choose Field Display
5. Add a Contextual Filter to your term reference field
6. Create a new "Taxonomy" View (let's call it "Folder Tree")
7. Add 2 fields (term name and term id). The second field can be excluded from display
8. In Relation: add a "parent term"
9. Add a third field (term id) and assign it to your parent relation. This field can be excluded from display
10. Choose Format "Tree (Adjacency model)" and select in the parameters : Ordered list + Main field (your first tid), Parent field (your tid assigned to the parent relation). You now should have a nice tree with all your terms nested
11. Add a 4th field "Global:View" (this comes with Views Field View) and choose your "Element view", display Master add \[tid\] in the Arguments textfield

Hope this help

Cheers

Edit by **iStryker**: This is what I got. The only thing I changed was make *Element View* a table view, and removed the default (row & strip) classes.
> 15 votes

# Answer
I created three views in Drupal 7.8 and Views 3 + Views Field, nesting one view into another using Include View, and I got such a result (attached).

Step-by-step how to do it:

1. Create vocabulary "Colors" and fill it in with tags.
2. Create a new view of taxonomy nodes Colors - I call it "Nodes of Colors"

2.1 Format Table , Settings: Grouping field: Taxonomy term: Name

2.2 Advanced Contextual filters: Taxonomy term: Parent term

2.3 Advanced Relationships: Taxonomy term: Content using Color

2.4 Set Fields: Taxonomy term: Term ID, Taxonomy term: Name, (field\_color) Content: Title

2.5 Filter criteria: Taxonomy term: Vocabulary (= Colors)

2.6 If you want you can also set "Exclude from display" for Term ID, Taxonomy term: Name

2.7 Set Path:/nodes-of-colors/%

2.8 Set no results behavior: Global: View area (we will come back to this later) 2.9 save

3.Create a new view of taxonomy nodes Colors - I call it "Nodes of Colors 2"

3.1 Format Table , Settings: Grouping field: none

3.2 Advanced Contextual filters: Taxonomy term: Term ID

3.3 Advanced Relationships: Taxonomy term: Content using Color

3.4 Set Fields: Taxonomy term: Term ID, Taxonomy term: Name, (field\_color) Content: Title

3.5 Filter criteria: Taxonomy term: Vocabulary (= Colors)

3.6 If you want you can also set "Exclude from display" for Term ID, Taxonomy term: Name

3.7 Set Path:/nodes-of-colors-2/%

3.8 Set no results behavior: Global: none

3.9 Save

Go back and edit "Nodes of Colors" again

4.1 go to Set no results behavior: Global: View area

4.2 Set View to insert: View: nodes\_of\_colors2 Display: page

4.3 set Inherit contextual filters

4.4 save

5 Go back to Views again (Type Term)

5.1 Create a new view of taxonomy nodes Colors - I call it "Colors Tree"

5.1 Format Table , Settings: Grouping field: none

5.2 Advanced Contextual filters: none

5.3 Advanced Relationships: Taxonomy term: Parent term

5.4 Set Fields: Taxonomy term: Term ID, Taxonomy term: Term ID , Taxonomy term: Name, View: Include View (Include View)

5.5 Filter criteria (1): Taxonomy term: Vocabulary (= Colors)

5.6 Filter criteria (2): (Parent) Taxonomy term: Term

5.7 If you want you can also set "Exclude from display" for Term ID and a label of Include View

5.8 Set Path:/colors-tree

5.9 Set no results behavior: none

5.10 save

...and this should be it, finally.
> 14 votes

# Answer
I haven't tried the D6 or D7 version of this myself but I thought I would mention it in case it's what you're looking for: Views Tree Module - D7 progress

*Edit*: There is now a D7 version, checkout the module homepage Views Tree
> 4 votes

# Answer
If you want to get the vid from the URL then use the following code.

```
$vid = $_GET['vid'];
$tid = 0;
$level = 0;
print taxonomy_tree($vid, $tid, $level);
function taxonomy_tree($vid, $tid = 0, $level) {
  $children = taxonomy_get_children($tid, $vid);
  $output = '';
  if ($children) {
    $output .= '<ul>';
    foreach ($children as $child) {
      $level++;
      $output .= '<li class="taxonomy-tree-lvl' . $level . ' ">';
print $level;
      $output .= l($child->name, 'taxonomy/term/'. $child->tid) . '(' . taxonomy_term_count_nodes($child->tid) . ')';
      $output .= taxonomy_tree($vid, $child->tid, $level);
      $output .= '</li>';

      $level--;
    }
    $output .= '</ul>';
  }

  return $output;

}

```

Or use the following code.

```
$vocabulary = taxonomy_vocabulary_load(2);//Here pass the vid
print $vocabulary->name;
$vid1 = $_GET['vid'];
if(!$vid1) {
$vid1 = 2;
print 'empty';
}
$vid = 2;
$parent = 0;
print get_child_terms($parent, $vid1);
 function get_child_terms($parent, $vid) {
      $sql = "SELECT td.tid, td.vid, td.name"
         . "  FROM {term_data} td"
         . "  JOIN {term_hierarchy} th on th.tid = td.tid"
         . " WHERE th.parent = %d"
         . "   AND td.vid = %d"
         . " ORDER BY td.weight, td.name";
    $terms = db_query($sql, $parent, $vid);
    $output = "";
    while ($aterm = db_fetch_object($terms)) {
        $output .= "<li>";
        $output .= l("$aterm->name", "taxonomy/term/$aterm->tid/all") . " ("
                .  taxonomy_term_count_nodes($aterm->tid) . ")</li>\n"
                .  get_child_terms($aterm->tid, $vid);
    }
    return ($output != "") ? "<ul style='list-style-type: none;
  margin: 0px 0px 0px 20px;
  padding: 0px;'>\n". $output ."</ul>\n" : "";
  }

```
> 3 votes

# Answer
Of course there is:

1. Set up your hierarchival vocabulary,
2. Add it to any selected content type,
3. Create a view listing nodes from that content type, with **contextual filter**:

* either "Content: Has taxonomy term ID" - if you want to list only nodes assigned to specific term,
    * or "Content: Has taxonomy term ID (with depth)" - if you want to list nodes assigned to a specific term as well as to its child terms.

    In this case, in filter configuration you need to set the depth - how many levels below (or above) you want this filter to work.

Then, assuming your view's URL is http://mysite.com/myview and 'Red' tid = 1, if you go to http://mysite.com/myview/1 it will list you all nodes assigned to either one of terms 'red', 'dark' and/or 'light'.
> 2 votes

# Answer
You could use the Taxonomy menu module. Here is a quote about it (from the module's project page):

> Transforms your taxonomy vocabularies into menus with ease!
>
> Features:
>
> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules
> 2 votes

# Answer
I'm trying to accomplish the same but haven't found much available in D7. Taxonomy Blocks module does it in a block - not views.
> 0 votes

# Answer
I believe I have found yet another way to solve this problem, and I think it's simpler than the rest of these solutions. It does not involve any extra modules and you only need one view.

Assuming you have created a *two level* hierarchical vocabulary (Colors) and a content type with a term reference to that vocab, do the following:

1. Create a new view and filter by "Taxonomy vocabulary: Machine name (= Colors)"
2. Add relationships: (1) `Taxonomy term: Content using Color` and (2) `Taxonomy term: Parent term`
3. Add the fields to the View: (1) `Title` (choose `field_color` in "Relationship" **and require this relationship**), (2) `Taxonomy term name` (do not use relationship and exclude from display) (3) `Taxonomy term name` (yes, again, this time choose `Parent` for relationship and exclude from display).
4. Now group it by clicking on Settings of Format: (1) grouping 1: `(Parent) Taxonomy term: Name`, (2) `Taxonomy term: Name`

Done. If you have more than two levels just add another Relationship of Parent using Parent as the relationship's relationship.

EDIT: if you don't require the relationship you'll end up with dupes. Parents will be listed twice if they have child terms that are referenced by nodes. So this limits the answer a bit in that top-level terms without nodes that reference it won't display. Also, because sorting is probably important, having any content referencing a top level term would potentially cause problems for you depending on display needs.
> 0 votes

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


# Question
Title: Replace views PHP field by views handlers - not working
I am migrating a site to Drupal 7 from Drupal 6 and came across a view which had custom code in Views PHP. The logic is:

1. There is a content type as 'Products'.
2. The 'Product' content type has a field called 'ISBN'
3. The 'ISBN' field is referenced in a custom table called 'activation\_code'
4. Each ISBN is activated using the activation code and there are multiple entries of activation codes per ISBN.
5. In the Views the fields which are displayed are 'ISBN' (coming from Content type Product), total number of activation codes per ISBN (coming from views php with each row's ISBN), activated activation codes (same as previous one).

I have seen a post with kind of similar implementation here: How to replace Views PHP field and sorting by custom Views handler?

My implementation is the following.

### activation\_code.module

```
/**
 * Implements hook_views_api().
 */
function clms_product_activation_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'activation_code') . '/includes/views',
  );
}

```

### activation\_code\includes\views\activation\_code.views.inc

```
function activation_code_views_data() {
  $data = array();

  $data['manage_products']['table']['group'] = t('Manage Product View');
  $data['manage_products']['table']['join'] = array(
    '#global' => array(),
  );
  $data['manage_products']['total_subscriptions'] = array(
    'title' => t('Total Subscriptions'),
    'help' => t('Total Subscriptions.'),
    'field' => array(
      'handler' => 'activation_code_total_subscriptions_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'activation_code_total_subscriptions_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
  );

  return $data;
}

```

The field handler is placed in the activation\_code\includes\views\handlers directory and it contains this code.

```
/**
 * @file
 * Contains the custom field data for total subscriptions.
 */

/**
 * Custom views handler for manage product views.
 */
class activation_code_total_subscriptions_field extends views_handler_field {

  /**
   * {@inheritdoc}
   */
  function query() {
    // Do nothing.
  }

  /**
   * {@inheritdoc}
   */
  function render($values) {
    $result = db_select('activation_code', 'ac')->fields('ac', array('nid'))
      ->condition('field_isbn', $values->field_field_isbn[0]['raw']['safe_value'], '=')
      ->execute();
    return $result->rowCount();
  }

}

```

The data is coming properly but while I sort, it gives me error 'Unknown column unknown in SQL'. Which I found that custom handlers if not known throws this type of error.

I believe that the sort handler I have written (activation\_code\includes\views\handlers\activation\_code\_total\_subscriptions\_sort.inc) is not getting called.

```
/**
 * @file
 * Contains custom sort function for Manage Products total subscription field.
 */

/**
 * Overriding views_handler_sort class.
 */
class activation_code_total_subscriptions_sort extends views_handler_sort {

  function query() {
    error_log('CALLED', 3, '/tmp/access.log');
    $this->ensure_my_table();
  }

}

```

I have mentioned this in .info file as such.

```
files[] = includes/views/handlers/activation_code_total_subscriptions_field.inc
files[] = includes/views/handlers/activation_code_total_subscriptions_sort.inc

```

Am I missing something? Even this gets called, what type of sort I can give to prevent the unknown column error?

**Update #1** Based on Matt's suggestion, I have tried but can't get the row values in `query()` method. In `$this->options` I am only getting this:

```
array (
  'id' => 'total_subscriptions',
  'table' => 'clms_view_manage_products',
  'field' => 'total_subscriptions',
  'relationship' => 'none',
  'group_type' => 'group',
  'ui_name' => '',
  'label' => 'Total Subscriptions',
  'exclude' => 0,
  'alter' =>
  array (
    'alter_text' => 0,
    'text' => '',
    'make_link' => 0,
    'path' => '',
    'absolute' => 0,
    'external' => 0,
    'replace_spaces' => 0,
    'path_case' => 'none',
    'trim_whitespace' => 0,
    'alt' => '',
    'rel' => '',
    'link_class' => '',
    'prefix' => '',
    'suffix' => '',
    'target' => '',
    'nl2br' => 0,
    'max_length' => '',
    'word_boundary' => 1,
    'ellipsis' => 1,
    'more_link' => 0,
    'more_link_text' => '',
    'more_link_path' => '',
    'strip_tags' => 0,
    'trim' => 0,
    'preserve_tags' => '',
    'html' => 0,
  ),
  'element_type' => '',
  'element_class' => '',
  'element_label_type' => '',
  'element_label_class' => '',
  'element_label_colon' => 1,
  'element_wrapper_type' => '',
  'element_wrapper_class' => '',
  'element_default_classes' => 1,
  'empty' => '',
  'hide_empty' => 0,
  'empty_zero' => 0,
  'hide_alter_empty' => 1,
)

```

**Update #2 - Table relationships & Use Case**

**Use Case:** There is a 'Product' content type (node). When a product is created, an ISBN is added to a field attached to the 'Product' content type. The field is called here 'field\_isbn'. So yes, 'field\_isbn' is a field in the "product" bundle. For each product associated with one ISBN there are many activation codes. Thus, users who uses those activation code, gets access to that product with the ISBN. The activation codes are stored in 'activation\_code' table. This is a custom table and the data comes from a different site.

**Table Relationships**

1. Custom Table: activation\_code
2. Node field table: field\_data\_field\_isbn

The table schema is here: https://gist.github.com/aneek/a748f87205b1a0dace1db57998d2be80

NOTE: There is a 'nid' column in activation\_codes table, but that is not a node id. So there is no relation with node table.

The relation is between `field_data_field_isbn.field_isbn_value` and `activation_code.field_product_isbn_value`. It's one to many relation.

In the old view the View's PHP module use to run this below:

```
$total_subscriptions = db_result(db_query("SELECT COUNT(`nid`) AS total_subscriptions FROM {activation_code} WHERE `field_product_isbn_value` = '%s'",  $data->node_data_field_isbn_field_isbn_value));
print $total_subscriptions;

```

In the new view I am trying to do the same but in `query()` method. Views generates the below query:

```
SELECT node.nid AS nid, node.title AS node_title, (SELECT COUNT(cac.nid) FROM {activation_code} cac
WHERE cac.field_product_isbn_value = 9781107875838) AS field_total_subscriptions, 'node' AS field_data_field_isbn_node_entity_type, 'node' AS field_data_field_product_status_node_entity_type
FROM
node node
WHERE (( (node.type IN  ('product')) ))
ORDER BY node_title ASC
LIMIT 25 OFFSET 0

```

I have written a dummy ISBN here as I need to replace this with a proper variable in the custom field handler. This is where I am currently stuck.

**Update #3** **The total code snippet (I am providing one handler and removing other two as they are similar.)**

**product\_activation.views.inc**

```
<?php

/**
 * @file
 * Contains the views hooks and alters.
 */

/**
 * Implements hook_views_data().
 */
function product_activation_views_data() {
  $data = array();

  $data['clms_view_manage_products']['table']['group'] = t('Manage Product View');
  $data['clms_view_manage_products']['table']['join'] = array(
    '#global' => array(),
  );
  $data['clms_view_manage_products']['total_subscriptions'] = array(
    'title' => t('Total Subscriptions'),
    'help' => t('Total Subscriptions.'),
    'field' => array(
      'handler' => 'views_handler_product_activation_total_subscriptions_field',
      'click sortable' => TRUE,
    ),
  );
  return $data;
}

```

**views\_handler\_product\_activation\_total\_subscriptions\_field.inc**

```
<?php

/**
 * @file
 * Contains the custom field data for total subscriptions.
 */

/**
 * Custom views handler for manage product views.
 */
class views_handler_product_activation_total_subscriptions_field extends views_handler_field {

  /**
   * {@inheritdoc}
   */
  function query() {
    $isbn = db_query("SELECT field_isbn_value FROM {field_data_field_isbn} WHERE entity_id = node.nid")->fetchField();
    $sql = "SELECT COUNT(cac.nid) FROM {activation_code} cac WHERE cac.field_product_isbn_value = {$isbn}";
    $table = $this->ensure_my_table();
    $this->field_alias = $this->query->add_field(NULL, "($sql)", 'field_total_subscriptions');
  }

  /**
   * {@inheritdoc}
   */
  function render($values) {
    $output = '';
    $value = $this->get_value($values);
    //dsm($value);
    return empty($value) ? '' : $value;
  }
}

```

The error that I am getting is, 'Column not found; Unknown column 'node.nid' in where clause. So this has also failed. I am sure I am missing something.

The whole views export is here: https://gist.github.com/aneek/706f92a3c13b50a06e3a4e7cdce8679f

# Answer
First off, I'm sure you already tried this: But if you are just doing a row count based on this one relationship, you should be able to do this with Views aggregation. Then you can sort of that. There are helper modules for this too.

For using a views handler you have everything setup pretty correctly. You do not however need to use a filter handler for this case. You are only trying to get click sort to work on a custom field, not create a custom filter field.

It looks like you are trying to sort total\_subscriptions "field" however this is not truly a field, it is simply a rowCount() that you are rendering on each row. When click sorting, it is attempting to run a query to sort total\_subscriptions, but when it queries that table, no such column exists. Try running a query and rendering the output into a field.

**You will need to:**

* convert your db\_select to a sql string and put it in the query definition
* figure out how to access your field\_field\_isbn raw value inside $this query()
* attach the sql query to a field\_alias on the table
* render the field in render($values)
* now, click sorting should automatically work, because the count value is held inside the query field

Here is an example of how I create a custom views field, counting all of the units for a project node, returned the units count into a field on the row, which allowed click sort to use. Note, we will not be adding a custom filter handler. Just a field handler with click sort.

**ec\_app.views.inc**

```
<?php
/**
 * Implements hook_views_data_alter().
 */
function ec_app_views_data_alter(&$data) {
  $data['node']['field_unit_types_count'] = array(
    'title' => t('Unit Types Count'),
    'help' => t('Count nodes by selected term.'),
    'field' => array(
      'handler' => 'ec_app_handler_field_unit_types_count',
      'click sortable' => TRUE,
    ),
  );
 }

```

**ec\_app\_handler\_field\_unit\_types\_count.inc**

```
<?php

class ec_app_handler_field_unit_types_count extends views_handler_field {

    function query() {
        $tid = $this->options['term'];
        //for you, this needs to be the value of field_field_isbn

        //build your sql instead of db_select
        $sql = "SELECT COUNT(*) FROM {field_data_field_units} fu JOIN {field_data_field_unit_types} ut ON ut.entity_id = fu.field_units_value
          WHERE fu.entity_id = node.nid AND ut.entity_type = 'field_collection_item' AND ut.bundle = 'field_units' AND ut.deleted = 0 AND ut.field_unit_types_tid = " . $tid;

        $table = $this->ensure_my_table();
        $this->field_alias = $this->query->add_field(NULL, "($sql)", 'field_unit_types_count'); //this should be the name of your field defined in data_alter or data
    }

    function render($values) {
        $output = '';
        $value = $this->get_value($values);
        return empty($value) ? '' : $value;
    }
}

```

and that should be all you need to make click sort work for a custom field in views.

Keep in mind I am using ec\_app\_views\_data\_alter($data) instead of ec\_app\_views\_data(). You can try my method while continueing to use hook\_views\_data(). Just try removing the sort and filter handlers. Just stick with 1 field handler and click sort = true.

**UPDATE #2 ONE METHOD OF GETTING FIELD ISBN VALUE IN VIEWS HANDLER QUERY()**

```
$isbn_query = db_query("SELECT field_isbn_value FROM {field_data_field_isbn} WHERE entity_id = node.nid");
$isbn_return = $isbn_query->fetchAll();
//dpm($isbn_return) //do this if you want to see the return. Only if you have devel module enabled

//you should only have 1 record so grab the first instance if its not empty
if (!empty($isbn_return[0]->field_isbn_value)) {
    $isbn_value = $isbn_return[0]->field_isbn_value;
} else {
    // do something different here because theres no isbn value.
    $isbn_value = 0;
}

```

Put this inside your query() function. This should get you the $isbn\_value. You can then include $isbn\_value in your next SQL statement that counts your records and adds the count to a field.

Note: you're probably asking yourself, how does it know which nid to select as the entity\_id. All he has there is "entity\_id = node.nid" which is not a php variable containing the node id of that row... When the view executes this query() it will plugin the true node id of that row.

If this doesn't work or if you need help writing the second sql statement, please post your entire views handler snippet for us to look at.

**UPDATE #3 HOW TO GET NODE.NID IN views\_handler\_field::query**

I think maybe you are failing at getting the node.nid because of how you are adding your custom field. Putting node.nid inside a sql query should definitely work. This is a guess, but try this:

Remove your hook\_views\_data and replace with hook\_views\_data\_alter(). Then append your custom field to the \['node'\] array.

**activation\_code.views.inc**

```
/**
 * Implements hook_views_data_alter().
 */
function product_activation_views_data_alter(&$data) {

//    $data['clms_view_manage_products']['table']['group'] = t('Manage Product View');
//    $data['clms_view_manage_products']['table']['join'] = array(
//        '#global' => array(),
//    );
    $data['node']['clms_view_manage_products']['total_subscriptions'] = array(
        'title' => t('Total Subscriptions'),
        'help' => t('Total Subscriptions.'),
        'field' => array(
            'handler' => 'views_handler_product_activation_total_subscriptions_field',
            'click sortable' => TRUE,
        ),
    );
//    return $data;
}

```
> 1 votes

---
Tags: 7, views
---


title: get translated field doesnt find field

text:
# Question
Title: get translated field doesnt find field
I have an entity which contains a field, it has content in that field , yet when I try to programmatically set something in that field, I get

```
InvalidArgumentException: Field field_myfield  is unknown. in                                          [error]
Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 509 of
C:\drupaldevsites\drupal-wcms-migration\docroot\core\lib\Drupal\Core\Entity\ContentEntityBase.php).

```

I have run updatedb but still cannot avoid this error . It makes no sense since the field is there and can be edited via the UI.

I have enabled it here had to enable that field to be translated on this page /admin/config/regional/content-language . but still getting error.

I ran array\_keys($entity-\>getFieldDefinitions()) and the field IS defined,

# Answer
found out I had a space after the field name in my set command!

```
$media->set('field_my_field_name ',array('value'=> $title));

```

instead of

```
$media->set('field_my_field_name',array('value'=> $title));

```
> 0 votes

# Answer
When you look in the code of ContentEntityBase::getTranslatedField() in line 509

```
  $definition = $this->getFieldDefinition($name);
  if (!$definition) {
    throw new \InvalidArgumentException("Field $name is unknown.");

```

you see that this is not related to translation. The error is what it says, that the field is not defined in the entity.

You can run `array_keys($entity->getFieldDefinitions())`, before you try to store data in the entity, to check if the field is defined.

`update.php` does not update entity definitions. This happens when you install the module or run as developer `drush entity-updates` after code changes. Did you check the status page for any errors?
> 0 votes

---
Tags: 8
---


# Question
Title: How do I search all contents including code from admin?
I am a Drupal newbie and I am frustrated in my search for methods that allow admin searches of code in node content fields ie CSS classes. I'm baffled that there is not a built-in default way to help admins search content like this.

I have looked at many projects for Drupal 7 and Drupal 8 and only a few Drupal 7 modules looked like they could have helped. None of what I have read for Drupal 8 appears to offer code search.

The documentation I have read, and the module I found are the following.

# Answer
> 4 votes
For a quick solution, you can edit the View that powers the Content page (or create a new View, edit a different View, etc), and add the body field as an exposed filter. Combined with a `LIKE` operator that should give you reasonably good results (though it will possibly depend on what input format you're using).

If you want something more like what you described, i.e. something that searches multiple fields at once, you could install the Search API module, create a results View, and add a combined filter that will search across all the desired fields. This approach takes a bit more effort, but might give more accurate results than the first one, especially if you use (for example) Solr as the backend.

# Answer
> 2 votes
What you're requesting is raw content based searching. Not (necessarily) the final markup sent to the user but the content stored in the database and the ability to search the raw HTML and markup of the items' content.

You are correct that Drupal Core has no built-in functionality for this. This is largely because Drupal development is catered to editorial users, or endusers with little or no *technical* knowledge of the underlying structure of a website -- such as HTML and CSS.

You've listed a good supply of D7 Modules that try to solve this task, should your site need it. Look to that module list issue queues to see if any have any Drupal 8 port in-progress.

Additionally these modules support content based searching:

As an example of an in-progress Drupal 8 port from the issue queues:

---
Tags: 8, nodes, search
---


# Question
Title: Using Commerce Feeds module, commerce file names are being changed when importing
I have an e-commerce site that sells albums. This product variation type of album has a field of type commerce file. It’s configured to have multiple files (mp3’s) attached, or bundled to it. I’m using the Feeds & Commerce Feeds module. Feeds uses csv files to create these products.

The Feeds importer works but the file names are being changed. It’s appending a ‘\_0’ to the file name.

for example: songname.mp3 -\> songname\_0.mp3 (see attached)

I’ve tried numerous different settings within the file sources option of the product variation type. I’ve checked and unchecked ‘File attach from server directory’ option

note - I have File Field Path module installed because the dirs. need to be different (dynamic) for each product. For example:

```
private://artists/artist_name/album_name/song_name.mp3

```

Utlimately what I want to do is create the dirs. and add the files to server myself and then have the Feeds importer simply reference files that are already there. I don’t want to copy or upload.

Any insight or help would be hugely appreciated!

# Answer
1. Go to structure/feeds importer
2. Select yourproductimporter - go to mapping/.
3. Go to Files:URI (commerce\_file:uri)
4. Click on the button below text "Rename if file exists."
5. Change to "Replace" and save the importer. That worked for me.

That will eliminate the \_0 or \_1.mp3 and keep the same file name as your database.
> 0 votes

---
Tags: commerce, files, feeds
---


# Question
Title: How to get the human readable content type name in a node template
I have created node template for my node, and its working fine.

I need to print content type name, which is like "Whitepaper" and has machine name "w1" in my node template. If I use variable `{{ node.bundle }}`, its printing the machine name. But **I need the human readable name**.

I tried many elements of node, content and page variables but I'm not able to print the human readable content type name.

Can anybody help?

# Answer
You should be able to get the human-readable name of the content type (or the "label") by using the following snippet in your node Twig template.

```
{{ node.type.entity.label }}

```
> 31 votes

# Answer
You can add the human readable name of the content type in a preprocess hook:

*mytheme.theme*

```
use Drupal\node\Entity\NodeType;

/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  $variables['content_type'] = NodeType::load($node->bundle())->label();
}

```

and use it in the node template:

```
{{ content_type }}

```
> 5 votes

---
Tags: theming, 8, nodes
---


title: Add a wrapper around two panes

text:
# Question
Title: Add a wrapper around two panes
I want to add a wrapper around the panes which are shown in red box in the given image. How to achieve it.

I have already tried Panels Extra Styles module but it is not providing a wrapper around two or more panes.

# Answer
Create mini Panel, and add that. In mini panel you give classes, so you can wrap a class.
> 1 votes

# Answer
You can do it with panels extra styles module, and fences module, here is an image explaining how to do it. wrapper div image, both modules are avilable for D7 and D8
> 0 votes

---
Tags: panels
---


# Question
Title: How to Add "Add to cart" Button in product categories display
I display my products through the category menu, so that when you click it, it shows the list of all the items in that category, ie: http://website/product-category/pasta

I want to have an "add to cart" button below the image and descriptions of every single items.

How can i do that?

thank you.

# Answer
Here's the code I that built the add to cart button using a specific product\_id:

```
<?php

$form_id = commerce_cart_add_to_cart_form_id(array($product->product_id));
$line_item = commerce_product_line_item_new($product);
$line_item->data['context']['product_ids'] = array($product->product_id);

$form = drupal_get_form($form_id, $line_item);
// render your $form somewhere

?>

```
> 0 votes

# Answer
If you have created a page like below using view then add "Add to cart form" field available on views.

> http://website/product-category/pasta

But if you are opening taxonomy default detail page where all item related to that category are showing then just go to your "Product Display" content type and click on manage display. Here you can find default and teaser view mode. Edit teaser view mode and drag your "Product Display content type" field to enabled area. Set label of the Product display to hidden and format should be "Add to cart form".
> 0 votes

# Answer
thank you.

I did find a solution on IRC drupal chat.

My issue was that i didn't had any relationship on the page, that's why i couldn't find the field.

So i did create a relationship: Indexed Node: Product and then i was able to add the field Product) Commerce Product: Add to Cart form.

thanks to everyone
> 0 votes

---
Tags: commerce, taxonomy-terms
---


# Question
Title: How can I use Drush to sanitize a database on a remote server?
I'm on Pantheon and I want to run some custom SQL queries to sanitize my dev server.

I have the queries in a file, `custom_sanitize.sqlqueries`.

It looks something like this:

```
UPDATE user__field_useragent SET field_useragent_value = 'Sputnik';
UPDATE node__field_useragent SET field_useragent_value = 'Sputnik';
UPDATE node_revision__field_useragent SET field_useragent_value = 'Sputnik';

TRUNCATE TABLE watchdog;

```

**Goal**

I want to run these queries on a remote server with a single Drush command.

**My Current Workaround**

I connect to the database with Sequel Pro, cut and paste the queries in, and run them.

**What I tried**

Based on the Drush 8 sql-query documentation, I tried to execute my file like this:

```
drush @alias.dev sql-query --file=custom_sanitize.sqlqueries

```

This fails:

```
failed to open stream: No     [warning]
such file or directory drush.inc:904

```

I assume this is because my local drush calls the remote drush on the server, and the file path is different.

So then I tried to input the content of the file this way:

```
`drush @alias.dev sql-connect` < custom_sanitize.sqlqueries

```

This fails with the following message:

```
-bash: PTY: command not found

```

So then I tried inputting the queries in at the command line:

```
drush @alias.dev sql-query "UPDATE node_revision__field_useragent SET field_useragent_value = 'Sputnik';TRUNCATE TABLE watchdog;"

```

This also fails:

```
PTY allocation request failed on channel 0
Command not supported as typed.

```

I also tried using `hook_drush_sql_sync_sanitize()`, but I couldn't get my hook picked up by the drush on Pantheon.

# Answer
Pantheon's terminus can **skip drush**, and pipe SQL directly into a "mysql connection command"

```
echo 'UPDATE users SET pass="12345"' | `terminus connection:info mysite.dev --field=mysql_command`

```

(source)
> 2 votes

# Answer
You can use `sql-cli` command for that:

> drush @alias.dev sql-cli \< custom\_sanitize.sql
> 2 votes

# Answer
You could use the db\_sanitization Quicksilver example, and sanitize automatically every time you pulled the database into your dev environment.

If that doesn't work for you, open a ticket with Pantheon, and I will look at it on Monday (if someone else doesn't help you sooner than that).
> 1 votes

# Answer
As a workaround, you can input the queries one by one:

```
drush @alias.dev sql-query "TRUNCATE table watchdog"

```

So, you can change every query in `custom_sanitize.sqlqueries` to be `drush @alias.dev sql-query "myquery"`, and then execute that file.
> 0 votes

---
Tags: database, drush
---


# Question
Title: PhotoSwipe display only one image from Views grid form
I created a grid view to display several node images thumbnails (3 columns, and multiple lines), and following PhotoSwipe usage found whithin the README.txt, I specified the CSS class "photoswipe-gallery" to display the field image.

Now when I click on one image from the view, I got the full sized Image as I wanted, but I can't move to the next or previous image that exist within my view grid.

Is there anybody knowing how to do it?

Thanks in advance

# Answer
After some investigations, I hook (?) the views-view-grid-default.tpl.php and wrap the grid within a:

```
<div class="photoswipe-gallery"> <table> ...</div>

```

block and now the script take correctly all images found in the grid table.

Of course I removed this class from the image field parameter.

Thanks
> 0 votes

---
Tags: 7, views
---


title: How do I show related content?

text:
# Question
Title: How do I show related content?
Using Drupal 7 and Views 3 I am trying to setup a block to show related content based on taxonomy terms.I have read numerous articles and threads on how to do this but none seem to work, this might be due to using a view and custom path rather than displaying the node directly.I have done the following.

1. Created nodes and added Taxonomy terms to each.
2. Created a view for each node, the views have a custom path.
3. Created a block view, added contextual filter on "Has Taxonomy Term ID". I have set default value "Taxonomy term ID from URL" and clicked the LOad Default from node page checkbox.
4. Added the block to sidebar.

My URL are of the format www/example.com/name , there is only 1 argument, I am struggling to understand how the filter can pick up the term from that URL and would like to know if there is a simple way around this. The problem seems to either lie with my URL or that I'm displaying the node through a view, I would have thought these were both common scenarios that wouldnt require any coding, any help on how to workaround this would be much appreciated. I am leaning towards using mini panels but having spent some hours with them would rather just use views if possible. Thanks

*EDIT* I think this is very likely view/path related, going to the content page directly displays the block with the related content, its on the View pages with their own paths this is not working. My views are simply Page views with normal filters on the content type and on a taxonomy term (which is different to the term on the contextual filter).

# Answer
> 7 votes
**Creating a related content view in Drupal 7:**

Show related content based on shared Term-pages (from any given vocabularies).

Each term page will be recognized by the term ID (TID) hidden in the pages’ URL.

## The process:

**Basic stages:**

1. Create a “Content” view-block.
2. Add a contextual filter: “Has taxonomy term ID”.
3. Choose “provide a fixed value”.
4. (From type): “Taxonomy term ID from URL“.

**Checking:**

• Uncheck “Load default filter from the term page”. • Check “Load default filter from node page, that’s good for related taxonomy blocks”.

• Check “Limit terms by a vocabulary”. • Check your desired vocabulary.

5. Select “Filter to items that share any term”.
6. Go down and check “Reduce duplicates”: This will several terms that relate to the same page – To appear. Only one will of them will.

https://www.daymuse.com/blogs/drupal-guide-related-content-term-views

## Optional:

If you would like that the current node won’t appear in the list:

1. Go to the view and add another, extra Contexutal filter.
2. Give it content: NID.
3. Select “Provide default value”.
4. Set the “Type” to “Content ID from URL”.
5. Go down in that window, click on “More”, and there check “Exclude”.

Note that this will exclude the current node in which the related is shown – From that very list.

It will do so by using the content ID which is a (hidden) part of the URL.

# Answer
> 1 votes
I guess the problem was using a view with a custom url with a contextual filter to display a block that gets its data from another view with a custom URL, this doesn't appear to be possible without custom code. In the end I used the panelizer module to display my node, added a sidebar in panelizer and added the content as block, on the block I was able to use the method described by Benia to add the contextual filter.

# Answer
> 1 votes
Why don't you try Views Related Content Module. Install this module and follow:

* Create a View block with content type
* Add "Related Content: Term" as Content Filter Criteria
* Select the vocabulary you want to short by
* Save the view and place the view block from drupal block administration page

That's it.

There's a step by step tutorial available on drupal forum.

---
Tags: 7, views
---


# Question
Title: Convert a date with format (2017-05-27) to save in node created field
I've been looking around for a little while for what I thought would be a simple question to answer but I cannot seem to find the answer.

The question is: How can I convert a date with the format `2017-05-27` into a Drupal safe format for saving into the database?

I have looked inside `Drupal\datetime\DateTimeComputed` but I'm not sure that is the right place. Any help would be appreciated.

# Answer
The node `created` field is a Timestamp Field. Use the php function strtotime() to convert the string to a Unix timestamp:

```
$timestamp = strtotime('2017-05-27');

```

and store the value in the created field:

```
$node->created->value = $timestamp;

```

You can also use the method setCreatedTime():

```
$node->setCreatedTime($timestamp);

```
> 4 votes

---
Tags: nodes, datetime
---


title: How am I getting spam with WSOD?

text:
# Question
Title: How am I getting spam with WSOD?
I get a small amount of spam email from my contact form, and haven't yet put a solution in place.

Recently got the wonderful WSOD (have fixed it since), and noticed i was STILL getting spam. Curious how this could still be happening, and if that means certain spam protection ideas may not work.

I was thinking of adding Antibot. Would this still work?

# Answer
> 2 votes
The WSOD may have been caused by actually visiting your site, loading the page etc.. for example some block load error. Whereas the spam is probably sent directly to the form action by HTTP POST.

As mentioned already, recaptcha may be a good option there.

---
Tags: advertising, wsod
---