# Question
Title: How to implement a simple shopping cart without Commerce and Ubercart?
I need simple solution for shopping cart without big monstrous modules like a Ubercart or Drupal Commerce. I've a small site (catalog) with a few products. I need add to each of them an `Add to cart` button, cart block and page (can be made using Views). Checkout must be just a form with few a fields (like Name, Address etc), which can be made using Webform.

Why Commerce and similar modules are not good for me: I don't need specific fields like SKU, product displays facilities, online payments, registration for user, tax calculation and other. I just want to keep it all simple.

Any suggestions?

# Answer
> 6 votes
The Basic cart module is the best solution for you...

> Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.

# Answer
> 2 votes
The Light Shop module is a simple and lightweight e-commerce solution which doesn't require the Drupal Commerce or Ubercart modules (as in your question title).

Here is a quote from its project page:

> * Session-stored basket.
> * Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
> * Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
> * Orders history. For each order will be created a separate node.
> * There is no dependence on other modules.
> * Full support for working with anonymous users
> * Integration with Views.

The configuration of this module (via `admin/config/lightshop`) is pretty forward:

### 1. On the settings page you need specify:

**General Settings**:

* The site e-mail for notifications about new orders.
* Specify what node types are product.
* Optionally you may specify whether to display the graph with quantity of the product and its price (and which field will contain this value).

**Notification Settings**:

* Check the appropriate box if notification of the created order must be sent to the customer also.
* Check the fields whose data you want to be included in the notification.

### 2. Choose the region for display basket block.

### 3. On permissions page set which roles can use the basket and make purchases.

# Answer
> 1 votes
Depends upon your further needs. Do you also need reports of orders placed? Which payment gateway are you going to use for checkout?

If you want it really simple, maybe you can add a paypal form. You can try this module https://www.drupal.org/project/pay

> This module can be used by other modules to collect and track payments. Through this API, any module can provide a payment form and payments can be handled and tracked centrally.

# Answer
> 1 votes
If you're using PayPal, you can just go to their site and create a button to copy and paste (no need for a dedicated module). PayPal captures their address and email which they forward to you once the transaction is complete.

This method may be a bit more Spartan than what you intend but should get the job done without extra overhead.

---
Tags: 7, ubercart, commerce
---


# Question
Title: How to notify site admin when user registers with a specific field checked
My case site has `student` and `teacher` accounts (teacher/student radio buttons). When user registers as a teacher, admin has to be notified so that admin performs further checks to accept the account.

How can I do this programmatically

# Answer
> 2 votes
You should be able to accomplish this easily using the Rules module:

1. Create a rule that triggers 'After saving a new account'
2. Add a condition that determines whether the value of the field is set to the teacher value (Using 'Data Comparison').
3. Add an action element to send a notification email (System \> Send Mail).

---
Tags: users
---


# Question
Title: Concatenate fields in a view with comma when values may be empty
One can easily concatenate fields in views with a re-write rule.. However, I have two fields, `age_range` and `warning`, the second of which may be empty. I want to display them like this:

> Ages 2+
>
> Ages 4-10, choking hazard

If `warning` is empty, I don't want to show a comma. If I make a rewrite rule like this

```
[age_range], [warning]

```

Then I get a result like this:

> Ages 2+,
>
> Ages 4-10, choking hazard

How can I avoid a trailing comma?

# Answer
> 2 votes
I would actually suggest doing the reverse of the answered question that you linked to for just the scenario you are describing.

1. Add Field B and Exclude it from the display.
2. In the Rewrite results area of Field B, enable Rewrite the output of this field.
3. On Field B, add a comma and the token for the raw value: ', \[field-b\]'
4. Under 'No Results Behavior' for Field B, make sure that 'Hide if empty' and 'Hide rewriting if empty' are checked.
5. Then rewrite your Field A to include Field B: '\[field-a\]\[field-b\]'. Make sure there is no space, so that the comma will immediately follow Field A if Field B has a value.

---
Tags: views
---


# Question
Title: Non-admin user gets empty results when viewing other user data with views
I've been searching around now quite a while and couldn't find a solution that worked for me. So, here's my question:

I created a **View** that basically just a list of all users on my page. The view displays the

* User name,
* Taxonomy term and
* User location.

For admin members the view works fine, but for non admins only the location is displayed, **name and taxonomy give no results**.

And,

I checked the permissions. The user is allowed to view other user profiles. He's allowed to view published content. Changing the query settings of the view didn't work

Thanks for your help.

**UPDATE:** *In the process of elimination I checked/unchecked every single permission. The result: When I give the user the permission to* `Administer Organic groups permissions` *the user can see all the fields in the view. But I cannot allow a non admin user to administer og permissions. Any ideas why this is somehow connectd to user information fields?*

# Answer
Try the following,

There is an option in views to not take into account permissions when running the query (dunno if it is on the query level or display level though)

Edit your View at: Advanced/Query settings/, On Query settings page, check `"Disable Query Rewritting"`

**Views UI: Advanced,**

>

**Query settings page,**

>
> 0 votes

# Answer
Okay, so here is the answer:

Go to `Administration » Configuration » Organic groups » OG permissions overview » Organic groups field access` and make sure all the permissions starting with `"View ..."` are checked for members and admin members.
> 0 votes

---
Tags: views, users, organic-groups
---


# Question
Title: Proper way to package translation files with a custom module?
I have a custom module. In this module all strings are in English. However, my website is in French and when installing the custom module, I'd like the French strings to be picked up and imported automatically.

What's the best way to **generate** and then **package** the `.fr.po` translation file with my custom module?

(With D7, I would use potx to generate the `.po` file for my module, then I'd put the file under `sites/all/modules/custom/MYMODULE/translations`. But potx no longer exists for D8 and the d.org documentation isn't very helpful.)

# Answer
potx itself isn't directly available as a Drupal 8 module, but it doesn't need to.

It also works as a drush extension and can be run on Drupal 8 code. Haven't tried it if providing a translations folder still works, but I think so.

So, still works pretty much the same as in Drupal 7.
> 1 votes

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


# Question
Title: how to identify when a user is viewing their profile?
I'm relatively new to Drupal and have created a module that among other things uses hook\_menu() to add a link to a user navigation "my gallery" this all works well except this link appears when a user views another user's profile. So what i want to do is add some code to tell Drupal not to display this link when a user is not on their own profile.

I'm guessing I need to change the access callback from user\_access to a custom callback that carries out this check. Any help would be greatly appreicated.

My code so far is the following one.

```
global $user;
// get name of current user
$currentUser = $user->uid;
// get profile url
$profileUrl = arg(1);
// compare usernames to determine whether the user is on their own profile.
if ($currentUser == $profileUrl) {
  // user is on their profile, display link
  $profileUrl = "i'm home";
}
else {
  $profileUrl = "away";
}

$items['user/%user/gallery'] = array(
  'title'            => $profileUrl,
  'page callback'    => 'drupal_goto',
  'page arguments'   => array('gallery'),
  'access callback'  => 'user_access',
  'access arguments' => array('access content'),
  'type'             => MENU_LOCAL_TASK,
);

return $items;

```

The problem is it seems to get fixated, so if I start on the admin profile it correctly displays "I am home"; however, if I view another profile this doesn't change as it should. How can I fix this?

# Answer
> 2 votes
You can try `'title callback'` attribute of hook\_menu function.

```
$items['user/%user/gallery'] = array(
  'title callback' => 'get_title',
  'title arguments' => array(1),
  'page callback' => 'drupal_goto',
  'page arguments' => array('gallery'),
  'access callback' => 'user_access',
  'access arguments' => array('access content'),
  'type' => MENU_LOCAL_TASK,
);

```

And now you can call the function

```
function get_title($user_id) {
  global $user;
  $currentUser = $user->uid;
  //get profile url for that you can use $user_id as user id
  $profileUrl = arg(1);
  // compare usernames to determine whether the user is on their own profile.
  if($currentUser == $profileUrl) {
    //user is on their profile, display link
    $profileUrl = "i'm home";
  }
  else {
    $profileUrl = "away";
  }
  return $profileURL;
}

```

# Answer
> 0 votes
You can use

hook\_user\_view

> The user's account information is being displayed.
>
> The module should format its custom additions for display and add them to the `$account->content` array.

e.g

```
function MYMODULE_user_view($account, $view_mode, $langcode) {
      //Declare $user to get the global $user object
      global $user;
      // Check if logged in user id matches viewed user account
      if ($user->uid == $account->uid) {
        $account->content['summary']['gallery'] =  array(
          '#type' => 'user_profile_item',
          '#title' => t('My gallery'),
          '#markup' => $gallery,  // TODO, get account gallery markup
          '#attributes' => array('class' => array('my-gallery')),
        );
      }
    }

```

# Answer
> 0 votes
You can use the Entity Visits module for your purpose. Excerpt from its project page:

> ... tracks the users who viewed the entity.

You have to apply the patch included in the issue about "Module does not register user visits" for it to work properly.

You can also use the User Visits Advanced module for the same purpose.

> The User Visits Advanced module is a contrib module for the User Visits module. It is extremely useful for social networking sites who wish to provide their users with statistics about the number of times a the users profile page is being viewed and by which other users. See the provided screen shot how the block of this module can look like.
>
> This module comes with its own database table to store statistics per user profile (uid). At cron time, the data from the user\_visits table is collected, aggregated and stored in the user\_visits\_adv table. It stores
>
> * the total number of visits per uid
> * the number of visits of the X past days per uid
> * the most recent visitors uids of the past Y hours

# Answer
> 0 votes
What I did was is this ...

1. Go to Structure \> Panels \> Manage Pages \> User profile template \> Edit
2. Create two variants, one called "Other user profile", "Own user profile"
3. Add a selection rule for the first one (other user profile)
4. Choose PHP Code

Use this code:

```
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if (strpos($actual_link, 'users') !== false) {
return TRUE;
} else {
   return FALSE;
}

```

---
Tags: users, routes
---


# Question
Title: Search keys get variable is in subsequent search pages and so search not returning any more results
I have a small form that posts the search page. The resultant link is like this:

http://www.example.com/search/node?keys=test

Then subsequent searches don't work, because the form includes the keys variable in the form definition:

```
<form action="/search/node?keys=test" ...

```

This means that subsequent searches don't work. How do I fix this?

**Another detail** \- If I type the search page directly into the address bar, i.e. `www.example.com/search/node`, I get `"Your search returned no results"` \- suggesting it is doing a search just when accessing the page directly. I think this may be related to the issue, but I can't work out why it is occurring.

# Answer
> 0 votes
You don't need to POST to **/search/node** as all its parameters are retrieve from query parameters. As such, you can make your basic form use the GET method with your `keys` input field. For example:

```
<form action="/search/node" method="get">
  <input title="Enter the terms you wish to search for." name="keys" value="" size="15" maxlength="128">
  <input type="submit"value="Search">
</form>

```

As for the "Your search returned no results" on loading **/search/node**, that's the default behavior.

---
Tags: 8, search
---


title: Breadcrumb Preprocess from Module

text:
# Question
Title: Breadcrumb Preprocess from Module
I'm currently using the preprocess\_breadcrumb hook in my .theme file to customize the output of my breadcrumbs like so:

```
function mytheme_preprocess_breadcrumb(&$variables){
    $node = \Drupal::routeMatch()->getParameter('node');
    $current_path = \Drupal::service('path.current')->getPath();
    $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $crumbs = explode("/", $result);
    if($node){
        $variables['current_title'] = $node->getTitle();
        $variables['crumbs'] = $crumbs;
    }
}

```

I then use breadcrumb.html.twig to use these new variables like so

```
    <nav role="navigation" aria-labelledby="system-breadcrumb">
    <h2 id="system-breadcrumb" class="visually-hidden">{{ 'You are here'|t }}</h2>
    <ul class="breadcrumbs">
        {% for crumb in crumbs %}
            {% if loop.first %}
        <li><a href="./">Home</a></li>
        {% elseif loop.last %}
        <li class="current"><a href="#">{{ current_title }}</a></li>
        {% elseif crumb == 'node' %}
        {% else %}
        <li> <a href="../{{ crumb }}">{{ crumb }}</a></li>
        {% endif %}
        {% endfor %}
    </ul>
</nav>
{% endif %}

```

However I'd like it more if all this was encapsulated in a module. In mymodule.module file I have

```
function mymodule_preprocess_breadcrumb(&$variables){
$node = \Drupal::routeMatch()->getParameter('node');
$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
$crumbs = explode("/", $result);
if($node){
    $variables['current_title'] = $node->getTitle();
    $variables['crumbs'] = $crumbs;
}

```

}

But this function never fires. Is there a way to use the preprocess\_breadcrumb hook from a module?

# Answer
Preprocess hooks work in themes and modules. It doesn't matter where you put it, the only difference is, that modules have higher priority.

What you have to do is to work on caching. Because of the variables you put in, you need a cache context on `url.path`,

```
$variables['#cache']['contexts'][] = 'url.path';

```

That doesn't make a difference for the first run after clearing the cache, but makes sure that the hook is run for every new path.
> 4 votes

---
Tags: 8, hooks, breadcrumbs
---


# Question
Title: How to place a menu link in views footer?
I have created a page that displays the latest news. On the right side of the page using context module i have placed a "Recent news" block (Created using views). The recent news block shows 4 recently created news. I have added a "link" field in each item to show "Read more" on the block.

I have created another page using views which displays the complete news created so far. I call this as news archive. My problem is i have to create a "To news archive" menu in the "Recent block" last line.

# Answer
> 2 votes
You have created a view for recent news. Just add a footer to the view and then implement php **l()** function for your menu in the global text area of the footer.

# Answer
> 0 votes
You might try to use a Views theming technique.

1. On the advanced pane of your view, click Theme information and pick one of the "Display output".
2. Paste the php code into a blank php file and place it in the `YOUR_THEME/templates` directory
3. Add the code you used at the bottom of the template or at any part of the view that suits you.
4. Press the Rescan template files button in the Theme information dialog

# Answer
> 0 votes
Try the views link area module that allow you to place links in header, footer or empty text of any views.
It works exactly the same way as the link field does so it handles perfectly aliases.

Download the dev version as it provides more options like adding rel and target attributes.

---
Tags: views, 7
---


# Question
Title: How can I fix a pager limited to 2 pages?
The pager on the home page of my website is limited to 2 pages, ie the paging links are only for page 1 and 2 and both `next` and `last` point to page 2, but there are a lot more pages than that.

Is there some setting which controls this?

# Answer
You can set items per page for the Home page at `Configuration/System/Site information/FRONT PAGE` as shown in following image:

>

And you can check also how many nodes you have promoted to the frontpage at `Admin/Content`. So these two settings will allow you set all this. Hope this will work.

**Additional:**

If you want more settings for the FrontPage, you can go to `Admin/Structure/Views/` and you can see a view named `FrontPage`, that is by default disabled. But you can enable. And that view works as a FrontPage. So in views setting you can set as you want.
> 2 votes

---
Tags: 7, paging
---


# Question
Title: How to redirect to external URL upon form submission
I've extended a `FormBase` and I've defined the `submitForm` method. In this method I want to redirect to an external URL (https://example.com/my/path?amount=33&gift=0&product\_id=1)

```
$myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
$redirect = Url::fromUri($myurl);
$form_state->setRedirectUrl($redirect);

```

And I get the error:

```
Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

```

Ok, no problem, let's create one:

```
$myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
$redirect = new TrustedRedirectResponse($myurl);
$form_state->setRedirectUrl($redirect);

```

Here's the error:

```
Argument 1 passed to Drupal\Core\Form\FormState::setRedirectUrl() must be an instance of Drupal\Core\Url

```

So it appears we've gone full circle. Is there a way that maybe I can convert the `TrustedRedirectResponse` to a `Url` object?

# Answer
> 13 votes
You'll want to use `$form_state->setResponse()` instead to utilize the `TrustedRedirectResponse` you're creating.

Something like this should work:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)->toString());
  $form_state->setResponse($response);
}

```

This response may be cached depending on your page cache settings. If you need to change this behavior, you can modify the caching metadata. This should disable this type of caching completely for the response (not tested):

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)->toString());

  $metadata = $response->getCacheableMetadata();
  $metadata->setCacheMaxAge(0);

  $form_state->setResponse($response);
}

```

---
Tags: forms, 8, redirection
---


# Question
Title: How do I expose the data stored in serialized fashion?
I have a table is the database, structure of which is

```
function suggestions_schema() {
  $schema['suggested_users'] = array(
    'description' => 'Suggested Users',
    'fields' => array(
      'uid' => array(
        'description' => 'User ID of the user for which suggestions are created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'suggested_uid' => array(
        'description' => 'User Id of the stylist users being suggested.',
        'type' => 'blob',
        'not null' => TRUE,
      ),
    ),
  );
}

```

uid stores the userID and Suggested UID stores the the uid of the users in serialised fashion.

eg for the same is

```
uid - 1
suggested_uid - a:3:{i:0;s:3:"287";i:1;s:3:"293";i:2;s:3:"455";}

```

which means that uid 1 has 3 suggested uid as 287, 293 and 455.

I am exposing the data of this table in views by:

```
function suggestions_views_data() {
  $table['suggested_users'] = array(
    'table' => array(
      'group' => 'Suggested Users',
        'base' => array(
          'field' => 'uid',
          'title' => 'Suggested Users',
          'help' => 'Suggested Users'
        ),
      ),
      // UID
      'uid' => array(
        'title' => t('User ID'),
        'help' => t('User Id'),
        'field' => array(
          'handler' => 'views_handler_field_numeric',
          'click sortable' => TRUE,
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'relationship' => array(
          'base' => 'users',
          'base field' => 'uid',
          'relationship field' => 'uid',
          'handler' => 'views_handler_relationship',
          'label' => t('User Id'),
        ),
        'argument' => array(
          'handler' => 'views_handler_argument_numeric',
        ),
      ),
      // Suggested UID
      'suggested_uid' => array(
        'title' => t('Suggested UID'),
        'help' => t('Suggested UID.'),
        'field' => array(
          'handler' => 'views_handler_field_serialized',
          'click sortable' => TRUE,
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_serialized'
        ),
        'sort' => array(
          'handler' => 'views_handler_sort'
        ),
        'relationship' => array(
          'base' => 'users',
          'base field' => 'uid',
          'relationship field' => 'suggested_uid',
          'handler' => 'suggestions_views_handler_relationship',
          'label' => t('User Id'),
        ),
        'argument' => array(
          'handler' => 'views_handler_argument_serialized',
        ),
      ),
    );
  return $table;
}

```

The data gets exposed and result in views is like

```
User ID: 1
Suggested Uid: Array ( [0] => 287 [1] => 293 [2] => 455 )

```

Now, I want to create a Relationship from the serialised data(Suggested UID) so that I can access the user details(Picture, Name etc) in the views. So in order to do so I have created a relationship handler:

```
class suggestions_views_handler_relationship extends views_handler_relationship {

  /**
   * Called to implement a relationship in a query.
   */
  function query() {
    // Figure out what base table this relationship brings to the party.
    $table_data = views_fetch_data($this->definition['base']);
    $base_field = empty($this->definition['base field']) ? $table_data['table']['base']['field'] : $this->definition['base field'];

    $this->ensure_my_table();

    $def = $this->definition;
    $def['table'] = $this->definition['base'];
    $def['field'] = $base_field;
    $def['left_table'] = $this->table_alias;
    $def['left_field'] = $this->real_field;
    if (!empty($this->options['required'])) {
      $def['type'] = 'INNER';
    }

    if (!empty($this->definition['extra'])) {
      $def['extra'] = $this->definition['extra'];
    }

    if (!empty($def['join_handler']) && class_exists($def['join_handler'])) {
      $join = new $def['join_handler'];
    }
    else {
      $join = new views_join();
    }

    $join->definition = $def;
    $join->options = $this->options;
    $join->construct();
    $join->adjusted = TRUE;

    // use a short alias for this:
    $alias = $def['table'];

    $this->alias = $this->query->add_relationship($alias, $join, $this->definition['base'], $this->relationship);

    // Add access tags if the base table provide it.
    if (empty($this->query->options['disable_sql_rewrite']) && isset($table_data['table']['base']['access query tag'])) {
      $access_tag = $table_data['table']['base']['access query tag'];
      $this->query->add_tag($access_tag);
    }
  }
}

```

Now if I add this relationship, the views query becomes:

```
SELECT suggested_users.uid AS uid, suggested_users.suggested_uid AS suggested_users_suggested_uid
FROM {suggested_users} suggested_users
INNER JOIN {users} users ON suggested_users.suggested_uid = users.uid
WHERE (( (suggested_users.uid = '1' ) ))
LIMIT 5 OFFSET 0

```

But what I want is that the data in the suggested\_uid(data stored in the serialised fashion) should behave as an individual data set. Eg for the same is

**Views Row 1**

> uid - 1
>
> suggested UID - 287

**Views Row 2**

> uid - 1
>
> suggested UID - 293

**Views Row 3**

> uid - 1
>
> suggested UID - 455

One of the way to achieve this is to create a SQL view (https://www.drupal.org/node/2458947).

Can someone please help me to figure out what's the optimal way to achieve this? Is there any other way using which I can show achieve this?

Thanks

# Answer
> 1 votes
> But what I want is that the data in the suggested\_uid(data stored in the serialised fashion) should behave as an individual data set.

If you're trying to query specific values from a serialized data field, you're going to encounter difficulties when querying for that data.

I'd suggest revising the database schema for your one to many relationship.

For example:

```
/**
 * Implements hook_schema
 */
function suggestions_schema() {
  $schema['suggested_users'] = array(
    'description' => 'Suggested Users',
    'fields' => array(
      'uid' => array(
        'description' => 'User ID of the user for which suggestions are created.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'suggested_uid' => array(
        'description' => 'User Id of the stylist users being suggested.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('uid', 'suggested_uid'),
    'indexes' => array(
      'uid' => array('uid'),
    ),
    'foreign keys' => array(
      'user' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid', 'suggested_uid' => 'uid'),
      ),
    ),
  );
}

```

This is similar to what Drupal core does for the `users_roles` table, matching UID to RID.

Another perhaps easier way to do it (less custom) is to simply add an entity\_reference field on the user account to reference the other "suggested users"

---
Tags: 7, views
---


# Question
Title: How to display vocabulary terms and their descriptions with their tagged content in a view?
Say I have two terms in a vocabulary, and I want to display their titles and descriptions, along with a list of nodes which have been tagged. Here's an example:

Page Title: Services

```
Term Name: Medical
Term Description: We're the best doctors in town!
Content tagged with term: Brain Surgery, Leg Amputation

Term Name: Business
Term Description: We'll make you rich!
Content tagged with term: Accounting, Management, Bookkeeping, Strategy

```

How could I accomplish this using Views in Drupal 7?

I've tried creating a term view, adding the term name and term description fields, enabling a relationship for 'Content with Term', adding a field for 'Content: Title', and grouping by Term name with 'Use rendered output to group rows' disabled, but I still get a ton of duplicates.

Any way to resolve this?

## Debunked Methods:

**Use aggregation!** \- Nope, this results in something like this (not what we're after here):

```
Term Name: Medical
Term Description: We're the best doctors in town!
Content tagged with term: Brain Surgery

Term Name: Medical
Term Description: We're the best doctors in town!
Content tagged with term: Leg Amputation

```

**Use the Views Distinct module!** \- Nope, nothing here seems to work either.

# Update

Jimmy's Answer works well for my situation. Alternatively, I also believe that creating a custom display for your taxonomy and developing a field that displays related content based on TID could circumvent your need for views at all. If you're desperate and less paranoid about logic-less templates, you could do that heavy lifting in your theme (don't do this).

# Answer
If you don't mind using some other contrib modules with views, Views Field View can be the best solution.

## Create content views

First, create a content views to list the content title which contains the taxonomy term, add field ***Content: Title*** and add the taxonomy term field as contextual filter. (e.g. ***Content: Tags*** (field\_tags) in screenshot)

> ***Use aggregation*** is to remove the duplicated content because same term can be attached on one content more then once.

## Create taxonomy term views

Second, create a taxonomy term views to list the ***Taxonomy term: Name*** and ***Taxonomy term: Term description*** under a vocabulary, which is similar to the one you have created.

> BUT, you **don't need** to add the relationship ***Content with Term*** neither the field ***Content: Title***

Field ***Taxonomy term: Term ID*** is used as contextual argument, so exclude it from display.

## Attach views field view

Add a views field, select the taxonomy term view you created and place `[!tid]` as the argument of Contextual filters.

## Result

All required data is ready now, you may need to override the views template files for modifying the output.

## Performance

> This method involves multiple views, the performance may become an issue if there are many contents and terms. You should enable the time-based cache on the content views.
> 4 votes

# Answer
I guess this has already answer. You can follow following answer where it has been prepared using Views module.

Displaying Drupal taxonomy term desciption in node
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to add a "read more" link on User profile teaser display?
I'm using Drupal 8 and I want to have a "Read More" Link on my User profile, that links from the Teaser display to the Full display. How can I do that?

Content types for nodes bring the "Links" field out of the box on the teaser display.

# Answer
This you can do using Views and providing the code for Link on User page, follow following steps.

**1.** **Creating the Complete User profile at default Drupal account page:**

1.1 Add the all the fields on the Default user-profile what you want on fullDisplay(Admin/Configuration/Account setting/Manage field). So any user when creates a account, he will have all section to fill-out. For example My Full user-profile has the following fields.

* Name
* Picture
* Bio

**2.** **Create the teaserDisplay**

2.1 Hide the fields which you do not want on the teaserDisplay. So, on the User-profile setting page(Admin/Configuration/Account setting/Manage Display), now hide what you do not want to show on Teaser Display. Now for my setting I want to Hide Bio. So I will just hide this field at Manage Display.

So current user-profile field settings are:

* Name
* Picture
* Bio - *Hidden*

*Now, till this stage, we set our Drupal's default account page as teaserDisplay but simultaneously we created those fields which we want on fullDisplay, hence we kept hidden but we will display all those hidden fields using Views.*

**3.** **Create the Views-fullDisplay**

3.1 Create a new view page, Select USER under Views setting. Under pager, choose 1 item. 3.2 Now on the setting page, add all following setting as shown in teh following image. So here we are accessing that Bio field which we hide on User profile page.

>

* Contextual filter setting: Under contextual setting select `User: User ID` and under that select `Display all results for the specified field`.
* Path: Now as shown in the view set the path `/user/%/view-page`. I have kept last part here, `/view-page` as I was just trying previously, you can change to `full-profile`, but you have to change that at all places.

**4.** **Setting the Link on the teaserDisplay page (so we can re-directed to fullDisplay)**

To provide the link, the link should take the User-Id from the URL and can able to pass that User-Id in views URL, so Views contextual filter can provide the result of that User, from where we have redirected. Hence, to solve this I raise separate question and you can follow answer as shown below. I am not providing answer as you have to just copy from there.

@ShawnConn has provided answer for how to add link on user-page. Full Credit goes to @ShawnConn for this answer.

How to get current path for user profile field?

**5.** **Output Image:**

**teaserDisplay- Default User Page**

>

**Full Display - Views with bio field**

>

*Now, this way you can add as many as field you want, just hide them so they does not display on teaser display and show in views so they display on fullDisplay page.*
> 2 votes

# Answer
What you can do is create your own custom teaser.

1. In Views, change FORMAT from Show: Teaser to Show Fields.

2. Add fields, title, use pic, user bio (for formatter you could use Summary or trimmed), and any other field you want.
3. Add **User ID** or **User Name** as a field. (depending on how your full profile view url is /fullprofile/\[name\]? or /fullprofile/\[uid\])

* Then rewrite the output of this field `<a href="/fullprofile/{{ uid }}">Read more</a>` OR with `{{ name }}`

Your full profile page view url should be like this `fullprofile/%` with a contextual filter of User ID or User Name that picks up the second url as parameter.
> 1 votes

---
Tags: users, 8, navigation
---


# Question
Title: How to change datatype of field in database table from varchar to int?
I have created custom table. Now I want to change datatype for a particular column in table. Column name is 'session\_number' and its current type is `varchar`. I want to change it from `varchar` to `int`. I used this to do so :

```
function mymodule_update_7053(&$sandbox) {
  db_change_field('abc', 'session_number', 'session_number', array(
    'type' => 'int',
    'size' => '255',
    'not null' => TRUE,
  ));
  drupal_flush_all_caches();
}

```

It doesn't change existing type from `varchar` to `int`. How to do it please guide.

# Answer
You must have some error message if the conversion is not accepted.

You first have to validate that this field is not a key or an index. See the db\_change\_field documentation about this.

After, I think 255 is not a valid value for the size key. The Schema API documentation tell :

> 'size': The data size: 'tiny', 'small', 'medium', 'normal', 'big'. This is a hint about the largest value the field will store and determines which of the database engine specific datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT). 'normal', the default, selects the base type (e.g. on MySQL, INT, VARCHAR, BLOB, etc.). Not all sizes are available for all data types. See DatabaseSchema::getFieldTypeMap() for possible combinations.

And finally, I'm not sure if the DB engine can support the VARCHAR to INT conversion. Then it means your column will be empty and cannot support the 'not null' =\> TRUE property.

Maybe you have to do this in more than one step.
> 1 votes

# Answer
According to Data Types, for the column type `int`, `size` only allows following value:

* `tiny`
* `small`
* `medium`
* `big`
* `normal`

If you put `256` as value, you will get below error message.

> SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that \[error\] corresponds to your MySQL server version for the right syntax to use near 'NOT NULL' at line 1

So the correct one should be:

```
function mymodule_update_7053(&$sandbox) {
  db_change_field('abc', 'session_number', 'session_number', array(
    'type' => 'int',
    'size' => 'normal',
    'not null' => TRUE,
  ));
  drupal_flush_all_caches();
}

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: Combination of textfields and checkboxes in a custom form
I need to create a custom form that contains a list of checkboxes and textfields next to each other, as in:

There are many meal items in the list. Right now I'm using something like:

```
$form[$meal_type->sku] = array (
    '#type' => 'fieldset',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form[$meal_type->sku]['meal'] = array (
    '#type' => 'checkbox',
    '#title' => $meal_type->title,
    '#return_value' => $meal_type->sku,
  );
  $form[$meal_type->sku]['quantity'] = array (
    '#type' => 'textfield',
    '#default_value' => 1,
    '#size' => 5,

  );

```

This creates an individual fieldset for each meal item and quantity. I just wanted to see if there are any suggestions for a better approach. Thanks!

# Answer
> 2 votes
I ended up using a `'#type' => 'container'` instead of `fieldset`. And I used `#prefix` and `#suffix` in the children to add specific classes for spans and horizontal alignment etc.

One other thing that seemed useful but I ended up not using: template files for form theming. This is a very useful tutorial:

http://themery.com/dgd7/advanced-theming/forms/with-templates

---
Tags: 7, forms
---


# Question
Title: How to prevent multiple votes in polls of the rate module?
I have installed the rate module, and set the emotion widget. I like this module but after I vote successfully, I can click the vote button again. Instead I want to popup a window which says" you have voted. don't vote again", to prevent people from voting multiple times.

# Answer
> 4 votes
The rate module hasn't built support for this. If you wanted to do this, your best option would be to

* Deny duplicate votes, it's up to you to decide how, but you could check the voting api table which stores the IP addresses of all who have voted then use `rate_vote_alter` hook. Doing it this way would make it impossible to change the vote.
* The other option is to use `rate_vote_alter` to stop the rate module from saving votes and do it yourself with `votingapi_set_votes`. That would make it possible to set criterias for which (old) votes should be deleted.

This could have been done easier if the rate module was built more flexible. You could consider making an issue and a patch for the rate module, to add this feature for others to use.

**Update:**
The alter hook is not defined anywhere, but done with `drupal_alter('rate_vote', $votes, $context)`. This means you should be able to do:

```
function my_module_rate_vote_alter(&$votes, $context) {
  ..
}

```

# Answer
> 0 votes
This is an example on how not saving the vote in the database.

```
function my_module_rate_vote_alter(&$votes, $context) {
  // Check the database.

  $context['save'] = FALSE;
}

```

# Answer
> 0 votes
Working code for folks:

```
/**
 * Implements hook_rate_vote_alter().
 */
function mymodule_rate_vote_alter(&$votes, &$context) {
  $cookie = $votes['tag'] . '_' . $votes['entity_type'] . '_' . $votes['entity_id'];
  // If the cookie is already set.
  if (isset($_COOKIE["$cookie"])) {
    // Indicating not to accept this vote.
    $context['save'] = FALSE;
  }
  else {
    // Set cookie and make sure that its valid for next 30 days.
    // This will populate the $_COOKIE["$cookie"] and make sure to block the
    // vote if user is trying to vote it more than once.
    setcookie("$cookie", 'ratevote', time() + (60 * 60 * 24 * 30), '/');
  }
}

```

hook\_rate\_vote\_alter() is available at rate.hooks.inc

---
Tags: 7, rating
---


# Question
Title: Update custom user fields programatically
how can I update custom user fields programmatically?

I've tried this but don't know how to get Id because I have to execute this code automatically on page load ..

```
$existingUser = user_load($uid);
$edit = (array) $existingUser;
$edit['field_company_name']['und'][0]['value'] = 'Ciklum';
user_save($existingUser, $edit);

```

# Answer
It should be something like this:

```
$existingUser = user_load($uid);
$existingUser -> field_company_name['und'][0]['value'] = "Ciklum";
user_save($existingUser);

```
> 10 votes

---
Tags: 7, users
---


# Question
Title: How to add only "Add to Cart" Button in a view
I have a view with all my product. My view display is TABLE. I'll want add a column where insert only "Add to Cart" button.

How can i do it?

Thanks

# Answer
If you are adding fields, just add **Add to Cart Form** field in the view. Attaching my view image just for your reference.
> 1 votes

---
Tags: views, commerce
---


title: Drush: Permission denied outside htdocs

text:
# Question
Title: Drush: Permission denied outside htdocs
I've been trying to solve this problem for hours now.

I successfully installed Drush locally and it works fine when I'm using it within XAMPP's htdocs folder. However, I want to move the Drupal folder to a virtual host outside htdocs. When I run drush inside the new folder, it says:

```
$ drush status

PHP Warning:  pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///usr/local/bin/drush/includes/startup.inc on line 359

Warning: pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///usr/local/bin/drush/includes/startup.inc on line 359
Error has occurred executing the Drush script found at /Users/ivan/drush
(errno 13) Permission denied

```

Tried to change folder owner to admin group, chmod -R 777 - nothing worked. I am running on OS X 10.11.6 and XAMPP 5.6.12.

Thank you for any help.

# Answer
> 5 votes
It seems you have two Drush installations - `/Users/ivan/drush` and `/usr/local/bin/drush` I'm guessing that `/Users/ivan/drush` isn't executable and hence causing the error. I suggest just removing `/Users/ivan/drush`.

---
Tags: drush, files
---


title: How do I reset the clean URLs?

text:
# Question
Title: How do I reset the clean URLs?
Another developer has sent me a completed Drupal 7 website. When I installed it, the home page uses clean URLs, which don't work; example.com/index.php?q=/node/123 does work.

When I go to example.com/index.php?q=admin/config/search/clean-urls, there is not a check box to turn clean URLs on. Is there a way to disable the clean URLs, and start the process again?

# Answer
> 10 votes
When clean URL are enabled, the page at admin/config/search/clean-urls is like the following one:

When clean URLs are not enabled, you should see a description such as the following one, and a button to test the clean URLs ("Run the clean URL test"):

> Use URLs like `example.com/user` instead of `example.com/?q=user`. If you are directed to a *Page not found (404)* error after testing for clean URLs, see the online handbook.

Once you click on the submission button ("Run the clean URL test"), Drupal would check if the clean URL are possible to enable, and show you the checkbox to enable them, which should be not selected. If that doesn't happen, the online handbook reported in the description has a link to How do I unset the clean URLs? where three methods are listed:

* Run the following Drush commands:

```
    drush vset clean_url 0 --yes

```
* Run the following MySQL commands:

```
    UPDATE variable SET value = 's:1:"0";' WHERE name = 'clean_url';
    TRUNCATE cache;

```
* If previous update statement didn't solve it, some drupal version may need a different key :

```
    UPDATE variable SET value = 'i:0;' WHERE name = 'clean_url';
    TRUNCATE cache;

```
* Alternatively, you can modify the appropriate settings.php file to include the following line at the bottom (or similar code in the site settings array you'll see there).

```
$conf['clean_url'] = 0;

```

# Answer
> 3 votes
seems exist some ways to disable and start again:

one way in settings.php

```
$conf = array(
    'clean_url' => 0,
);

```

other way (database):

Browse on "variable" table in Drupal database, and change the value of "clean\_url" from s:1:"1"; to s:1:"0";

you can confirm this here http://drupal.org/node/5590

# Answer
> 0 votes
A common cause for clean URLs not working on a site you received from another developer is that the .htaccess file that comes with Drupal got lost in transmission somewhere (e.g. when someone copied the site by dragging and dropping files; .htaccess would be a hidden file, or when someone does a "cp -R \*" - again, .files left out). It is required to have the web server translate the clean URLs the site generates because of the setting in something that the Drupal router can actually understand.

---
Tags: uri
---


# Question
Title: How to set permissions to a particular role?
I want to create an ***IT role***. Superadmin should only create this IT role and enable or disable the permission for this role anytime (which roles this Superadmin can assign to the users), if this admin wishes to. ***IT role*** should not be permitted edit any of the users.

The Superadmin will decide which roles an IT person (IT role) can assign to users. Users with role IT role can not assign the roles above their position, this is a simple funda. For example, such users (with the IT role) cannot assign ***Admin role***.

Superadmin designed the IT role in such a way that he can assign Forum Admin, Writer and Writer Admin. Hence, he can assign these roles he wish to.

Permissions to setup for IT roles:

* Such user can create a users.
* Such user can block or activate the users.
* Such user can assign the existing roles to the users he wants and can revoke it.
* Such user cannot delete.

# Answer
> 3 votes
Looks like you should try the Role Delegation module. Some details from its project page:

> ... allows site administrators to grant specific roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
>
> The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions on the permissions page.

# Answer
> 3 votes
In addition to @Pierre.Vriens answer, You can look at following modules to fine-tune your need, if you are dealing with multiple admin roles.

**1.** Administer Users by Role

> This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

**2.** Role assign

> RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.

Both module has D7 and D8 version. In case what you are using.

---
Tags: users
---


# Question
Title: Insert value into field before and after specific string
I need help with update function.

I have database table with three fields. One of them is code field with html div and script. Example: `<div id='id1'></div><script type="text/javascript">/* Banner */</script>` My problem is, how am i supposed to insert some condition inside script tags and to end it before closing script tag? How should i write `db_update` to accomplish that?

Thanks in advance.

# Answer
> 0 votes
Sounds like you should be parsing the field with a regex function that matches the content between the script tags. Then you can rebuild your string and update the row.

http://regexr.com/3du5i for an example

# Answer
> 0 votes
Well, after some time, i have found a solution with `drupal_substr`. First cut off the starting part and ending part and after that just take out the middle part and wrap it in a new variable with conditions between the parts.

---
Tags: database, updating
---


# Question
Title: How to sort only own webform submissions in a view?
I have a view that lists all users webform submissions.

I want to be able to have the view show the name of the user instead of his id and display only his own webform submissions.

**Image-1**

>

# Answer
> 1 votes
The solution was to specify as Filter criteria "webform submission:user " and in fields I added the same criteria. Then I customized it by creating a label name.

The video tutorial Drupal Views Module: Creating lists of content on your Drupal site really helped me discovering Views and find an answer to my question (I recommend it for every beginners like me).

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


# Question
Title: Override Theme table function used in contributed module?
There is function used in Ubercart module :

```
function theme_uc_recurring_user_table($variables) {
    ........
}

```

I want to override result of this function and did by below method in `template.php` file of my theme:

```
function MYTHEME_preprocess_table(&$variables) {
  global $user;
  if ($user->uid) {
    if (current_path() == "user/me/recurring-fees") {
      if(!$variables['header'][7]) {
        $variables['header'][7] = "Donation";
      }
      if(!$variables['rows'][0]['data'][7]) {
        $variables['rows'][0]['data'][7] = l('Update Donation', '/donation');
      }
    }
  }
}

```

I just added table column header and data below that. But I did this by current path but I think there must be some right approach.

I am trying to find but not able to figure out how exactly we can achieve this.

Please suggest !! Thanks

# Answer
> 2 votes
`theme_uc_recurring_user_table()` **is** a theme hook (not a table function), and its preprocess function is `hook_preprocess_uc_recurring_user_table()`.
From the preprocess function you can just change the content of `$variables` which, in the case of `theme_theme_uc_recurring_user_table()` just contains `$variables['uid']`.

What you need to do is overriding the theme hook implemented from the module, which is quite easy, since you are doing it from a theme.

```
function MYTHEME_uc_recurring_user_table($variables) {
  $uid = $variables['uid'];
  drupal_add_css(drupal_get_path('module', 'uc_recurring') . '/uc_recurring.css');

  // Set up a header array for the table.
  $header = array(t('Order'), t('Amount'), t('Interval'), t('Next charge'), t('Status'), t('Remaining'), t('Options'));

  if ($GLOBALS['user']->uid) {
    $header[] = t('Donations');
  }

  $recurring_states = uc_recurring_fee_status_label();

  // Build an array of rows representing the user's fees.
  $rows = array();

  foreach (uc_recurring_get_user_fees($uid) as $fee) {
    // Get the user operations links for the current fee.
    $ops = uc_recurring_get_fee_ops('user', $fee);

    // Add the row to the table for display.
    $rows[] = array(
      'data' => array(
        l($fee->order_id, 'user/' . $uid . '/order/' . $fee->order_id),
        theme('uc_price', $fee->fee_amount),
        array(
          'data' => check_plain($fee->regular_interval),
          'nowrap' => 'nowrap',
        ),
        format_date($fee->next_charge, 'short'),
        '<span class="recurring-status-' . intval($fee->status) . '">' . $recurring_states[$fee->status] . '</span>',
        $fee->remaining_intervals < 0 ? t('Until cancelled') : $fee->remaining_intervals,
        array(
          'data' => implode(' | ', $ops),
          'nowrap' => 'nowrap',
        ),
      ),
    );
  }

  if (empty($rows)) {
    $rows[] = array(array(
        'data' => t('Your account has no recurring fees.'),
        'colspan' => 7,
      ));
  }
  elseif ($GLOBALS['user']->uid) {
    $rows[0]['data'][] = l('Update Donation', '/donation');
  }

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

```

---
Tags: 7, theming, ubercart
---


# Question
Title: Why does my select list not translate to another language in Views?
I have a View for **Search in property**, which has many fields and some of them are drop-downs (select lists).

When I switch the language to *Arabic*, everything is translated, but the drop-down is still in English (= default language).

I performed these steps:

* I translated my select list in Manage fields and translate the options there
* then I put them in Manage display to default translated.

But it's not working. Check the image for more details:

Any ideas about how to solve this problem?

# Answer
> 3 votes
I found the answer for this finally ...

After doing all the steps like the image that I attached before, you should delete the old FILTER CRITERIA and add the New translated one to make the select list translate :

After doing so, the select list will be translated.

---
Tags: views, i18n-l10n
---


# Question
Title: error while installing RESTful Web Services and HAL module
I'm trying to install RESTful Web Services and HAL Module in Drupal 8 core , but it is showing the following error.

> ERROR: The always\_populate\_raw\_post\_data PHP setting should be set to -1 in PHP version 5.6. Please check the PHP manual for information on how to correct this. (Currently using always\_populate\_raw\_post\_data PHP setting version Not set to -1.)

Can anyone help me?

# Answer
The error message says you should put this in php.ini.

```
always_populate_raw_post_data=-1

```

If you don't have access to the PHP configuration, this is also possible in .htaccess.

```
php_value always_populate_raw_post_data -1

```

This only works if the web server admin allows to override options in .htaccess.
> 3 votes

---
Tags: 8
---


# Question
Title: Impossible to edit nodes, log to in etcetera after enabling Boost and editing .htaccess
After installing and enabling Boost in my Drupal 7 site (locally on WAMP and I also tried it on a remote test site) it's not possible to send any forms, e.g. not possible to edit and save nodes, not possible to login etcetera.

The actual Boost caching works though. When I remove the generated htaccess rules from my .htaccess file, everything works as normal again (except that the Boost caching stops to work of course).

My guess is that it's something in the generated htaccess rules that my site does not approve of.

Here is how the added rows look like:

```
  ### BOOST START ###

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

#  # Apache 2.4 bug workaround
#  # Enables Search from home page https://drupal.org/node/2078595#comment-8724321
#  RewriteCond %{REQUEST_METHOD} ^(POST)$
#  RewriteCond %{REQUEST_URI} /
#  RewriteRule .* / [S=3]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTPS} on [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=2]

#  # Apache 2.4 bug workaround
#  # Enables caching of index/ home page
#  RewriteCond %{REQUEST_URI} ^/index\.php$
#  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}/\_%{QUERY_STRING}\.html -s
#  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}/\_%{QUERY_STRING}\.html [L,T=text/html]

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

  ### BOOST END ###

```

Anyone who can help?

# Answer
I finally found out that my question had an answer in this thread.

So I went back to Boost version 1.0, generated the htaccess code, pasted it in my .htaccess file and then updated to version 1.1 again (without changing the .htaccess file). Now everything seem to work fine.
> 0 votes

---
Tags: 7, .htaccess, caching
---


# Question
Title: Replacement pattern in view field template
I have a body field view template:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

```

What I want is:

```
if nid == 1
print $output =  view_embed_view('my custom view')
else
print $output;

```

How can we do this?

**Note**: I'm already using the Views Field View module, but can't figure out as how to apply this condition of nid.

# Answer
In view template file of body field, write this code;

```
$nid = $row->nid;
$body = $row->body;
if($nid == 1):
  $view = views_get_view('VIEWS_MACHINE_NAME');
  $view->set_display('DISPLAY_ID');
  $new_view = $view->preview('DISPLAY_ID');
  print render($new_view);
else :
  print $body;
endif;

```
> 4 votes

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


# Question
Title: What is the best (secure) way to run PHP code on a Drupal 8 system?
I am pretty new with Drupal. I have installed Drupal 8.17 on my webserver and now I am configuring it.

It runs on Ubuntu 16.04 with Apache 2.4 and PHP-7.0, the DBMS is PostgreSQL 9.5.

I would like to execute some PHP code is some pages. I have read that there was `PHP Filter` in Drupal 7, but it is now moved to modules and it warns user than:

> **Warning** Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site. There are better alternatives out there that do not expose such vulnerabilities on your site.

But I cannot find any alternative over the web. Then I found Drupal SE, and I am asking for user advice: **What is the best way (I mean secure way) to run PHP code on a Drupal 8 system?**

I must connect another PostgreSQL DB, perform query on it and display results in Drupal. Essentially this will be done in pages that only administrator can read an modify.

# Answer
> 4 votes
Some Drupal devs are keen on **never** putting PHP code in the Database, but this means you will have to know the intricacies of Drupal 8 in order to figure out how to expose what you need by creating a custom module. This can be a time sink if you just want to do something super simple.

But if you aren't that hardcore, turning on the PHP is fine if you just don't have the time or need to create a custom module to say print something out from the $user array.

I personally just use the PHP module on my sites. It's quick and efficient vs making a custom module. Obviously deciding on which approach to take depends on the site and client your working with. Does it have valuable user data? Does it have millions of user hits a day? Or is it just a purely informational site with only a few hits a day? Do you think the client would mess around with other parts of the site or are they just purely just updating content?

---
Tags: blocks, external-scripts
---


# Question
Title: How to give to the creator of a node the option to hide the name of the author?
I need to provide a way for hiding the name of the user who created a node, if the creator of a node wants to do so. In such cases, it should show *Anonymous* as the author of the node.

Any suggestions about how to implement this?

# Answer
There are a few things in the original version of this question that really need review ...

> Content may add only authorized users on my site.

In Drupal you cannot have content that adds users, so I'm going to assume it's rather the opposite you're looking for, ie: "*Content may **only be added by** authorized users on my site*".

> I need to implement the functionality (option) of hiding a user name (author of сontent) if user wishes it.

Unless you have special customizations in place in your site, Drupal allows for ***multiple (authorized) users*** to author (change) content. So your "***if user wish it***" is a not clear enough: maybe you mean "the original author" (who first created the node), or maybe you mean "the user who last edited (changed) the content". For the sake of simplicity, I'm going to assume "the original author".

> That is, to make him/her "the anonymous author of" сontent.

If you agree with my above assumptions, here is a blueprint of how you could implement this:

1. Add a custom field to your content type, which is a boolean (true/false, yes/no, 0/1, whatever fits) that can be used when creating a node to have the original node author indicate if author should be shown (yes) or marked as "anonymous" (no).
2. Use the Rules module to ensure that the "Authored by" value always remains the "original node author" (who created the node). This basically ensures that attempts to change the node author (similar to what is suggested in codenext's answer) will be rejected. Only using Rules should be sufficient to implement this (rather basic) validation. But if needed (to further enhance these validations), add the Rules Forms Support module.
3. Use a preprocess function in your theme (similar to what is suggested in Zuzuesque's answer) to actually display the node author as requested by ... the original node author.

Note that if the original node author ever want to change his/her mind, that's still possible with this approach: just change the value of the custom field value as desired (after doing so, the logic in step 3. will ensure it's processed accordingly).
> 3 votes

# Answer
What you need is provided by Default in Drupal,

>

If I write my name: it will show:

```
Submitted by codenext on Wed, 07/20/2016 - 11:14

```

If I leave blank: it will shown:

```
Submitted by Anonymous (not verified) on Wed, 07/20/2016 - 11:14

```
> 2 votes

# Answer
I am not sure if there is a single 'best way' to do this. An easy way would be to add a boolean field to your content type and call it something like 'post anonymously' or 'hide my username'.

Then it depends where you want to show the information. If you are using the Views Module this is particular easy:

1. Add the field for user name and hide it from display.
2. Add the boolean field.
3. Under the no result behavior of the boolean field (check the option to count 0 as an empty field) and output your username + any optional text like authored by.
4. Rewrite the boolean field and add your text for anonymous authors.

**If you are not using Views** you will want to use a proprocess function to manipulate the part of the page you display the author name on - e.g.: if you want to change how the author is shown on the node itself use `template_preprocess_node(&$variables)`:

```
YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if($node->type == 'your_node_type') {
    //change text if author wants to stay anonymous (else keep original)
    if ($node->field_your_bool_fieldname[0]['value'] == 1) {
      $variables['submitted'] = t('Submitted by anonymous on !datetime', array('!datetime' => $variables['date']));
    }
  }
}

```
> 2 votes

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


# Question
Title: Display Suite: Edit tab missing on user profile
Using Display Suite (DS), I've overridden the `user profile page` in order to create a custom layout. However, the edit tabs that would normally appear when a user is logged in are no longer visible. How can I add them back?

I'm not sure if it's a factor, but I'm also using a custom-made Panels template within DS. Since I'm only using this layout on the user profile, I'm open to adding the edit tabs directly to the template, if possible.

I'm open to any methods that would be considered "best practice". Thanks in advance!

# Answer
> 1 votes
Further answers are welcome, however, I eventually found an easy solution to this issue. Because **Display Suite supports tokens**, I was able to create a custom field that outputted an edit button. Here's an example of the html I used: `<a href="[user:edit-url]"><i>CUSTOM ICON</i></a>`.

In order to hide this icon from unauthenticated users, I enabled **field permissions** which is available when the **Display Suite Extras** module is enabled. Once enabled, you can adjust what fields are displayed for each user role in the permissions menu. Hopefully this is helpful to anyone experiencing a similar issue.

# Answer
> 0 votes
I do not know, how you are overriding. Hence suppose for trial, I want to divide the layout in Left and right and, put some fields in right and some in left side. And moreover, the Number of article authored by the user, which you had created using views as a block in your previous question. That view block I added using DS(Add block field) in right-bottom. I did all things using Manage display tab which is being added by default on each node by DS.

Now, this all I did using DS and on User page. I am posting screen-shop of that. I have every setting tabs as it was previously including Edit tab. I do not see any interference by DS. Could you please explain your method? I do not think you need anything else, you can set layout using only DS.

>

---
Tags: 7, theming, display-suite
---


title: Update module to dev without Drush

text:
# Question
Title: Update module to dev without Drush
Is there a simple way to update a module to the dev version without Drush? Ideally, within the admin console, but I could also use ssh to manually loa the files to the correct places. For the purposes of this question, assume Drush sadly doesn't exist.

# Answer
Drush is a very useful tool and it will take some tasks from your hands, including running update.php after updating a module.

However if you cannot (or do not want to) use Drush, there are plenty of other options to update modules. You can use FTP to delete the module folder and then upload a new version of the folder. You can use SSH to obtain the module zip file by using `wget` and then delete the module folder and extract the zip file. Basically any possible way to get the contents of the zip file to your destination is a valid updating method.

Keep in mind that you cannot always safely unzip one module directly over another one. Always delete or empty the previous module version first. The reason for this is that several (class) files might have been removed from the module, but would not get removed from the file system this way. Drupal's registry might still load these files but then find another class with the same name in another file, resulting in fatal errors.

And no matter how you update the modules files, always stick to the regular updating instructions. This includes always running `update.php`.
> 2 votes

---
Tags: 7, updating, ssh
---


# Question
Title: Custom theming: How to list multiple content types in the same page and use regions too
I created two content types: **articles** and **press releases** and I want to display those in the same page. I also am developing a custom theme.

So I created a view for that with the machine name `press_release_list`, created a template for it: `views-view--press-release-list.html.twig` and it works perfectly.

The problem is, I cannot make use of regions. I mean, I have `content` and `side_menu` regions and I want to add a twitter feed to the side menu. I add the block through "block layout" menu, it can be configured to be displayed on **article** and **press release** nodes however there is no option for the view I created...

I'm quite new to Drupal so what would be the best way to do this, is there a way to display the block on the view or is there a better option than creating a view?

# Answer
> 0 votes
In block layout the visibility for content types works only, if the content type is a route match. That means, you have requested a node with that specific content type through the url.

It does not work for nodes that are displayed as result of a view.

To configure the visibility for a view you can define in the tab "Pages" the url of the view or a pattern of urls, that matches multiple views.

---
Tags: views, theming, 8
---


title: Disable cache for one JS file / library

text:
# Question
Title: Disable cache for one JS file / library
I'm using Drupal 8.1.7 and use group module. When a user display a group or an article linked to a group (/group/... or node/...), I want to specify some specific CSS for each group.

I develop a module that do the trick (verify if we display a group or an article, get the group and load a JS file that modify the CSS style of the page). Work great on my dev drupal with no cache, but when I test the module in production with cache active, the JS file seems to be load only once. Have to do a `drush cr` to load again the file.

There is any way to tell Drupal to load the file everytime, or don't put it in cache ? In the mymodule.libraries.yml maybe ?

```
color:
  js:
    js/mymodule.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings
    - core/drupal

```

# Answer
> 1 votes
With the current approach, you want your JS file to be loaded globally so either custom module, or directly in the theme.

However this is not the best solution. What you want is to preprocess the node, check if it belongs to any group and add identifying classes. With that you can then target with CSS.

If you really want to go the difficult, look at `#lazy_builder` placeholders. This blog post has a nice explanation.

# Answer
> 3 votes
I can not believe that you will have one different JS for every group. So caching is cool, and I assume your problem is the triggering of a function in the JS.

You can use the Drupal.behaviors to call a function in your JS everytime a page is loaded, i.e.

```
(function ($, Drupal) {

  Drupal.behaviors.anyInit = {
      attach: function () {
        myInitFunction();
      }
  }
})(jQuery, Drupal);

function myInitFunction() { do something }

```

And you can pass variables to the JS (like your group name), by attaching them to your rendering array, like so:

```
$build['#attached']['library'][] = 'bootasde/asdejs';
$build['#attached']['drupalSettings']['bootasde']['proreos_server'] = SystemTools::getProreosServer();
$build['#attached']['drupalSettings']['bootasde']['checktyp'] = 'a';
$build['#attached']['drupalSettings']['bootasde']['id'] = $id;

```

Then you access that variables in your JS like:

```
  var server = drupalSettings.bootasde.proreos_server;
  var id = drupalSettings.bootasde.id;
  var tp = drupalSettings.bootasde.checktyp;

```

Hope that helps.

Another way could be to add the group names to the CSS classes in your twig template and have some special selectors for each groupname.

---
Tags: 8, caching, theming
---


# Question
Title: Installed a module, broke my site. And now I have no way to turn it off
I'm still wrapping my head around Drupal 8 and installing modules during my learning process. Now I installed this module: https://github.com/iwhitcomb/foobar and it totally broke my site:

In Drupal 7 I used to be able to just goto the terminal and do a **drush sqlc** and manually update the modules table in the database to disable it. But in Drupal 8 there is no modules table for me to make edits.

* How do I disable this new module I installed via the drush command line? (drush pm-uninstall doesn't work as it throws the same error in the shell)

# Answer
> 0 votes
Just remove the module folder and the site will work again. And do a clear cache. I'm not sure if it leaves any orphaned entries in the Database. If so, how would one delete them?

---
Tags: 8, drush
---


# Question
Title: Is it possible to add a button to a field_collection?
I've created a custom entity module, and the form for it uses field\_collections. The only form field I've defined programmatically is the title, the rest of the fields and field collections for this form I've defined via the Drupal 8 interface.

I have a particular field collection with 8 dropdowns and a large textarea. I want the person using the form to be able to set the 8 dropdowns to certain values automatically based on the contents entered in the textarea, but only by clicking a button since they should also be able to manually set the dropdowns. The field\_collection itself has unlimited allowed values, so there should be one button for each instance of that field collection in the form.

It was my plan to just get an inactive button into the form and add a front-end script to have it trigger a Javascript function, but I can't seem to figure out how to get a button in the form. It doesn't seem to exist as an option in field\_collection field definitions. I had a prototype of this working in jQuery, but I'd rather not use jQuery to insert elements into the form if I can avoid it. So far Googling has proven fruitless. Is it possible to do this with `hook_form_alter()` perhaps?

# Answer
I ended up asking Sacrilegious, one of the regulars in #drupal-support, and he offered this solution:

Define a new class in {module root}\Plugin\Field\FieldWidget names FieldCollectionCustomEmbedWidget.php

```
<?php

/**
 * @file
 * Contains \Drupal\{module}\Plugin\Field\FieldWidget\FieldCollectionCustomEmbedWidget.
 */

namespace Drupal\{module}\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\field_collection\Plugin\Field\FieldWidget\FieldCollectionEmbedWidget;

/**
 * Plugin implementation of the 'field_collection_custom_embed' widget.
 *
 * @FieldWidget(
 *   id = "field_collection_custom_embed",
 *   label = @Translation("Embedded custom"),
 *   field_types = {
 *     "field_collection"
 *   },
 * )
 */
class FieldCollectionCustomEmbedWidget extends FieldCollectionEmbedWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['custom_button'] = [
      '#markup' => '<div class="guess-compatibility js-form-button field-add-more-submit button js-form-submit form-submit">button text</div>',
      '#value' => t('button text'),
      '#attributes' => [
        'class' => [
          'my-custom-button-class'
        ],
      ],
    ];

    return $element;
  }
}

```

Then under Structure, I went into the settings for the form containing the field that needed this button, and under "Manage Form Display", I changed the widget type of the field to the newly added "Embedded Custom." Now the button is there.
> 3 votes

---
Tags: 8, entities, javascript
---


title: Modular content and syndication

text:
# Question
Title: Modular content and syndication
I am trying to sketch out a Drupal 8 based solution by which content is authored in a modular way, with an arbitrary number of different modular blocks of content, that would also allow nodes to be pushed (or pulled) to other separate Drupal 8 installs. (The essential idea being that a set of editors have access to a set of simple modular blocks to build content which is likely to be duplicated across different separate sites and another set of editors have access to a more complicated set of blocks to build content that is not necessarily meant to be duplicated.)

So far I can't seem to find any obvious solutions, most seem to require knowledge of the content configuration beforehand. Is there an obvious solution I'm overlooking or just ignorant of?

A combination of Paragraphs and Deploy module have been suggested to me. I'm still evaluating their combination to determine if it's suitable but any additional suggestions would be very helpful!

# Answer
> 0 votes
It looks like this is currently not possible for Drupal 8, using community maintained modules. The Feeds Extensible Parsers module is not ready, which means the services+feeds method is not feasible, and the Deploy module is not ready. (Though methods may become available in the future for this particular workflow.)

---
Tags: 8
---


title: where to edit styles in a sub-theme?

text:
# Question
Title: where to edit styles in a sub-theme?
I created a foundation sub-theme and am now customizing my site. I am confused as to where to edit styles sometimes. For example there are these styles are generated somewhere which I can't find where. If I wanted to change the padding and line-height, what is the correct way of going about this?

```
@media only screen and (min-width: 40.063em)
.top-bar-section li:not(.has-form) a:not(.button), #topbar-forms li:not(.has-form) a:not(.button) {
    padding: 0 0.5208333333rem;
    line-height: 1.5625rem;
    background: #FFFFFF;
}

```

# Answer
> 1 votes
I find it's generally easier to track down CSS selectors by disabling CSS aggregation and then using your browser's inspector feature. This will give you a file and line number to reference for tracking down the selector in question. Often times, you may be able to simply copy-and-paste the selector in question into your subtheme and edit it as needed.

You'll always want to make your CSS and template changes in the subtheme; don't touch the base theme just like you wouldn't touch Drupal core to make code changes. This ensures that if there is an update to the base theme, you can apply it without losing all of your customizations.

Many base themes already have a CSS file structure or directory in place to help you figure out where to put your selectors. If not, the architecture is very much up to your personal preferences. You could put everything in one file if there are only a couple of changes, but most people use some sort of systematic CSS architecture, such as SMACSS, to keep things organized on more complex projects. Alternately, it might make sense to you to mirror the file structure already found in the base theme. You normally don't need to copy all the CSS files from the base theme, just create files to hold any new or customized selectors as needed.

If you haven't yet, check your base theme for a README file, or look at their online documentation for more hints on properly customizing it using a subtheme.

**Follow-up, more specific to SASS and Foundation theme:**

If you're looking for the SASS file that a selector comes from, the easiest way to trace that down is by enabling SASS source map generation in the subtheme's `Gruntfile.js`. Add `sourceMap: true,` to the `sass` options in `grunt.initConfig()` similar to this:

```
grunt.initConfig({
  ...
  sass: {
    dist: {
      options: {
        outputStyle: 'compressed',
        sourceMap: true,
        includePaths: ['<%= global_vars.theme_scss %>', '<%= global_vars.base_theme_path %>/scss/'].concat(bourbon)
      },
  ...

```

You may also need to enable loading of CSS source maps in your browser's settings (See the "Enabling source maps in the browser" section from http://thesassway.com/intermediate/using-source-maps-with-sass.

Using source maps to trace back to the specific selector from your OP, it seems to be located in `path/to/themes/zurb_foundation/scss/foundation/components/_top-bar.scss`. Looking at the base theme's SASS, you can see it utilizes variables for determining the `padding` and `line-height` properties:

```
.top-bar-section {
  ...
  li {
    ...
    &:not(.has-form) {
      a:not(.button) {
        padding: 0 $topbar-link-padding;
        line-height: $topbar-height;
        background: $topbar-link-bg;
        ...
      }
    }
  ...

```

And those variables are defined elsewhere in the base theme (do a text search to find them) with the `!default` property:

```
$topbar-height: rem-calc(45) !default;
...
$topbar-link-padding: ($topbar-height / 3) !default;

```

This means they can be set to something else in your subtheme's SASS before they are used in the base theme's SASS in order to override the base theme's defaults. I can't tell from the OP, but I'm guessing changing the value for $topbar-height might accomplish both changes you are attempting to make. Doing things in this way (overriding !default variables from the base theme) is less likely to cause alignment issues elsewhere in the theme, so it's generally the preferred methodology (assuming the theme is doing a good job of utilizing SASS, which seems to be the case for the ZURB Foundation base theme)

In order to do this in your subtheme, I'd recommend either adding the variable overrides to your subtheme's `scss/base/_init.scss` file, or creating a new `scss/base/_overrides.scss` file and editing the main theme SASS file at `scss/your_theme_name.scss` to `@import "base/overrides"` it just below the existing `@import "base/init"`.

For example, try adding this to the bottom of the subtheme's `scss/base/_init.scss file` to double the top bar's height:

```
$topbar-height: rem-calc(90);

```

---
Tags: theming
---


# Question
Title: How to use set() on a field within a field collection?
I have a custom entity type, and I'm defining its form, which extends `ContentEntityForm`. During my `save()` function, I want the form to conditionally unset fields based on the values of other fields. (example: unset the value of a list select field if a certain checkbox is checked off)

I can't seem to accomplish this with `$form_state->setValue()` or `$form_state->setValueForElement()`, in both cases my code is seemingly ignored and the select widget is not unset upon finishing saving (although a var\_dump of `$form_state->getValues()` at the end of the function shows that the values array is indeed being modified the way I want it to be).

However, the following code seems to work nicely for the `title` field (defined via `baseFieldDefinitions()`, is not inside a field collection):

```
$entity = $this->getEntity();
    $entity->set('title', array(array("value" => "aaaaaaaa")));
$entity->save();

```

My title for the newly saved entity does indeed show up as "aaaaaaaa"

Is it possible to target fields inside field collections in this way using this `$entity` object? Or is this the totally wrong approach?

# Answer
> 1 votes
It's not really clear to me why you don't change the values on the entity, but save() is too late.

The entity is built in buildEntity()/copyFormValuesToEntity(), if you want to change how it is build based on form\_state values, you have to change them by overriding those methods and doing your changes first.

---
Tags: 8, entities
---


# Question
Title: Does drush need to be installed as root?
Per http://docs.drush.org/en/master/install/

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

So I try it but get the following error:

```
[Michael@devserver ~]$ php -r "readfile('http://files.drush.org/drush.phar');" > drush
[Michael@devserver ~]$ php drush core-status
PHP Warning:  pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///home/Michael/drush/includes/startup.inc on line 359

Warning: pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///home/Michael/drush/includes/startup.inc on line 359
Error has occurred executing the Drush script found at /home/Michael/drush
(errno 13) Permission denied
[Michael@devserver ~]

```

So then I try running it as root.

```
[Michael@devserver ~]$ su -
Password:
[root@devserver ~]# php /home/Michael/drush core-status
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/Michael/drush
 Drush version          :  8.1.2
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

[root@devserver ~]#

```

So, all is good, and I just need to install it as root? Any way I can install it as a normal user? Thanks

# Answer
> 7 votes
Not sure exactly what's going on there but I can reproduce it using the installation instructions.

The problem is related to the execution path (haven't looked any deeper). If you move out of the folder you downloaded drush into and execute, it'll work. (`cd ~/..; Michael/drush core-status`).

That's probably why it works when you `su` \- your working directoy changes to /root. An unfortunate red herring, the problem doesn't appear to be related to permissions at all. Had you run `sudo php drush core-status`, it still wouldn't have worked.

# Answer
> 15 votes
**NOTE** The issue described in the Question has now be fixed in the latest Drush version.

No, Drush does not need to be installed as root.

I've submitted Drush pull #2246 to update the current Drush install instructions.

This install method fixes the issue as per Drush pull #2246:

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > /tmp/drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > /tmp/drush

# Test your install.
php /tmp/drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x /tmp/drush
sudo mv /tmp/drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

# Answer
> 0 votes
I was getting this error as well. For my case it did turn out to be a permission issue on the given account. I needed to make sure the **~/.drush** directory (and its sub directories) where owned by the proper account:

```
chown -R <account_name>:<account_group> /home/<account_name>/.drush

```

# Answer
> 0 votes
If you change the order of the commands so that you make drush executable before you test the install, it works. (At least it did for me):

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Test your install.
php drush core-status

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

---
Tags: installation
---


# Question
Title: How do I create a base content type and subtypes ("bundles")?
I've been trying to figure out how to create a base content type and subtypes (bundles) in Drupal 8, but haven't been able to figure it out.

For example:

**Base Content Type**

* Base Event (fields: event name, start/end dates and times, location, etc.)

**Subtypes (Bundles)**

* Seminar
* Conference

I looked into:

* **ECK (Entity Construction Kit)** module: didn't seem to be working 100% in Drupal 8. Using their example, I was able to create a 'Vehicle' ECK base type and 'Car' and 'Truck' ECK subtypes, but wasn't able to define any fields for the 'Vehicle' base type that would be shared between 'Car' and 'Truck'. Also, the types appeared under 'ECK Types' in 'Admin \> Structure', so not sure if they would be usable throughout Drupal in the same way that regular Content Types are used/referenced?
* **Paragraphs** module: doesn't seem to the right module for this

It looks as though I have to do this through code somehow, but couldn't find any clear documentation that explains step-by-step how to do this in Drupal 8.

Any help would be greatly appreciated. Thank you.

# Answer
> 2 votes
Creating entity is quite complicated, but it will be easier if you generate a base code with Drupal console command first.

```
drupal generate:entity:content [options]

```

> ## Options
>
> * `--module` The Module name.
> * `--entity-class` The content entity class
> * `--entity-name` The content entity name
> * `--base-path` The base-path for the content entity routes
> * `--label` The label
> * `--has-bundles` Entity has bundles
> * `--is-translatable` Content entity translatable

---

I post some useful tutorial / documentation here:

---
Tags: 8, entities
---


# Question
Title: How do you use 'drush site-install' to install a multisite with separate databases using a single command?
I regularly use `drush site-install` to install single Drupal 8 sites from the command line. It works great.

I'm now working on building a Drupal 8 multisite. It'll have separate databases per site.

Can `drush si` be used to install a multisite from the command line? Does it use Drupal8's sites.php?

I saw Need Steps to Install multisite configuration using only drush. i.e multi-site install having different database, but I'm not clear on what's actually done there.

I figured it should be able to, but I can't find any HowTo docs for multisite.

# Answer
In the link you provided, @greg\_1\_anderson mentioned using `--sites-subdir`. This option is used to create a site folder under `<DRUPAL_ROOT>/sites/`.

For example, if you run `drush si --sites-subdir=example1.com`, it will create a example1.com folder under `<DRUPAL_ROOT>/sites/`, settings.php will also be generated in this folder. It contains the database configuration.

Since it is a multi site structure, you may not want to share the same database. You have to specify the database information with `--db-url`.

For example:

* DB: MySQL
* root username: username
* root password: password
* host: localhost
* table name: `example`

You can specify above information with `--db-url=mysql://username:password@localhost/example`.

A more complex example involving setting more sites for a multi-site configuration could be the following.

```
drush si --sites-subdir=example1.com --url=mysql://username:password@localhost/example1
drush si --sites-subdir=example2.com --url=mysql://username:password@localhost/example2

```

Moreover, if you want to have different database credentials for different sites, you can dynamically create the separate username and password at the same time.

```
drush si --sites-subdir=example1.com --url=mysql://user1:newpassword1@localhost/example1 --db-su=username --db-su-pw=password
drush si --sites-subdir=example2.com --url=mysql://user2@newpassword2@localhost/example2 --db-su=username --db-su-pw=password

```
> 5 votes

---
Tags: 8, database, drush, multi-sites, installation
---


# Question
Title: how can I identify sidebar blocks in my theme
I am working on a theme that I inherited and somehow the sidebar blocks are only coming out on the front page although I have set them up to come out in all of the pages in the block setup. The programmer has made many template pages which is where I believe he has blocked the sidebar block from coming out but I am not sure where that code is.
Where can I find the code that would disable a sidebar block from coming out.
If I switch templates I can make the blocks come out but I need to do it with the current template.

# Answer
> 0 votes
Check (**page.html.twig** D8) or (**page.tpl.php** D7) and check (**themename.theme** D8) and (**template.tpl.php** D7)

Worst case scenario, backup first, then start deleting template files one by one and flushing the cache and checking, until you see the one that affects it.

---
Tags: theming
---


# Question
Title: What is going wrong with the file_field_path redirect for my files?
I am using the fieldfield\_path module to create a redirect for my files as they come in during a migration (this is so that I can give an original path in the migration, and create a redirect, allowing me to redirect at the apache level from the old url to a new one, but also have extra information in the path that wasn't available from the old site path. The fieldfield path file path is set to `publication_documents/pub/[node:field_doc_type_book]/[node:nid]` for my book content type public files field.

When I look at my migration messages I see the following message:

```
Creating redirect from
private://publication_documents/pub/old/1565/filename.pdf to
private://publication_documents/pub/book/37544/filename.pdf

```

Which is what I would expect, the nodeid of the node the file is attached to is 37544. Unfortunately when I actually visit `/system/files/publication_documents/pub/old/1565/filename.pdf` I get redirected to `system/files/publication_documents/pub/book/149678/filename.pdf`

Which is a page not found error page. It is a mystery where the number 149678 came from, but I can confirm that the redirect happening is the one actually stored in the redirect table. I've looked through all of the node and revision ids, file ids, etc. that I could think of as possibly being the source of this mystery integer, but have had no luck so far. I removed all the migrated data and ran the migration again, but the integer on the redirect is still the same.

What might be happening? Why is drupal telling me it is creating one redirect, but actually creating another? I suspect it is actually creating the one it is telling me about, but then replacing it with another, but so far, I don't have any information to prove either theory.

I am using the media module, and wonder if that is somehow messing things up. I also have pathauto active.

# Answer
It turned out that what was happening is that the old redirects were never being deleted when I rolled back my migrations. When I did a reimport, the source for the redirect already existed so new ones weren't being created. To solve this I implemented `hook_node_delete` as follows (I need to delete redirects to `system/files/publication_documents/{either int or pub}/{the value of a field}/{node id}`) :

```
function MYMODULE_node_delete($node){
    // Delete alias.
    $nid = $node->nid;

    $type = $node->{'field_doc_type_' . $node->type}[LANGUAGE_NONE][0]['value'];
    foreach (array('pub', 'int') as $status) {
        redirect_delete_by_path('system/files/publication_documents/' . $status . '/' . $type . '/' . $nid);
    }
}

```

This works when the redirects have been created with the current $nid, but this wasn't true for any of the existing redirects in the system, so I wrote remove\_redirects.php:

```
<?php
redirect_delete_by_path('system');

```

and then I rolled back my entire migration and ran `drush scr remove_redirects`

This cleared out the existing redirects, so I can run the migration again, and future rollbacks will get rid of the redirects too.
> 0 votes

---
Tags: 7, path-aliases, redirection, media
---


# Question
Title: Hide field results not matching exposed filter
I have an Autocomplete (Tags style) field with multiple values in the field.

I'm using exposed filters to display nodes with one or more values in the Autocomplete field matching the filters.

I want the node field to display only the matched values, not all of them when rendered in a view.

For example. Say I have three nodes with the following field values:

Then I apply exposed filters of **Orange** and **Grape**. This results in the following (as Node A does not contain these values):

What I want is values not in the exposed filters to also disappear, so the user can see exactly what selected fields matched the node. Like so:

I assume this can be done using the Global PHP field, but really need some help to figure it out.

# Answer
I managed to do this by creating a module that implements hook\_views\_pre\_render()

Your field values will need to be taxonomy references for this to work, like so:

```
function MyModule_views_pre_render(&$view) {
    // Set the view we want to work with
    if ($view->name=='your_view') {
        // print out your array, so you know what you have (comment out in live site)
        drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');
        // Check to see if the filter has been triggered, otherwise you will get errors
        if (isset($view->exposed_input['exposed_filter_name'])) {
            foreach($view->result as $result_id => $result) {
                // cycle through each view result row, check that each result exists in the exposed filter. if it does not, then remove it.
                foreach ($result->field_your_field as $field_id => $field_val) {
                    //find the TID related to your result
                    $field_tid = $result->field_your_field[$field_id]['raw']['target_id'];
                    // Check if the TID is missing from the exposed filter values
                    if (array_search($field_tid, $view->exposed_input['exposed_filter_name']) === false) {
                        // Now look through your field values to find the TID missing from the values
                        if (($key = array_search($field_val, $result->field_your_field)) !== false) {
                            // And remove it
                            unset($result->field_your_field[$key]);
                        }
                    }
                }
            }
        }
    }
    // Finally re-number array to account for missing elements - i.e. [1],[3],[4],[6] to [1],[2],[3],[4] (optional, but tidier)
    $result->field_your_field = array_values($result->field_your_field);
}

```

Note that `field_your_field` is written like that because you need to append an extra `field_` to the machine name. e.g. machine name `field_my_field` would become `field_field_my_field`
> 0 votes

---
Tags: entities, views
---