# Question
Title: How to avoid caching on access callbacks?
I am using Views Access Callback module to set my custom callback access check. I have written a custom module and implemented the hook provided by this module. I have added a condition to return `TRUE` and `FALSE`. But the access callback get cached.

```
/**
 * Implements hook_views_access_callbacks().
 */
function my_custom_views_access_callbacks() {
  return array('my_custom_module_access' => t('Allow my views access.'));
}
function my_custom_module_access() {
  $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
  if (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] == Crypt::hashBase64($password)) {
    return TRUE;
  }
  return FALSE;
}

```

I have added callback like above. So when I `drush cr` from command line it will return `FALSE` because there is no session in terminal. So when I access the view in browser it still shows access denied because of cache I guess.

My question is how to handle this callback without being cached?

# Answer
I did this using following way :

```
function my_custom_preprocess_page(&$variables) {
  $url = Drupal\Core\Url::fromRoute('<current>');
  if ($url->getInternalPath() == 'my-view-page') {
    $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
    if (!isset($_SESSION['my_custom_pass']) || (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] != Crypt::hashBase64($password))) {
      throw new AccessDeniedHttpException();
    }
  }
}

```

**Edit:** We can add our dependency to access object in our access hook.

```
/**
 * Implements hook_node_access().
 */
function my_custom_node_access(NodeInterface $node, $operation, AccountInterface $account) {
  $access = new AccessResultNeutral();
  $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
  if (!isset($_SESSION['my_custom_pass']) || (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] != Crypt::hashBase64($password))) {
    $access = new AccessResultForbidden();
  }
  $access->addCacheableDependency($_SESSION);
  return $access;
}

```
> 1 votes

# Answer
The hook\_ENTITY\_TYPE\_access() should return \Drupal\Core\Access\AccessResultInterface type. This is missing here, try

```
use Drupal\Core\Access\AccessResult;
    function my_custom_school_access() {
        $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
        if (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] == Crypt::hashBase64($password)) {
           return AccessResult::allowed();
        }
        return AccessResult::forbidden();
    }

```
> 0 votes

---
Tags: 8
---


title: Importing XML using feeds API

text:
# Question
Title: Importing XML using feeds API
I have some data of type *Images* where I want to import in the format of **xml** named 'images.xml' which containing **images url** and **information**.

I want to import this file programatically using feeds API.

How can I achieve this?

for this i use following code:

```
$source = feeds_source($importerId);
$config = array(
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => FALSE,
      'use_pubsubhubbub' => FALSE,
      'designated_hub' => '',
      'request_timeout' => NULL,
      ),
    ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'url',
        ),
      'rawXML' => array(
        'xpathparser:0' => 'xpathparser:0',
        ),
      'context' => '//image',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          ),
        ),
      'allow_override' => 1,
      ),
    ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'url',
          'unique' => FALSE,
          ),
        ),
      'update_existing' => '0',
      'input_format' => 'full_html',
      'skip_hash_check' => 0,
      'bundle' => 'images',
      ),
    ),
  'content_type' => 'images',
  'type' => 'images',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
  );
$source->importer->addConfig($config);

$featcher_config = $source->getConfigFor($source->importer->fetcher);
$featcher_config['source'] = $url;
$source->setConfigFor($source->importer->fetcher, $featcher_config);
//$source->save();
//node_save($source);
$source->startImport();

```

But this code show "Download of failed with code -1002" and no images are import...

# Answer
> 1 votes
It depends somewhat on your use case. For example are you scraping the images off a web page or are you using a direct image file URL.

If you are scraping from a web page you can use the feeds image grabber module.

That module provides additional settings where you can configure a CSS selector for the page that is in your XML file.

The module will then request that page and scrape the image from it based on the selector you configured then add the image to the imported item.

# Answer
> 0 votes
IF you are getting those images from a website using a XML format. Use the SimplePie Core parser.The parser will allow you to get the images with their URL.

---
Tags: feeds
---


# Question
Title: dynamic block title for block-view of referencing nodes
I have a block listing nodes that all reference the same 'parent node' (etity reference). I would love to see the title of the referenced node as a title of that block.

Example: on a record label website there could be nodes for albums. Every album node references one artist. On an album page there would be a block listing "Other Albums of Artist XY".

I know my question is quite similar to this question "Dynamic block titles" but the solution on that question suggests using Tokens in the block's body, along with some h2-tags, so that it would look like the block's title.

Sounds like a swell workaround – however – since the block I use comes from a view, there is no body I could place tokens in.

Another workaround that almost did the trick was to add the referenced content type to the fields of the view, hide the output, then use tokens in the header of the view (again with h2 tags). But I only could get the referenced node fully rendered, making it impossible to use as a fake block title.

How can this be done? I would gladly welcome any hints and/or pointers…

Thanks! t.

# Answer
After a couple of days of tinkering I finally found the solution – and I think it's a good idea to document it here in case somebode else needs a similar setup.

First under "Fields" I added the referenced node by adding the result of the entity reference field I want to display in the block title, e.g. *related band (parent of album)* –– and set it to hidden ("Exclude from display").

Now the result of this field is available in "Header: Global: Text area" as a token. Checking "Use replacement tokens from the first row", selecting the correct token and adding it to the header text field above.

This makes the content of the related node available – and actuually I get the full content of the node, all displayed in the header region of the block. This is nice, but too much.

To limit the display to the headline only, I first installed the module https://www.drupal.org/project/token\_filter – this adds "Tokens" to the pulldown "Text format" underneith the "Header: Global: Text area".

Next step was to add a small function to the template.php that will add functionality to use individual templates for every Text format separately as described over here: http://fredparke.com/blog/using-custom-template-files-different-display-modes-drupal-7

And this is the function:

```
function THEMENAME_preprocess_node(&$vars) {
  // Custom display templates will be called node--[type]--[viewmode].tpl.php
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__' . $vars['view_mode'];
}

```

Now I can add a template named like this: node--artist--token.tpl.php and through this I can trigger, how the artist page is displayed, when loaded as a token. In my case: adding and some classes to the title did the job.

There is probably easier ways to do this – but this way gives me 100% controll of what is displayed – and how and where… Hope this helps somebody someday.
> 0 votes

# Answer
Add the content title a second time, but this time set the relationship so that the artist's name is displayed. Set the display of this title to hidden, and make sure it has a label which reads : 'Other albums by'.

Then in the Format section, select settings, and then group by this artist title field you have just added and hidden.

The title will get wrapped in an h3. If you want to wrap it in an h2 then you will have to override the views template, one of the suggestions in the Style Output of the provided theme information.
> 1 votes

# Answer
In the current version of Views (3.14), you can write tokens in the title field.

It doesn't say so in any help messages, but I have tested it on https://simplytest.me and it worked.

You can see the available token names by selecting the last field and activating `Rewrite the output of this field` and folding out `Replacement patterns`.
> 0 votes

---
Tags: blocks, entities
---


# Question
Title: How to create a bulk grant view form for the node access module?
I'm completely new to Drupal and trying to learn it, but it's pretty hard.

The Node Access module is great and I want to make functionalty for it for bulk grant for several users. The idea is to have a form grid with several users in columns and nodes and grants in rows. It will look like that:

What I've come to so far:

```
function table_test_form($form, &$form_state, $node) {
  $form_values = &$form_state['values'];
  if (!$form_values) {
    $form_values = array();
// Get node titles for the first column
        $results = db_query("SELECT DISTINCT title, node.nid
      FROM node_access
      LEFT JOIN node ON node_access.nid = node.nid
      WHERE node.nid < :nid
      ORDER BY node.nid", array(
        ':nid' => 5,
      ));
    foreach ($results as $noderow) {
      // make an array for every row
      $form_values['noderowid'][$noderow->nid] = array(
        'name' => $noderow->title,
      );
      $current_nid = $noderow->nid;
      //Get users and grants for the current node
      $results_grants = db_query("SELECT uid, name, grant_view
      FROM node_access
      LEFT JOIN users ON uid = gid
      WHERE nid = :nid AND uid < :uid
      ORDER BY uid ", array(
        ':nid' => $current_nid,
        ':uid' => 5,
      ));

//      Tried this but didn't work
//      if ($results_grants) {
//        while ($row = $results_grants->fetchAssoc()) {
//          $items_grants[] = array(
//                                    $row['name'] => $row['grant_view']
//          );
//         }
//      }
      $items_grants = $results_grants->fetchAllKeyed(1,2);
//    add the grants for every user to the node row
      $form_values['noderowid'][$noderow->nid][] = $items_grants;
    }
  }

  if (!isset($form_values['noderowid'])) {
    $form_values['noderowid'] = array();
  }

  $noderows = $form_values['noderowid'];

  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $node->nid,
  );

  //  the table.
  if (is_array($noderows)) {
    $form['noderowid'] = array('#tree' => TRUE);

    foreach ($noderows as $key => $field) {
        if(!isset($form['noderowid'][$key])){
        $form['noderowid'][$key] = array();
    }
    $form['noderowid'][$key]['name'] = array(
        '#type' => 'hidden',
        '#value' => $field['name'],
      );
    $arr = $form['noderowid'][$key];
      //add checkboxes
            foreach ($arr as $nodetitle => $f){
               if($nodetitle!='name'){
                    $form['noderowid'][$key][$nodetitle] = array(
                      '#type' => 'checkbox',
                      '#default_value' => $f[$nodetitle],
                    );
               }
            }
    }
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save Grants'),
  );
  return $form;
}

function theme_table_test_form($variables) {
  $output = '';
  $form = $variables['form'];
  $rows = array();
//get the names of the users and put them in the header
  $uid = 5;
  $sql = "SELECT name FROM users WHERE uid < :uid  ORDER BY uid ASC";
  $result = db_query($sql, array(':uid' => $uid));

  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $items[] = array(
      'data' => t($row['name'])
      );
    }
  }
  // make table.
  unset($rows);
  $noderows = element_children($form['noderowid']);
  if (count($noderows) > 0) {
    $header = $items;
    $rows = array();

    foreach ($noderows as $key) {
      $row = array();

   // first column
      $row[] = $form['noderowid'][$key]['name']['#value'];
   // other columns
      foreach(array_slice($header, 1) as $usr){
              if(!isset($form['noderowid'][$key][$usr])){
                $form['noderowid'][$key][$usr] = array();
         }
          $row[] = drupal_render($form['noderowid'][$key][$usr]);
      }

      $rows[] = $row;
    }
    $output .= theme('table', array('header' => $header, 'rows' => $rows));
  }

  $output .= drupal_render_children($form);

  return $output;
}

```

It renders the users and nodes names, but not the checkboxes.

I guess it's a pretty bad code and there are too many queries to the database, but I want to just make it work for now.

Any suggestions?

# Answer
Assuming this is for D7, this is a typical case to handle using the Rules module, combined with Views Bulk Operations, with zero custom coding. So if you are "*completely new to Drupal and trying to learn it*" (as in your question), you may want to try to learn to walk before trying to fly. Read on for further details.

Advice: the Node Access module is ***unsupported*** (repeat: unsupported). You really should consider using the Content Access module instead.

What you actually need to do is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

> * You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
> * However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
> * You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displays with at least one VBO field will be selectable.
> * The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

For your case, for the Rules Action you can use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?".
> 2 votes

---
Tags: forms, users
---


title: Ckeditor not applying to textarea

text:
# Question
Title: Ckeditor not applying to textarea
I have a **`textarea`** field in a custom module form , I guess there is ckeditor library by default in core in d8 . I tried the following :

```
$form['fieldset']['email_template'] = array(
  '#type' => 'text_format',
  '#format' => 'full_html',
  '#title' => t('E-mail template content'),
  '#default_value' => "<br><br><br>" . $dvalue,
  '#description' => t('A valid template for email trigger.<b> Please type ":" for variable suggestions</b>'),
  '#attributes' => array(
                ),
  '#required' => TRUE,
  '#cols' => 60,
  '#resizable' => TRUE,
  '#rows' => 13,
  //'#wysiwyg' => TRUE,
            );

```

I followed the link : https://www.drupal.org/node/1031160

But the ckeditor is not applying to the textarea as expected . Any idea ??

**UPDATE**

I was not given the text\_format as `ckeditor` in https://base\_url/admin/config/content/formats .  I defined a new format which can apply to which all fields needed as ckeditor . cheers

# Answer
> 3 votes
Go to `/admin/config/content/formats` and check the CKeditor is enabled for FULL HTML. Also, could be a role issue, by default Full HTML is for admins only.

## Important:

For safety/security reasons FULL HTML should be used by admins only. You're better off using `basic_html` as your format if this form is for authenticated or anonymous users. You may need to adjust the roles so anonymous can use it.

# Answer
> 1 votes
1. Go to configuration \> Click Text formats and editors
2. you will find Full HTML option click on configure
3. Select Text editor has Ck Editor and whatever options you want and click on save

Run your code . You will find ckeditor in textarea

---
Tags: 8, wysiwyg
---


# Question
Title: Is it possible to bypass one specific view for authentic users?
I have a specific view. This is running well under admin rights but not with specific other roles which do not have the permission “Bypass content access control”

Debugging with devel tools and related blocks as well as change permissions setttings in the role is not solving the problem :-(

Is there a easy way to create the possibility to give this specific view a "Bypass this view only for authentic users" ?

# Answer
> 1 votes
Under *Advanced\>Other\>Query Settings*, try checking `Disable SQL rewriting`.

---
Tags: views, users
---


title: Are rules limited by user roles?

text:
# Question
Title: Are rules limited by user roles?
I'm looking a bit into the Rules module and it seems to have a lot of possible uses.

However, one thing isn't really clear to me. Are Rules dependent on the current user's permissions? For example, if a user doesn't have permission to change a certain content node, but he can do something that triggers a rule that changes that content node, will the node be changed or not?

With other words, are rules executed from "administrative" permissions or from the current user's permission?

Update: I've tested out 2 permissions. Creating a content node and editing a content node by using rules when the user doesn't have permission to do so directly. In both those cases Rules doesn't follow the current user's permission and creates/edits the node without a problem. Of course this is by no means exhaustive testing, but for simple node-related operations Rules isn't hindered by the user. (Using the latest version of Drupal and Rules) If it ever is, I've selected the answer that bypasses the problem.

# Answer
> 1 votes
I've definitely run into problems with this before and it's pretty annoying..

One possible way out of it is to create an extra role with the required permission and in rules, add it, force save user, do stuff, remove role.

---
Tags: 7, rules
---


# Question
Title: Date popup - how to restrict typing into the textfield and return timestamp instead of formated date
In D7 I'm using date popup form element:

```
$form['sidebar']['reg_date']['from'] = array(
    '#type' => 'date_popup',
    '#title' => t('From:'),
);

```

When user click the textfield a popup calendar will appear, but user also can type the date into the textfield. But he can write something invalid like '44444' and this value will be returned in form state values without any form error. It would be useful if this module had an option for restricting typing date by keyboard. Is there any option for this?

I also have one side question: Is there any option to return unix timestamp value instead of formatted date in form state values? In my case it returns date in format '29.5.2016'.

# Answer
You can use `['#attributes'] = array('readonly' => 'readonly');`

Ex:

```
    $date_format = 'd/m/Y H:i';
    $form['campaign_popup'] = array(
          '#type' => 'date_popup',
          '#date_format' => $date_format,
          '#default_value' => variable_get('campaign_popup'),
          '#title' => t(' Campaign Start Date.'),
          '#date_label_position' => 'within',
          '#date_year_range' => '0:+3',
          '#datepicker_options' => array('minDate' => 0),
          '#attributes' => array('readonly' => 'readonly'),
    );

```
> 4 votes

---
Tags: 7, datetime
---


# Question
Title: Video Embed Field: Check All My Videos on existance?
My question on drupal.org did not have an answer: To check if YouTube video exists in all my nodes?

Please yow to do these?

# Answer
the quickest solution is to query the DB and export all youtube video IDs. After you can write a custom PHP script to check if the video exists. Here is an example of the code you could use: https://stackoverflow.com/a/21069917

A more *Drupalistic* approach is to write a custom module which do the same thing. For example it could implement a drupal cron task or a batch procedure to verify each Youtube field content using the code suggested before.

I hope this suggestion will be helpful.
> 1 votes

---
Tags: 8, media
---


# Question
Title: How do I limit a taxonomy dropdown exposed filter to the terms used by nodes in view results?
I'm trying to create a custom node search view, that takes Taxonomy terms as a filter (dropdown - autocomplete not an option). The problem I have, is that there could be \>1000 terms and I would like to restrict the dropdown to show only the taxonomy terms that are already in use by the nodes returned in the initial view results. Does this make sense?

Can anyone advise if this is possible, and if so, how best to achieve it?

# Answer
> 1 votes
Like you can already read on the bug report from Drupal.org which you've copied from, a good solution is to use Views Selective Filters. It does exactly you're asking for.

---
Tags: views, 8
---


# Question
Title: How do I make the bootstrap dropdown menu work?
I like to install in a bootstrap subtheme dropdown menu. But it does not work in my subtheme. Using the bootstrap theme it works.

my jolly.info.yml looks like this core: 8.x type: theme base theme: bootstrap

```
name: 'Jolly'
description: 'Theme for ...'
package: 'Bootstrap'

regions:
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  highlighted: 'Highlighted'
  search: 'Suchleiste'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'

libraries:
  - 'jolly/global-styling'
  - 'jolly/bootstrap-scripts'

```

my jolly.libraries.yml looks like this

```
global-styling:
  css:
   theme:
     css/style.css: {}

bootstrap-scripts:
  js:
    bootstrap/js/affix.js: {}
    bootstrap/js/alert.js: {}
    bootstrap/js/button.js: {}
    bootstrap/js/carousel.js: {}
    bootstrap/js/collapse.js: {}
    bootstrap/js/dropdown.js: {}
    bootstrap/js/modal.js: {}
    bootstrap/js/tooltip.js: {}
    bootstrap/js/popover.js: {}
    bootstrap/js/scrollspy.js: {}
    bootstrap/js/tab.js: {}
    bootstrap/js/transition.js: {}

   dropdown:
    css:
      css/styles.css: {}
    js:
      js/dropdown.js: {}

```

and I use the same

> menu--main.html.twig

like the bootstrap theme.

I try so many things but do not find what's wrong or what kind of dependency is necessary.

Can anybody help?

# Answer
Add dependency in libraries.yml file just below the bootstrap js file:

dependencies:
\- core/jquery
\- core/drupal.ajax
\- core/drupal
\- core/drupalSettings
\- core/jquery.once
> 1 votes

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


# Question
Title: display selectable drop down options based on a checkbox selection
I am trying to create a form in Drupal. I want to create the following situation: if a checkbox is selected I want to display a drop down menu. can you please suggest a way to do it.

# Answer
> 2 votes
You can use Drupal form api states.

Example:

```
function example_form_states($form, &$form_state) {

  $form['click_me'] = array(
    '#type' => 'checkbox',
    '#title' => t('Click me!'),
  );

  $form['example_states'] = array(
    '#type' => 'select',
    '#title' => t('Lorem ipsum dolor sit amet'),
    '#options' => array(
      0 => t('Test 1'),
      1 => t('Test 2'),
     ),
    '#states' => array(
      'visible' => array(
        ':input[name="click_me"]' => array('checked' => TRUE),
      ),
    ),
  );

  return $form;
}

```

**Additional Resources** https://api.drupal.org/api/examples/form\_example!form\_example\_states.inc/function/form\_example\_states\_form/7.x-1.x https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7.x#states

# Answer
> 2 votes
**Programatic way**

```
  $form['checkbox_form'] = array(
    '#type' => 'checkbox',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('checkbox_form', TRUE),
  );

  $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('selectbox'),
    '#options' => array(
          TRUE => t('Yes'),
          FALSE => t('No'),
     ),
    '#states' => array(
      'visible' => array(
        ':input[name="checkbox_form"]' => array('checked' => TRUE),
      ),
    ),
  );

```

Second form element `visible` makes the trick.

**Module Way**

Use Conditional Fields module.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.

---
Tags: forms, ajax, navigation
---


# Question
Title: How to allow a particular user to take quiz very next day in drupal
I have gone through so many question asked here but not find exact answer. The main problem I have faced is to create a quiz using 7.x-4.0-rc2, I made some user who can take quiz. One user can take quiz only once, but I need that particular user can take quiz again very next day (After 12AM).

# Answer
I would suggest to make use of rules:

1. Create user role (by hand) which always access to quiz let say QUIZER
2. On Event "I want to enter Quiz"
3. Look up Time Last entered date from current olr
4. Check if allowed to go on
5. Add role quizer to current user
6. On event "I'm stopping the Quiz"
7. Remove role quizer from current user
8. Save Time last entered Quiz in user profile
> 0 votes

---
Tags: 7, quiz
---


# Question
Title: Creating a marketplace for tour activities
I am tying to setup a website that will sell tour activities.

People (local guides) can login in and create a profile and define 1 or multiples activities (i.e. a waking tour of Manhattan) with a description, a price and a calendar of availabilities (maybe just now a simple calendar system not linked to availabilities).

Tourists will come on the web site, choose an activity (by category, location...) and will choose a date for it and book it online.

I need to track the orders in the admin area and have it in the Profile of the person who created the activity.

I tied to do this with D7, marketplace module, calendar module and Ubercart but I have lots of difficulties to do it.

Do you have tips on which modules would be the best to do that (Ubercart / Drupal Commerce)... ?

I have also been looking to "rooms", "simple reservation" modules but it seems that they does not fit my needs.

Regarding the invoicing, payment, commission revenues tracking, I will plug the API of an external system like LemonWay.

Thanks.

Emmanuel.

# Answer
As someone else suggested: take a look at the Booking and Availability Management Tools for Drupal (BAT).

Roomify.us, the business providing the BAT framework announced that they are also providing solutions specifically for tours and activities rather than just rooms and fixed places.

The BAT system integrates with Drupal Commerce and its various payment gateways. It also takes over the Drupal logic very well with 'types', 'type bundles', 'events' and 'units'.

Once you understand how it works conceptually it should not be too difficult to modify BAT so that it can become a kind of marketplace where users can create their own units on the basis of pregiven tour types you have defined.
> 1 votes

# Answer
I would suggest looking registration module along with commerce registration. I would create a content type for the activities with fields for the various things you listed. Use references to associate the activity created to the user. You can then create a view that lists the associated activities on the profile of the user.

Not familiar with the LemonWay part. Pretty sure commerce integrates with a number of the gateways available.
> 0 votes

---
Tags: commerce, ubercart, datetime
---


# Question
Title: Remove image banner on individual pages?
I have zero experience with Drupal or any other similar systems. I have simply been given access to a Drupal website (that was created by an external company) at work and told to make changes. I have managed to somewhat figure out a few general basic things but having many problems that are making me lose my mind.

My current problem is this: there are a bunch of basic pages with the usual stuff, a side menu, content area, etc. They also have a banner image along the top (created as a field in the content type "basic page"). I need to remove the banner image from just one page. Simple. Or so I thought. I can't seem to figure this out. I tried making the banner image field not required and leaving it empty, but an image still appears.

Any sugestions?

PS. I'm not sure but I think it's Drupal 7 (that's right, I don't even know how to check that).

# Answer
> 2 votes
On the `body` element there are page classes for each "node", and in Drupal every node has a number, called the "nid" or "node id".

The services page nid is 65.

Look at the body element in your browsers inspector (right click, "Inspect"), you'll see something like this for the body:

```
<body class="html not-front not-logged-in one-sidebar sidebar-first page-node page-node- page-node-65 node-type-page i18n-en-gb blue">

```

For every node in the site there is always going to be the `page-node-[node-id]` class, e.g. `page-node-65`

By "banner" I assume you mean the photo of the oil rig? If so you can use the body class and the wrapper on that image:

```
.page-node-65 .cover {
  display: none;
}

```

But - consider this a stop gap solution, you need to figure out how the site is structured/built and try to remove the picture/banner from being there in the first place.

# Answer
> 1 votes
These banners will almost comes from Blocks section.

1. Goto `"www.yoursite.com/admin/structure/block"` try searching for block name
2. Click on `Configure`
3. In the Visibility section -\> Check this `"All pages except those listed"`
4. Enter `<page URL>`
5. Click on `Save block`

Attached image for reference.

---
Tags: 7, media
---


# Question
Title: PHP Parse error: syntax error, unexpected T_FUNCTION in redhen_activity.module on line 608
After migrating from dev to prod on Bluehost when I run `update.php` I get a 500 error and I get the below error in error in `error_log`.

> PHP Parse error: syntax error, unexpected T\_FUNCTION in redhen\_activity.module on line 608

This is D7 with the latest update to the Open Outreach Distribution. The odd thing is that my dev site (running as a subdomain) works just fine.

# Answer
Line 608 contains anonymous function.

```
$filtered = array_filter($message_types, function($var) {
  return strpos($var, 'redhen_') !== FALSE;
});

```

Here is the good explanation from DanChadwick on Drupal.org. Let me quote it here as well.

> That line of code is an anonymous function. There are only 2 reasons I know of why PHP choke on an anonymous function.
>
> 1) Use of PHP \< 5.3, where anonymous functions aren't supported.
>
> 2) Use of an opcode cache that doesn't support anonymous function. APC works. Searching the issue queue will reveal another that doesn't, whose name escapes me at the moment.
>
> I'd venture that your other functioning sites either
>
> a) aren't displaying components
>
> b) are using an older version of webform,
>
> c) are using a newer version of PHP or
>
> d) aren't using the same op code cache.

So the best solution is to upgrade your PHP version.

To check your PHP version, either:

1. use the PHP cli `php -v` or
2. use the `phpinfo()` function.
> 1 votes

# Answer
I think you're using PHP 5.2 or earlier, which doesn't support closures. You can find out which version of PHP you're using `phpinfo()`.

Lindly upgrade to PHP 5.3+, or use `create_function`, or write a static function and pass it as a callback.
> 1 votes

# Answer
Thanks for all your help. Unknown to me, Bluehost downgraded my PHP version. When they upgraded it to 5.6.24 everything worked. I battled this error for weeks! It was very frustrating!
> 0 votes

---
Tags: 7
---


title: Get raw URL from field link

text:
# Question
Title: Get raw URL from field link
I have set up a node--home\_page.tpl.php template with the following:

```
  <a href="<?php print render($content['field_primary_section_link']); ?>">
    <div id="primarySection">
       <?php print render($content['field_primary_section_image']); ?>
       <h1><?php print render($content['field_primary_section_title']); ?></h1>
        <?php print render($content['field_primary_section_body']); ?>

    </div>
  </a>
  <!-- END Primary Section -->

```

I want the anchor tag to contain the raw URL from the field\_primary\_section\_link but it is pulling in everything around it. I just want the plain URL but am unsure how to do. Any help would be appreciated.

# Answer
You can dump `$content['field_primary_section_link']` using var\_dump() or if you have devel module installed in your project you can use dpm() and you'll see a bunch of arrays there and check the raw url that you need.
> 1 votes

# Answer
Use file\_create\_url(). It gives you the absolute path if you feed it the file's FID.
> -1 votes

---
Tags: entities
---


# Question
Title: How can I have conditional content within page body that is dependent upon the domain?
We are planning to use Domain Access to manage 5 different domains that will share content. The majority of our pages will be shared across all 5 domains and will look identical on each domain. Domain Access makes it trivial to handle this use case. However, on some of the pages, 95% of the content will be identical and 5% of the content will be dependent upon the domain that is serving the page.

One possible solution is to create a unique page for each domain and publish it to the appropriate domain. Although this works, it is difficult to maintain because we would need to maintain changes to the identical content across 5 unique pages.

Another option would be to embed PHP in the page, such as

```
shared content for all 5 sites here.

<?php if ($_SERVER['HTTP_HOST'] === 'domain1.example.com') { ?>

domain1 specific content here

<?php } else if ($_SERVER['HTTP_HOST'] === 'domain2.example.com') { ?>

domain2 specific content here

<?php } ?>

```

Again, this would work, but has several disadvantages. I am looking for a way to share the identical content across the domains and yet have site specific content within a page in a way that makes it feasible to maintain and easy for content editors (non-technical users) to edit. Does anyone have any suggestions?

# Answer
The sites module has support for multiple domains and managing content across those domains.

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

If you are using the same template file for the page where you are displaying your content, then you can implement the 'hook\_site\_access()' from the sites module in the template file, and gather the content you desire to display based on the domain name.

In addition, depending on the type of content you are displaying, you might be able to get away with simply using the Views or Context integration from the Sites module, rather than editing your template file manually.

Another option is to use Drupal's taxonomies to classify your content. Then, you could use any of the solutions above (custom code in page template, Views, or Context) to filter only the content which is categorized to be displayed on the domain you are on.

In any case, if you want two different versions of the same page to display on different domains, you will need two different nodes, and they will need to be classified accordingly. I'm not sure if there is any way around maintaining multiple nodes if the content varies by domain.

However, when the same node is to be displayed on multiple domains, this kind of architecture will allow you to display it only on a specific subset of domains you choose.
> 0 votes

# Answer
Using the Domain Access module, you can put this in your **template.php** file:

```
function YOURTHEMENAME_preprocess_page(&$vars) {
  global $_domain;
  $vars['current_domain'] = $_domain['domain_id'];
}

```

Once this is done, you'll have a variable you can use in your **.tpl-files**. The code above provides the domain's *ID*, which you can find in `admin/structure/domain` by hovering over the "edit domain" link.

You can use it like this:

```
<?php if (isset($current_domain)): ?>
    <?php if ($current_domain == 1): ?>
        <div class="show-this-on-primary-domain">
            <h1>Welcome to my primary website</h1>
        </div>
    <?php elseif ($current_domain == 2): ?>
        <div class="show-this-on-another-domain">
            <h1>Welcome to another website</h1>
        </div>
    <?php endif; ?>
<?php endif; ?>

```

(Source)
> 0 votes

---
Tags: domain-access
---


# Question
Title: How do I add a class to local task links in Twig template?
I've used custom templates to add BEM style classes to both the local tasks UL wrapper and the individual LI items, I'd like to also add a class to the actual local task (tab) link.

This is the default code in the Classy template:

```
<li{{ attributes.addClass(is_active ? 'is-active') }}>{{ link }}</li>

```

Is there no way to simply add a class to the `{{ link }}` item?

# Answer
```
{% set link = link|merge({ '#attributes': { 'class': [ 'your', 'custom', 'classes' ] } }) %}

<li>{{ link }}</li>

```
> 13 votes

# Answer
you can add a class with the attribute array of the TWIG function :

```
{{ link(item.title, item.url, { 'class':['my-custom-class'] }) }}

```

unfortunately, this overrides any classes added preprocessing by other contrib modules. Im currently looking for a way to append new class to the {{ link }}
> 4 votes

# Answer
You can't from the template, but you can do it from a preprocess hook. If you look at the original from Drupal:

```
function template_preprocess_menu_local_task(&$variables) {
  ...
  $variables['link'] = array(
    '#type' => 'link',
    '#title' => $link_text,
    '#url' => $link['url'],
    '#options' => $link['localized_options'],
  );
}

```

In a theme, you could add a class in your own preprocess, something like this should do the trick:

```
function THEME_preprocess_menu_local_task(&$variables) {
  $variables['link']['#options']['attributes']['class'][] = 'my-extra-class';
}

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: how to render content type's fields in Custom Module Form
I'm new to Drupal 8 and I'm trying to create a form that allow to fetch my content types hierarchy and show its fields using ajax callback, but unfortunately none of the fields shows up eventhough the ajax works fine and callback function correctly fired? The Fields Types in my ContentType is {body:text\_with\_summary, price:decimal, title:string} As I Tried with debugging it seems that my code cannot define those types as form field types

here is my code in MyForm.php File:

```
public function level3SelectedCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $fields = MyController::contentTypeFields('MY_VOC');

    foreach ($fields as $field){
        $name = $field->id();
        $label = $field->label();
        $type = $field->getType();
        $desc = $field->getDescription();
        $form['fields_wrapper']['field_'.$label] = array(
            '#type' => $type,
            '#description' => $desc,
            //'#options' => '',
            '#attributes' => array(
                'class' => array(
                    'myField'
                ),
            ),
            );
        $ajax_response->addCommand(new HtmlCommand('#fields-wrapper', $form['fields_wrapper']['field_'.$label]));

    }

    $ajax_response->addCommand(new InvokeCommand('#fields-wrapper', 'change'));
    $form_state->setRebuild(True);

    return $ajax_response;
}

```

My Controller Function is:

```
static function contentTypeFieldsAsFields($contentType) {
    // Get the definitions
    $fields = array_filter(
            \Drupal::service('entity.manager')->getFieldDefinitions('node', $contentType), function ($field_definition) {
                return $field_definition instanceof \Drupal\field\Entity\FieldConfig;
            }
    );
    return $fields;
}

```

# Answer
> 1 votes
To get an empty form of a content type you would use code like this:

```
$node = \Drupal\node\Entity\Node::create(['type' => 'page']);
$form = \Drupal::service('entity.form_builder')->getForm($node);

```

To open this form with ajax, put the form in a controller:

```
public function contenttypeform(NodeTypeInterface $node_type) {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => $node_type->id(),
    ]);
    return $this->entityFormBuilder()->getForm($node);
  }

```

Configure a route for this controller and open the form in an ajax modal like this example from ConfigSync.php:

```
$links['view_diff'] = array(
            '#type' => 'link',
            'title' => $this->t('View differences'),
            'url' => Url::fromRoute($route_name, $route_options),
            'attributes' => array(
              'class' => array('use-ajax'),
              'data-dialog-type' => 'modal',
              'data-dialog-options' => json_encode(array(
                'width' => 700
              )),
            ),
          );

```

# Answer
> 1 votes
Thanks @4k4 for your great help but I've solved it how to use it in drupal 8 here is my FormBuild code but unfortunately not all fields shown just the title and there is the warning shown in console:

*Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. VM3435:19 \[CKEDITOR\] Error code: editor-incorrect-destroy. VM3435:19 \[CKEDITOR\] For more information about this error go to http://docs.ckeditor.com/#!/guide/dev\_errors-section-editor-incorrect-destroy*

and here is my Form Build Code:

```
$form['fields_wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'fields-wrapper', 'class' => ['hiddenselect']],
    ];

    if ($form_state->getValue('level1') != false) {
        $val = $form_state->getValue('level1');
        $this->fields = MY_Controller::contentTypeFieldsAsFields($val);
        $node = \Drupal\node\Entity\Node::create(['type' => $val]);
        $myform = \Drupal::service('entity.form_builder')->getForm($node);

        foreach ($this->fields as $field) {
            //$name = $field->id();
            $n = $field->getName();
            $form['fields_wrapper'][$n] = $myform[$n];
        }

```

and here is my ajax callback code:

```
public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    $val = $form_state->getValue('level1');

    foreach ($this->fields as $field) {
        $n = $field->getName();
        $ajax_response->addCommand(new HtmlCommand('#fields-wrapper', $form['fields_wrapper'][$n]));
    }
    $ajax_response->addCommand(new InvokeCommand('#fields-wrapper', 'change'));

    $form_state->setRebuild(True);

    return $ajax_response;
}

```

# Answer
> 0 votes
Use

```
\Drupal::entityManager()->getFieldDefinitions('entity_type','bundle');

```

It will give all fields related to content type.

`EntityFieldManagerInterface::getFieldDefinitions()`

---
Tags: entities, 8, taxonomy-terms, ajax
---


# Question
Title: How to set webform to show previous submissions to users?
I've got a webform I'm maintaining, and I'm not sure how to expose or suppress the "View Previous Submissions" link on a per=role basis. The previous submissions link is visible to the admin, but it's not visible to the user. I've looked at the role based permissions the webform settings but nothing looks obvious.

# Answer
> 1 votes
Be sure to confirm "Access own webform submissions" and "Edit own webform submissions" permission for the roles in question.

---
Tags: webforms, users
---


title: URL Aliases - Patterns Error

text:
# Question
Title: URL Aliases - Patterns Error
I'm getting a list of the following errors in my new drupal website. Any idea where this is coming from and what I need to do to fix it?

```
The Default path pattern (applies to all content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Applications (applies to all Applications content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Careers (applies to all Careers content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Events (applies to all Events content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Executive Team (applies to all Executive Team content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for News (applies to all News content types with blank patterns below) is using the following invalid tokens: [node:created:custom:Y], [node:created:custom:m], [node:created:custom:d], [node:title].
The Pattern for all Products paths is using the following invalid tokens: [node:title].
The Default path pattern for SlideShow (applies to all SlideShow content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Solutions (applies to all Solutions content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Test Type (applies to all Test Type content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Webform (applies to all Webform content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern (applies to all vocabularies with blank patterns below) is using the following invalid tokens: [term:vocabulary], [term:name].
The Pattern for user account page paths is using the following invalid tokens: [user:name].

```

# Answer
> 1 votes
Just in case other might encounter it and bump in this page. To recap on how we fixed this error. In @MG1 case, restore the database from live site and downgrading the php version on her local machine from 7.0.8 to 5.4.42 and upgrading the Drupal core module in latest version did fixed the problem all errors are gone.

We also encounter this one just in case other's encountered it.

> Fatal error: Call to undefined function form\_process\_autocomplete() in /Users/\***/Documents/Sites/Link-New/includes/form.inc on line 1850

this one help us out in trouble https://www.drupal.org/node/2610498

Note: This might be fix in other way but in MG1 case this solved the problem.

---
Tags: path-aliases, tokens
---


title: Video Filter module warning

text:
# Question
Title: Video Filter module warning
I have installed the video filter module on my site. I added the following to my video source field.

```
[video:https://www.youtube.com/watch?v=686A5yPMWrs]

```

When I view the node, I get the following warning:

> Warning: Illegal string offset 'id' in Drupal\video\_filter\Plugin\Filter\VideoFilter-\>process() (line 91 of modules/video\_filter/src/Plugin/Filter/VideoFilter.php).

Is this something to pursue and fix? Is it safe to just disable the warnings when I push the site live?

# Answer
> 1 votes
The Video Filter module is still in alpha so it's very likely this is a bug. You should consult the issue queue to see if it exists, and create a bug report if it doesn't exist.

As for the ignore and deploy/pursue and fix question, it depends on how fault tolerant you are. Certainly the project maintainers (and community) would appreciate the bug fix. Deploying early release code is risky, but if the functionality is little used and has no chance of catastrophic results (e.g. complex DB manipulation that could result in corruption.) then deploy/ignore can be a fine strategy (regardless, you should always have warnings turned off on production).

---
Tags: 8, input-formats
---


# Question
Title: Altering relationship in Views contextually
I need to alter a Views relationship contextually: since the View is embedded into another node, the relationship is defined by a field's value of a parent node.

I presume the only way to add a relationship is using hook\_views\_data\_alter, but I'm not quite sure if it's going to work inside a preprocessor function (I'm creating a View for a certain node type) and what's the proper way of using it. The related field will be a Nodequeue instance (Nodequeue module is integrated with Views using relationships), its name will be contained in that parent node's field.

Thanks in advance!

# Answer
I did eventually discover simple solution, so perhaps it comes in handy for anyone else later. views\_data\_alter, of course, is not meant to apply an existing relationship, but rather to create a new one. To apply an existing relationship programmatically - Nodequeque in my case - you need to call in add\_item function of view class:

```
$view->add_item($view->current_display, 'relationship', 'node', 'nodequeue_rel', array('names'=>array('myqueue'=>'myqueue'), 'required'=>1, 'limit'=>1))

```

where an array is a set of options like: the name(s) of queue(s) and whether any nodes excluded from chosen queque(s) should be added (1 - bool - implies that only nodes inside the chosen queque will be added).
> 0 votes

---
Tags: views, nodes
---


title: Manage Display Field Label not changing

text:
# Question
Title: Manage Display Field Label not changing
In Content Types-\>Manage Display-\>Label, there is the options of Above, Inline and Hidden, except no matter which one I choose, the page shows all field labels as Above. I have "clear Caches", restarted Apache, I even created a new content type to check if it was just the one content type.

What can make the field's label not show "inline"? Where and how to get it back to normal?

# Answer
Sounds to me there is a clashing between the Drupal orders to the CSS.

It is either a clashing with the CSS or a bug (I also experience bugs with manage display in Drupal 8 but different than the one you describe).

Anyway to check if this is CSS related, just replace the theme with another and check then.
> 0 votes

---
Tags: entities
---


# Question
Title: Keeping old site live while testing new site?
I'm helping my university department upgrade their Drupal website from 6 to 7 (university doesn't support 8 yet). So far, I've been able to install and test the new site on my local machine, but now it's time to move it to the actual host so that users (mainly the department secretary) can start to populate pages with content. Can I have a Drupal 7 site live on a subdomain like test.dept.university.edu while keeping the Drupal 6 version live on dept.university.edu?

Apologies if this is a naive question - I've read a lot about creating clones of existing sites for testing, but this assumes that one is upgrading within the same Drupal version.

# Answer
> 1 votes
In short, yes you can, but this has a little to do with drupal. To clone a Drupal site is nothing more than copying the drupal root directory (codebase) and taking a database dump. It's quite easy then to transfer all these on any other environment and with some `settings.php` tweaking you will have an up and running clone of your site. The hard part is to migrate from D6 to D7, but you have already done this as far as I understand.

I would propose you to setup a staging environment by using a clone created from your local environment and start adding/editing content there. It dosen't really matter under which hostname that (staging) will be, it may well be the `test.dept.university.edu` because you can make the production's url (`dept.university.edu`) to point back (redirect) to the staging machine when all things are in place and the time to go live has come.

This is a rough idea but I guess that the meaning is quite clear.

Let the mods to decide if this question should be close or not.

---
Tags: upgrading
---


# Question
Title: How can I log the flags users put, then auto unflag them?
I used this link to set up a UserPoints Store:

Drupal 7 - How to Set up a Simple UserPoints Store.

I need help finishing one thing:

* When user flags item
* some code starts working and logs the fact that this specific user just flagged this specific page(content)
* Once this information is logged somewhere.
* the page(content) that the user see's as \[Already Flagged\] needs to automatically unflag.
* So that user can flag it again if he/she wishes.

If you look in the link above it can be understood that flagging a item(page/content) deducts points from the UserPoints system. As soon as the user presses `flag this` they get the option to type in the quantity they would like to "purchase" or flag. I need this quantity logged too.

In short, this is an example of how it should log:

```
User | Time/Date | Quantity |  Page
-----+-----------+----------+--------
id2  | 8/18/2016 |     3    | /node/9
id7  | 2/13/2016 |     1    | /node/5
id4  | 4/28/2016 |     1    | /node/1

```

I hope it makes sense. It would make more sense if you take a look at the info in the link.

# Answer
> 1 votes
**The Log**

Userpoints transactions are automatically "logged" in that Views can display them with all required data. So if I understand the question correctly, flags is irrelevant here in terms of logging as you just want the userpoints transactions.

Create a "userpoints transactions" view.. Not "content" or "user".

1. Add a relationship for `Userpoints Transactions: User`
2. Add fields for
`(Users) User: Uid (Uid)`,
`Userpoints Transactions: Timestamp (Timestamp)`,
`Userpoints Transactions: Points (Points)` and
`Userpoints Transactions: Entity ID (Entity ID)` (according to your link, this should be the node id)
3. If you have more than one category of userpoints, you can add a filter for `Userpoints Transactions: Category`

**Automatic Unflag**

It sounds like in your link, *Business Rule 2: Unflag an item* is unneeded in your case? I'd just change this to a rule where the the flag is unflagged and then redirect to the node / page if needed. I'm not really sure what the requirements are here.

---
Tags: 7, views, users, rules, flags
---


# Question
Title: If field date is 15 days away from today, change another field value
OK, this is specific:

I have a content type with two fields:

1. First is a expiration date field (d-m-y format);
2. Second is a select list field: "green, red, yellow, empty"

WHAT I NEED:

When there is 15 days left for the expiration date of a specific node, the select list field from that node should automatically change to "yellow".

Is this possible using, for example, rules module? Is there any other option?

Thank you!

# Answer
> 3 votes
Hmm.. This sounds like it could be done with Rules and VBO.

1. Create a VBO view of nodes that match your date requirement using filter `date field > relative date`. You might also want to filter out nodes that have already been changed.
2. Create a rule:

* Event: Cron or maybe the Rules Once per Day module
    * Action: Load a list of entity IDs from a VBO view
    * Action: Loop list
    * Action: Change / Add field using `Set a data value` if it's a single value field or `Add item to list` if it's a multi-value field.

EDIT: As of November 2017, this feature whereby VBO supplies Rules has been a bit broken and requires a patch to work.

---
Tags: entities, rules
---


# Question
Title: Prod CentOS core-only site work fine but local Ubuntu backup has no css loaded
I made a backup of my prod CentOS site to local Ubuntu. The site is all core --- Both by means of templates or modules; No contribs whatsoever. No customizations.

Yet the **CSS won't load** for whatever theme.

These are the only errors in `drush ws --full`

```
 128377  file      File temporary://filedOb2TA could not be moved/copied because the destination directory public://js is not configured correctly.   notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128376  file      The file permissions could not be set on public://js.                                                                              error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128375  file      File temporary://fileEzTm0r could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128374  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128373  file      File temporary://fileBagPhj could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128372  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128371  file      File temporary://fileII1wDa could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128370  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128369  file      File temporary://fileYPV93p could not be moved/copied because the destination directory public://js is not configured correctly.   notice    http://localhost/benia/  127.0.0.1  19/Aug 22:06
 128368  file      The file permissions could not be set on public://js.

```

Trying to fix it, I made sure that under `admin/config/media/file-system` the tmp folder is `/tmp` and then created a directory named `tmp` folder in root and gave it 755. I also gave 755 to `sites/default/files`

* Tried 777 for both (including `sudo chmod 777 files/ -R`).
* Tried `sudo chgrp www-data files -R`

While reading on how to fix these in D.O but it wasn't quite clear from what I've read; Most solutions included patches and I don't think its valid for my case. Maybe a Linux expert could shed some light why it happens.

# Answer
Did you try the 777 recursively inside the files folder? (so it applies on `files/css` and `files/js` subfolders)

Also I would check if SELinux is enabled on your CentOS server to discard you downloaded an incomplete copy of your website due to lack of permissions. Use the `getenforce` command to check if it's set to permissive. In case of necessary you can use the following command to set the context of files folder to read/write:

```
chcon -R -t httpd_sys_rw_content_t files

```
> 1 votes

# Answer
A few thoughts:

1. Have you made sure that you have a /css and /js folder in your /sites/default/files directory?
2. Have you tried just deleting these folders and recreating them (I think you should be able to do this without any issues)?
3. Have you tried turning JS and CSS aggregation off in `/admin/config/development/performance` to see if that works?
4. Have you cleared your caches? You can go to `/admin/config/development/performance` or `/rebuild.php` to do that.
> 0 votes

---
Tags: 8, backups
---


# Question
Title: Adding javascript to admin view and user view
I have a form with a text plain long description field. Added Javascript to limit the amount of characters allowed in the field.

```
(function($){
    $("#edit-field-busines-0-value").attr('maxlength','500');
})(jQuery);

```

It works for the Authenticated users view, but not for the Admin users view? How can I have this work on the Admin view also?

# Answer
Is it possible that this library is being pulled in by your public theme, but not by your admin theme? Authenticated users probably are maybe not seeing the edit from in the context of your admin theme, like admins are. If so, add the library to your admin theme too (you can create a sub-theme of Seven and add it there).
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: Dificulties in modifying or duplicating a view
I'm using drupal 8 (it seems to me exact version is 8.1.8) as CMS. I created many views, and I would like to modify them o to duplicate those views. But, mainly after I set a contextual filter, is not possible to modify the view.

And I 'm experiencing troubles too in duplicate a view and then modify the parameters.

Is there any know issue about those difficulties?

# Answer
> 0 votes
Instead of creating multiple views, have you considered using additional displays from the base view instead? That way they can share common configuration, but you can do things like apply a contextual filter to just certain displays.

---
Tags: views, 8
---


# Question
Title: How do I get a user field from an entity reference?
I'm working with the Twilio module to create a Rule that will send out an SMS message when a user creates a specific piece of content. Here's how I've got things laid out at the moment.

1. I have a content type called Office (*field\_office*), which contains the regional office name (imported from LDAP, but that probably doesn't matter.)
2. I have an entity reference user profile field called *field\_user\_office* that links to the Office content type.
3. I created a content type called Blast Message with an entity reference field called *field\_office\_sms* which also links to the Office content type. When a user wants to create an SMS they create one of these nodes and select one or more offices to send to.

When I set up my rule I'm not seeing the fields exposed as I expected. I tried adding two Entity has field conditions, *Parameter: Entity: \[node\], Field: field\_office\_sms* and *Parameter: Entity: \[node\], Field: field\_mobile\_phone*, the last of which is the actual mobile number saved in the users' accounts.

How do I navigate from the original content (Blast Message) through the Offices, then to the specific Users who are linked to that office, and ultimately retrieve their mobile phone numbers?

# Answer
You need to use the action: Fetch entity by property.

1. Condition: Entity has field \> node: field\_office\_sms
2. Fetch entity by property \> User \> Property: field\_user\_office \> Value: node: field\_office\_sms:nid
3. Loop: List: \[entity-fetched\]
4. Action: Send SMS \> list-item: field\_mobile\_phone
> 0 votes

---
Tags: entities, rules
---


title: How to filter a view with another view?

text:
# Question
Title: How to filter a view with another view?
Let me explain my situation. I have in D7

1. 4 different taxonomy list. Each taxonomy list is connected to other data in the system
2. A content type cFoo
3. 2 different roles : contentmanager (CM) and user. hhahaha what else is new :-)

The CM is creating a entityque based on taxonomy terms which will result in let's say: tlist.

The user should select for an cFoo a term from tlist but if he used a term already in another cFoo he may not select it again.

I did testing and research but do not get the complete puzzle complete... I thought about the following solution for the user.

Build a webform with a selectbox with values of tlist. Contextual reference to this form will be cFoo.nid. Before loading this list in the webform it should already be filtered. Let say we have another view with terms already used named tListUsed. After the webform I will implement a rule to submit the selected term to the cFoo.

So now I have two views. tList, tListUsed. The basic question was: How to filter tList with view tListUsed?

**UPDATED QUESTION**
With the help of flags modules and views\_exclude\_previous modules i do not got this problem working. There is a approach on: https://www.youtube.com/watch?v=cQrw7Ydo1to which I now try to implement.

The strategy is now as follows: Load the list of tListused into a global var. Use this var as a contextual filter with multi values to exclude.

**On which hook should I execute the building of tListUsed. It cannot be in the view itself as it is a filter to the view.**

ps: question edited as setting up the tList for the CM is working and after trying some modules.

# Answer
For those who need to implement this as well. I solved this by the following code. However in this code $tid\_to\_remove is not a view but generated on the view itself.

```
function MODULENAME_views_post_execute(&$view){

  switch ($view->name){
  case "VIEW_MACHINE_NAAM";

    GLOBAL $user;

    // Go through the view and build a list of items which should be removed
    $data = $view->result;
    $tid_to_remove = array();
    foreach ($data as $row => $rowinfo) {
      if ($rowinfo->users_node_uid == $user->uid ){     // if the current row belongs to the current user
        $tid_to_remove[] = $rowinfo->tid;  // added to the array
      }
    }

    // Optimize the array to unique values
    $tid_to_remove = array_unique($tid_to_remove);

    // Go through the view again en remove all values which are stored in $tid_to_remove
    $data = $view->result;
    foreach ($data as $row => $rowinfo) {
      if (in_array($rowinfo->tid,$tid_to_remove)){
        unset ($data[$row]);
      }
    }

    // place the values back into the view
    $view->result = $data;

  break;
  }
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How to set defaults for a custom Views display?
I'm maintaining a module that provides a new type of Views display (extending the built-in `views_plugin_display_page`).

When the user chooses to add my type of display, I'd like to set up some sensible defaults, like creating a default url path, a default display\_title, and some defaults for the additional options my module defines in the display's `options_form`.

How do I set these defaults?

# Answer
The class `views_plugin_display_page` defines its options (and defaults) through the `views_plugin_display_page::option_definition()` method. This method is just a series overridden methods that extends from the view base class. In a similar manner, your custom plugin can override this method:

```
// defined in your views_plugin_display_page descendant class
function option_definition() {
  $options = parent::option_definition();

  // @TODO: set your own options plus override any other options
  // defined in parent classes. For example:
  // $options['path'] = array('default' => 'my-default-view-path');

  return $options;
}

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: How NOT to delete original account picture when uploading a new one?
When a user updates his account picture (default "picture" field,) his existing picture is deleted and replaced with the new uploaded picture. This is normally done by default.

How, using Rules (or any other way,) do I prevent the system from deleting the original stored picture so that the old and new picture reside in the same directory?

Thanks. :)

**Update:** Someone suggested making the field multiple value. I do not want users to be able to upload several account pictures. All I want is that a newly uploaded picture will indeed replace the old one but the old picture not to be deleted. Like I said in a comment below, the Heartbeat module takes a snapshot of the account picture. When users uploads a new picture, the old picture in the snapshot no longer displays (of course, it was deleted!) and a blank empty space is shown instead. Keeping the old picture would solve this issue.

# Answer
When a user adds a new pictures make a copy of this pictures with rules to a user specific directory. When a user wants to restore his picture browse this directory, let the user decide which picture he wants and copy it back with rules.
> 0 votes

---
Tags: 7, rules
---


title: Can't login after migration

text:
# Question
Title: Can't login after migration
I moved my website from my computer to another one, I moved drupal folder and the database with `backup & migrate`, I used to do it every day and now on the first call, The website worked, but after login with admin, I can't acces the website. I tried changing `$cookie_domain`, but it was already commented, also `rewrite_module` is enabled on apache, I'm workin on localhost. help me guys, thank you

# Answer
Use drush upwd to reset your password

`drush upwd --password="givememypasswordback" "admin"`

If you don't have drush installed do it via MySQL. Here is a related article.
> 0 votes

---
Tags: users
---


# Question
Title: How to update some field of all article nodes programatically and set it equal to its title?
I have a field name 'field\_new' in a content type 'article'. I want to insert the value of node title on this field (all the nodes) programatically.

What I have done to achieve, I am using hook\_node\_update for this, but it is not updating the field values.

```
function modulename_node_update($node) {
  $new_value = $node->title;
  $node->field_new[LANGUAGE_NONE][0]['value'] = $new_value;
  field_attach_update('node', $node);
}

```

It would be great if there are another alternatives to do this.

# Answer
hook\_node\_update \- Respond to updates to a node. This is useful when you wants to update a field during node save. This will not helpful in this case because you wants to update all your exiting nodes.

1.Hope this code will helps you. You will get an idea but this is not the exact code for copy and paste.

```
<?php
    // Get all nodes of 'article' type, populate the field with a value of '1'.
    $articles = db_query("SELECT nid, vid FROM {node} WHERE type = 'article'")->fetchAllAssoc('nid');
    foreach ($articles as $nid => $values) {
      $fields = array(
        'entity_type' => 'node',
        'bundle' => 'article',
        'deleted' => 0,
        'entity_id' => $values->nid,
        'revision_id' => $values->vid,
        'language' => LANGUAGE_NONE,
        'delta' => 0,
        'field_data_field_new' => 'title need to fetch',
      );
      db_insert('field_data_field_new') //data table name
        ->fields($fields)
        ->execute();
      db_insert('field_revision_field_data_field_new') //revision table name
        ->fields($fields)
        ->execute();
    }
    ?>

```
2. Another suggestion is Views Bulk Operations (VBO). You need investigate on it. Bulk field update?
3. Updating a single field value for a particular content type:

```
 $article_nodes = node_load_multiple(array(), array('type' => 'article'));
    foreach ($article_nodes as $article_node) {
          $article_node->field_new[LANGUAGE_NONE][0]['value'] = 'title value';
          field_attach_update('node', $article_node);
        }

```
> 5 votes

# Answer
As per the "*It would be great if there are another alternatives to do this*" in your question: yes there are alternatives, using Rules and Views Bulk Operations and without writing custom code, as further detailed below ...

# Step 1: Create a Rules Component

Have a look at this example of a **Rules Component** (in Rules export format):

```
{ "rules_set_an_initial_value_for_some_field" : {
    "LABEL" : "Set an initial value for some field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_new" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "[node:title]" } }
    ]
  }
}

```

Some more details to further explain the above above example:

* This Rules Component will be used in "Step 2" below.
* It assumes a field with machine name `field_new` and content type is `article`.
* It sets the value of that `field_new` field equal to the node title.

Note that I also added the Rules Condition `Entity has field` to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

If you want, just grab (copy) the exported rule above, change all occurences of the machine name of that field to match the machine name of your field. After doing so you can simply import this Rules Component in your own environment (if you have Rules UI enabed).

After you imported this Rules Component, navigate to `admin/config/workflow/rules/components` in your own site. Then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Node identifier*** and hit the ***`Execute`*** button. Depending on the node id you selected (i.e. if it has that field, and if the Rules Condition is satisfied), your node will be updated accordingly.

After you're confident your Rules Component works perfect for all variations of your nodes, move on to step 2 below.

# Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of **all your nodes** to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

**Attention**: to process lots (thousands?) of nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

# Video tutorials

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

Happy VBO-ing while Rules-ing!
> 4 votes

---
Tags: 7, entities
---


# Question
Title: No class for images when working with a specific theme (no .field--name-field-)
I have installed a new theme and when I go to DOM I can't see classes for the image fields; These are available for styling the page's image fields.

For example, if I write in the css file: `.field--name-field-bestimageever img {display: none;}` the image keep appearing.

This never happened to me with any other theme and I would thank an experienced themer for giving an explanation on how to add this, from which many other people could enjoy.

# Answer
> 0 votes
The most likely scenario is that the theme does not implement those field classes. Not all themes implement classes the same, but rather take a *bottom up* approach - the theme starts off very "clean" with only enough classes to support core behaviours etc, leaving it to the themer to add more classes as required. An example of this is the Stable base theme.

---
Tags: media
---


# Question
Title: How do i ajaxify /Use ajax on Side bar custom menues so that links are loaded to my content div without refreshing page
I have a vertical menu on My site ,I want to use ajax to load the Menu link into the content so the page doesnt have to reload,Please how can i go about it ,I tried the ajaxify module it doesnt seem to work properly.

# Answer
> 0 votes
You can use `ajax_pages` module.

> **Features**
>
> * Works inobtrusively out of the box
> * Requires only minimal theme modifications
> * Browser address bar updating using HTML5's history.pushState()
> * Full page reloading (page\_top, page and page\_bottom regions)
> * Transparently ajaxifies forms, including GET ones Handles redirects
> * Loads additional CSS and JS files as required
> * JS/CSS preprocessors and aggregation friendly
> * Ajax requests are GET and fully cacheable (also with Boost!)

# Answer
> 0 votes
TO add ajax reload feature to a side bars;Menu Bars
\*Download Jquery Ajax\_load Module
\*Install it from your module page
\*Click the configuration button just to the right of the module after installing (Within the module page)
\*Enter the target,Ajax call back
\*Go to content type ,and choose the content type basic page,click manage display
\*Choose jquery display
\*Configure to your taste(I set the content to default so that the content can be visible while using the ajax feature)
Thats all Test your link

---
Tags: 7, javascript, ajax
---


# Question
Title: How to show first X items and add and ellipsis [...] if there is more items?
I have a View that displays books and authors of each book.

## BOOK 1

* Author 1, Author 2, Author 3, Author 4, Author 5

## BOOK 2

* Author 6, Author 7

What I want to do is to show only first 3 authors of each book and add an ellipsis \[**...**\] **if there is more authors**. It's easy to display first 3 items (Multiple Field Settings) but how to add an ellipsis to it?

---

## BOOK 1

* Author 1, Author 2, Author 3 **...**

## BOOK 2

* Author 6, Author 7

How can I do that?

# Answer
After thinking a lot, I found an "**easy**" way to do it :)

In my views,

* I added the **author** field as normal.
* I enabled the `Exclude from display` option.

* In **MULTIPLE FIELD SETTINGS**, I set it to display only 1 value, starting from 0.

Then I added the author field again, for 3 times with the settings above.

For each, I changed the **Multiple Field Settings** as below:

* 2. author: display 1 value, starting from 1.
* 3. author: display 1 value, starting from 2.
* 4. author: display 1 value, starting from 3.

For the 2. and 3. authors I enabled the `Rewrite the output of this field` option and this is the rewrite text for author 2: `, [field_author_1]` and this is for author 3: `, [field_author_2]`.

I also enabled the `Rewrite the output of this field` for the 4. author and this is the rewrite text: `...`

As a final step I added a `Global: Custom text` to views and this the text:

```
[field_author][field_author_1][field_author_2][field_author_3]

```

**It's done!**

* If there is only one author it displays **Author 1**
* If there is two authors it displays as: **Author 1, Author 2**

*(remember the rewrite:`, [field_author_1]`).*

* If there is three authors it displays as: **Author 1, Author 2, Author 3**
* And if there is more than three authors it displays as: **Author 1, Author 2, Author 3 ...**

*(remember the rewrite for author 4:`...`)*
> 2 votes

# Answer
I have not tested this, so consider this an educated guess:

Go to `/sites/all/themes/yourtheme/` folder and in **template.php** add the following code:

```
function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    if (isset($vars['fields']['field_example'][3]->raw)){
      $vars['fields']['field_example']->content = $vars['fields']['field_example'][0]->raw . ', ' . $vars['fields']['field_example'][1]->raw . ', ' . $vars['fields']['field_example'][2]->raw . '...';
    }
    else {
      $vars['fields']['field_example']->content = $vars['fields']['field_example']->content;
    }
  }

```
* replace **yourtheme** with the actual name of your theme
* replace **view\_name** with the name of your view.
* replace **block\_1** with the machine name of your view.
* replace **example** with the name of your field.
> 2 votes

# Answer
Even though those authors are probably not a term reference, you may want to try an approach similar to what is suggested in post installation issue "Trimming a Views Term reference field", using a combination of "***Multiple field settings***" and "***Rewrite results***" Here is a quote from it:

> Select the field in the list, it will be in the form "Content: Tags", where tags is the field name (do no use )
>
> With Formatter set to "Plain text" (if you do not see formatter, skip this) and "Link this field" unchecked
>
> We are going to use a combination of "Multiple field settings" and "Rewrite results"
>
> Set "Multiple field settings" so it only display some terms, I am going to limit to 4 (we will call this max terms). I also have the separator set to ", "
>
> Now under "Rewrite results" check "Trim this field to a maximum length", I also unchecked "Trim only on a word boundary" and "Add an ellipsis". Pick a value for maximum length, note this is per tag. Lets pick 3.
>
> So total length = (max terms) * (maximum length + length of separator)
>
> In this example this becomes (4) * ( 3 + 2 ) \[separator is a comma and space\] for a total of twelve.
>
> If you add ellipsis's the calculation becomes total length = (max terms) * (maximum length + length of separator + length of ellipsis)

Note the ***Multiple field settings*** (as in your question) in the above suggestion ...
> 0 votes

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


# Question
Title: How can I avoid the feed link is printed in my theme?
My current theme displays a *Subscribe to* link that is output from the core/themes/stable/templates/misc/feed-icon.html.twig template. I don't want to display it in my theme. Whatever I try, I can't find which template or which string prints this link.

How can I avoid the link is printed?

# Answer
> 3 votes
If this is a view, you can hide the feed icon using this method.

> Go to Structure \> Views \> Frontpage \> Edit. Then click on "Feed" at the top. In the second drop-down box, select "Disable Feed." Then "Save" the change.

# Answer
> 1 votes
You can use **hook\_preprocess** with code:

```
function YOUR_THEME_preprocess_views_view(&$vars) {
  $vars['feed_icons'] = FALSE;
}

```

See views-view.html.twig for more detail.

---
Tags: views, theming, 8, feeds, navigation
---


# Question
Title: Hide language flag on this language page?
I have 2 languages on my Drupal 8 site and use Language Icons module for them:

* Latin and
* Celtic

I think it is not convenient to have both flags on each version. But D8 does not add language code class in body and I cannot hide flag.

Please where is solution?

# Answer
if you want add class language to body. You can use **hook\_preprocess\_html** with code:

```
function Your_Theme_preprocess_html(&$vars){
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['attributes']['class'][] = $language;
}

```

class current language will add to body.
> 1 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: field_get_items gives me an array of node IDs. Can I filter these by type without using node_load()?
I have an entity reference user field for more than one content type. I need to filter the node IDs by content type without using `node_load()`. Is it possible?

If not, how badly would it affect performance to send the user ID to a view and filter them there?

# Answer
> 0 votes
Unless you have a map of those ids -\> types somewhere outside the DB to reference, no, it's not possible. You could go directly into the node table yourself, of course, and avoid node\_load specifically, but there's no way to do it without a db hit.

It's impossible to say how performant a View would be without knowing how your site is built, server specs, traffic info, and so on. The best thing to do would be to try it and benchmark.

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


# Question
Title: How to keep class object during form process
If I have an object (e.g. student object - this is my own custom class)

I would like to initiate this object during 'student registration' form initialization (or form build) and keep the object until I finish with the form (form submitted).

Is there any placeholder for me to hold this object in the FormBase class? Where I should declare my class? And how to keep the object?

Example in my code:

```
<?PHP

namespace bla;

use bla
use bla
use bla

class myCreateForm extends FormBase {

  private $student; // i want to initiate this (new student()) and keep until form submit
  /* where i should declare this? and how to keep it? */

  /**
   * Class constructor.
   */
  public function __construct($param) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'id_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    //a lot of code here code here
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    //a lot of code here code here
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $output = $this->student->save(); // at the end, i would like to have my own save process which my class will handle it.
    drupal_set_message($output);
  }

}

```

# Answer
> 2 votes
No, if this is a value object then a service not the answer.

I would recommend you look at entities. Drupal will do a ton of work for you if you use (content) entities for your value objects.

See https://www.drupal.org/node/2192175 for example for documentation, also check out the entity module for additional functionality that is not yet in Drupal core.

With content entities, there is a standard EntityForm class that contains an entity and allows you to save it.

That said, what you are doing basically works, $this-\>student will be available, but be aware that on the first form submission, formBuild() is called again, so it will build another object. The same for entities. If you really want to prevent that, you need to store your object in the database, e.g. with the tempstore API.

---
Tags: forms, 8
---


# Question
Title: How does Drush figure out modules that have updates?
How does Drush get information about installed and disabled modules and updates for them?

I'm facing issues since drush is trying to update modules that AREN'T in the modules directory nor in the system table anymore.

I had to remove them since they were causing problems. But in the end I got nothing but more problems.

How could I get drush to understand these do not exist anymore and do not need to be a)checked and b)especially not updated.

I've tried drush rr to "make it clear" but it keeps trying these causing errors that crash all other updates etc.

Update:

These the modules. Simplenews \[simplenews-7.x-1.1\], Simplenews Bounced Mail Handler \[Simplenews\_BMH-7.x-2.x-dev\], Simplenews Statistics \[simplenews\_statistics-7.x-1.0-alpha1\]

**I can confirm that I can remove the simplenews rows from system table but they come back as soon as I run: drush rr OR drush pm-list --pipe --type=module --status=disabled--no-core**

# Answer
Use `pm-uninstall` to completely remove a module from your system.

If you have already deleted the code for the modules in question, the safest and best thing to do is put the code back and run pm-uninstall. If you just want to get rid of the reference to the module in the system table, you could take matters into your own hands, and just do this: `drush sqlq "delete from system where name in ('moduleone', 'moduletwo');"` If you do that, though, then the module won't have a chance to remove any other unneeded assets that would be deleted if you used pm-uninstall.
> 0 votes

---
Tags: drush, debugging, updating
---


# Question
Title: How to translate contact message field labels
I have multiple contact forms in my multilingual D8 website:

* questions or remarks
* order gift voucher

Those have custom fields (like field\_phone, field\_amount, ...)

For my custom fields, the form-element-label.html.twig with label is a string, whilst the core "message" field is a TranslatableMarkup object.

**How do I provide the translation for field labels of these forms?**

# Answer
> 4 votes
Standard fields of a contact form are predefined in code. Custom fields are in configuration and the translation works differently.

This should work:

1. Enable the module "Configuration translation"
2. /admin/structure/contact/manage/feedback/fields
3. Add field
4. Enter an english label
5. Configure the field type
6. Choose Tab "Translate contact message fields"
7. Add a translation in another language
8. Enter a translated label

# Answer
> 1 votes
**A possible (temporary) sollution:**

In theme\_form\_contact\_message\_form\_alter I've put an array with all the fields that need translation. Based on those fields I change the "#title" variables if the "#title" variable is a string. A TranslatableMarkup "#title" doesn't need another translation:

```
function theme_form_contact_message_form_alter(&$form,

  \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Change items

  $title_items = array(
    'subject',
    'message',
    'name',
    'mail',
    'field_amount' ,
    'field_phone',
    'field_receiver',
  );

  foreach ($title_items as $form_item) {
    if(isset($form[$form_item])) {
      $item = $form[$form_item];
      if($item['#type'] == 'container') {
        if(isset($form[$form_item]['widget'][0]['value']['#title'])) {
          if(is_string($form[$form_item]['widget'][0]['value']['#title'])) {
            $form[$form_item]['widget'][0]['value']['#title'] = $form[$form_item]['widget']['#title'] = t($form[$form_item]['widget'][0]['value']['#title']);
          }
        }
      } elseif ($form[$form_item]['#type'] != 'item') {
        // Make sure the item is not a pre-filled element.
        if(isset($item['#title']) && is_string($item['#title'])) {
          if(is_string($item['#title'])) {
            $form[$form_item]['#title'] = t($form[$form_item]['#title']);
          }
        }
      }
    }
  }
}

```

---
Tags: 8, forms, emails
---


# Question
Title: How to edit the label color for published or not published in Admin?
I tried to change the color of the text under the "Published" column of the node content listing.

I need the published text to be in green color and the unpublished text to be in red color.

In the view I have edited the output of the following field:

**Administration: Nodes (Content)**

**Configure field: Content: Published**

Rewrite Output :

`<span class="label label-success">[status]</span>`

Please check the screen shot for a better understanding.

# Answer
> 0 votes
There are some ways to do that, one may be the implementation of the following preprocess function: hook\_preprocess\_views\_view\_table. Here is a code sample:

```
/**
 * Implements hook_preprocess_views_view_table.
 */
function my_module_preprocess_views_view_table(&$vars) {
  $view = $vars['view'];
  $results = $vars['result'];
  if ($view->name == 'my_view_administration_nodes' ) {
    foreach ($results as $row => $result) {
      $vars['field_classes']['status'][$row] .= $result->node_status ? ' published' : ' not-published';
    }
  }
}

```

---
Tags: views
---


title: Node not showing

text:
# Question
Title: Node not showing
Hi all I am facing problem with bootstrap theme I am unable to show node when I edit the node.all data shows node/edit path but not in node

> I don,t know what is this issue problem with bootstrap them I am using sub theme and make my custom template but same problem with parent theme please give me suggestion for this thanks in advance

# Answer
> 0 votes
it happened to me before , first check the themes setting and make sure you edit nodes in your default admin theme , then check you have no errors in your bootstrap templates , if it still displays a blank screen while you try to edit try deactivating bootstrap theme

---
Tags: 7, theming
---


# Question
Title: How to get the field settings values in filed constraint validator
I have created custom type field with custom field settings, attached custom constraint successfully called its validator.

The question how to get the field settings values in the validate function, below code sample may explain

```
/**
 * Validates the CustomCheckConstraint.
*/
class CustomCheckConstraintValidator extends ConstraintValidator {
 protected $context;
 public function validate($data, Constraint $constraint) {
   //$data parameter holds the field value
   //how could I get the field settings here and validate the value based on
}
}

//attached constraint here
public static function    propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
  ->setLabel(t('type'))
  ->addConstraint('CustomCheck')
  ->setRequired(TRUE);
return $properties;

```

}

> Edit: After berdir answer

now the **$data** variable is an object holds the whole filedType object value and settings.

The problem is I couldn't get the field settings from getSettings() function returns

> Error: Call to protected method

The same error occurs when I tried to send field settings value from **propertyDefinitions** function

# Answer
> 4 votes
If they are field storage settings, then you could pass them along as arguments to the constraint.

If not, then add the constraint on the field type, not on the property. You can do that directly in the annotation, see \Drupal\file\Plugin\Field\FieldType\FileItem as an exampe. Then you get the whole field item in your validator and you can access the values and the definition/settings.

---
Tags: entities, 8
---


# Question
Title: How to put google analytics script PHP to my sites?
I apply a Google analytics service. I got a code.

```
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'MY UA CODE', 'auto');
  ga('send', 'pageview');
</script>

```

My drupal use AT Commerce this theme. Where do I put this code to my folder's file? There is an optional method. The php is here where I want to add to my block and let it call the above script.

\<?php include\_once("analyticstracking.php") ?\>

Do I follow the same name analyticstracking.php or just add the above script to an existed php file? Thanks.

# Answer
You can install module Google Analytics. Or paste script to file html.tpl.php.
> 1 votes

---
Tags: google-analytics
---


# Question
Title: How do I wrap a view row inside a <div>?
I have bad-designed a view, and the result is that I have the following scheme:

* Field 1: Category (taxonomy)
* Field 2: Node title
* Field 3: Image
* Field 4: Other data (PHP processed).

The problem is that I need field 1 to appear just once for a group of nodes and not always. As I had to redo all the View, I have made the following process, please tell me if there is a better solution.

Instead of not displaying field 1, grouping by that, etc., as I have some PHP process on it, I do the following:

In views-view-fields.tpl.php I identify the category, and prepend *\[\[BEGIN\]\]*. I identify the last field and append *\[\[END\]\]*.

In views-view-unformated.tpl.php I replace \[\[BEGIN\]\] and \[\[END\]\] with `<div>` wrappers; depending on the valued inside (`preg_match`), I make the category title appear just once at the beginning of the list of products.

Please tell me if that is a valid approach (it works) or it should be more desirable to re-draw the view (hours of changing fields, logic, etc.).

The string replacement outputs an additional `<div>` which wraps all the complete row of fields. This I had in the view as the field 1 was just another field and did not encapsulate anything. Maybe even if I would set it as grouping field it didn't encapsulate anything. The result I want (and get) is:

```
<div class="other-class" id="category-119"> divs and HTML stuff from the view  </div>

```

The only easy and fast way of doing a `<div>` encapsulation of the row is using those delimiters in the template files.

# Answer
1. Add field and `Exclude from Display`.
2. Add `Global: Text area` in the **header**.
3. Check `Use replacement tokens from the first row`
4. Enter the row pattern
5. Use css to make it look part of the first row

That will output the first row's field in the header.
> 1 votes

---
Tags: views
---