title: parent page title on sub menu

text:
# Question
Title: parent page title on sub menu
I am building a website where i generate a submenu based on my main navigation. The structure looks like this:

* Home
* About
* Work at
    + vacancies
* contact

when you land on one of the level 1 pages, a submenu will appear in the sidebar with the children links of this page. i want the title of the parent page to show above this menu.

also, on the vacancies page there's a overview of vacancies, and when you go to one of the detailed vacancies i want it to show "Work at" and not "vacancies" in the submenu title.

i've tried alot of things but can't find the right solution for it.

# Answer
> 1 votes
The menu\_block module with the patch in https://www.drupal.org/node/2809699 should work.

**Note**: you'll have to select the "Use the following as title" field to "Active trail's parent title" when configuring your block.

---
Tags: 8
---


# Question
Title: How do I display, in a ColorBox popup, a caption AND a title (caption from image 'alt' attribute and title from 'title' attribute
I am trying to display in a ColorBox popup, a caption AND a title (caption from image 'alt' attribute and title from image 'title' attribute). The colorbox is opened when an image is clicked.

Here is an example of what I want to do.

>

The img will be something like the following.

```
<img typeof="foaf:Image" src="http://localhost:4444/img.jpg" width="336"   height="254" alt="LEGEND / CAPTION balbalblalblalba balbalblalblalba balbalblalblalba" title="TITLE balbalblalblalba balbalblalblalba balbalblalblalba" class="">

```

Do you have any idea of how can I do that?

I am using:

* Colorbox 7.x-2.10
* Drupal 7.35

The colorbox module settings are the following.

>

# Answer
> 0 votes
Add "colorbox" class to your element. You could also select by `document.getElementsByTagName("img")`, but we don't really want to select every single img tag.

```
var cbox = document.getElementsByClassName("colorbox")

for (var i=0, i < cbox.length; i++) {
  cboxTitle = cbox[i].title;
  cboxAlt= cbox[i].alt;

  cboxTitle = "<span class='title'>" + cboxTitle + "</span> <span class='alt'>" + cboxAlt + "</span>"
}

```

You then just got to make colorbox print out the title tag and style it the way you want.

---
Tags: 7, javascript
---


# Question
Title: Change max length of link field link text
In order to modify the length of a file field description field I put the following line in settings.php:

`$config['file.settings']['description']['length'] = 512;`

Now I want to do the same for the link field. How can I change the max length of the link text (without patching the module)?

I think the problem is that FileWidget.php gets the length from the configuration

`'#maxlength' => $config->get('description.length')`

whereas it is hardcoded in LinkWidget.php:

`'#maxlength' => 255`

# Answer
> 2 votes
If you go for module then you can check Maxlength module.

> Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node)

---
Tags: 8, navigation, configuration
---


# Question
Title: sort views comments by vote result keeping thread
I want to show comments of nodes ordered by vote result (most popular comment at the top of the list). I have installed voting API, rate and views module. Then add a yes/no voting to comments and enable threading for comments in order to let users reply each other.

I created a views to show comments in most popular order with these sort criteria:

```
Comment: Thread (asc)
SUM(Votes: Value)

```

Now the problem is that when views tries to keep thread it sort theme by post date (asc/disc) and do not see the second sort criteria.

So how can I sort comments by vote results keeping threading?

EDIT:

# Answer
**Main problem**

Currently there is no way to tie all the children and grandchildren comments to the Main Parent (original/first ever parent). Also, need a way to separate the Main parent from all the children.

**TL, DR Solution**

Use the Views field view module to separate the children from main parent, and add all children as a field. That way, we are able to sort Main Parent's by Votes without affecting the children and grandchildren.

But there is no way to just show all children and grandchildren of a Main Parent CID; therefore, create a custom module to solve this problem, so we can use the view field technique.

### Detailed Solution

**Requirements**:

Views field view, Entity API, Main PID (custom module below).

---

**main\_pid.info**

```
name = Main PID
description = Links all children and grandchildren comments to the main parent by saving main parent cid into main_parent_pid field when comment is saved.
package = custom
core = 7.x

```

**main\_pid.module**

```
<?php

/**
 * Implements hook_comment_presave()
 */
function main_pid_comment_presave($comment) {

  $pid = $comment->pid;

  if ($pid > 0){

    while ($pid > 0) {
      // Implements comment_load()
      $load_comment = comment_load($pid);

      $pid = $load_comment->pid;
      $cid = $load_comment->cid;

    }

    $comment->field_main_pid[LANGUAGE_NONE][0]['value'] = $cid;

  }

  elseif ($pid == 0) {

    $comment->field_main_pid[LANGUAGE_NONE][0]['value'] = 0;

  }

}

```

Now in comments add a new field called Main PID with machine name of `field_main_pid`. You can do this programmatically or using the Drupal UI (I will leave this up to you)

Now, hide field from display

---

**In your view:**

In fields, add `Comment: Rendered Comment` (Thanks to Entity API)

In fields, add `Comment ID`

---

Now add a new block

Click on block, and change the display name

In fields add `Depth`

In fields, add `Comment: Rendered Comment` (Thanks to Entity API)

The style settings will allow you to indent the children with CSS.

Example:

```
.depth-1 { width: 480px; margin-left: 10px; }
.depth-2 { width: 470px; margin-left: 20px; }

```

In Filter Criteria, add `Content: Main PID`

Only the Main parent has PID of 0, therefore, this will show all the children only

Then add `Content: Thread` in Sort and `Main PID` in Contextual Filter

So your **Children View** should look like this:

---

**Going back to the first View**:

In Filter Criteria add Main PID

This time equal to 0, since we only want the main parents.

Now in Fields, add `Global: View` (Thanks to Views field View)

Your **Original/Main View** Should look like this:

**Important:** Add contextual filter of NID here (forgot to do that).

Lastly, In Sort Criteria, add the `Votes Value` (Not shown on screenshot since I did not bother to install Voting API and Rate) and remove the default `Post date`.
> 2 votes

---
Tags: 7, views, comments, rating
---


# Question
Title: How to flag if a 'webform' exists on a page?
I an fairly new to Drupal and have a custom module in which I need to write some PHP logic. It needs to insert a flag basically, on any page which contains a 'webform' of any kind.

I see the webform api page, but I don't see anything which would just tell me if a webform is on a page.

I have tried this if statement to insert my little flag - but it is showing on every page. I assume because drupal calls every `page` a `form`? so technically my code bit is flagging every page?

```
if (function_exists(form_id)) {
    $variables['s.event4'] = "event4";
  }

```

Any help?

# Answer
> 2 votes
This appears to be a preprocess function. If it's hook\_preprocess\_page(), you can do this:

```
function hook_preprocess_page(&$variables)
{
  if(isset($variables['node']) && $variables['node']->type == 'webform')
  {
    $variables['s.event4'] = "event4";
  }
}

```

---
Tags: 7, webforms, flags
---


title: Contact form placeholder translation

text:
# Question
Title: Contact form placeholder translation
I am working drupal 8 site. In this site I create a contact form for contact page. I am able to translate field label but I want to translate my placeholder.I can't find any option for translate contact forms placehoder in drupal 8.

# Answer
> 2 votes
Normally you should be able to translate the placeholder in configuration translation as described in https://drupal.stackexchange.com/a/191927/47547. @Berdir pointed out that there is an open issue that prevents this: https://www.drupal.org/node/2546212

A workaround is to make the placeholder translatable in a form alter hook:

```
function mytheme_form_contact_message_feedback_form_alter(&$form, $form_state) {
  $form['subject']['widget']['0']['value']['#placeholder'] = t('Please enter a subject');
}

```

After visiting the translated form you can translate this string in the user interface translation.

If you want to translate all placeholders in the form and use the untranslated strings from the widget settings:

```
function mytheme_form_contact_message_feedback_form_alter(&$form, $form_state) {
  array_walk_recursive($form, function (&$value, $key) {
    if ($key === '#placeholder' && is_string($value) && $value !== '') {
      $value = t($value);
    }
  });
}

```

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


# Question
Title: Send email to customers after particular period of time?
I am using the Drupal Commerce module and I have a product type service for license to be sold on site. I have different licences (products) like 1 year license, 2 year license, 6 months license and many more.

I need to send an email to customers 1 month prior to their license expiration date. Like if customer purchased a license for 1 year, then the email should be sent 11 months after date of purchase. Similarly with other products like after 5 months if license is for 6 months.

How can I achieve this using the Rules module?

# Answer
> 5 votes
Answering my own question.

I have finally done this using hook\_default\_rules\_configuration() I have created a test rule with static values, then exported it and used the hook mentioned above to modify the values on run time.

This worked best for my requirements.

# Answer
> 2 votes
Use the `Rules Scheduler` (a sub-module of the rules module) for sending such eMails.

You would have to create a Rules Component (to actually send an appropriate eMail) and a rule (which schedules that Rules Component), which is similar to the exported rules shown in my answer to "How to send an email to an author on a specific date using date field specified in a node?". Just replace the "`field_weaning_date`" by what corresponds to your "1 month before expiration date".

If you don't have an expiration date, you could also use something like "order creation date", and combine that with (eg) "after 5 months from now" (for a license of 6 months). And if in the same rule you'd want to combine this logic for licenses that expire after 6 months, or 1 year, or 2 years, you can do so by using either the Conditional Rules module, or a Rules Component (in which you include Rules Conditions about the expiration date).

Obviously, you'd want to use some Rules Event that corresponds to something like your "Customer purchases license".

PS: I'm assuming this question is about D7.

---
Tags: commerce, rules, emails
---


# Question
Title: Profile 2, user relation access? A hard one!
The site contains 2 user types besides admin, lets call the 2 user types "Private" and "Corporate".

Private users have a "profile 2" type, where alot of different fields are filled.

In a view or likewise, "Corporate" users need the ability to search for users, and when they go to a users profile, ONLY a few fields should be visible - rest hidden.

Then when (Corporate user) viewing the (Private users) profile, they need a "button" or likewhise where they can ask for permission to view full profile.

Now the private user should recieve a mail that states a "Corporate user xxx" want to see their full profile. ONLY when the "Private" have accepted this, all fields should be visible, BUT ONLY to this ONE specific user of the "Corporate" role - not all other users with the "Corporate" role.

What modules can make this node/user access work?

# Answer
Here is a zero code solution.

Flag \+ Rules \+ Rules Block Visibility \+ Views

1 flag for "request"

1 flag for "allow"

When "request" flag is flagged \>\> send e-mail with link to flagging user profile.

Then other person opens link and sees their profile and clicks the "allow" flag.

If user is listed in the Allowed flag list, then show View Block with the all the fields, if not, then show View block with limited fields.

---

Here is an indepth example to using Rules Block Visibility: How to stop a Views block from displaying to admins, such as user/1?
> 0 votes

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


# Question
Title: Open Atrium: How to add an action button on a view node
I can add a button on the node edit form using a `hook_form_alter` and adding a new element to `$form['actions']`.

However, I would also like to add a button to the node view, next to `+ Create`. I assume there's an api for this but I can't seem to find it in the code or in documentation.

# Answer
I found the solution. First, some terminology: the links in the dropdown menu on the bottom right are called `Contextual Tabs`. Second, the buttons with an icon are called `Extracted Tabs`. These settings are found in two different locations.

First, make your menu item a regular context tab. Go to `admin/openatrium/setting` and open the `Contextual Tabs` fieldset. Fill in the link to your page/menu item:

Next, extract the Contextual Tab as a button. Go to `admin/config/user-interface/contextual-tabs` and fill in the link and/or the label to your page/menu item in the `Tabs to extract` textarea:

Your link will now be displayed as a button with an icon of your liking.
> 0 votes

---
Tags: 7, distributions
---


# Question
Title: How to restrict block for particular subpath, yet allow for all other subpath of a specific parent path?
I have created the custom page and assigned for the *Underwriting* content type nodes like underwriting/*, but I want to restrict the block for a node of that content type; for example, show it for underwriting/*, but not for underwriting/example.

Is it possible to restrict a block for particular sub-path, and allow it for all the other sub-paths of a specific path?

# Answer
> 2 votes
**Assuming all of your underwriting/\* nodes are of a certain content type and this content type does not have anything else than underwriting/\* as path**

Go to `/admin/structure/block` and find your block and click on Configure link.

Then under Visibility settings, Pages tab, select all pages except for `underwriting/example`

and then

# Answer
> 0 votes
Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

As per the "*if you can do it with Rules, you can use it to control block visibility*" above, you have the power of Rules available to implement all sorts of custom logic.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_pages" : {
    "LABEL" : "Show block on selected pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "underwriting\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "\/example",
              "operation" : "ends"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

***Voilà ... Easy, no?***

PS: no need for the (dangerous) PHP filter either (which is no longer in D8 core either ...).

# Answer
> 0 votes
You need to enable the *PHP filter* core module. You will get a new option for a block restriction.

More Info

Restricting blocks to certain pages

```
<?php
if (arg(0) == 'underwriting' && arg(1) != 'example') {
  return TRUE;
}
else {
  return FALSE;
}
?>

```

---
Tags: 7, blocks
---


# Question
Title: Nexus theme tb mega menu showing below slideshow
I am using the Nexus theme however when using tb mega menu it shows below the slideshow. I know it has something to do with the z-index but where and how do I change this?

# Answer
> 0 votes
You need to find out the class of tb mega menu and add

```
{
    position: absolute;
    z-index: 2;
}

```

**Note: z-index max display on top.**

---
Tags: 7, navigation
---


# Question
Title: Contextual filter with multiple entity reference fields
Troubles with displaying content in a sidebar block with a View. Actually, the website is in Dutch, so I'll replace the names of Content Types with something easier, like A, B, C, D.

I have 4 entity types: A, B, C, and D. These are articles referencing each other. So, a node for entity type A on the screen, has additional relevant information in B, C, and D.
While the node from entity type A is on the screen, I want to display the links to the different nodes in B, C and D in a sidebar block.

So in each entity type, I have Entity Reference fields, for example a node from type A has fields refB and refC and refD.

All working fine, with the links being correctly displayed within the node display, and I can jump between content from each entity type using the Entity Reference fields.

So, for the sidebar block, I created a View that contains the refB and refC and refD fields, and added a relationship (just for refB initially, to reference the content in entity type B), and a contextual filter on the Nid, getting the value from "Entity from URL".

Nothing gets displayed in the block however.
When I remove the contextual filter, all possible values for the entity reference fields are displayed. So either I'm getting everything or nothing, but not the relevant entity reference fields from the node in entity type A only.

Articles on this subject explain the Relations and Contextual Filter configuration, but can't get it right apparently.

# Answer
I think it's because you did not select a Relationship in your field.

Example: Title field (By the way, field\_test is my entity ref field name)

**Also make sure your contextual filter does not have a relationship**
> 0 votes

# Answer
Solved the problem already. Apparently I was making this too complex. Created a new view, just adding the refA, refB, refC and refD entity fields. Then a contextual filter with Nid as "Content ID from URL"

And that's it, working fine. No relationships required apparently. Because the Entity reference already contains the "relationship info".

I think a Relationship is only required if one wants to match nodes on specific content in fields ?

So in this case, no relationship link required.
> -1 votes

---
Tags: views, entities
---


# Question
Title: How I can change the value of a commerce product field after Completion process?
I want to change the value of one of my product custom fields when "Checkout completion". I created that custom field myself, with machine name `field_prodstat`.

How I can do that with the Rules module?

# Answer
Preface: I'm assuming this question is about D7.

Create a custom rule (using the Rules module) like so:

* Rules Event: checkout completion event.
* Rules Condition: entity has field, for the field with machine name "`field_prodstat`" (which will make that field available as a token you can select in subsequent Rules Events and/or Rules Actions).
* Rules Action: set a data value, for the field with machine name "`field_prodstat`".

### Update

Below is an attempt to also address your comment below this answer, the relevant part of that comment is like so:

> I have a content type called "Appointment". When that appointment status = "Accepted Pending Payment" I created a rule to build a new product for that "appointment". So now I have a product related to that appointment. I just want to update "Appointment" status to "Paid" when his product appear in an order with status = invoiced. I don't know if you have any other proposal to do that.

That comment starts revealing your real question, which is pretty different from your original question. To answer your *real* question is not something that can be explained in just a few phrases. I suggest you have a look at the video tutorial about Removing Items From the Cart Using Rules which demonstrates a scenario which is pretty similar to what you're asking for (in your extra comment). Here is part of what is shown in that video (quote is from that link):

> * Create a rule that loops through all the line items when the order is about to be saved. Have it call a component (rules subroutine) for each line item to see if that line item should be removed.
> * Create the component that does the work. It needs to take two arguments (line item and the order-about-to-be-saved).

To make this also work for your case, I think you'd be close if you only replace the last Rules Action in the used Rules Component by a Rules Action that applies the update you're asking for in your comment.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to implement a Subscribe block functionality?
I wonder how to implement a block similar to the block shown below, to integrate with the Subscriptions or Notification module.

Basically it sends emails to user everytime a new article is added.

Any suggestions?

# Answer
> 0 votes
Assuming this question is about D7 (at least), I wouldn't recommend using either of both modules anymore. This because these days there is a way better alternative available, which is the Message Stack. It consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of the modules' object orientated architecture).

If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

**Attention**: the Message Stack is really amazing (I think), but also not obvious to get started with it. Especially if you try to do so only using site building techniques. But after you ***climbed this Drupal Message ladder***, you might not ever want to consider building a site without it ... trust me.

---
Tags: notifications
---


# Question
Title: Not all custom theme styles shown in ckeditor window
In my theme.info.yml file I set my theme CSS to be also used in the ckeditor window. The problem is that in my CSS I declared some styles to be only applied within #content section, so it doesn't show in ckeditor. I tried these styles to be shown in the editor through classes like

```
.cke iframe body ul {
  list-style-type: disc;
}

```

but it doesn't work...

# Answer
Ok, the mistake was to use classes outside the iframe. This way it works:

```
body.cke_editable ul {
 list-style-type: disc;
}

```
> 0 votes

---
Tags: theming, 8, wysiwyg
---


# Question
Title: Allow VIEWS accessing PARAGRAPHS fields collection
I have a content type called "**Slideshow**" where users can create any number of "**slideshow**" nodes. This content type has a field called "**Slide**" which is a field collection of other fields (caption, image, description, and link). The user can add multiple "**Slides**" to each "**Slideshow**" node (I can achieve this with the help of either PARAGRAPHS or FIELD COLLECTION modules).

Then I use VIEWS to create Blocks of the "**Slideshow**" content type to display specific nodes using contextual filter **Nid**.

MY PROBLEM IS: In VIEWS I can only list "title" and "**slide**" fields (as rendered) of the "**slideshow**" content type, whereas I need to list the fields inside the "**Slide**" field (the caption, image, description and link) so that I can customize them using VIEWS. Is there any way to achieve this? (allowing VIEWS to access the fields of PARAGRAPHS module).

POSSIBLE SOLUTIONS: In VIEWS I added a relationship "**Slide**", this allowed me to list the fields inside "**Slide**" field. the problem is that I'm trying to avoid relationships as it uses a lot of LEFT JOINS and this may decrease performance. my website uses lots of these slideshows and galleries multiple time in the same page and I don't want to lose performance.

Any help will be much appreciated.

# Answer
> 1 votes
In D8 your View's are automatically cached; thus, your query is results are cached, so I wouldn't worry too much about this. Nonetheless, you can enable `Show performance statistics` in views settings (`/admin/structure/views/settings`), to see how long it takes.

Testing with 1 field, the View Render Time is ~1.20ms faster when you create a View of Show: Field Collection Item and then add relationship to node rather than a View of Show: Content with a relationship of field collection.

---
Tags: views, 8, entities, paragraphs
---


# Question
Title: How do I obtain the result summary from within a form on the view page?
I have a design requirement or ask that wants to have a search form at the top of a Views page look like the attached image.

So there is an exposed full text input, exposed sort by filters.

However, the result summary for the view would appear to need to go in the middle of the form.

Since this is on a View page, is there a way to get the current View and fetch its result summary within a `hook_form_alter()`?

# Answer
> However, the result summary for the view would appear to need to go in the middle of the form.
>
> Since this is on a View page, is there a way to get the current View and fetch its result summary within a `hook_form_alter()`?

Don't complicate your Drupal life, and just KISS.

I assume you already added the Result Summary to your View's header. So just:

**style.css**

```
.view-id-[your-id] .view-header {

  position: absolute;
  top: 70px;

}

```
> -1 votes

---
Tags: views, 8, forms
---


title: Form element is not rendered

text:
# Question
Title: Form element is not rendered
I am trying to render the form element below in *telisim* module but it's not working, no output (see the screenshot).

The telisim.module file looks as follow:

```
//hook_menu

function telisim_menu() {
    $items['simcodes'] = array(
    'title' => 'SIM CODES',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('telisim_examples'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
* Implements hook_element_info().
*/

function telisim_element_info() {
  return array(
    'telisim_notepad' => array(
      '#input' => TRUE,
      '#process' => array('porta_teslisim_notepad_process_callback'),
      '#theme_wrappers' => array('telisim_inline_form_element'),
    ),
  );
}

function porta_teslisim_notepad_process_callback($element, &$form_state, $complete_form) {

 $element['#tree'] = TRUE;

  // Normal FAPI field definitions, except that #value is defined.
  $element['areacode'] = array(
    '#type' => 'textfield',
    '#size' => 3,
    '#maxlength' => 3,
    '#value' => $element['#value']['areacode'],
    '#required' => TRUE,
    '#prefix' => '(',
    '#suffix' => ')',
  );
  $element['prefix'] = array(
    '#type' => 'textfield',
    '#size' => 3,
    '#maxlength' => 3,
    '#required' => TRUE,
    '#value' => $element['#value']['prefix'],
  );
  $element['extension'] = array(
    '#type' => 'textfield',
    '#size' => 4,
    '#maxlength' => 4,
    '#value' => $element['#value']['extension'],
  );

   return $element;

  }

  function _telisim_element_theme() {
  return array(
    'telisim_inline_form_element' => array(
      'render element' => 'element',
      'file' => 'telisim.module',
    ),
    'telisim_checkbox' => array(
      'render element' => 'element',
      'file' => 'telisim.module',
    ),
  );
}

function telisim_examples($form, &$form_state){

  $form['a_form_example_element_discrete'] = array(
    '#type' => 'telisim_notepad',
    '#title' => t('Discrete phone number'),
    '#default_value' => variable_get(
      'form_example_element_discrete',
      array(
        'areacode' => '999',
        'prefix' => '999',
        'extension' => '9999',
      )
    ),
    '#description' => t('A phone number : areacode (XXX), prefix (XXX) and extension (XXXX).'),
  );

   dsm($form);
    return $form;
}

```

# Answer
I see two problems:

1) Your hook\_theme() implementation is named incorrectly, meaning it will never be called. This:

```
_telisim_element_theme()

```

Should be this:

```
telisim_theme()

```

2) You haven't implemented `theme_telisim_inline_form_element()`, so there is no HTML for the form element to render.

You need to create this function, and output the relevant HTML for your form element inside the function.
> 1 votes

---
Tags: 7, theming, hooks
---


# Question
Title: How do I reset URL for Product Display when replacing the main product? (instead of having an increment added to the URL)
I am having trouble with URLs after replacing items by a delete/re-import. The site uses Pathauto module.

I am adding content to a Drupal Commerce site using Feeds. I had uploaded the Product Variations and then Product Display for one product type. I realized that there were several mistakes with the CSV file and decided to start from scratch.

I deleted the original products by going to Products \> Manage Products. From the "List" tab, I selected all of the products and chose "Bulk Action" \>\> "Delete". The products were deleted from the website, but the URL was incremented by a "-0" and the original now returned a "404" error.

Desired: `www.XYZ.com/product/widget`

vs.

Less than desired: `www.XYZ.com/product/widget-0`

How do I return the Product Display to the "widget" URL without the "-0"?

If I try to override it by manually making the update on the Product Display, I get an error message that indicates that URL is already taken.

I would like to clean this up for SEO. Please advise.

Thanks, keb

# Answer
> 2 votes
I am not sure why this happens in Commerce Kickstart, while it does not happen with regular Drupal. Almost as if the product's path are cached or something, but clearing all caches after deleting a product did not change the outcome. But I did find an easy solution.

You can fix that by deleting your Aliases, go to `/admin/config/search/path/delete_bulk`

And then regenerating them

---
Tags: commerce, path-aliases
---


title: admin/people/permissions no access

text:
# Question
Title: admin/people/permissions no access
I can not access `admin/people/permissions`, even the link to permissions in the backend-menu is not visible. But I am logged in as admin! So what can be the problem here?

# Answer
Your administrative role probably lacks the "administer permissions" permission.

If you have Drush installed:

```
$ drush role-add-perm 'administrator' 'administer permissions'

```

You may also want to make sure your site still defines the 'administrator' role, since occasionally developers may manually delete the default roles from the DB (really not a good idea unless you know what you're doing). If you can't view available roles you can run this Drush command:

```
$ drush role-list

```

If it's not there, then you may have to create a new role to replace the admin role that was deleted and assign the role to yourself, and give your new role the 'administer permissions' permission:

```
$ drush role-create 'administrator'
$ drush user-add-role 'administrator' 'your username'
$ drush role-add-perm 'administrator' 'administer permissions'

```

If for some reason you don't have terminal access to your server, then you may need to download and enable the Devel module and PHP filter, then write a script that you can paste and run in /devel/php, but that should really be your last resort. https://drupal.stackexchange.com/a/56495/72084

p.s.: I believe Drupal gives user 1 the administrator role and completely unrestricted access by default. So if you are logged in as someone other than user 1, and/or if the administrator role has been deleted, that may explain how this problem came about. https://www.drupaleasy.com/quicktips/beginner-tip-what-special-about-drupal-user-1
> 4 votes

# Answer
simple solution - but hard to find: it was a problem with a backend theme. Changed to the standard theme for backend and can access permissions and the link/tab is here again.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to create a rule for changing a user field to a random string?
Using the Rules module, I would like to have a replacement the is a random string.

I have added a new user field (= `some_var`, which is a 'Text field' data type), which I would like to change to some random string after the User account is created.

Any ideas or hints to get this to work?

# Answer
> 1 votes
There is a (sandbox) module for it, which is the Rules Random module. Here is a quote about it (from the linked page):

> A simple rule action to generate either a random string or integer. Can define the length of the random result. For random strings, can also choose to include numbers and lowercase letters.

Either you just use that module, or you look at its source code to understand what it takes to include this logic in your own (custom) module.

With that, all that's needed is to create a custom rule like so:

* **Rules Event**: use whatever event that fits your requirements (eg: After saving a new account).
* **Rules Condition**: "Entity has field", related to your `some_var` field. That will make this field available for subsequent processing in Rules Conditions and/or - Actions.
* **Rules Action**: Use the action provided by this module, to set a value for your `some_var` field.

# Answer
> 0 votes
There is also another (sandbox) module for it, which is the Rules generate string module. Here is a quote about it (from the linked page):

> A simple rule to generate a random string, given optional parameters of length and character set.

Either you just use that module, or you look at its source code to understand what it takes to include this logic in your own (custom) module.

Obviously, creating your custom rule (using the Rules generate string module) is similar to the prior answer: just replace the Rules Action by the one provided by this module.

---
Tags: 7, entities, rules
---


# Question
Title: How do I use non-admin theme for page containing node form?
I've created a custom route where I return node add form with a controller. It works fine, but for the administrator user it is using the administrator theme. I tried using the following, but it doesn't help.

```
  options:
    _admin_route: FALSE

```

Is there a good approach to achieve this? As I remember, in Drupal 7, it worked fine with `hook_admin_paths()`.

# Answer
> 3 votes
Well, the issue was related to the bug in metatag module, it was in version 8.x-1.0-beta11.

It caused break of my routes when they ended with `/add`. It was trying to handle prefix of path as entity type, so my routes worked fine only if I had `_node_operation_route: TRUE` in route options. But if this option is set `_admin_route: TRUE` is added by core.

I updated metatag module to the latest version (8.x-1.0 currently) and found they've added check for existing entity type, so I'm not forced to use `_node_operation_route: TRUE` anymore and I'm able to output custom routes in a default site theme.

---
Tags: 8, routes
---


# Question
Title: How to get all the fields defined by a particular module?
Suppose i have a module1 where i define fields and i get list of all the fields in module2 using module1\_fields\_info(); this is done in D7. How to get list of fields defined by module1 in module2 in Drupal 8?

# Answer
> 3 votes
hook\_field\_info() defines *field types* in Drupal 7, so I think you're actaully interested in field types, not fields?

If so, field types, like any other plugin definition have a provider key, if you want to get the field types of a certain modules, call \Drupal::service('plugin.manager.field.field\_type')-\>getDefinitions() and then filter on the provider key:

```
$field_types = \Drupal::service('plugin.manager.field.field_type')->getDefinitions();
$field_types = array_filter($field_types, function (array $definition) {
  return $definition['provider'] == 'yourmodule';
});

```

Code example written in browser and untested.

# Answer
> 2 votes
This depends on how module1 defines the fields. Supposed it defines an entity type with the module name you can get the field informations like in this example for the user module:

```
$field_manager = \Drupal::service('entity_field.manager');
$fields = $field_manager->getFieldDefinitions('user', 'user');

```

The first parameter is the entity type and the second the bundle. If an entity has no bundles you use the entity type a second time.

If module1 defines a content type, then you get the fields by using the same function on the node and the content type name:

```
$fields = $field_manager->getFieldDefinitions('node', 'module1_type');

```

If module1 defines extra fields on another entity, for example the user, you get all fields defined in `hook_entity_extra_field_info()` hooks by module1 and other modules:

```
$extra_fields = $field_manager->getExtraFields('user', 'user');

```

The result in all cases is a keyed array with field definitions. You get the field names with

```
$field_names = array_keys($fields);

```

---
Tags: 8, entities
---


# Question
Title: Views exposed filter in block redirects to homepage instead of current page
Problem is similar to `drupal.org/node/1807916` #65.

I'm using Views ("7.x-3.6+4-dev" in D7.21) exposed filter in bartik, with my filter exposed as block in sidebar. When I click the reset button I am redirected to homepage instead of current page as desired.

URL shown:

> "localhost/?field\_sku\_value=123&field\_name\_value=&field\_component\_value=&op=Reset"

(last filter values)

Filter exposed on Views Page is ok.

Try to tweak `$form_state['redirect']` in `views_plugin_exposed_form.inc` doesn't work. Any idea?

# Answer
There is a jquery fix for this issue. See https://drupal.org/node/1109980, #23.
> 1 votes

# Answer
If your view is rendered inside a panel, you can choose the option "Use Panel path" in the pane settings of your view display.
> 1 votes

# Answer
The solution from https://www.drupal.org/node/1264316#comment-6930726 worked for me. Just copy the views-exposed-form.tpl.php to views-exposed-form--block.tpl.php from views module folder to your template folder and change the reset button code to:

```
<?php if (!empty($reset_button)): ?>
      <div class="views-exposed-widget views-reset-button">
        <input type="reset" id="edit-reset" onclick="history.go(0)" name="op" value="Reset" class="form-submit">
      </div>
<?php endif; ?>

```
> 1 votes

---
Tags: 7, views, redirection
---


# Question
Title: drush status only showing drush info, not drupal info
I have drush installed globally on my VPS (thanks to a previously answered question on here :D), logging in as root all works fine, but using a different user (let's call it *drushuser*) if I run:

```
drush @mysite st

```

I just get the drush version etc, not the drupal info. I assume this is down to the 'root' path in my alias:

```
'root' => '/home/accountname/public_html',

```

so logged in as root on the VPS that works - but what should I change it to for *drushuser*? I'm guessing drush is currently looking in /home/drushuser/home/accountname/public\_html and not finding drupal (since it doesn't exist there) so just giving the drush info instead?

I've tried '../accountname/public\_html' which didn't work.

# Answer
> 1 votes
If the `drushuser` account doesn't have read permission to the directory, it won't be able to run and bootstrap Drupal to get information, so it falls back to displaying the status it can which is Drush status.

If `drushuser` isn't the same as `accountname` above, it's very unlikely that `drushuser` will have access to the home directory of `accountname`. The root user can read files in every directory, so that is probably why it works as root.

You should be able to run drush as `accountname` or if you can put the public\_html files into a shared location and make sure that the permissions are set so that both users share a group that has read access.

---
Tags: drush
---


# Question
Title: How do you do download the files folder from the Acquia cloud service?
I just setup acquia cloud and have a site setup. I've did a git clone to my local desktop along with downloading the DB manually. But how do I get the files downloaded to my local desktop so I can do my own local testing?

Is there a quicker way to do this via drush to get the latest files and db pulled down?

# Answer
> 9 votes
You can read up on some drush specific tasks that you can do in this Elevated Third blog post

Acquia supplies drush commands and aliases that tie into Acquia Cloud API calls. So you can actually simply use the alias and the `rsync` drush command:

```
drush rsync --progress @sitename.env:%files @localenv:%files

```

You can also create and download Acquia database backups with the `ac-database-instance-backup` and `ac-database-instance-backup-download` commands.

Also, if you want an "all-in-one" solution, the newer versions of Acquia DevDesktop tie directly to your Acquia cloud account and can get database and file syncs automatically.

---
Tags: drush, files, acquia-cloud
---


title: Cron issue with Drush 8

text:
# Question
Title: Cron issue with Drush 8
My Drupal 6 sites are hosted on a Linux server with Apache 2.2, PHP 5.5, MySQL 5.6 installed. I use Drush 8 which I installed via composer. I set a cron job via cPanel which runs every day this script:

```
#!/bin/bash
# Script to execute all the cron jobs with drush
echo '**************** French site *******************'
cd /home/myuser/public_html/fr/sites/fr.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** English site ******************'
cd /home/myuser/public_html/en/sites/en.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** Spanish site ******************'
cd /home/myuser/public_html/es/sites/es.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** Completed **********************'

```

But it fails and ends with:

```
**************** French site *******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

<br />
<b>Warning</b>:  proc_open(): Descriptor item must be either an array or a File-Handle in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>434</b><br />
<br />
<b>Warning</b>:  proc_get_status() expects parameter 1 to be resource, boolean given in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>435</b><br />
<br />
<b>Warning</b>:  proc_close() expects parameter 1 to be resource, boolean given in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>436</b><br />
**************** English site ******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

<br />
<b>Warning</b>:  proc_open(): Descriptor item must be either an array or a File-Handle in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>434</b><br />
<br />
<b>Warning</b>:  proc_get_status() expects parameter 1 to be resource, boolean given in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>435</b><br />
<br />
<b>Warning</b>:  proc_close() expects parameter 1 to be resource, boolean given in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>436</b><br />
**************** Spanish site ******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

<br />
<b>Warning</b>:  proc_open(): Descriptor item must be either an array or a File-Handle in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>434</b><br />
<br />
<b>Warning</b>:  proc_get_status() expects parameter 1 to be resource, boolean given in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>435</b><br />
<br />
<b>Warning</b>:  proc_close() expects parameter 1 to be resource, boolean given in <b>/home/myuser/.composer/vendor/drush/drush/includes/startup.inc</b> on line <b>436</b><br />
**************** Completed **********************

```

The strange thing is that when I manually run `drush -v core-cron` on any site, the cron run ends successfully. I really don't know where the problem comes from.

# Answer
> 0 votes
Following the comments to the question, I've added `php -v` as the first line of my script after the shebang line and run it both manually and through cron.

Manually, I've run `sh myscript.sh` and got:

```
PHP 5.5.33 (cli)

```

and the script's ended successfully.

Through cron, I've got:

```
PHP 5.5.33 (cgi-fcgi)

```

and the script's ended in failure.

So it's indeed a php-cgi / php-cli problem: cron is using php-cgi instead of php-cli in my case.

But since I'm hosted on a managed VPS and since I don't intend to use D6 for much longer, I've finally found easier to write another script using wget:

```
#!/bin/bash
# Script to execute all the cron jobs with wget
echo '**************** French site *******************'
wget --no-cache --spider http://fr.mysite.com/cron.php
echo '**************** English site ******************'
wget --no-cache --spider http://en.mysite.com/cron.php
echo '**************** Spanish site ******************'
wget --no-cache --spider http://es.mysite.com/cron.php
echo '**************** Completed **********************'

```

It's a little slower than using drush but it runs well.

# Answer
> 2 votes
I would suggest that instead of calling `cd` within your script, you either set up drush aliases or pass the `--root` and `--uri` parameters to the cron request.

```
/home/myuser/.composer/vendor/bin/drush -v --root=/home/myuser/public_html --uri=fr.mysite.com core-cron

```

That should make sure that drush is running in the right context.

You can also make sure that drush is running with the php that you would like by setting the `DRUSH_PHP` environment variable.

---
Tags: drush, cron
---


title: Can't get Drush to function

text:
# Question
Title: Can't get Drush to function
I have a local site but drush doesn't seem to be functioning correctly:

$drush status=

```
PHP executable         :  /usr/local/bin/php
PHP configuration      :  /usr/local/etc/php/5.6/php.ini
PHP OS                 :  Darwin
Drush script           :  /Users/myuser/vendor/drush/drush/drush.php
Drush version          :  8.1.5
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :  /Users/myuser/.drush/sitename.aliases.drushrc.php

```

It's not listing anything about the drupal site, so I can't run any drush commands on the local.

Does anyone know how to set this up correctly?

# Answer
I'm reporting back to provide my solution.

The site itself was Drupal v 7.51. As you can see, I was using Drush v. 8.1.5.

Reverting back to 7 corrected the issue and was done fairly easily following the modules unraveled tutorial here: https://modulesunraveled.com/blog/install-drush-7-and-8-and-automatically-switch-versions-based-project.

Regards
> 2 votes

# Answer
Drush 8.1.5 should work just fine with Drupal 7. There shouldn't be a need to revert back to drush-7 just for that.

Typically if you don't get back any Drupal information from `status` it's because you're running it from a different directory without the `--root` parameter specified. If status returns a line of `Drupal root` but still doesn't give status of database, etc. it's possible that it can't read the settings.php file.
> 0 votes

---
Tags: drush
---


title: How do I make fields available?

text:
# Question
Title: How do I make fields available?
I am using Drupal 7, the Ubercart and Rules module; I plan to use the Views Rules) module. I want to use the Rules module to automatically publish nodes that contain data from a Ubercart order.

I'm attempting to automate a few processes on my Drupal 7 site after the completion of an order with Ubercart. Upon completion of an order, I would like to automatically publish a content type that contains data from the order (price, customer/user, seller, product name, entity reference data, etc). I can create the rule to publish the content type, but I'm struggling to figure out how to get the data from the order into the content type.

My approach so far has been to tag the order upon completion of an order, then fetch the order data. However, when I drill down into data selectors, the values I need are not available. Furthermore, I'm not sure I would know how to get it loaded into the content type upon publish.

I've come across Views Rules module which, to my understanding, will allow me to define the values to fetch. I've created views that I can load into Rules, but it appears that the View will return all results of the view instead of the result I need upon completion of the order (maybe I'm wrong about this?)

I just need a nod in the right direction on how to accomplish this. I'm just not sure if my approach is right. I have the basics of Rules, and have only constructed very simple rules. I imagine what I want to accomplish will require a more complex construct of Rules. Any suggestions are greatly appreciated, particularly on how to use Views to accomplish what I need.

# Answer
I don't understand most of this.. "publishing a content type?" You sure you don't mean "creating a node"?

Anyways, in conditions for the rule, choose "entity has field" for each field you need. This will allow you to use them in actions.
> 0 votes

# Answer
It seems that you're struggling (quite) a bit with how to use the Rules module to implement what you're looking for, together with the Views Rules module. Some details about the Views Rules module (from its project page):

> Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (either), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

1. Create a view (using Views) so that you have 1 Views result (row) with all the order details you want to be processed, whereas that view has fields (columns) for your price, product name, seller, etc. You'll need these View fields later on as values to be processed by your rule, "*to get the data from your order into the content type*", as in your question. Important: use a Views display type of "Rules".
2. Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop". In your case it may well be that you only have 1 views result (row), but the general concept is that you have "a number" of rows.
3. For each iteration step in your Rules loop, perform a Rules Action to "*do your thing*" (= get the data from the order in your content type). At that point you'll have all data from each column of your Views results available as so called Rules Parameters. So at that point it's a piece of cake to populate the various fields of your content type.
4. The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

***Easy, no?***
> 0 votes

---
Tags: 7, views, rules, ubercart
---


# Question
Title: How to change the site logo in a preprocess function?
I want to set my site logo programmatically, so that I can change the logo based on URL args.

I am able to set the `$variables['logo_img']['#uri']` with the following code in MYTHEME.theme but still the logo displayed does not change.

I have cleared registry.

I have tried setting my own logo and using default logo settings in theme settings UI:

```
function THEME_preprocess_page(&$variables) {
  $variables['logo_img']['#uri'] = 'http://newlogo.jpg'; }

```

I have also tried this:

```
function THEME_preprocess_page(&$variables) {
  global $base_url, $base_path;
  $variables['logo'] = $base_url . $base_path . drupal_get_path('theme','THEME') . '/images/logos/newlogo.svg';
}

```

Any help?

# Answer
> 6 votes
**How to change the site logo in .theme preprocess function?**

The site logo is no longer in the page template. You can change it now in the branding block:

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'system_branding_block') {
    $variables['site_logo'] = '/newlogo.jpg';
  }
}

```

**Caching**

You mentioned you want to change the logo based on URL args. This would be difficult to do this in the system branding block, because the template is not rendering the render array, but transferring only the content of three variables and so any attempt to add cache meta data would be useless.

You have two options. Implement your own site logo block plugin in a module or use this theming only solution:

* disable the site logo in the branding block
* set a variable with the url for the logo in page preprocess `$variables['logo']`
* add your own markup to the page twig to output the site logo

page.html.twig:

```
<a href="{{ path('<front>') }}" title="{{ 'Home'|t }}">
   <img src="{{ logo }}" alt="{{ 'Home'|t }}" />
</a>

```

By doing this in the page template you avoid caching problems because the page is already cached for each url separately.

# Answer
> 2 votes
If you need caching, you can do it with a pre\_render callback from `hook_block_view_system_branding_block_alter()`, in which you set `$build['content']['site_logo']['#uri']` and add cache metadata. This overrides the logo in the system branding block and preserves caching.

below is an excerpt from Drupal's color module where they use exactly this method.

You probably want something like this for caching:

```
CacheableMetadata::createFromRenderArray($build)
  ->addCacheContexts(['url.query_args'])
  ->applyTo($build);

```

You can define your logo's path in `$build['content']['site_logo']['#uri']`.

Full code:

```
/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function color_block_view_system_branding_block_alter(array &$build, BlockPluginInterface $block) {
  $build['#pre_render'][] = 'color_block_view_pre_render';
}

/**
 * #pre_render callback: Sets color preset logo.
 */
function color_block_view_pre_render(array $build) {
  $theme_key = \Drupal::theme()->getActiveTheme()->getName();
  $config = \Drupal::config('color.theme.' . $theme_key);
  CacheableMetadata::createFromRenderArray($build)
    ->addCacheableDependency($config)
    ->applyTo($build);

  // Override logo.
  $logo = $config->get('logo');
  if ($logo && $build['content']['site_logo'] && preg_match('!' . $theme_key . '/logo.svg$!', $build['content']['site_logo']['#uri'])) {
    $build['content']['site_logo']['#uri'] = file_url_transform_relative(file_create_url($logo));
  }

  return $build;
}

```

---
Tags: 8, theming
---


# Question
Title: Reaction after click on custom link inside views
I have a views which select all not validate "event". And the purpose is to add a button to validate the "event". My hope is when I click on the button a popup ask you to confirm the validation. if yes i want to use rule to make this action. My issue is that i don't know how to begin it

# Answer
Have a look at the Rules Link module. Some details from its project page:

> This module lets you create links which trigger arbitrary functionality with the help of Rules.
>
> Features:
>
> * Attach the link to any entities.
> * Show the link only for certain bundles.
> * Narrow the entities on which the link will be shown using the visibility conditions.
> * The links are usually displayed using Views.
> * For entities that can be displayed, the links can be shown on node view.
> * Supports an arbitrary number of additional Rules parameters for passing context via Views.
> * 3 types of links: Javascript, Normal and Confirmation form links.
> * Use individual permissions for each link.

Some more details (from its README.txt):

> To create a new link go to admin/config/workflow/rules\_links and click on "Add rules link". Enter the title of your link and set all the settings. After clicking on the "Save Rules Link" button, the module will generate a new And- and Rules-Set and their forms will be embedded into the rules link editing form.
>
> The And-Sets are called Visibility Conditions and will define when to render the links. The Rules set is the rule, that will be triggered on clicking the rule. Additionally Rules Links also generates access permission for each link, which you'll have to set in admin/people/permissions.
>
> The best way to display the links is currently using views. Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.
>
> Alternatively you can use render the links directly in the entities that can be displayed, using the option 'Show link in entity' in the Rules Links settings.
>
> Note that this will not work for links were the parameters have multiple paramaters.
>
> If you would like to render a link yourself in a theme or in a module, than use the function `rules_link_render_link()`.

PS: I'm assuming this question is about D7.
> 2 votes

---
Tags: views, nodes, rules
---


# Question
Title: How to restrict field permissions to referenced user?
I have a submit-review process where submitters choose their reviewer. The reviewers are linked By User Reference module. Submissions are public but have an Accept/Deny review button implemented with Button Field which only should be accessible by referenced user.

Workflow fields submodule seems to accomplish that behavior but unfortunately I can't get it to work with Workflow. There is an incompatibility of versions and maintenance seems not to be very active.

So I try to build my own solution using hook\_field\_access() like that:

```
function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && ($field['field_name'] == 'field_accept_review' || $field['field_name'] == 'field_decline_review')) {
        // is current user == node reviewer?
        return ($entity->field_reviewer == $user->uid);
    }
}

```

Do I have to use user\_load() before getting to the uid of the linked user?

# Answer
I assume field\_reviewer is an user reference field with only a single value allowed. If so use the following to get the referenced user's uid which is directly stored in field\_reviewer array in submission:

```
// is current user == node reviewer?
if (!empty($entity->field_reviewer)) {
  $reviewerId = $entity->field_reviewer['uid'];
  return ($reviewerId == $user->uid);
}
return FALSE;

```
> 1 votes

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


title: Collapse Text Module and Bullets

text:
# Question
Title: Collapse Text Module and Bullets
I have my collapsing working, but I'd like each collapsing title to have a bullet. When I try, my bullets are on a line by themselves, one line higher than the title. I thought I could accomplish this through CSS but can't figure out how.

Thanks so much!

# Answer
> 0 votes
## CSS

I'm going to assume you are using the default markup that the Collapse Text module generates, which is fieldsets. I'm being intentionally verbose in the CSS rules below so you can see the html elements along with the classes I mean to target, just in case your markup is different. You will probably not need so much specificity.

**To insert bullets before each title, you can use the following CSS in your theme:**

```
fieldset.collapse-text-fieldset legend span a.fieldset-title {
    display: list-item;
    list-style-position: inside;
}

html.js fieldset.collapse-text-fieldset legend span.fieldset-legend {
  background: none; /* Removes the arrows */
  padding-left: 0; /* Depends on your theme */
}

```

## Outcome

## Explanation

Collapse Text wraps each collapsible chunk of text in a fieldset and adds a few wrapper classes like `collapse-text-fieldset`. I suggest specifying one of the wrapper classes before targeting anything inside the collapsible fieldsets to avoid selecting all of the fieldsets on the page or on the site depending on where in the theme you're adding the CSS.

Your theme may have different indentation or padding applied to fieldset elements. In my test case there was 15px of padding-left on all fieldset legends as part of the base styles of my theme, and I wanted to remove that in order to avoid unnecessary space.

---
Tags: 7
---


# Question
Title: Do not show picture when video available
Got a content type with some text, and a video field and an image field (and some other stuff, like entity references between nodes, but not relevant for this question).

When displaying nodes for this content type, I don't want to display the image, if there is a video available.
So the image displays if the video field is empty. If a video was added to the node, the image should not display.

Can only be done by modifying the node template I assume? So I would need to copy the node.tpl.php and rename it to node--contenttype.tpl.php (with contenttype being the name of the content type)

But the PHP code in there just prints then entire $content so I cannot interfere with the displaying of the image separately.

Is there another customisation (the one producing the html for the node probably?) where I can wrap some "if" statement around the image field that check for presence of content in the video field?

# Answer
> 1 votes
You can use conditional fields module for this. https://www.drupal.org/project/conditional\_fields and set the dependency for your field. See the screenshot it will help you.

# Answer
> 0 votes
The node template is probably where you want to be doing your changes.
Just because the current template renders the $content variable (render array), doesn't mean it has to be done that way.
The template will have many other variables defined you can use, including the fields.
The easiest way I have found to see what variables and render arrays are available in a template is to install the devel module and output the value of the `get_defined_vars()` function.
eg (put this in the template file after installing devel).
`dpm(get_defined_vars())`

Doing it in a preprocess function (to alter and add variables before they get to the template) is also an option.
Setting variables in here to be used in the template is usually favored as it keeps your template clean.
As an example, in the preprocess function you could set a variable for if the video is available, eg. `$hasvid = true;` then in your template you could have a simple if statement checking `$hasvid` while at the same time keeping your template free of any complex PHP that may confuse a themer who has limited PHP experience.

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


# Question
Title: What's the right way to have a contextual link on controller action?
I just installed a custom module and created a controller with index function in it. I want to have a contextual link for this. I have following code in index function.

```
public function index() {
    return [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: hello'),
        '#contextual_links' => [
            'mymodule' => 'mymodule.another_action',
        ],
    ];
}

```

File : mymodule.links.contextual.yml

```
mymodule_configure:
  title: 'Configure Custom Module'
  route_name: 'mymodule.another_action'
  group: 'my_module'

```

Please suggest the right way.

# Answer
> 1 votes
I did this using a reference from below.

Adding the contextual link render element

I added a variable to the theme, and passed contextual link in controller function to twig template using that variable. Please see code below.

File : mymodule.module

```
function mymodule_theme() {
  return [
    'mymodule' => [
      'template' => 'mymodule',
      'variables' => [              //Added a variable content
        'content' => '',
      ]
    ],
  ];
}

```

File : mymodule.links.contextual.yml

```
mymodule_configure:
  title: 'Configure My Module'
  route_name: 'mymodule.route_name'
  group: 'mymodule'

```

File : IndexController.php

```
public function index() {
    $data['content'] = [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: index'),
    ];

    $data['#contextual_links'] = [
        'mymodule' => [
            'route_parameters' => [],
        ],
    ];

    return [
        '#theme' => 'mymodule',
        '#content' => $data,        //Pass Contextual link to the variable
    ];
}

```

File : mymodule.html.twig

```
{%
set classes = [
'contextual-region'
]
%}

<div {{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}                     //Render here
</div>

```

--

Thanks

---
Tags: 8, navigation
---


# Question
Title: Why Recent log message is showing anonymous user?
Whenever I do cron/clear cache, that activity are shown as anonymous in log message, while my login activity are shown with my name as shown in following image.

>

Should not be user be administrator's name instead of "Anonymous(not verified)" in case of cron? Is this by design or I am missing something in config? Thanks.

# Answer
> 5 votes
Running cron happens automatically when someone visits your site by default. Drupal does that automatically once every few hours to run certain cleanup/background tasks.

Additionally, cron jobs always run as anonymous user, that's why it is logged as that, even if you trigger it manually as admin.

# Answer
> 5 votes
> Why Recent log message is showing anonymous user?

because

> // Force the current user to anonymous to ensure consistent permissions on cron runs.

You can see code here.

```
$this->accountSwitcher->switchTo(new AnonymousUserSession());

```

**Any current user will be switch to anonymous user.**

Anyone have cron url with token can run cron. You can find url at admin/config/system/cron. And cron task will auto with you setting auto cron.

# Answer
> 0 votes
Some times some user who is not login/anonymous user try to do some activities with the system and those restricted activities logged in the system. This activity may done by the spam user as well.

Yes definitely you need to stop this action.
I think you need to check

```
/sites/default/settings.php should definitely have:

$update_free_access = FALSE;

```

Drupal Security Tip: disabling anonymous access to cron

Secure cron.php

---
Tags: 8, users, log-messages
---


title: Installation profile glitch

text:
# Question
Title: Installation profile glitch
When I construct unattended installation using for instance:

```
drush site-install my_inst_profile \
  --account-mail='helpdesk@acme.com' \
  --account-name='siteadm' \
  --account-pass='sitepass' \
  --db-su='dbadm' \
  --db-su-pw='dbpass' \
  --db-url='mysql://drupal:drupal@mysqldb/drupal' \
  --locale='pl' \
  --site-mail='site@acme.com' \
  --site-name='MY Site' \
  --yes

```

and even the simplest possible installation profile `my_inst_profile.info.yml`, `my_inst_profile.install` and `my_inst_profile.profile` taken directly from How to write a Drupal 8 installation profile, the resulted installation is malfunctioning.

The symptoms are as follows:

1. Lack of the middle part of the GUI
2. No administrator role in the resulted system
3. Stark theme used as a default one even if `info.yml` file indicates any other theme.

It is relatively easy to handle 2 and 3 using:

```
drush role-create 'administrator'
drush config-set user.role.administrator is_admin true

```

and

```
drush pm-enable seven --yes
drush config-set system.theme admin seven --yes

```

respectively. But the first one exceeds my Drupal capabilities.

There is some discussion and an issue queued on the net (see Adding translations to installation profile upon installation), but the proposals are no longer valid, as there is no /includes/locale.inc and even `locale_add_language()`, in Drupal 8.

Does anybody have any hints, on how to bring together ambition to use custom distribution with necessity to build localized site?

# Addendum 1

Here is `my_inst_profile.info.yml`

```
name: my_inst_profile
type: profile
description: 'Installation profile dedicated for ACME company.'
core: 8.x

distribution:
  name: ACME Installation Profile

# Required modules
dependencies:
  - node
  - history
  - block
  - block_content
  - breakpoint
  - color
  - config
  - comment
  - contextual
  - contact
  - quickedit
  - help
  - image
  - options
  - path
  - taxonomy
  - dblog
  - search
  - shortcut
  - toolbar
  - field_ui
  - file
  - rdf
  - views
  - views_ui
  - editor
  - ckeditor

themes:
#  - bartik
  - seven
#  - stark

```

Here is `my_inst_profile.install`

```
<?php
/**
 * @file
 * Install, update and uninstall functions for the profilename install profile.
 */

/**
 * Implements hook_install().
 *
 * Perform actions to set up the site for this profile.
 *
 * @see system_install()
 */
function my_inst_profile_install() {
  // First, do everything in standard profile.
  include_once DRUPAL_ROOT . '/core/profiles/standard/standard.install';
  standard_install();

  // Can add code in here to make nodes, terms, etc.
}

```

Here is `my_inst_profile.profile`

```
<?php
/**
 * @file
 * Enables modules and site configuration for a standard site installation.
 */

use Drupal\Core\Form\FormStateInterface;

function my_inst_profile_form_install_configure_form_alter(&$form, FormStateInterface $form_state) {

  $form['site_information']['site_name']['#default_value'] = 'MY Site';
  $form['site_information']['site_mail']['#default_value'] = 'helpdesk@acme.com';
  $form['admin_account']['account']['name']['#default_value'] = 'siteadm';
  $form['admin_account']['account']['mail']['#default_value'] = 'helpdesk@acme.com';
  $form['regional_settings']['site_default_country']['#default_value'] = 'PL';
  $form['regional_settings']['date_default_timezone']['#default_value'] = 'Europe/Warsaw';

}

// Add any further custom code here like hook implementations.

```

As I mentioned at the beginning, this is just a starting point for further installation profile development.

# Answer
> 4 votes
Those are not bugs and have nothing to do with locale.

The standard install profile sets up the administrator role, the theme configuration and many other things, see standard\_install() and its default configuration files like the overriden system.theme.yml.

I guess you mean the local tasks with "middle part of the GUI", that is a block and also set up by Standard, like many other blocks too.

If you create a new theme, it makes sense to look at standard on how it does things and copy the parts you need from it.

---
Tags: 8, installation, installation-profiles
---


# Question
Title: Does Drupal 8 core by default collect visitors data?
I am searching a lot since last few days but not getting an answer. I am in process of preparing Privacy Policy of site. I am not providing any user registration or user login facility but anonymous user can post comments. Now, question arises after I read following Q&A on DA,

Don't collect IP addresses in Drupal 7

Now, since I have no intention to collect any user information(have not enabled statistics module), then I can simply write, "I do not collect any user information". Again, question comes, what if the code is collecting IP address/Hostname without our knowledge.

So, if there is a way to know what information are collected, and how saved then we can be sure about that, and can state in privacy policy or If Drupal core is not collecting any data, then also we can be sure about that and write "We do not collect any visitor's data". Is there a way we can know?

**Note: Please let me know, if this question is going toward Privacy policy(away from drupal), I will move this to SO. But, again it is related Drupal CMS code, so I thought to ask here first.**

---

## UPDATE:

Have raised the issue at Drupal core: Legal privacy policy statement of Drupal core

and it you see the comment there is a link to other issue: Privacy Concerns as GDPR Compliance, which says there is already work going on and regarding this module creation is underway, module will be General Data Protection Regulation.

**Please add comments in issue, if you want to add some suggestion.**

# Answer
The answers and comments in the linked question for Drupal 7 are still valid, with one exception. Drupal 8 gets the client ip address from `Symfony\Component\HttpFoundation::getClientIps()`. This returns the client ip from the header `REMOTE_ADDR`, unless you set up a trusted proxy. In this case you would have to configure this proxy to obfuscate the visitor's data.

In all other cases it should be enough to overwrite part or all of the ip address in a Symfony middleware.
> 3 votes

---
Tags: 8, users
---


title: Admin menu vanishes

text:
# Question
Title: Admin menu vanishes
I was installing some modules. Suddenly, the helpful buttons across the top for admin mode disappeared. Can anyone tell me what happened and what I have to do?

I am able to go to `{website}/admin` and essentially see the same buttons on the page that, I guess, I would see across the top of the page, but I wonder if I am missing out on some functionality.

But even if I still have the functionality, I still can not find the place where I can install new modules, and the system is telling me I need the "views" module to view some content I need to manage.

# Answer
> 1 votes
You maybe disabled the `help module`

And to be able to install new modules through your admin you need to enable `Update manager`

# Answer
> 0 votes
I was able to fix this issue by ftp'ing some modules for the Admin Menu. The modules I had already installed expected it and, when they did not find it, the menu could not be displayed.

---
Tags: 7, navigation
---


# Question
Title: How to prevent a Rules Action to happens twice using Rules Event User account validated?
I've set up a rule that sends you an HTML email when you activate your account. It seems to throw back a notification about:

> Notice: Undefined variable: attachment in SmtpMailSystem-\>mail()

But it seems to send the email anyway, but what I don't understand is that I receive 2 emails everytime I test it. I've checked the log files and it seems to log that an anonymous user has used the validate URL to confirm their email address, then sends the email. Then it opens up a session for this new user, and then sends them the email again.

I've set the rule to run on '***When the user account is activated***' and if I turn the rule off I get no emails, so it isn't that there is anything else sending an email too, it is only this rule, it just seems to do it twice.

Can anyone offer a solution?

I'm using the SMTP, Mimemail and Mail System modules

If anyone needs me to post any specifics about the rule, or the error or the email text etc, just ask, I just didn't want to flood the post with huge blocks of code if it might not have helped.

*EDIT1*

Log file output (obviously I have flipped the order for it to make sense, log files are recent most recent first)

* New user: unset\_username (fake@email.com). // When I create a new account
* Sending mail to: "Firstname Lastname" // Emails out the verification request
* E-mail validation URL used for Firstname Lastname with timestamp ...
* Sending mail to: "Firstname Lastname" // Emails out the confirmation email once
* Session opened for Firstname Lastname.
* Sending mail to: "Firstname Lastname" // Emails out the confirmation email again

*EDIT 2*

Determined the issue is nothing to do with the emails, tried re-creating the rule but sending an output to the page rather than sending HTML email, it was confirmed that this rule runs twice (and hence nothing to do with emails in particular) by the fact that the message was output twice as well.

**UPDATE**

As Molot has pointed out this isn't anything to do with emails, just the rule happening twice. I'll leave the text above incase anyone else is trying to send out emails on verification and they come to the same conclusion I did, so they can find this and understand whats happening.

# Answer
> 1 votes
### Understanding what's happening

Your question seems like a variation (IMO not a duplicate) of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

> some other module code is calling a `user_save` on `hook_user_update` triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

### Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

### Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like \[account:last-login\] = never?". More specifically:

* Add a Rules Condition like: ***User does NOT (!!!) have a role with role id = "`4`"***.
* Add a Rules Action like: ***Grant User the role with role id = "`4`"***.

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "`4`" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

* The **1st time** your Rules Actions will still be performed (and grants the designated role).
* the **2nd time** not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.

In other words: "***this will prevent your Rules Actions to happen twice***" (as in your question).

---
Tags: 7, rules, emails, actions
---


title: Create a View Linking to Content

text:
# Question
Title: Create a View Linking to Content
I'm new to Drupal in general and am having some trouble with creating a view to display and link the information I want.

I have a content type called Project. This content type has a boolean called "Project Status" where "true" is labelled as "In Progress" and "false" is "Completed".

I want to create a block view to use as a sidebar on my page that lists all projects where the project status is true, and links to those projects by their title. I can make the view display the list of the projects that are in progress, but I can't figure out how to make it link back to those projects.

How do I do this?

# Answer
I found the issue was in the "Fields" section of the view. If you click the "Content: Title" field, there's a checkbox to link to the content. I suspect this wasn't checked in the view that I was having trouble with, but it is enabled by default.
> 1 votes

# Answer
The title field will have an option on its settings to "Link this field to its content". Check off that box and save the view, and the titles should be linked to their node detail page.
> 1 votes

---
Tags: views, 8
---


title: How can I add a theme template to site?

text:
# Question
Title: How can I add a theme template to site?
Bootstrap has templates like *new age*, *creative*, *clean blog*, etc. How do I add these templates to my site?

My workflow didn't work out well.

* I copied the starter kit *less* to themes/custom
* I renamed it to testtheme
* I renamed all THEMENAME.yml files to testtheme.yml
* I executed `git clone https://github.com/BlackrockDigital/startbootstrap-new-age.git`

Edit: \- Installed and set as Default (backend)

Unformatted bootstrap

```
edit 2:
global-styling:
 ` css:
    theme:
      css/style.css: {}
      css/new-age css: {}
      css/new-age.min css: {}

bootstrap-scripts:
  js:
    js/new-age.js: {}
    js/new-age.min.js: {}

```

# Answer
> 2 votes
Follow the following steps to add the bootstrap:

```
1. Put the bootstrap theme in the theme folder.
2. If you want to create a sub theme then copy the cdn folder from starterkits and rename. (themename)
3. Rename .info.yml , .libraries.yml and .theme files with your themename.

```

Include the CSS in theme.libraries.yml file. Like below

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

global-scripting:
 css:
  theme:
   js/script.js: {}

```

---
Tags: theming, 8
---


title: Create two dynamic select lists

text:
# Question
Title: Create two dynamic select lists
Hi, I want to create a drupal view that display as the uploaded image. There are two select list. First select list is static. According to the selected category sub category should by populated. All categories and subcategories are stored as taxonomy term. Any idea would be appeciated.

# Answer
> 2 votes
You can take a look at the Taxonomy menu module. Some details about it (from its project page):

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

Also look at this post:

How do I direct link a view to a taxonomy menu?

# Answer
> 2 votes
Your usage of the word "view" and the tag in your question is misleading, since IMO your question is not about the Views module.

As an alternative to using taxonomy terms, you should give it some thought to rework what you're trying to do using regular *fields*. By doing so, you can use the Conditional Fields module to achieve your goal. Excerpt from the Conditional Fields project page:

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

So if you have a field labeled (say) ***`Category`*** with 11 possible values `Electronics`, ..., `Other` (as in your question), you could combine this with a ***`Subcategory`*** field labeled (say) `Electronics` with 12 possible values `Mobile Phones`, ..., `Video Games & Consoles` (as shown in your screenprint for subcategory). Then add 10 more similar *subcategory* fields for `Cars & Vehicles`, ..., `Other` and you're done.

PS: I'm assuming this question is about D7.

---
Tags: views, theming
---


title: How to check payment successfully?

text:
# Question
Title: How to check payment successfully?
I use module ubercart. Payment method is PayPal. I want process some task after user payment successfully. I write custom module. I want know how to check user payment successfully with some hook, event can catch?

# Answer
I have the answer with suggestion of maintainer module. I can use `hook_uc_payment_receipt_insert()` to do that.

```
/**
 * Implements hook_uc_payment_receipt_insert().
 */
function uc_payment_uc_payment_receipt_insert(PaymentReceiptInterface $payment) {
  $order = $payment->getOrder();

  // Log a message against the order.
  $method_name = $payment->getMethod() ? $payment->getMethod()->getPlugin()->cartReviewTitle() : t('Other');
  $log_message = t('@method payment for @amount entered.', array('@method' => $method_name, '@amount' => uc_currency_format($payment->getAmount())));
  $order->logChanges(array($log_message));

  // Automatically mark paid orders as "payment received".
  // @todo Remove when Rules is available.
  if (uc_payment_balance($order) <= 0) {
    $state = $order->getStateId();
    if ($state == 'in_checkout' || $state == 'post_checkout') {
      $order->setStatusId('payment_received')->save();
    }
  }
}

```

Source
> 1 votes

---
Tags: 8, ubercart
---


title: Show form after youtube video ends

text:
# Question
Title: Show form after youtube video ends
I am having a watch video button which shows a YouTube video in color box. I want to show a form (webform/custom form) to appear after the video ends in the same color box itself. If users fill the form and submit it, the form should disappear, showing only the video that was ended in the colorbox. I am trying to achieve it using using the Youtube player API but not able to achieve my objective.

Is there some other way to achieve it?

# Answer
> 2 votes
That looks doable by youtube-api.

What you can do is have the form loaded already when you should the color box, with `display: none` on form block.

Now with help of youtube api you can detect video end and can toggle visibility to `display: block;`

Refer here for youtube api example:-

source https://stackoverflow.com/questions/7853904/how-to-detect-when-a-youtube-video-finishes-playing

---
Tags: webforms, javascript
---


# Question
Title: How to display different sets of images per page in sidebar?
I'm trying to show different sets of four images in sidebar depending on which page a visitor is viewing. Aside some trouble I'm wondering whether a proper workflow should be as follows:

1. Create "Four Images" content type set up as a single multiupload image field.
2. Create "These Four Images", "Those Four Images", etc. content.
3. Create as many views as content units in step two set up as a grid block.
4. Add every block to sidebar in Block Design and restrict each block to be displayed using "Visibility-\>Pages".

So I'm getting a Sidebar in Block Design rapidly filled with four images views. Is there any other cleaner way of doing this?

# Answer
> Create as many views as content units.
>
> Is there any other cleaner way of doing this?

Yes, you do not need to create a View for each of your nodes/pages/content. You can create a dynamic view which automatically passes the Content ID to Views.

1. Create "Four Images" content type set up as a single multiupload image field.
2. Add these "Four Images" to you node.
3. Create a View Block

4. In View, for Fields, add your image
5. **Click on Advanced** (far right), for Contextual Filter add `ID` .Provide default value, Content ID from URL. (**Note:** The view preview will go blank, which is normal, since the View edit page does not have a Content ID.)

6. Go to blocks (`/admin/structure/block`), and add the View block to a region. For Visibility settings select the content type that you want this to appear in.
> 1 votes

---
Tags: views, 8, blocks, media
---


# Question
Title: Drupal Installation modules leftovers cleanup
I have some questions that more experienced Drupalers might know.

When you have been developing a Drupal site, installing, uninstalling and testing various modules for different set of functionalities, when the launch day comes how do you clean up leftovers of the modules? To be more specific.

1. How do you remove folders that are not needed anymore from the sites/all/modules folder?
2. How do you remove leftover database tables?
3. Is there a contrib module that can actually do that? Cleanup a Drupal Installation?

Thanks in advance.

# Answer
> 1 votes
While I personally keep and eye on module listing page and make list of modules to be uninstalled at the time of going live, usually the 'To Uninstall' list contains some UI wrapper modules like views\_ui, devel, etc. But searching for any contrib module I came across unused\_modules, I think it might be worth trying what this module gives out of the box.

1. How do you remove folders that are not needed anymore from the sites/all/modules folder? https://www.drupal.org/project/unused\_modules
2. How do you remove leftover database tables?

You can you schema module, which basically identifies tables and modules relation and also list down orphan tables, this can give you a list of tables which might be just left over tables.
3. Cleanup test data content.

delete\_all module seems to allow to cleanup the test content with different variation via drush.

---
Tags: 7
---


title: How do I print only 2 menu links?

text:
# Question
Title: How do I print only 2 menu links?
I want to print the menu items as follows.

```
Menu1   Menu 2    Menu3     More
                            Menu4
                            Menu5

```

I am getting them as in the following screenshot.

The *More* menu should contain only *Menu 4* link. I created these menu links from the administrative pages.

I printed the menus using the following code.

```
$menutopleft = menu_navigation_links('menu-top-left-menu');
print_r(theme('links__menu-top-left-menu', array('links' => $menutopleft)));

```

# Answer
Try this from admin panel. Create hierarchical menu for this. See the screenshots
> 0 votes

---
Tags: 7, theming, navigation
---


# Question
Title: Can't create content without field title
I wanted to remove the field title from my content because I don't need it and don't want the user to see it or create it so I remove it.

But now when trying to create new content the following error occurs:

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

Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null: INSERT INTO {node_field_data} (nid, vid, type, langcode, title, uid, status, created, changed, promote, sticky, revision_translation_affected, default_langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12); Array ( [:db_insert_placeholder_0] => 6 [:db_insert_placeholder_1] => 6 [:db_insert_placeholder_2] => imovel [:db_insert_placeholder_3] => en [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => 1 [:db_insert_placeholder_6] => 1 [:db_insert_placeholder_7] => 1486378602 [:db_insert_placeholder_8] => 1486378720 [:db_insert_placeholder_9] => 0 [:db_insert_placeholder_10] => 0 [:db_insert_placeholder_11] => 1 [:db_insert_placeholder_12] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Drupal\Core\Database\Statement->execute(Array, Array) (Line: 610)
Drupal\Core\Database\Connection->query('INSERT INTO {node_field_data} (nid, vid, type, langcode, title, uid, status, created, changed, promote, sticky, revision_translation_affected, default_langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12)', Array, Array) (Line: 81)
Drupal\Core\Database\Driver\mysql\Connection->query('INSERT INTO {node_field_data} (nid, vid, type, langcode, title, uid, status, created, changed, promote, sticky, revision_translation_affected, default_langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12)', Array, Array) (Line: 32)
Drupal\Core\Database\Driver\mysql\Insert->execute() (Line: 917)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->saveToSharedTables(Object) (Line: 855)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->doSaveFieldItems(Object) (Line: 263)
Drupal\Core\Entity\ContentEntityStorageBase->doSave(NULL, Object) (Line: 392)
Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 761)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object) (Line: 364)
Drupal\Core\Entity\Entity->save() (Line: 356)
Drupal\node\NodeForm->save(Array, Object)
call_user_func_array(Array, Array) (Line: 111)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object) (Line: 51)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object) (Line: 585)
Drupal\Core\Form\FormBuilder->processForm('node_imovel_form', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 48)
Drupal\Core\Entity\EntityFormBuilder->getForm(Object) (Line: 113)
Drupal\node\Controller\NodeController->add(Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 139)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 38)
Drupal\webprofiler\StackMiddleware\WebprofilerMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

I already saw Automatic Nodetitle but it only works for Drupal 7 and I'm working on 8

# Answer
> 3 votes
One trick you can set a default value for node title and Exclude from display.

The preferred way to do this is to use the create hook.

```
use Drupal\node\NodeInterface;

function mymodule_node_create(NodeInterface $node) {
  if ($node->getType() == 'node_type') {
    $node->title = 'Test12';
  }
}

```

or

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "new_content_type_node_form") {
    $form['title']['widget'][0]['value']['#default_value'] = 'Test12';
  }
}

```

Exclude Node Title module for hide the title or You can check from display setting as well to hide.

# Answer
> 0 votes
You can use Automatic Entity Label to generate titles automatically, so that user don't have to enter manually.

---
Tags: 8, entities
---


title: Display Users emails with views

text:
# Question
Title: Display Users emails with views
I want to display the users emails with views, but it doesn't show for the users, only the administrators can see them.

How can i display them to the users with views, and i have a warning: Email address for a given user. This field is normally not shown to users, so be cautious when using it.

# Answer
> 1 votes
I found a way to do it by using user\_presave, i created a field\_profile\_email field using this answer : https://drupal.stackexchange.com/a/205308/65949

---
Tags: views, 8
---


# Question
Title: AJAX pagination with back button Drupal view
I have one view of a multimedia page wherein I use AJAX for pagination. The view shows the result of a multimedia image. When I click on the image it goes to the inner content page. In the inner content page there is a back button. When I click the button, it goes back to the previous page from where I came.

When I click on the back button it always forwards me to the multimedia page. But I want it to forward me to pagination page 2 if I came from page 2.

# Answer
> 1 votes
There is a module views\_ajax\_history which uses https://github.com/browserstate/history.js to maintain the current state of page and push them into browse history with HTML5 history api. This library support fallback if history api is not supported by older browser.

---
Tags: views, ajax
---