# Question
Title: Is there a way for Forena to restrict the debugging messages to selected roles?
The Forena data source has the option of displaying the generated queries on the screen via the `Debug` option.

The problem here is that the messages are displayed for all users or reports while this debug option is enabled, which is undesirable as it means a developer cannot be designing new queries during normal working hours.

Is there a way to restrict the debug messages to select roles only?

# Answer
> 1 votes
# 1. About the debug option

The `debug` option for a Forena data source is one of the options you enter when defining a data source. If enabled (value = `TRUE`), it'll actually trigger logic as shown in this logic:

```
  public static function debug($short_message='', $log='') {
    if ($log) {
      watchdog('forena debug', $log, NULL);
    }
    if ($short_message) {
      drupal_set_message(check_markup($short_message));
    }
  }

```

# 2. Restrict debugging messages to selected roles.

Defining the options for a data source (such as the `debug` option) can be done as described in the tutorial that comes with Forena (i.e. within the Data Sources Settings):

* Defined using Forena's configuration data tab (within the admin UI).
* Defined within settings.php files which allows for including PHP logic.
* Defined by a module using a forena\_alter\_repos hook.

So the actual answer to your question depends on how you define the data source, as further detailed below.

### a) Using Forena's configuration data tab (within the admin UI).

Using this option there is no way to answer your question, except if you would want to hack the logic shown above (which I do not recommend).

However by using the Disable Messages module you should be able to restrict the debug messages to select roles only (though it'd still write the watchdog messages). Refer to "Option 1" in my answer to "How to show messages starting with "Debug : " to an administrator only?" for more details on that (not sure if "Option 2" of that answer would make sense in this case also).

### b) Using a settings.php file

Include the desired PHP logic to assign a value (`TRUE` or `FALSE`) to `$conf['debug']`. Have a look at the `repos/sample/settings.php` file that comes with Forena for an example to start from.

### c) Using a custom module

Using hook `forena_alter_repos` (documented within Available Hooks in the Development Guide).

# 3. Alternative solution

From your question, it seems that your developer is designing new queries (during normal business hours) in your production environment ... There must be good reasons to do (allow) that.

However, as an alternative, you could also define an additional data source that points to the same database, and for which you enable the `debug` option. If you combine this with "***Access \[data source\] Data***" (as described in Forena's Permissions) you could easily limit access to this data source to developers only. And after the data blocks (SQL queries) that they created are finish (approved), just MOVE the file containing that SQL query to the regular data source.

Disclosure: I'm a co-maintainer of Forena.

---
Tags: 7, users, forena
---


title: Migrate : user update resets user roles

text:
# Question
Title: Migrate : user update resets user roles
Using the Migrate module, I created an import task that creates and updates user info from a csv file. The update is launched using drush.

```
drush -l http://localhost.atrium.com mi Utilisateur --update

```

All the users are updated appropriately but the user roles, which are not in the migration mapping, are reset for every user that's updated.

How can I avoid that and keep the user roles for every account that's updated ?

Thanks !

# Answer
We added these lines after line 162 in the user.inc file to not reset the user roles ...

```
    //and keep the roles too
    $old_account = user_load($account->uid, TRUE);
    $account->role_names = $old_account->roles;

```
> -1 votes

# Answer
You can add fields to be explicitly ignored by adding `addUnmigratedDestinations` to your class:

```
$this->addUnmigratedDestinations(array(
  'roles',
  'role_names',
));

```
> 0 votes

# Answer
I experienced the same problem today. I import users from a csv file. Roles have been set manually on the imported users and were removed on second migrate import with --update flag.

I searched for a solution that does not need to hack the migration files and my solution, that works for me, is the following.

I set "roles" to map my Source CSV "roles" column, which is not in the csv file itself and add that field in the prepareRow function of the migration.

```
public function prepareRow($current_row) {
// Always start your prepareRow implementation with this clause. You need to
// be sure your parent classes have their chance at the row, and that if
// they return FALSE (indicating the row should be skipped) you pass that
// on.
if (parent::prepareRow($current_row) === FALSE) {
  return FALSE;
}

// We need to preserve the users roles, if this is a user, that has been
// imported before.
$current_row->roles = array();
if (!empty($current_row->migrate_map_destid1)) {
  $account = user_load($current_row->migrate_map_destid1, TRUE);
  if (!empty($account->roles)) {
    $current_row->roles = array_keys($account->roles);
  }
}

return TRUE;

```

}
> 0 votes

---
Tags: migrations, users
---


# Question
Title: How to let users mark ( like) other users?
In my project I'd like to let users to mark (kinda like) other users.

What solution should I use? Appreciate any feedback.

# Answer
You can use Flag module. It does have integration with Views module. So you can configure and customize.

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
>
> Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
>
> In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.
> 2 votes

# Answer
Using the Flag module as suggested in the previous answer is indeed the typical solution to answer this question. If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

However, often times, depending on your specific case, some of the Flag related modules are usefull also, such as (partial list):

* Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
* Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.
* Flag Lists, to allow users to create custom lists.
* Flag Weights, to add weights to Flags (to be used for sorting).
* DraggableViews, to make Views draggable (so that they can be rearranged by Drag'n'Drop.).
* Flag Friend, a pre-built flag for marking other users as friends (using the Flag module).
* Flag Abuse, a pre-built flag for marking offensive content, with some extra administrative features.
* Flag, Hide & Mute, for users to hide individual nodes, such as site-wide announcements or advertisements, and/or to suppress all posts by users they do not want to see.
* Flag Files, to flag media files.
* Flag Service, to allow Flag to be accessed via a web services interface through the Services module.
* DLike, provides a Facebook like "Like" functionality using the Flag and Lightbox2 module.
* Conditional Flags, provides an extra API to Flag module, for custom conditions between flags.
* Organic Groups Flag Integration, extends the flag module with organic groups support allowing the administrators of each group to override the global flag settings for their group.
* Context Flag, allows the use of Flags as conditional triggers for use with the Context module.

Refer to its community documentation for way more details.
> 2 votes

---
Tags: users
---


# Question
Title: How do i get views field labels in the template file
I am creating a view, and displaying view by using custom template files. As per theme suggestions I named the template file for fields as `views-view-fields--blog-display--page.tpl`. In this file I want to display labels for the view fields which i have given while adding fields. I tried using

```
<?php print $fields['label']->content; ?>

```

But not able to get the label. What am I doing wrong?

# Answer
As far as I see in the documentation for views-view-fields.tpl.php (I did not test it myself), the syntax seems to be something like the following:

```
<?php print $fields['myfield']->label; ?>

```

(you can also use `$fields['myfield']->label_html`)
> 0 votes

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


# Question
Title: How do I set start date with the core date field?
I need set the start date (e.g. *now +1*) for my date field. How can I do this on Drupal 8.1.x?

# Answer
> 3 votes
When you create your field, you have the option of setting a default value. Set the **Default Value** to **Relative Date** and then ender "+1 day" into the textfield, and proceed with setting up the field.

When you create new entities with that field, it will default to the current time +1 day, which you can then change if needed.

# Answer
> 1 votes
The core date field doesn't support a start and end date, it's a single value field. See this discussion for the nitty-gritty for when the field was originally added, and the current issue about adding end-date support.

Date 'range' fields, with the option for a start/end date, are supported by the contributed Date module. Though the D8 version is still in dev so YMMV.

---
Tags: 8, datetime
---


title: db_select order by custom field value

text:
# Question
Title: db_select order by custom field value
I need to get all nodes of some content type and order them by integer field of this content type.

```
$nodes = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->join('content_type_field_name', 'p', 'p.entity_id = n.nid')
    ->condition('n.type', 'content_type_name')
    ->orderBy('p.content_type_field_name', 'DESC')
    ->execute()
    ->fetchAll();

```

But it does not work.

What should I do?

# Answer
> 4 votes
It seems you are using wrong Table name and wrong Field name also. Your query should look like something below:

```
$query = db_select('node', 'n');

$query->join('YOUR_TABLE_NAME', 'p', 'p.entity_id = n.nid');

$query
  ->fields('n', array('nid'))
  ->condition('n.type', 'content_type_name')
  ->condition('n.status', '1')
  ->orderBy('p.YOUR_CUSTOM_FIELD_NAME', 'DESC');

$results = $query->execute()->fetchAll();

```

---
Tags: nodes, database
---


# Question
Title: How to allow node authors to mark the best comment and to promote this comment on the top of list
In my project comments are prices so its important that commenters see author's choice. I want to allow authors to choose the best comment that would get this comment promoted on the top of a comments list. Can I do it with Rules or some other ways?

# Answer
> 0 votes
As discussed in the comments above, you can create a global Flag, say *Best price*, for comments. In order to reorder the comments, you can create a comment View which displays all comments of a certain node with the flagged ones on top. Afterwards, display the associated block on the node's page.

Maybe there is an easier way to reorder the comments, but this should at least work and illustrate the strength of the Views module. Underneath is my exported View, which you can easily import and adapt to your needs if necessary:

```
$view = new view();
$view->name = 'reordered_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'Reordered comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access comments';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Relationship: Flags: best_price */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'comment';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'best_price';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['label'] = '';
$handler->display->display_options['fields']['comment_body']['element_label_colon'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Flags: Flagged */
$handler->display->display_options['sorts']['flagged']['id'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['table'] = 'flagging';
$handler->display->display_options['sorts']['flagged']['field'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['sorts']['flagged']['order'] = 'DESC';
/* Contextual filter: Comment: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'comment';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');

```

---
Tags: rules, comments
---


# Question
Title: setcookie doesn't work in submit function nor tpl.php
I just copy and pasted set cookie sample code(http://www.w3schools.com/php/php\_cookies.asp) to my module and tpl.php

In my module, I put the setcookie in my submit function as below:

```
function custom_request_price_form_submit($form,&$form_state){
   $cookie_name = "user";
   $cookie_value = "John Doe";
   setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

   if(!isset($_COOKIE[$cookie_name])) {
       drupal_set_message("Cookie named '" . $cookie_name . "' is not set!");
   } else {
       drupal_set_message("Cookie '" . $cookie_name . "' is set!<br>");
       drupal_set_message("Value is: " . $_COOKIE[$cookie_name]);
   }
}

```

Im my node--XXX.tpl.php, I just copy the code without modification as below:

```
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}

```

However, no matter how I refresh the webpage, the message always shows "Cookie named 'user' is not set!"

I also tried user\_cookie\_save function, but no luck. Does anyone know why my cookie setting doesn't work?

# Answer
Thank you everyone, I got the answer. It seems Drupal supports session instead of cookie.(Sorry I cannot find the reference again.) Therefore, I used session to implement my function.

Here are some reference:

Example for session: https://www.drupal.org/node/360542

How to set session expiration: https://www.drupalgardens.com/documentation/cookie/expire
> 0 votes

---
Tags: 7, cookies
---


title: How to map views url to blog url

text:
# Question
Title: How to map views url to blog url
In my site I am using blogs module. When I used `sitename/blog` default blog page will display. But my requirement is, I have created a view to display the blogs, this is on the path of `sitename/blog-display`. I want to display this view when i type the url `sitename/blog`. please suggest me how can I solve this. Thanks in advance for any suggestions.

# Answer
Create a custom module with this code:

```
<?php

function MYMODULE_menu_alter(&$items)
{
  $items['blog']['page callback'] = "MYMODULE_blog_replace";
  $items['blog']['file'] = "MYMODULE.module";
  $items['blog']['module'] = "MYMODULE";
}

function MYMODULE_blog_replace()
{
  return views_embed_view('VIEWMACHINENAME', 'default');
}

```
> 0 votes

---
Tags: 7, views, theming, uri, nodes
---


title: Migrating a changed view

text:
# Question
Title: Migrating a changed view
I've created a view that I then turned into a 'Feature.' I then successfully added this feature to a second site by copying the module files from the first site into the module folder of the second. Only the first-site has the D8 Features Module.

Then on the first site I changed the Title of the View and went through the process of detecting the change and regenerating the Feature:

1. Edit the view with the new title
2. Go to the Features Config page where the state of the feature shows "Changed"
3. Import the code back into the database (i.e. 'revert')
4. Re-re-edit the view title
5. Export the view as a feature

Now I want to import the changes of the first-site Feature into second-site Feature.

1. Uninstall the imported/copied module from second-site
2. Replace module folder of second site w/ new module from first-site
3. Re-install the module

I then receive a long error:

> Unable to install My Image Gallery, core.base\_field\_override.node.my\_image.promote, core.entity\_form\_display.node.my\_image.default, core.entity\_view\_display.node.my\_image.default, core.entity\_view\_display.node.my\_image.teaser, field.field.node.my\_image.body, field.field.node.my\_image.field\_my\_image\_field, field.storage.node.field\_my\_image\_field, node.type.my\_image already exist in active configuration.

Obviously there is a problem with either my procedure or my understanding of how to use the 'Feature' feature of Drupal 8, or I have a misconception of what it's supposed to do. Any help would be appreciated.

# Answer
> 0 votes
Procedurally, you should skip steps 3 and 4 in the first list. For views, reverting will delete the view's config from the database, which is why you had to re-re-edit the title. FYI, reverting works differently for other objects.

> In some cases (e.g. views), the revert operation will delete the respective configuration in the database, so the system will instead use the default configuration that is defined in the feature module's code.

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

I am not sure what caused the error you received. It might be related to the steps you used. I'd try again and see what happens. :)

---
Tags: 8, features
---


# Question
Title: Render node author profile image in node template
I am working on customization Node template file in Drupal 8, I added another field to user in `admin/config/people/accounts/fields` ( my field is **field\_bio**). Now I want to render author image( with specified image style) and **field\_bio** in node template\`.

How can I achieve this?

# Answer
If you like to do this in ui with one line of code:

1) add a view mode for user and name it "nodeview":

> /admin/structure/display-modes/view/add/user

2) activate the new view mode "nodeview" at the bottom of this page in "Custom Display Settings", then you get a new tab for the view mode "nodeview". Configure which fields are displayed and how they are formatted:

> /admin/config/people/accounts/display

3) Use the new view mode to render the author of the node in node preprocess:

```
$variables['author'] = \Drupal::entityTypeManager()->getViewBuilder('user')->view($variables['node']->getOwner(), 'nodeview');

```

4) Put the variable in twig

```
{{ author }}

```

This method allows full customization in ui and it is fast, because the rendered author gets cached and will be reused in every node referenced.
> 5 votes

---
Tags: theming, 8
---


# Question
Title: Boost not working on pages with ?_utma Google Analytics cookie in url
Boost works on every page, but it doesn't work on pages with Google Analytics variable in the URL. For example, `http://stratton.wanderlustfestival.com/?__utma=1.485948833.1348167330.1348796515.1348837057.31&__utmb=1.3.9.1348837058695&__utmc=1&__utmx=-&__utmz=1.1348167330.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)&__utmv=-&__utmk=172983075` doesn't show `<!-- Page cached by Boost @ 2012-09-27 16:23:18, expires @ 2012-09-28 04:23:18 -->` while `http://stratton.wanderlustfestival.com` does.

# Answer
Boost saves the page cache in a file named after the page + the query string, the limit on the length of a filename is 255 in Linux so for pages with very long name/query string combinations caching will fail.

This should show up as an error in the Drupal log and if it does the solution is edit the .htaccess: Find the comment "Caching for anonymous users", after this you'll find a line "RewriteRule .\* - \[S=4\]", replace this line with the following code:

```
RewriteRule .* - [S=6]

# If the page/query string combination is not over 255 characters, skip the following 2 rewrites
RewriteCond %{QUERY_STRING} "utm_campaign"
RewriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{REQUEST_URI}_%{QUERY_STRING} ^(.*\/)([^\/\n]{0,255})$
RewriteRule .* - [S=2]

# Custom Campaign Query
# Create file if not already boosted
# One campaign item is lost for file creation.
ReWriteCond %{QUERY_STRING} "utm_campaign"
ReWriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html !-s
ReWriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}? [L,T=text/html]

# Boosted file for campaign (now with query string).
ReWriteCond %{QUERY_STRING} "utm_campaign"
ReWriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html -s
RewriteRule .* cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html [L,T=text/html]

```

This makes sure that if the page/analytics query string combination is too long it will cache the page without query string instead, the first request will be redirected to the page without the Analytics query string, the next request will be served from cache and the query string will stay intact.

Note that this code is aimed at long url's with Google Analytics tracking variables only but can be (and possibly should be) rewritten so it can be used universally.
> 5 votes

# Answer
I ran into this issue in June 2016 after installing Boost on fairly busy site. Note that there are two related issues when requests exceed 255 characters: (1) Boost generates an error in the log and doesn't finish creating a cache file and (2) "orphaned" temporary files will appear in the boost cache (files beginning with "boost").

After studying the nice answer by @midnightMotion a while, I decided to try a fix in .htaccess

Using Boost 7.x-1.1, this is what I have added:

```
# If the page/query string <= 255 characters, skip following 2 rewrites
RewriteCond %{REQUEST_URI}_%{QUERY_STRING} ^(.*\/)([^\/\n]{0,255})$
RewriteRule .* - [S=2]

# No cache file - strip query and redirect to create
# One campaign item is lost for file creation.
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_\.html !-s
RewriteRule ^(.*)$ http%{ENV:protossl}://%{HTTP_HOST}%{REQUEST_URI}? [L,T=text/html]

# Cache file exists - use it
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_\.html [L,T=text/html]

```

Note syntax is adjusted slightly for a newer version of boost. I also adjusted the "skip" after the intial boost rule to s=4 to skip the new stuff above when boost isn't triggered.

This appears to have fixed the errors in log, the orphaned boost temp files, and the general problem of long uri + queries not getting a cache.

I'm not an htaccess expert my any means, so please jump in with suggestions.
> 0 votes

---
Tags: 6, caching
---


# Question
Title: block['content'] contail both string and form
I created a form and used a block to show it. I would like to add a message before the form. Before I added "You can use the form below," the form was working fine. Right now, it doesn't work.

The code is the following one.

```
$block['content'] = '<strong>You can use the form below</strong>';
$block['content'] .= '<strong>Enter your email</strong>';
$block['content'] .= drupal_get_form('custom_request_price_form');

```

It just shows "Array" where it should show a form. Why does this happen?

# Answer
`drupal_get_form` returns an array, so you can't concatenate it with a string.

Something like this will work, using a render array:

```
$block['content'] = [
  'preamble' => [
    '#markup' => '<strong>...</strong>',
  ],
  'form' => drupal_get_form('custom_request_price_form'),
];

```
> 4 votes

---
Tags: 7, blocks
---


title: How to manage tickets event?

text:
# Question
Title: How to manage tickets event?
I have to handle tickets request. Let me explain (sorry for my english):

On the site, each authenticated user create a club (Master Club) and members (Master Members). Master Club and Master Members are two content types.

Each club administrator (authenticated user) must be able to send a request for tickets event and indicate the tickets number by listing the name, address and other data of the shareholders chooses from its list.

The structure is similar TICKET module: Site administrator create a content type EVENT. For each EVENT specify the sector( SECTOR\_A, SECTOR\_B,.....) and for each SECTOR how many tickets want.

scenario: Let's say you require 3 tickets for SECTOR\_A and 2 tickets for SECTOR\_B:

This request must be sent to the site administrator which can confirm this request or notify club administrator that instead of 5 tickets they can take only 2 tickets for SECTOR\_A and 1 tickets for SECTOR\_B..

The club administrator receives this notification and can accept the site administrator's request indicating the members(from its membership list) who want to assign these 3 tickets or refuse.

How set it ?

# Answer
> 2 votes
The Ticket module is a good point to start.

> Ticket is a module that provides ticketing and registration for events (and more abstractly, entities). Events may have multiple ticket types, each with a unique set of requirements and registration fields.

---
Tags: 7
---


title: How to import userpoints?

text:
# Question
Title: How to import userpoints?
The User Points module doesn't have migrate integration yet. Looking at the API I can probably use userpoints\_service\_add to assign "starting point" values for each user in a batch script.

Is there an option to update the "starting point" value for a user when I go live? Or do I have to calculate the difference and just add an adjustment?

# Answer
You want to use userpoints\_userpointsapi(), not the service wrapper.

The system is designed to only ever allow new transactions in order to change the total amount of points a user has. So yes, if you want to set it to a fixed value, you need to calculate the difference from the actual amount of points a user has and grant him the difference.
> 1 votes

# Answer
I am thinking that you could do this with the data module to expose you old tables to views. Then using views bulk operations and rules to copy the userpoints to the new users.

I am curious what are you migrating from? Doesn't userpoints have an upgrade path?
> 0 votes

# Answer
These days there is a Migrate integration available for User Points, as confirmed also in the User Points issue "Migration support for User Points".

Comment nr 17 in it includes a patch, which according to Comment nr 18 of that issue works perfectly.

And as per Comment nr 21 of that issue, it's included in the 7.x-1.1 release.
> 0 votes

---
Tags: 7, migrations, userpoints
---


# Question
Title: How to change the date of rewarded User Points?
When users publish a node on my website, they are rewarded some User Points with Rules. So when one publishes a new node on 25th June 2016, the User Points are stored with the exact same date.

As an administrator, I published some nodes where I changed the author and the date (say, 25th June 2012) in *Authoring information* in the node's form. However, after publishing, the User Points were of course stored as granted on 25th June 2016 instead of 25th June 2012.

Is it possible to change the date of a User Points transaction and replace it with the same time on which the linked entity (i.e. the node) was created? That is, in this case, the date of the transaction should be 25th June 2012.

I am aware that one can manually change the data in the database, but I suppose (and hope!) that there is a more efficient way.

# Answer
Have a look at the User Points Contributed modules as a possible alternative. I.e. its submodule **userpoints\_retroactive**. Excerpt from that project page:

> Award users points for their nodes, comments and votes that they have created so far, before userpoints was enabled on the site.

Comment nr 9 of issue nr 1187616 contains a patch with these enhancements:

* Ported the module to Drupal 7.
* Added support for retroactive revisions.
* Made provisions to store the timestamp of original node and revision.

So instead of trying to change the dates of the User Points transactions, I'd delete the transactions you already have, and try to recreate these transactions using this patch.

PS: there is also Berdir's Api documentation about this submodule ... (maybe that helps somehow).
> 0 votes

---
Tags: 7, userpoints
---


title: Content Type Segmentation

text:
# Question
Title: Content Type Segmentation
I need to know if there is a way to create a content type and within the content type to create a field which this field should be segment.

For Example :

at the beginning i will have an image, this will be the default image. and in case i will choose an option like to display only for authenticated user another image field will be opened , and in the display all unauthenticated users will see the default image and authenticated users will see the second image.

Is there something like this ?

Thanks

# Answer
You can create a template for that specific content type like

```
node--yourcontenttype.tpl.php

```

and inside you can check for the user roles like so

```
// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // print one image
} else {
  //print the other one
}

```
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Inherit all styles from base theme expect a few
I am doing a base theme and child theme. I want the child theme to inherit all the css from the base theme expect a few for which i will have the stylesheet in this child theme. How will i achieve this ?

# Answer
As noted on the sub-theme page, a sub (or child) theme will inherit all the parent's css files "as long as you declare at least one stylesheet in your sub-theme's .info file".

You can override a stylesheet simply by declaring one of the same name in your sub-theme's .info file. If there is a stylesheet you don't want in your sub-theme, just add an empty file with same name to the sub-theme's .info file.
> 2 votes

# Answer
Another alternative is to use the template.php file

```
 <?php
 global $theme;
 if($theme=='parent_theme_name'){
   drupal_add_css('//fonts.googleapis.com/css?family=Montserrat:400,700|Trocchi', array('type' => 'external', 'group' => CSS_THEME));
 }

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Autocomplete won't work for entity reference field unless User > Administer Users permission is granted
I have an entity reference field (users) on a node in D8, and the autocomplete suggestions won't show unless the **User \> Administer Users** permission is granted to the role.

I'm trying to let event creators select who is presenting a certain topic, but I don't want them to be able to edit users' settings. Any ideas?

# Answer
The endpoint that provides AJAX entity reference completion (`system.entity_autocomplete` in **system.routing.yml**) is configured with with `requirements._access: 'TRUE'` property. This should make the **/entity\_reference\_autocomplete/%/%/%** path accessible to any user.

As such, check for any module that might be modifying its permissions.
> 3 votes

---
Tags: 8, entities, users, nodes, ajax
---


# Question
Title: List publications by same Author on Staff page
I'm using the biblio module to manage publications on my site. I've a content of type "Staff" that display all workers. These workers have publications that are listed on the publication page (using the biblio module). Now the Staff node has a field name (wich content the workers first and last name). Now I want to list all biblio (publications) that has the same "Author name" as "Staff name" on a staff page. The idea is to link Staff name with biblio Authors name, and use this to list every publication containing this workers (staff) name on this particular workers page. At the end, I'll habe to add pulbications just once and they will be listed on every workers page containing the name of the author. How can i achieve this? I've tried everyting i could, but could not find a solution. Thanks for your help.

# Answer
use views and add a relationship to the author inside the view
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: Customizable product bundles, user can add/remove products
I'm looking for ways to implement an e-commerce for an organic farmer who sells their products, he offers products and product bundles. Every product bundles has its own price. Each bundle are predefined products group. But I want that when the user buys, can unchoose at most, two products of the bundle and change them for another product in a predefined group of products.

I wonder if anyone knows how I can work this way the product bundles. I've been searching, I saw Tech Talk about commerce bundles, I tried commerce\_bundle... but I can't find anything to do this.

Any idea or clue is welcome!

# Answer
> 2 votes
My solution goes here based on Drupal Commerce-

**Step 1**: Create Product Bundles using Commerce Bundle module. (which you already know).

**Step 2**: Now you have bundles. The next step is your custom functionality to **swap at most two products from the bundle**.

Add a new step to your checkout process to implement the custom functionality refer Add a new step in Commerce checkout, explore commerce\_checkout.api to get the hold on this.

Adding a new step is nothing but adding a new pane (inside a checkout page) in a Drupal Commerce checkout process where you can list the products in the cart and process them using hook\_form\_alter(). Refer this link for more details hook\_form\_alter.

You can make use of hooks provided by Drupal Commerce such as commerce\_cart.api, commerce\_order.api to edit/update the cart.

**Step 3**: After processing the cart contents you can update the order details/status using commerce\_order.api.

You can alter the checkout pane settings from **Home » Administration » Store » Configuration » Checkout Settings** page.

**Note**: You must have Drupal 7 module development knowledge to implement the above solution.

I hope this helps! Thank You.

---
Tags: commerce
---


title: How to alter body of contact form?

text:
# Question
Title: How to alter body of contact form?
When submitting a message in my site contact form in Drupal 8.x I have printed a message

```
print_r($message['body'][1]);die;  //in my modulename_mail_alter(&$message)

```

I get the following message

```
Drupal\Core\Render\Markup Object
(
    [string:protected] => Message

   Test Message

     First Name
               Rahul

     Last Name
               gaikwad

)

```

How can I change the body content of the email.

# Answer
Alter how exactly? You can cast the markup object to a string, then you can change the string or completely replace it.

Also check out the default integration that the contact\_storage module has with swiftmailer to allow sending mails as HTML. That might get you much further than trying to change this string.
> 1 votes

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


# Question
Title: How to programmatically display a select list label instead of the value?
I created a select list box in the following format

```
Gender
1|Male
2|Female

```

I want to display the follwing information in a table but I am getting "1" for male and "2" for female.

Here is my code:

```
function display_results_submissions(){
$results = db_query("SELECT * FROM {users}");
$header = array( t('Name'), t('Mail'), t('Gender'),);

foreach($results as $result){
        $rows[] = array(

            $result->name,
            $result->mail,
            $result->gender,

            );
    }

    return theme('table', array('header' => $header, 'rows'=>$rows));
}

```

I want to display Male or Female instead of "1" and "2". How can I do so?

# Answer
When saving the gender, the value that is stored in the database is the key and not the value. Hence, your database contained 1/2 instead of Male/Female. So, your query was right and only needed to format the key before storing in `rows[]`.

```
function display_results_submissions(){
  $results = db_query("SELECT * FROM {users}");
  $header = array(t('Name'), t('Mail'), t('Gender'));
  foreach($results as $result){
    $gender = $result->gender == '1' ? t('Male') : t('Female');
    $rows[] = array(
      $result->name,
      $result->mail,
      $gender,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}

```
> 2 votes

# Answer
I think you should use entity\_metadata\_wrapper because when the select label changes you don't have to change your code.

Following lines will do what you want:

```
$wrapper = entity_metadata_wrapper('user', $result->uid);
$gender = $wrapper->field_user_gender->label();

```

So your code would look like:

```
function display_results_submissions(){
  $results = db_query("SELECT * FROM {users}");
  $header = array(t('Name'), t('Mail'), t('Gender'));
  foreach($results as $result){
    $wrapper = entity_metadata_wrapper('user', $result->uid);
    $gender = $wrapper->field_user_gender->label();
    $rows[] = array(
      $result->name,
      $result->mail,
      $gender,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}

```

There is a good blog post at http://www.mediacurrent.com/blog/entity-metadata-wrapper
> 3 votes

---
Tags: forms, database
---


# Question
Title: How to attach custom CSS to a Views output?
I created a View to list a custom entity content.
I'd like to add my custom CSS file to the generated page.
I tried to use a Text Area in the footer with `{{ attach_library('amap/yyy') }}` where *amap* is my custom module and *yyy* is my custom library.
And of course, the CSS is not loaded...
Any idea why?

# Answer
> 6 votes
You will need hook\_views\_pre\_render().

And here is an example:

```
/**
 * Implements hook_views_pre_render().
 */
function base_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'this_is_my_view_with_no_css' && $view->current_display == 'page_1') {
    $view->element['#attached']['library'][] = 'base/test';
  }
}

```

# Answer
> 0 votes
Is your custom css loaded with you theme? I might be misunderstanding you question, but if you trying to apply your custom CSS to your view's result and your CSS is loaded with your theme then, in editing the view, click on the field you want to edit. Click 'Style Settings' and you'll see options for adding HTML and CSS to the field. Click 'Create a CSS class'. Enter a new CSS class name. Set the class names to those in your custom theme CSS file you want to use. Clear your cache and check the view. note: the preview will not show CSS changes.

If you are not loading your custom css with your theme, I suppose you could include it in the .info for Views. Though you would have to redo that each time views updated.

---
Tags: views, 8
---


title: How do I build a view of menu items?

text:
# Question
Title: How do I build a view of menu items?
### Scenario

* "landing page" content type, with node 1 at path node/1
* corresponding menu item A (with path node/1)
* children menu items of this menu item, B, C, D (with arbitrary paths http://google.com, zee/bang, and node/1234)

### Objective

* Build a view which displays on node/1, whose results are links B, C, and D.

In Drupal 7, i would have used https://www.drupal.org/project/menu\_views to accomplish this.

How best to achieve this in Drupal 8?

# Answer
> 0 votes
Right now, I think D8 is too initial state to have a contrib solution for something "custom" like this. Personally, I would leave Views, and going instead:

1. Set up a route to a controller
2. In controller inject your own custom services and return the results in twig.
3. In your own service, inject any other service you need and to the business logic here.

---
Tags: views, 8
---


# Question
Title: Different theme of Media module audio player in Firefox and IE and chrome
I installed Media module, and there is a content type for audio files. The Manage display of the audio field is *Audio*. But the player has different themes in different browsers. This is what Firefox displays

**This is for IE**

**and it is chrome**

What is the problem? why do they have not the same theme?

thanks

# Answer
> 1 votes
If I am not mistaken, these are the native displays for the HTML5 `<audio>` element in different browsers. I don't think the Media module has anything to do with it, it probably only displays the markup without adding any theming.

---
Tags: 7, entities, media
---


# Question
Title: Constantly getting "The website encountered an unexpected error. Please try again later."
I wondered if I can get some advice regarding working with Drupal 8. I've tried installation after installation and sooner rather than later I'm effectively bricking the installs by just installing third party modules.

Can someone please advise how I can debug effectively? I'm not a dev but can do some basic dev tasks.

I used to use for Drupal 7 in settings.php:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

However, I have no luck with this in Drupal 8.

It's getting incredibly frustrating when trying out new modules for this constantly to be happening.

Log file reads (which I've Googled) prior to asking.

> \[proxy\_fcgi:error\] \[pid 15594:tid 139919129229056\] \[client 79.70.230.243:47902\] AH01071: Got error 'PHP message: Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "file\_type" entity type does not exist." at core/lib/Drupal/Core/Entity/EntityTypeManager.php line 125\n'

A second site outputs:

> \[pid 15594:tid 139919154407168\] \[client 79.70.230.243:49570\] AH01071: Got error 'PHP message: Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "file\_type" entity type does not exist." at core/lib/Drupal/Core/Entity/EntityTypeManager.php line 125\n', referer: http://domainname/user/login

Despite me having the above information, I really don't know what is causing this. Furthermore, I never do as reading the log files and following those error messages (like the above ones) doesn't clearly illustrate which module is causing the problem.

# Answer
That exception is thrown by `EntityTypeManager::getDefinition()` when it doesn't find any definition for the entity with the ID passed as argument.

```
  if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
    return $entity_type;
  }
  elseif (!$exception_on_invalid) {
    return NULL;
  }

  throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));

```

The ID of that entity could confuse: It's not the File entity Drupal core implements because its ID would be *file*, not *file\_type*. That is the entity defined from the File Entity (fieldable files) project, in its FileType.php file.

I take you installed the module, and uninstalled it, but your site still have some instances of that configuration entity. I would try cleaning Drupal cache, and if that doesn't work, I would re-install the module, go to /admin/structure/file-types, delete any entity listed there, and uninstall the module again.
> 2 votes

# Answer
What module is this? I checked there is no `file_type` entity in core. This is caused by a contrib module.

You probably have the source files still in your installation. Look for the missing plugin. This should look like this:

> modules/modulename/src/Entity/FileType.php

When you found the module which is causing this, try to reproduce the error with a clean install and go to the issue queue of the module.

To set up debugging in D8 look at:

**/sites/example.settings.local.php**

```
/**
 * @file
 * Local development override configuration feature.
 *
 * To activate this feature, copy and rename it such that its path plus
 * filename is 'sites/default/settings.local.php'. Then, go to the bottom of
 * 'sites/default/settings.php' and uncomment the commented lines that mention
 * 'settings.local.php'.
 *
 * If you are using a site name in the path, such as 'sites/example.com', copy
 * this file to 'sites/example.com/settings.local.php', and uncomment the lines
 * at the bottom of 'sites/example.com/settings.php'.
 */

```

Most important is the backtrace information you get with that, this could give you some clues what is causing your error.

Most times you get errors after removing a module it helps to clear the cache.
> 1 votes

---
Tags: 8, debugging
---


# Question
Title: Location Module fields are not available under Search api fields
I am using Search API's Default Node index. I am using Location module to store Location data. But location module fields are not available under Search API Related fields.

I know this has been an issue but was just wondering if this could ever get fixed? I could have used Geolocation or Geofield modules and used the fields in search api. But unfortunately when i used location module i was not using Search API.

Now I have 10000 Nodes using location module to store location details.

What could be the solution? How to make these fields to be used under Search api so that i can use facets and eventually show them on MAP.?

Please help!

Thanks in advance.

# Answer
As pointed out here, you can achieve that by means of a combination of modules:

Search API Location + Search API Solr + Location field (creating an aggregated location field).

You will need an extra step by implementing `hook_search_api_solr_documents_alter()` because the longitude and latitude need to be indexed with the right format.
> 1 votes

---
Tags: entities, search, location
---


# Question
Title: Get content of selected option after user select any option from select field
I have created a content type, This content type form having a select box.

I need to develop a functionality like once the user select any option from select field the following textbox should having options like auto-complete data to respected selected option.

I can not create taxonomy and dependency because the database is very large. unable to add all data to taxonomy.

I want to do it by using ajax on change option. How can I achieve this?.

Can anyone suggest the easiest method?

# Answer
> 2 votes
I have done same with User Roles and Users. Check below code if you can find it helpful.

```
function custom_menu(){
    $items = array();
    $items['custom'] = array(
        'title' => 'custom',
        'description' => 'Custom',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('custom_form'),
        'access callback' => TRUE,
    );

    // " % " is the RID coming from '#autocomplete_path'.
    $items['autocomplete/%'] = array(
        'page callback' => 'autocomplete_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

function custom_form($form, &$form_state){
    $options = array();
    $roles = user_roles($membersonly = TRUE); // Getting list of Roles.

    // Removed "Authenticated" role from the list.
    // That is not listed in "users_roles" Table.
    array_shift($roles);

    foreach ($roles as $key => $value) {
        $rid = user_role_load_by_name($value);
        // Give RID to each role as their key in array.
        $options[$rid->rid] = $value;
    }

    // Defining $role as selected value of Select list.
    $role = !empty($form_state['values']['roles']) ? $form_state['values']['roles'] : '';

    $form['roles'] = array(
        '#type' => 'select',
        '#title' => 'Role',
        '#options' => $options,
        '#ajax' => array(
            'wrapper' => 'auto-wrapper',
            'callback' => 'select_callback',
        ),
    );

    $form['auto'] = array(
        '#type' => 'textfield',
        '#title' => 'Users',
        '#autocomplete_path' => 'autocomplete/' . $role, // Pass RID to path.
        '#prefix' => '<div id="auto-wrapper">',
        '#suffix' => '</div>',
    );

    return $form;
}

function select_callback($form, &$form_state){
    return $form['auto'];
}

function autocomplete_callback($role, $string = "") {
  $matches = array();
  if ($string) {
    $query = db_select('users', 'u');

    if(is_numeric($role) && $role != ''){
        $query->join('users_roles', 'ur', 'ur.uid = u.uid');
    }

    $query->fields('u', array('name', 'uid'));

    if(is_numeric($role) && $role != ''){
        $query->condition('ur.rid', $role)
            ->fields('ur', array('rid'));
    }

    $query->condition('name', db_like($string) . '%', 'LIKE')
      ->range(0, 10);

    $result = $query->execute();

    foreach ($result as $user) {
      $matches[$user->name] = check_plain($user->name);
    }
  }

  drupal_json_output($matches);
}

```

# Answer
> 1 votes
This ought to do it:

JS:

```
$(function() {
    $('#text').change(function() {
         $('#output').val($(this).val());
    }).change(); // Trigger the event
});

```

HTML:

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">    </script>
<select name="text" id="text">
    <option value="Stuff 1">Option1</option>
    <option value="Stuff 2" selected="selected">Option2</option>
    <option value="Stuff 3">Option3</option>
</select>

<input id="output" type="text" />

```

JSFiddle: http://jsfiddle.net/QZ3ff/999/

---
Tags: ajax
---


# Question
Title: How to send html/plain-text mails based on user settings?
Using mail function i am send mails to multiple users with comma separated values in Drupal 8. But in that mail id users, some users selected mail preference as html and some users selected plain-text settings. So how can i send the html/plain-text mails programatically based on users settings?

# Answer
If we are talking about hardcoding (not interface), you have to loop through the
addressee list, load that user, and based on his preferences send html, or plain text.
> 1 votes

---
Tags: 8, emails
---


# Question
Title: How do I extend a configuration form without using hook_form_alter()?
I want to extend some fields in a config form of a module with another module in Drupal 8. I created a config form in a module (e.g. custom\_1) and now I want to add some more fields from another module (e.g. custom\_2). custom\_1 has a dependency on custom\_2. I tried `hook_form_alter()` but it didn't resolve the issue.

Is there any other way to achieve this in Drupal 8?

# Answer
> 3 votes
**Solution:**

I came out to this solution:

I created a custom\_1.routing.yml file and write the following code in it.

```
#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_1\Form\CustomConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

```

I created a CustomConfigForm.php file in custom\_1/src/Form/CustomConfigForm.php.

```
    namespace Drupal\custom_1\Form;

    use Drupal\Core\Form\ConfigFormBase;
    use Drupal\Core\Form\FormStateInterface;

    class CustomConfigForm extends ConfigFormBase {
      public funtion getFormId() {
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames() {
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
          // Form code here
         return buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

```

Now, I have to merge some more form fields from another module custom\_2. To achieve this, I followed the following steps. I created a custom\_2.routing.yml file and write the following code in it.

```
#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_2\Form\CustomTwoConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

```

I created a CustomTwoConfigForm.php file in custom\_2/src/Form/CustomTwoConfigForm.php.

```
    namespace Drupal\custom_2\Form;

    use Drupal\Core\Form\FormStateInterface;
    use Drupal\custom_1\Form\CustomConfigForm;

    class CustomTwoConfigForm extends CustomConfigForm  {
      public funtion getFormId(){
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames(){
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
           $form = parent::buildform($form, $form_state);
          // Form code here
         return parent::buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

```

This resolve the issue for me without using `hook_form_alter()`.

Thanks

---
Tags: forms, 8
---


# Question
Title: Ahah helper alwas getting error, but on other page no error
I have forms with Ahah helper. When I tried to fill the form, it always getting this error:

```
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'A' not found or invalid function name in xxx\includes\form.inc on line 378.

```

A = name of function, but that function is exist xxx = location of drupal

Line 378 is:

```
$form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);

```

At page\_new\_init, there is no error at all. But, at page\_initedit there's always error. This is the .module code:

```
$items['new/init/1'] = array(
    'title' => 'Add new',
    'type' => MENU_LOCAL_TASK, //MENU_NORMAL_ITEM,
    'page callback' =>'page_new_init',
'access arguments' => array('new'),
);

$items['new/editinit'] = array(
    'title' => 'Edit',
    'type' => MENU_CALLBACK, //MENU_NORMAL_ITEM,
    'page callback' =>'page_initedit',
'access arguments' => array('new'),
'file' => 'act.edit.inc',
);

```

And this is the form on function "page\_new\_init":

```
function page_new_init(){
  global $user;

 $output .= drupal_get_form('form_new_add2',$id,$codeact);

  return $output;
}

function form_new_add2(){
  global $user;

    $form = array();
    ahah_helper_register($form, $form_state);
    drupal_add_js("sites/all/modules/act/javascript/jss.js");

    $form['input']['account'] = array(
    '#type' => 'textfield',
    '#title' => t('Account Code'),
    '#size' => 60,
    '#default_value' => $account,
    '#required' => TRUE,
    '#autocomplete_path' =>'compose/code',
    '#ahah' => array(
        'event'   => 'change',
        'path'    => ahah_helper_path(array('input')),
        'wrapper' => 'input-wrapper',
        'method' => 'replace',
        'progress' => 'throbber',
    ),

    $form['input']['access_code'] = array(
    '#type' => 'select',
    '#title' => t('Access Code'),
    //'#required' => TRUE,
    '#default_value' => $access_code,
    '#options' => opt_accesscode(),
    );

  return $output;
}

```

And this is the other function "page\_initedit":

```
function page_initedit(){
  global $user;

 $output .= drupal_get_form('form_initedit',$id,$codeact);

  return $output;
}

function form_initedit(){
  global $user;

    $form = array();
    ahah_helper_register($form, $form_state);
    drupal_add_js("sites/all/modules/act/javascript/jss.js");

    $form['input']['account'] = array(
    '#type' => 'textfield',
    '#title' => t('Account Code'),
    '#size' => 60,
    '#default_value' => $account,
    '#required' => TRUE,
    '#autocomplete_path' =>'compose/code',
    '#ahah' => array(
        'event'   => 'change',
        'path'    => ahah_helper_path(array('input')),
        'wrapper' => 'input-wrapper',
        'method' => 'replace',
        'progress' => 'throbber',
    ),

    $form['input']['access_code'] = array(
    '#type' => 'select',
    '#title' => t('Access Code'),
    //'#required' => TRUE,
    '#default_value' => $access_code,
    '#options' => opt_accesscode(),
    );

  return $output;
}

```

On "page\_new\_init", there is no error at all, Ahah helper works fine. But on "page\_initedit" the error comes up:

```
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'form_initedit' not found or invalid function name in drupal\includes\form.inc on line 378.

```

What should I do?

# Answer
In .module file, I have to load .inc file. That's what I forgot! :(

```
include_once(drupal_get_path('module', 'act') .'/act.edit.inc');

```
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Creating a watchdog log when publishing status changes on my own ContentEntityBase
I have a hierarchy of Entities derived from ContentEntityBase. Now I want to create a log when the publishing status ( = status field) changes.

What is the best method to override/implement for this purpose? In the Entity that extends ContentEntityBase or in the Form that extends ContentEntityForm?

Or somewhere else? I don't want to use a hook!

Thanks. Rainer.

# Answer
I would like to go for hooks (maybe events), **hook\_ENTITY\_TYPE\_update**. You can find more about it in details here.

You only have to check if "status" field is being changed after update, and using the logging factory to put it into logs. This is also "form" independent (means it will run each time when entity gets updated), which is more general approach, and better for your system (more consistency).
> 1 votes

# Answer
Thanks ssibal, with your hint I found an answer. In the hook page on drupal.org I found the dirty fact: "Get the original entity object from $entity-\>original."

So I implemented the hook, set a breakpoint and found that stack:

```
proreos/preosanwalt/preosanwalt.module.preosanwalt_anwalt_entity_update(): lineno 110
proreos/core/lib/Drupal/Core/Extension/ModuleHandler.php.call_user_func_array:{proreos/core/lib/Drupal/Core/Extension/ModuleHandler.php:402}(): lineno 402
proreos/core/lib/Drupal/Core/Extension/ModuleHandler.php.Drupal\Core\Extension\ModuleHandler->invokeAll(): lineno 402
proreos/core/lib/Drupal/Core/Entity/EntityStorageBase.php.Drupal\Core\Entity\EntityStorageBase->invokeHook(): lineno 167
proreos/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php.Drupal\Core\Entity\ContentEntityStorageBase->invokeHook(): lineno 418
proreos/core/lib/Drupal/Core/Entity/EntityStorageBase.php.Drupal\Core\Entity\EntityStorageBase->doPostSave(): lineno 470
proreos/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php.Drupal\Core\Entity\ContentEntityStorageBase->doPostSave(): lineno 304
proreos/core/lib/Drupal/Core/Entity/EntityStorageBase.php.Drupal\Core\Entity\EntityStorageBase->save(): lineno 395
proreos/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php.Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(): lineno 747
proreos/core/lib/Drupal/Core/Entity/Entity.php.Drupal\Core\Entity\Entity->save(): lineno 358
proreos/core/lib/Drupal/Core/Entity/EntityForm.php.Drupal\Core\Entity\EntityForm->save(): lineno 283
proreos/proreos/src/Form/ProreosEntityFormBase.php.Drupal\proreos\Form\ProreosEntityFormBase->save(): lineno 81

```

Going backward from that I found that EntityStorageBase is setting that dirty original right before it calls the Entity's preSave method.

So, the correct approach to do it without a hook in my EntityBase is this:

```
  public function preSave(EntityStorageInterface $storage) {
       parent::preSave($storage);

       $org = $this->original;
       if ($org->isPublished() != $this->isPublished()) {
         proreos_auditinfo("Publish Status geändert, ".$this->getAuditString());
       }
  }

```

I think we should have a documented API call here in EntityInterface instead of that dirty "original" property - I'll file that as feature request at drupal.org.

Thanks. And btw. I don't like the hook system anymore because I don't like to mix that procedural approach with my OO code.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to use t() function for a text with anchor links?
I have a text that I must show in 5 languages. I am using `t()` for that. The text is:

> In case of any issues, please Contact Us for assistance.

I want the phrase "Contact Us" to be a link. So this is what I have done:

```
$text = t('In case of any issues, please ')."<a href="link/to/path">".t('Contact Us')."</a>".t('for assistance');

```

I suspect that this might not be the correct way to do this as this will break the translation. I fear that the sentence will not be translated as a whole but in parts.

Am I right?

And if I am, what could be the correct way to do it?

# Answer
> 21 votes
You're absolutely correct; you should never concatenate strings with `t()`, the whole point is that it uses placeholders so you don't have to. Specifically:

```
// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => '<a href="http://drupal.org/handbooks">'. t('the Drupal Handbooks') .'</a>'));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at <a href="http://drupal.org/handbooks">the Drupal Handbooks</a>.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

```

Instead of those you should use the following:

```
// Do this instead.
$external_link = t('Look at Drupal documentation at <a href="@drupal-handbook">the Drupal Handbooks</a>.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to <a href="@administer-page">the Administer screen</a> in the main menu.', array('@administer-page' => url('admin')));

```

See Dynamic or static links and HTML in translatable strings for full details.

# Answer
> 5 votes
I suggest you try `l()` function and learn it, it is very good and simple. and solution for you

```
l(t('yourtext'),'link/to/path');

```

I hope can learn you drupal base method to write your links in drupal :)

**updated Part:**

```
$link='<a href="link/to/path">'.t('Contact Us').'</a>';
t('first part of your context @link the end part of your text',array('link'=>$link));

```

# Answer
> -3 votes
This solution is work for you.

```
drupal_set_message(t('Payment Method Added Successfully -  '.l('add anchor link')),'status');

```

---
Tags: i18n-l10n
---


# Question
Title: How to link to files using a relative path?
My site is in `sites/sandbox` folder. When I upload to live server, this will change to `sites/mysite`

In file system settings, the public file system path is set to `sites/sandbox/files`. When site goes live, I plan to change this to `sites/mysite/files`

File module is enabled and I am uploading PDF files. When entering content, how can I link to an uploaded file using a relative path that won't break when the site goes live?

Or perhaps the site directory name ('sandbox') should never be changed?

# Answer
The Pathologic module will fix all of that for you automatically when you move it over

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.
> 3 votes

# Answer
Did you try file\_create\_url() ?

`$file_uri = file_create_url(file_build_uri('images/example.jpeg'));`

The above snippet will give the file URL. Besides, I recommend transliteration module for the sites that deals with file uploads.
> 4 votes

# Answer
Use `base_path()` (function) OR $base\_path (global var) that will result `/sites/mysites` OR `/sites/sandbox` for your sites. Always use it in themes and every where. This will give you ease to sync both sites with any edit.

Links can be produced

```
l('Link Title', base_path() . "/files/filename.ext");

```

OR

```
global $base_path;
l('Link Title', $base_path . "/files/filename.ext");

```
> 1 votes

# Answer
The LinkIt module is a pretty comprehensive solution for inserting links into fields and wysiwygs in really any format you choose. I'm using File Entity and Media and using the LinkIt WYSIWYG integration allows me to insert links to files however I'd like, including direct links to the file for the desired "open in browser" behavior. It's also got a great autocomplete search function for finding nodes or files. I wish I had found it sooner.
> 0 votes

---
Tags: 7, files
---


# Question
Title: How do I include a custom module translation?
I have a Drupal 8 custom module (custom\_module) and a custom\_module-8.x-1.0.da.po file I added to sites/default/files/translations, but my translations are not getting Imported during the module installation, even though translations are available for import in admin/reports/translations. Am I missing any step?

I don't want to put my custom\_module-8.x-1.0.da.po file in sites/default/files/translations; I prefer it to be inside the module directory, if possible.

# Answer
> 3 votes
Add `interface translation project` and `interface translation server pattern definitions` to custom\_module.info.yml. You can use a custom path for your translation po file by setting the `interface translation server pattern` to whatever you want.

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


title: Drupal 8 block cacheing

text:
# Question
Title: Drupal 8 block cacheing
I have written a block, displayed on the right sidebar of my drupal 8 site. It reads the database, and shows today's reports. But the block's output is aggressively cached, so that it never shows the up-to-date details. The block's code is being called, and returns the correct data, but this is ignored. (Pages created by controller classes do similar work, but are not cached. What's the difference?).

After reading many help pages, I'm frustrated; I can't get the block to show up-to-date details. The solution seems to involve setting '#cache' on the render array returned, but I can't see how.

Help please!

# Answer
It all depends on what you want to do exactly. I have a block that is dependent on the user thats logged in, and it may also be changed from time to time based on some other code being run.

In this example

```
'#cache'=>[
        'contexts'=> [
            'user',
            'route',
        ],
        'tags' => [
          'Block:smn',
        ],
      ],

```

It gives it context for which to cache and the tag allows me to invalidate the cache for just this block if I run some other code that will affect what is rendered

in this example if some entity is deleted i use hook\_entity\_delete

```
function foo_entity_delete($entity){
    $cache = \Drupal::service('cache_tags.invalidator')->invalidateTags(array('Block:smn'));

}

```

and my block will be removed from cache and the next time I visit the page it will be rendered with new information.

for more info on tags, and contexts you can cache with: https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x
> 0 votes

---
Tags: caching
---


# Question
Title: How to generate URL alias without %20 in URL?
We have a custom field that is being used to generate the URL alias.

One issue we have found is that when we set the page to "Autogenerate URL Alias" and set the URL pattern to "`[node:field_custom_url]`", we are still getting "`%20`" where the space should be.

We have done the following, but nothing seems to work. We needed assistance to see what else needs to be configured. Ideally, any spaces should be replaced with a "`-`" instead of "`%20`". Any thoughts?

Current settings (found in `admin/config/search/path/settings`):

* Path pattern = "\[node:field-custom-url\]" (we even tried \[node:field\_custom\_url\], but it did not work)
* Create a new alias. Delete the old alias. = Enabled
* Separator = "-"
* Transliterate prior to creating alias = Enabled
* Reduce strings to letters and numbers

# Answer
> 1 votes
Your field token is failing the condition inside `pathauto_clean_token_values`, specifically as the token name has the reserved word `url]`.

See function `pathauto_clean_token_values`:

```
function pathauto_clean_token_values(&$replacements, $data = array(), $options = array()) {
  foreach ($replacements as $token => $value) {
    // Only clean non-path tokens.
    if (!preg_match('/(path|alias|url|url-brief)\]$/', $token)) {
      // Convert language object into language code before pathauto_cleanstring().
      if (isset($options['language']->language)) {
        $options['langcode'] = $options['language']->language;
      }
      $replacements[$token] = pathauto_cleanstring($value, $options);
    }
  }
}

```

There's a `preg_match` which looks for:

* `path]`
* `alias]`
* `url]`
* `url-brief]`

in the token names, and your `[node:field_custom_url]` token will fail the 3rd pattern: `url]`. That's why your spaces are never replaced by the separator. You need to change your field machine name to be something not ending with the list above.

# Answer
> 3 votes
It is proved that I wrote wrongly in the beginning, thanks @Beebee.

> I have read through the code of `pathauto` module. The module implements the token replacement after replacing the space with defined separator. So there is no clue by configuration. I would consider it is a design fault of the module.

`pathauto` module clean the url only when the token name does not match with the pattern `/(path|alias|url|url-brief)\]$/`. You can find it in the `function pathauto_clean_token_values()`. Obviously, the module author would like to prevent the url alias to be clean twice. As your field name is `custom_url`, so it is escaped from the checking.

You can fix this by changing your field name or writing your own module as I stated before.

---

If you know how to create custom module. I would recommend you to implement hook\_pathauto\_alias\_alter for the purpose.

```
/**
 * Implements hook_pathauto_alias_alter().
 */
function mymodule_pathauto_alias_alter(&$alias, array &$context) {
  $separator = variable_get('pathauto_separator', '-');
  $alias = preg_replace('/\s+/', $separator, $alias);
}

```

# Answer
> 3 votes
Have a look at the Transliteration module. Some details about it (from its project page, with some bold markup added to it):

> Provides one-way **string transliteration (romanization)** and cleans file names during upload by replacing unwanted characters.
>
> Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.
>
> Whether you use **transliteration for URLs** (when using Pathauto 2.x), however, is a matter of personal taste. ...

---
Tags: 7, entities, path-aliases, uri
---


title: Only front page works

text:
# Question
Title: Only front page works
I am trying to set up a local server to try out drupal 8.1.3 and so far I was able to set up my profile and website but I cannot go to any pages other than the first page. (Welcome page, front page)

I have used the following link to install Drupal:

https://www.howtoforge.com/tutorial/how-to-install-drupal\_8-with-apache-and-ssl-on-ubuntu-15-10/

Few things to note:

* I'm not sure if I have CleanURL, tried to fix this issue but couldn't succeed I believe.
* I have tried multiple different approaches to fix issues like CleanURL, SSL connection, Apache2 (AllowOverride All) etc
* I tried adding "?q=" and while this doesn't make the page crash, it just directs me back to the front page

Currently, I am playing around with four files to try to figure out my problem: ".htaccess", "apache2.conf", "drupal.conf" and "settings.php"

**I want to be able to access the Drupal tools to modify the website and run it locally**, I simply want to test Drupal, I wanted to share this because it may simplify the solution.

Some of the code that I have added while trying to fix my situation:

drupal.conf:

```
            <Directory "/var/www/drupal">
                    Options FollowSymLinks
                    AllowOverride All
                    Require all granted
            </Directory>

```

apache2.conf:

```
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

```

.htaccess:

```
RewriteBase /

# homepage redirect
RewriteRule ^$ /SUBDIRECTORY/index.php?q= [L]

# if directory or regular file...
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} =/favicon.ico
# stop here
RewriteRule ^ - [L]

# if a regular file in SUBDIRECTORY directory
RewriteCond %{DOCUMENT_ROOT}/SUBDIRECTORY/%{REQUEST_URI} -f
RewriteRule .* SUBDIRECTORY/$0 [L]

# Redirect everything to /SUBDIRECTORY
RewriteRule .* /SUBDIRECTORY/index.php?q=$0 [QSA]

```

settings.php:

```
$settings['trusted_host_patterns'] = array(
  '^127.0.0.1$',
  '^localhost$',
  '^www.example.com$'
  );

```

PS. I have tried both localhost and an example website url like www.example.com but it didn't help. PS2. I am only using Firefox currently but I don't think the problem is with the browser.

I hope I was able to follow the question guidelines, I am really trying my best to make it a question "suitable" to the website, I am sorry if I made a mistake.

Edit1: I have rewrite already enabled.

# Answer
I believe the problem was due to the location of my .htaccess file. (The main problem was the Clean URLs.)

My original location was /var/www/drupal/sites/default/files; after, I moved it to /var/www/drupal. The .htaccess file started to being read. Previously, it was not being read.

I hope this helps someone else! This also may not be the solution because I am having a different issue now.
> 2 votes

---
Tags: 8, .htaccess, configuration
---


# Question
Title: Drush error: "ContainerAwareEventDispatcher" does't implement EventDispatcherInterface::getListenerPriority
I'm using Drupal 8.1.2 and Drush 8.1.2 (OS X 10.11.5, PHP 5.6.19)

In all of my drush-commands, there occurs an error, that there is a missing implementations of the symfony `EventDispatcherInterface::getListenerPriority` in the drupal core.

The error occurs on clean drupal installations and also on updated. I've tried to solve the problem by installing a different drupal-version (older and latest -\>8.1.2) and older drush-versions (via composer, 8.1.0), but without any results.

This is the my stacktrace:

```
localhost:web3 myusername$ drush up
PHP Fatal error:  Class Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Symfony\Component\EventDispatcher\EventDispatcherInterface::getListenerPriority) in /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php on line 233
PHP Stack trace:
PHP   1. {main}() /Users/myusername/.composer/vendor/drush/drush/drush.php:0
PHP   2. drush_main() /Users/myusername/.composer/vendor/drush/drush/drush.php:12
PHP   3. Drush\Boot\BaseBoot->bootstrap_and_dispatch() /Users/myusername/.composer/vendor/drush/drush/includes/preflight.inc:66
PHP   4. drush_bootstrap_to_phase() /Users/myusername/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php:59
PHP   5. drush_bootstrap() /Users/myusername/.composer/vendor/drush/drush/includes/bootstrap.inc:473
PHP   6. Drush\Boot\DrupalBoot8->bootstrap_drupal_full() /Users/myusername/.composer/vendor/drush/drush/includes/bootstrap.inc:354
PHP   7. Drush\Boot\DrupalBoot->bootstrap_drupal_full() /Users/myusername/.composer/vendor/drush/drush/lib/Drush/Boot/DrupalBoot8.php:135
PHP   8. drush_cache_get() /Users/myusername/.composer/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php:537
PHP   9. dt() /Users/myusername/.composer/vendor/drush/drush/includes/cache.inc:75
PHP  10. Drupal::translation() /Users/myusername/.composer/vendor/drush/drush/includes/output.inc:163
PHP  11. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal.php:592
PHP  12. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
PHP  13. Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:329
PHP  14. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:494
PHP  15. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
PHP  16. Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:236
PHP  17. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:494
PHP  18. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
PHP  19. Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:236
PHP  20. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:494
PHP  21. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
PHP  22. spl_autoload_call() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:272
PHP  23. Symfony\Component\ClassLoader\ApcClassLoader->loadClass() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:0
PHP  24. require() /Users/myusername/Projects/drupal/web3/vendor/symfony/class-loader/ApcClassLoader.php:110

Call Stack:
    0.0001     225296   1. {main}() /Users/myusername/.composer/vendor/drush/drush/drush.php:0
    0.0012     391568   2. drush_main() /Users/myusername/.composer/vendor/drush/drush/drush.php:12
    0.2267    8520768   3. Drush\Boot\BaseBoot->bootstrap_and_dispatch() /Users/myusername/.composer/vendor/drush/drush/includes/preflight.inc:66
    0.2292    8527928   4. drush_bootstrap_to_phase() /Users/myusername/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php:59
    0.3374    8636336   5. drush_bootstrap() /Users/myusername/.composer/vendor/drush/drush/includes/bootstrap.inc:473
    0.3376    8638920   6. Drush\Boot\DrupalBoot8->bootstrap_drupal_full() /Users/myusername/.composer/vendor/drush/drush/includes/bootstrap.inc:354
    0.3921   16940128   7. Drush\Boot\DrupalBoot->bootstrap_drupal_full() /Users/myusername/.composer/vendor/drush/drush/lib/Drush/Boot/DrupalBoot8.php:135
    0.3955   17096672   8. drush_cache_get() /Users/myusername/.composer/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php:537
    0.3956   17097472   9. dt() /Users/myusername/.composer/vendor/drush/drush/includes/cache.inc:75
    0.3957   17098416  10. Drupal::translation() /Users/myusername/.composer/vendor/drush/drush/includes/output.inc:163
    0.3957   17098464  11. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal.php:592
    0.3958   17106856  12. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
    0.3979   17338080  13. Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:329
    0.3979   17338520  14. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:494
    0.3979   17345920  15. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
    0.3979   17345920  16. Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:236
    0.3993   17525976  17. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:494
    0.3993   17533424  18. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
    0.3993   17533424  19. Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:236
    0.4005   17688296  20. Drupal\Component\DependencyInjection\Container->get() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:494
    0.4007   17817768  21. Drupal\Component\DependencyInjection\Container->createService() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:177
    0.4007   17818600  22. spl_autoload_call() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:272
    0.4008   17818880  23. Symfony\Component\ClassLoader\ApcClassLoader->loadClass() /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/DependencyInjection/Container.php:0
    0.4011   17866704  24. require('/Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php') /Users/myusername/Projects/drupal/web3/vendor/symfony/class-loader/ApcClassLoader.php:110

Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Class Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher contains 1 abstract method and must therefore be declared abstract or implement the remaining methods
(Symfony\Component\EventDispatcher\EventDispatcherInterface::getListenerPriority) in /Users/myusername/Projects/drupal/web3/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php, line 233

```

I'm pretty sure that this error is drush-related. What do I miss?

# Answer
> 0 votes
Try using a site-local Drush instead of a globally installed Drush.

See:

https://pantheon.io/blog/avoiding-dependency-hell-site-local-drush

---
Tags: drush, 8, event-subscribers
---


# Question
Title: Internal links no longer working. Getting MAMP virtual host info instead
My local site is running Drupal 7.43 using MAMP on Mac OS X 10.10.5. The site was running fine until recently, when all of the links on the front page were no longer working correctly. Each link now opens the same page. Here is a screenshot of that page.

>

After much digging, I found out that turning off clean URLs allows me to access the rest of the site, which is a CiviCRM installation. I downloaded the files and database from a live site to verify the backup worked. It does work, but only if clean URLs are disabled. Why does it happen?

# Answer
> 0 votes
Since turning off Clean URLs seems to at least be a work around for your issue, it sounds that you have not correctly configured Clean URLs. To correctly enable/configure Clean URLs, refer to Configure Clean URLs in the installation guide.

If you're not familiar with Clean URLs yet, I suggest to review that documentation (for the version of Drupal that you're using) and make sure your server is correctly configured before proceeding.

Here is a summary of common steps/issues:

* With Apache HTTPD as web-server, you have to enable `mod_rewrite` and configure the necessary rewrite rules in the `.htaccess` file.
* Usually, theses rules are applied automatically, when `mod_rewrite` is enabled. But in some cases, the `AllowOverride` directive is too restrictive to allow this.

# Answer
> 0 votes
After commenting out the line "RewriteBase /" in the .htaccess file, clean urls worked as expected and I no longer have a problem with the internal links.

---
Tags: 7
---