# Question
Title: How to make certain nodes available to anonymous users?
I am having a site that hosts a number of content items (nodes) that are available to registered users. We would like to make some of those data available to anonymous users, too, via a view. I have encountered so far two issues:

1. The nodes have attachments and currently the attachments are saved in Drupal's **private** storage. When an anonymous user will try to access the attachment directly, they will see an error.
2. Currently, I deny to anonymous users the permission to *View published content*. Thus, when a user clicks a link to a node, he will see an *Access Denied* error. This can be perhaps solved by using Content Access.

The solution I can think of is to clone the nodes I want to make public and make public their cloned counterparts but I dislike data copying as a practise. Any other ideas?

# Answer
> 4 votes
Just add a field to your nodes, similar to the "checkbox" as described in the question "How to allow users to post content and easily overrule its default access settings?". That field is used when creating a node, to indicate if the node should be viewable by anonymous users also (the default probably being "no").

With that, you could use the Rules module and the Content Access module to implement what you're looking for, similar to what I described in my answer to that same question mentioned above.

This approach should work for brand new nodes being created, while it should also work if you add such field to existing nodes. Though you'd have to experiment a bit to see which Rules "Event" is the bet fit in your case (I'd assume that node create and/or node update is what you'd need).

If you only want "*some of those data*" to be available to anonymous users, then you may want to add the Field Permissions module also (so that only the relevant fields can be viewed by anonymous users.

# Video tutorials

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

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


# Question
Title: Display related nodes with taxonomy hierarchy in a View
MY taxonomy is set up like:

```
* Parent term
    * Child term

```

I have a content type with a term reference so they can select the term it is associated with.

And I need a view that displays a result like:

```
* Parent term
    * Child term
        - Related node
        - Related node
        - Related node
* Parent term
    * Child term
        - Related node

```

Is this possible with drupal 7 Views 3? I am able to relate nodes with only one level of taxonomy hierarchy, but not two. Every example I have come accross does not display related nodes with children terms, only with parent terms. Any help would be appreicated!

# Answer
> 1 votes
I was able to accomplish this functionality through the use of two separate views combined into one. I could not find a way for Drupal to handle this out of the box. Essentially I am using one view to show the nodes related to the child terms, and using another view to bring in the *View displaying child related nodes* and sort it under the parent term.

The modules I used were: Views PHP, entity reference

## **Create your taxonomy vocabulary**:

> ```
>  * Parent term
>      * Child term1
>      * Child term2
>
> ```

## **Create a content type**

Once created add a Entity Reference field of type *Term Reference* referencing your taxonomy vocabulary's children terms you have created. Create a handful of nodes.

## **Create a View Block displaying content (related Nodes)**

After creating the View Block of content (the content type with the reference, show fields, HTML list), include the fields you want to show for the *related node* and give that view a contextual filter of the Entity reference field you used for the content type. Simply set the settings of the contextual filter under **When the filter value is NOT available** to *Hide View*. You can optionally set the no results behavior as well.

## **Create a view displaying taxonomy terms (Master view)**

Create a view of taxonomy (HTML List, Show fields), add a relationship of **Taxonomy term: Parent term** and require this relationship. Add field `Taxonomy term: Term ID` and hide from display. Add field `taxonomy term: Name` and under the field setttings, set the relationship to *Parent*, then hide from display. Add field `Taxonomy term: Name` to display the name of the term. Finally add a `Global: PHP` field and under the **Output code** provide the following snippet:

```
<?php
   $viewNodeDetail = views_get_view('YOUR_VIEW_BLOCK_MACHINE_NAME');
   $viewNodeDetail->set_arguments(array($row->tid));
   print $viewNodeDetail->preview('BLOCK_MACHINE_NAME');
?>

```

Under the view format settings set the **Grouping field Nr.1** to the `(Parent) Taxonomy term: Name`.

This will treat the view block as a field (the view block is the child term + node and the master view sorts by the parent term). This will give you an end result of:

> * Parent term
>     + Child term
>         - Related node
>         - Related node
>         - Related node
> * Parent term
>     + Child term
>         - Related node

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


# Question
Title: How do you properly use "Fetch entity by id" in Rules in order to access its fields?
I am trying to set up a RUle that loads and node (Fetch entity by id) and then, on another action, I want to access fields of the fetched entity. However, while I see the loaded node on the data selector of the next actions, I cannot seem to access its fields, only its "normal properties".

Any ideas?

# Answer
I got to this question whilst searching for a different solution to my own problem, but I think I know what's wrong anyway, even if it's 2 years old, it might help someone in the future :P

I think you have to add a condition to determine the type of Entity you are looking at, either by using 'Entity has field' or 'Data comparison' to determine what content type you are looking at. The reason you only see the 'normal properties' by which I assume you mean NID, Author, Title etc, is because it cannot guarantee it has the fields you want, until you determine what content type it is
> 2 votes

# Answer
You can use the rules\_conditional module This module gives you the option to add conditions in the actions area:
> 2 votes

# Answer
For anyone still looking for an answer to this, I used a workaround for my case.

I wanted to get field data on a node that was two links away from the one I had in rules. Loading the first referenced node was simple enough, but to load the second one I had to use PHP in the field that I eventually wanted the data to be outputted in and use node\_load. Theoretically this would work for any level of separation.

This probably won't work for a lot of cases, but it might be useful for a couple.
> 1 votes

---
Tags: rules
---


title: How can I make the sidebar more narrow?

text:
# Question
Title: How can I make the sidebar more narrow?
I am trying to make the sidebar more narrow in a Bootstrap 3 theme, in Drupal 8. There is no numbered class like col-sm-4 here that I could change. What is the right approach to take in this case?

```
<div class="row">
  {% if page.sidebar_first %}
    <aside class="{{sidebar_grid_class}}">
      <!--#sidebar-first-->
      <section id="sidebar-first" class="sidebar clearfix">
        {{ page.sidebar_first }}
      </section>
    </aside>
  {% endif %}
</div>

```

# Answer
> 0 votes
col-sm-4 will be applied via a function in the theme. if you search through the theme for where the variable is set you can change it there. Possibly in the .theme file.

---
Tags: 8, theming
---


# Question
Title: How to add pager at the bottom which allow shifting between views?
I am looking for how to add pager in the complex set of view content. In my case, \- I have 5 views with different titles, and have 10 items in each views. \- Now, I want to divide each view in 2 pages, so 5 items on each page, so that 5 views will have 10 pages in sum. \- and these all 10 pages has to be connected by single pager 1,2,3....10. \- So on Page-1 View-1 title and its 1stpage and on Page-2 same title and half content of View-1 as described above (5+5). \- and on Page-2 Views-2 with its title and on Page-3 views-2 title and half content of Views-2.. \- So, on till views 5. (Please see First image for easy understanding)

Now, what I tried, (1) I added views in views using Views field view module, So I had Main Views which have that 5 views as field and can set 1 item(1 view) per page, so each view will go on each page, but again for dividing each that inside view/sub-view in 2 parts I have to add pager to that each 5 views with 5 items,....So on in the final product MainView(inside Sub-view) will have two pagers....I tried and attaching the Screenshot in the second image.

And Second point, Probably everybody would have seen the Drupal Documentation section of drupal.org. At the bottom the following type of PAGER (shown in attached image- 3) which allow the shift from one topic to other topic. Will it be possible in the above case.

# Answer
Create 10 different page views. Example:

In Page View1 click on add page

In your view pager, select Display specified number of items.

Then add an offset of 5 (so your view will start from row 6)

**If you're going to make changes to anything make sure you select this page override**, otherwise it will make changes to all your page views. (On previous screenshot, see my pager options, I forgot to do that. Should be this page override)

On your footer Add Global text area. (remember this page override)

Then use html to create your own pager. (this is for view 2)

```
<a href="/view1">1</a> <b>2</b> <a href="/view3">3</a> .... <a href="/view3">Next ></a> <a href="/view10">Last >></a>

```

Then change code accordingly for view 3. (remember this page override)

**Now we will need to hide the real pager**.

Under Advanced, click on theme info. Then click on Display Output and copy the entire code that's there.

Create a new file and paste the code there.

Now find and delete the `<?php print $pager; ?>` line.

Now rename the new file to `views-view--[view name goes here]--page.tpl` (In my case my view is called sadfsafd)

Note: Do not use `views-view.tpl.php` as your template name, because that will affect all of your views, and we don't want that. By using `views-view--sadfsafd--page.tpl` I am only affecting the sadfsafd view.

Then upload views-view--\[view name goes here\]--page.tpl to your sites/all/themes/template folder.

Now clear/flush Drupal cache.
> 1 votes

---
Tags: views, paging
---


# Question
Title: Display content that reference the logged in user using Views
I have a content type Job with a Entity Reference field. This field (field\_data\_field\_job\_applicants) has a target type of User, and maximum number of values set to 10.

What I have got working so far is adding the users (specifically their uid) to this list when they click "Apply Job" on a job page.

What I am trying to do now is: when a job applicant logs in, they will see a collection of jobs they applied for.

More specifically, I want to tell the Views block to only display jobs where \[current-user:uid\] is referenced by field\_data\_field\_job\_applicants.

# Answer
1. Create a content view and add a contextual filter for the field you created. My test contextual filter was called `Content: User Ref Test`. Your contextual filter will have the same name as the field you created.

2 . In the contextual filter's settings, click `Provide Default: User ID from logged in User`. This will only show content where the user has been referenced.
> 1 votes

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


# Question
Title: Sensitive data on configuration managment
How can I prevent some sensitive data (e.g. password for the SMTP module) from getting into my repo as part of the Configuration Management system?

# Answer
From page 17 of the Drupal PCI Compliance Guide:

> **Removing credentials from settings.php.** One can include a `settings.local.php` file within `settings.php` to ensure that sensitive information is not distributed.

This is good advice and is what most people do.

If you have a lot of information you want to store securely, looking at the Encrypt module or even a Lockr integration might be advisable.
> 1 votes

---
Tags: configuration
---


title: Date form to unix timestamp

text:
# Question
Title: Date form to unix timestamp
I'm using Drupal 7.8, and am trying to get the user to specify a date using the drupal date form. I want to take this date, and save it to a database as a unix timestamp. The trouble is, I think the data given by the date form is based on the user's current timezone. Does drupal provide anyway to convert the form data back to unix time? Is there an easier way to handle dates?

# Answer
I'm pretty sure the values stored using the date attribute are unaltered and just passed on in an array. So the question would be if the user submits the date for UTC or his/her timezone. I would say the latter ;-)

I'm no expert on date settings and timezones, but had seen this question before on stackoverflow, so taking that into account I assume you can do this:

```
global $user;
$datefields = $form_state['values']['submitted_date'];
$submittedDate = "{$datefields['year']}-{$datefields['month']}-{$datefields['day']}";
$timezone = $user->timezone;
$newdate = new DateTime($submittedDate, new DateTimeZone($timezone));
$unixts = $newdate->getTimestamp();

```

This would require the user to have set his/her timezone accurately in the account settings.
> 10 votes

# Answer
I think you want to store the timestamp of the user, you can use strtotime function for converting the date to unix timestamp. I used the below code for the same :

```
$date = $date['year'] . '-' . $date['month'] . '-' . $date['day'];
$timestamp = strtotime($date);

```
> 0 votes

# Answer
Use mktime():

```
$values = $form_state['values'];
$unix = mktime(0, 0, 0, $values['date']['month'], $values['date']['day'], $values['date']['year']);

```

This will produce a unix time converted using the time zone of the current user.
> 0 votes

---
Tags: forms, datetime
---


# Question
Title: Display/Print both full content and teaser in node.tpl
I want to display both full content and teaser content at the same time in node.tpl.php Here is an example of what i want to display

```
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a href="#mini" data-toggle="tab">Mini Table</a></li>
    <li><a href="#full" data-toggle="tab">Full Table</a></li>
</ul>
<div id="table-tab" class="tab-content">
    <div class="tab-pane active" id="mini">
        TEASER DISPLAY
    </div>
    <div class="tab-pane" id="full">
        FULL CONTENT DISPLAY
    </div>
</div>

```

I search for it but didn't find the answers. Please Help

# Answer
I think this would be worked for you.

for teaser use

```
$rendered_teaser = render(node_view(node_load($node->nid), 'teaser'));
print $rendered_teaser;

```

and for full use

```
$rendered_full = render(node_view(node_load($node->nid), 'full'));
print $rendered_full;

```
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: How to Filter Node Reference Field Values Using Multiple Views?
I have a node reference field called *field\_parent\_dept*. I re-use this field in several content types. The list of nodes that can be referenced are provided by a view. The values are filtered based on logged in user.

I'd like to add this field to a new content type, but the departments need to get filtered in a completely different way. I need a new view to accomplish the filtering. It appears I need to create a new field, because the view is a field setting. *Field settings apply to the field everywhere it is used.*

Are there any other options?

# Answer
According to my understanding and the following answer, I believe you can reuse that same field. It will get cloned and then you can go and modify the field settings. This will affect only that field instance, specific to the entity/bundle (node/content-type).

Hope this helps!

Difference between Field and Field Instance?
> 0 votes

# Answer
If you give that department a different user role, you might be able to create groups of filters in the view that provides the values if you can get current user role as a filter option.

So click the "add/rearrange" next to filters. Then one group of filters for these roles OR another set of filters for the special role.

I can't test it right now but it could be an easy way to handle it.
> 0 votes

---
Tags: nodes
---


title: How to link on block

text:
# Question
Title: How to link on block
I work on D8. I Create to custom block with display content and Read More option. The URL alias is about\_us of `node/2`, I want to add read more link with `node/2` and show about\_us on URL.

# Answer
If you have created that custom block using a view , yo can easily add link to the respective node.You can add `content: link` in the FIELDS section
> 0 votes

---
Tags: nodes, blocks
---


title: Export translations of field labels

text:
# Question
Title: Export translations of field labels
Drupal 7. I work on multi language site. I have a content type with entity translation fields. I've added translation to field labels and settings on my DEV copy of site and now I need to export and import it to Production.

Is there any module in Drupal 7, that helps me to export and import field labels/settings? Or maybe someone tell me, how to export values from "locales\_source" and "locales\_target" tables and import it to my Production database? Because I see only "lid" auto increment field in both tables.

Locales Source table

Locales Target table

# Answer
Problem resolved by Drupal standard translation export. I just check "Fields" and select "Existing strings and the plural format are kept, only new strings are added." when Import \*.po file.

admin/config/regional/translate/export
> 0 votes

---
Tags: entities, i18n-l10n
---


# Question
Title: How to select files from /sites/default/files with IMCE filebrowser?
Somehow the settings of directories in the configuration of IMCE (7.x-1.7) is pointing to \<root\>/. which lets met start in the private\_files directory but not in the (public) files directory.

I couldn't figure it out where to change this. I tried to set a path to the public files directory with \<root\>/.. but Drupal would not allow me.

The settings under Home\>Administration\>Configuration\>Media is set to: Public file system path: sites/default/files Private file system patch: sites/default/files/private\_files

Anybody having a clue ?

# Answer
> 0 votes
Create a new IMCE profile from

> admin/config/media/imce/profile

Don't forget to add the **Permitted file extensions** and **Directories** while creating the IMCE profile.

# Answer
> 0 votes
Please do check the required permission , specially for Apache user, ie `www-data` as this is the user which operates on behalf of the server. If you want to check whether it is a permission or some other issue, you can use the following command ( `For temporary basis and not on production`) to change the permission of files directory.

`sudo chmod -R 775 /sites/default/files/`

and

`sudo chown -R root:www-data /sites/default/files/`

In place of root, use your usernamem who is the main owner of the directory or

---
Tags: files
---


# Question
Title: How to auto unpublish a node after edit and later published by admin?
I need to unpublish my node after edit. For this I created a rule. It's doing the unpublish of my node after editing. But after this I am not able to again publish this node.

I also need to fire a mail to admin after update.

# Answer
Here's how you can do this:

1. Create a rule on node update event.
2. Add Condition where user role is not "Administrator/Moderator". (This will make sure that the content doesn't get unpublish when admin is updating it.)
3. If required, Add condition where content is of type "Article".
4. Add Action "Unpublish content" under node section and save.
5. Add another action "Send Mail" under System. Add required details to send email and save.

Above steps will unpublish content and notify site admin using email. After which site admin can navigate to "Admin =\> Content", review the content and approve. If you need to provide a custom/different UI, you can create a list using views and VBO module and allow site admin to Approve Content.
> 2 votes

# Answer
Your rule is firing for both node edits so you need to add conditions to your rules to check for the published status.

So for your unpublish rule, add a condition that the node is currently published.

The email to admin can be sent using a rules action.
> 1 votes

# Answer
It will be better if you use Work bench access module .It provides various functionality and control over node publish.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Thumbnail preview not showing in Video Embed Field Module
I am using Video Embed Field Module for embeding videos in dupal 7 site. The thumbnail preview is not showing. I created a view block in the preview section of the view its shows the thumbnail but when the block in in some region of page it only displays the title.

# Answer
Did you check the access permissions for your thumbnail images
> 1 votes

---
Tags: files
---


# Question
Title: How to stop line breaks in textarea with multiple lines ( Text area (multiple rows) )?
I have Filed in my content type with widget **Text area (multiple rows)**. when some one paste content into this having line breaks, my requirement is to remove line breaks and save it in single line text.

I have selected **Text processing** as **Plain text** in filed settings. And in **plain text** format support to convert line breaks into html br tag is not checked.

Please suggest some way to remove line breaks while pasting content into this field.

current:

Required:

In short is there any way to **Make textarea to behave like textfiled while saving content** ?

Thanks!

# Answer
Check that the field is set to plain text in the "Manage Display" page of your content type.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How do I create individual fields on a node?
I would like to use individual Taxonomy fields on a node - not a preconfigured Content Type. e.g.

* Color: Red
* Year: 2015
* Project details: Short description.

This is just working fine with the Core Field Module. The downside of it is that it's preconfigured on the Content Type. Users can’t add more fields to a node. I need more flexibility. E.g: Thus, I am using a text field with unlimited Number of values.

**Example with Core Text Fields**

However I am missing Taxonomy’s term reference feature: People have to type in all data on every node. I hope this makes sense. I’ve created a quick mockup to show what I am looking for. **I would love to define individual description and Taxonomy terms.**

What’s the best way to get full flexibility?

# Answer
> 1 votes
I think the Field Collection and Field Collection Views modules would help you a lot. It allows you to have unlimited fields inside a node and in your case, I guess you'd have the taxonomy and a field for the answer.

This video does an infinitely better job of explaining it than I ever could.

https://www.youtube.com/watch?v=\_GlfYhsk3X0

# Answer
> 1 votes
Have a look at my answer to "How to add new data to a predefined list?", which describes what you can do with the Select (or other) module.

In your case, you could use that module also to define 2 fields, which I'd label something like so (or anything else you'd prefer):

* **Attribute** (with values like Material, Color, Year, ...).
* **Value** (with values like Plastic, Red, 2015, ...).

Obviously, if "I" would then want to add like "Taste = Sweet", I'd just have to add "Taste" to the 1st field, and "Sweet" to the 2nd field.

*Sweet* enough?

---
Tags: 7, taxonomy-terms, entities
---


# Question
Title: How to restrict content for Anonymous users after they viewed more than two articles?
After an anonymous user viewed more than two or three articles, I want to redirect such user to the login/register page.

Any suggestions about how to make this work somehow?

# Answer
Not sure if it is the only way to get this to work, and not sure if it is the most elegant way, but it should be doable as detailed below. It does not require any "custom" code, only some (often used) contributed modules.

# Rule 1 - Count the visits

The Flag module can by used to flag (eg) articles, which itself can be done automatically (behind the scenes) via the Rules module (= 1st rule). To make the Flag module work for anonymous users also, you'll need to get the Session API involved. For more details on that, refer to:

# Rule 2 - Trigger the redirect

With that, you have "a" counter (= number of articles flagged by a user) that you can use as a Rules Condition in a 2nd rule, whereas this 2nd rule can be triggered by a Rules Event like "after an article gets flagged". In that Rules Condition you just check if the counter exceeds your limit (= 2 in your case), then you perform the Rules Action (in the 2nd rule) which is to redirect to your login/register page.
> 5 votes

# Answer
You can take a look at the Node Limit module. Some more details about it (from its project page):

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

Works well, but I don't have tested it with anonymous users.
> 2 votes

---
Tags: redirection, users
---


title: Module configuration translation

text:
# Question
Title: Module configuration translation
I cannot find any good examples on how to make a module configuration translatable. Could someone give me a starter example to build off with?

# Answer
> 1 votes
In config there are only few field types that are translatable by default text, label and i think date\_format(you can check the schema types to see which field types exactly are translatable by default). You can also make any value translatable by adding the `translatable: true` flag to the field. Now, copy your **config/install** directory into **config/install/language/LANGCODE** and edit each one of those config files and keep only the translatable fields..and translate those :)

If you want to provide translations for you module so `t()` function will pick them up, that is a bit strange in D8 compared to D7 but to put it simply you have to edit your module's info file and put in the following lines:

```
'interface translation project': yourprojectname
'interface translation server pattern': relativepathtotranslationsdirectory/%project-%version.%language.po

```

---
Tags: 8, configuration
---


# Question
Title: How to change items under edit tab on user account page?
I know how to remove the user tab completely from the user menu with hooks.

I want to know where I can find the template file that render the items under this tab (or where I can edit what to show under this tab) as I want to hide some parts for all users).

I have tried ***Home » Administration » Configuration » People » Account settings***. But it only changes items on the user account page **NOT** the edit tab.

# Answer
If you'd like to hide fields or properties from the user account edit form, you can create a custom module implementing either hook\_form\_alter() or hook\_form\_FORM\_ID\_alter(). The ID of the form in question is 'user\_profile\_form'.
> 4 votes

# Answer
I come from check how the page is created and for this Drupal use various function. So I think that the best for you is install the Theme developer module with the simplehtmldom API module (**You must use simplehtml API version 7.x-1.12 if you want Theme Developer to function properly.**)

> Theme Developer relies on the Devel module as a dependency. Once enabled, you may click on any part of the page and a sexy popup display shows which theme function/template outputted the HTML, and what other files could have done so. Armed with this info, a themer may quickly and accurately override the presentation. Further, all the variables passed into the template/function are presented for review.

To learn how to use the module you can read (or watch) about the Theme developer module.
> 3 votes

# Answer
If the only challenge is to hide some account required fields on the register tab, you can also use field\_permissions together with required\_by\_role.
> 2 votes

---
Tags: 7, theming, users
---


# Question
Title: How to check whether a username is in use?
I'm currently trying to implement a function to check if a user already exists. I've read that this could be done by Rules whit the condition "Entity exists by property" but I can't find it anywhere. I've tried it with Rules 7.x-2.2 & Rules 7.x-2.3

Is this option still available or not? Or is it located in a other module?

it's related to this question: How can I check whether a username is in use?

# Answer
> 1 votes
If you check this issue you will see that the condition has not yet been added to Rules. A patch is available if you wish to test it.

# Answer
> 2 votes
Drupal 7 has a function to return a user object by username:

```
$user = user_load_by_name($name);
if(!$user){
    // User doesn't exist
}
else {
    // User exists
}

```

function user\_load\_by\_name

And a function to return a user object by email:

function user\_load\_by\_mail

# Answer
> 0 votes
Use this snippet and you can check whether the user selected name is available or not.

```
$name = 'user_selected_name';

$user = db_select('users', 'u')
    ->fields('u', array('name'))
    ->condition('u.name', $name, '=')
    ->execute()
    ->fetchAssoc();

    if($user) {
        print "user exists";
    }
    else {
        print "Name is available, You can take it.";
    }

```

# Answer
> 0 votes
Assuming you want to check for the existence of a username for new users (who are registering), there *is* a module that implements that functionality, albeit in `7.x-1.x-dev` status... It's kind of hard to find because the name is a little complicated, but you might give it a try or even just look at the source code to get a feel for the way that module checks for username existence. It's called Username originality AJAX check.

---
Tags: rules
---


title: Private message prefill message body

text:
# Question
Title: Private message prefill message body
I'm using Drupal 7 Privatemsg module. To prefill the message body, I use the following hook but don't get anything displayed.

```
function MyModule_privatemsg_message_view_alter(&$vars) {
  module_load_include('pages.inc','privatemsg');

  $vars['message']['body'] = "<i>Dear Friend</i>,\n <strong>you rock!</strong>";
}

```

Any help ?

# Answer
> 0 votes
One solution is to use the Prepopulate module and then customize the URL to send a privatemsg. This works well if you are using Views to generate the links, for example.

---
Tags: 7, privatemsg
---


# Question
Title: How to assign a role to a user depending on order subtotal using Ubercart?
I am using ubercart in drupal 7 . I need to assign a role to user after checkout. For this I created a rule using checkout complete. But I need to assign a role depend on order subtotal. this option is not meeting me on rule.

# Answer
> 3 votes
If you want to use that "*Order subtotal*" in a Rules "***Condition***", you could try to first add a Rules condition `Entity has field` (related to the field containing that "*Order subtotal*").

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition, somewhere it says:

> *The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*.

So if you don't have an appropriate "field" for it, then you may be able to get it to work also by using that 'content is of type'.

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

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


# Question
Title: How to delete a node/nodes created by a user with rules?
How would I delete a users content automatically when a certain rule triggers?

The content is of a certain content type.

# Answer
1. Add an action for "Fetch by Property" \> Node
2. Property \> Author
3. Value \> The user
4. Add a Loop
5. Add an action for "Delete an entity \> List Item" inside the Loop (on the right)
> 1 votes

---
Tags: rules, nodes
---


# Question
Title: How do I add a custom CSS file for default theme?
For example - I have enabled Zircon as my default theme. I want the user menu account to appear on left. I want to add a custom CSS file where I can write a CSS elements and add to a default theme on site.

# Answer
> In Drupal 8, stylesheets (CSS) and JavaScript (JS) are loaded through the same system for modules (code) and themes, for everything: asset libraries. Asset libraries can contain one or more CSS assets, one or more JS assets and one or more JS settings.

More details on https://www.drupal.org/developing/api/8/assets
> 3 votes

# Answer
Add your custom CSS file to `themes/zircon/css/` lest suppose your file name is `yourfile.css`, then open `zircon.libraries.yml` and add your Css file name to end of this section

```
css:
  base:
   includes/bootstrap/css/bootstrap.css: {}
   includes/bootstrap/css/bootstrap-theme.css: {}
   includes/fonts/oswald_regular/stylesheet.css: {}
   includes/fontawesome/css/font-awesome.min.css: {}
   includes/slick/slick/slick.css: {}
   includes/slick/css/style.css: {}
   includes/monokai/monokai.min/css: {}
   includes/flexslider/flexslider.css: {}
   css/html.css: {}
   css/page.css: {}
   css/block.css: {}
   css/view.css: {}
   css/slideshow.css: {}
   css/responsive.css: {}
   css/print.css: { media: print }
   css/yourfile.css: {}

```

save and close the file and **clear the cache**.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Why does webform configuration not let me choose existing content types
I've installed the `Webform` module and would like it to configure so that I can add a form to a `Basic page` content. But `/admin/config/content/webform` does not let me specify any content types. Where is that setting hidden? Thanks!

**EDIT1**
What I'm seeing:---------------------------

What I would expect to see:

Why don't I get the choice of the existing content types??

# Answer
Admin Menu --\> Structure --\> Content Types --\> Basic Page's Edit --\> Webform tab --\> select Enable

I not sure is this what you mean.
> 2 votes

---
Tags: webforms
---


title: How can I override taxonomy term page?

text:
# Question
Title: How can I override taxonomy term page?
I have created a Vocabulary (**categories**) with terms (**term1, term2, term3..etc**). After that I created a content type (**Product**) with fields title, description, image. Also, created field called "product type" which is a term reference (categories). Furthermore, I am displaying all terms list in page like term1 term2 term3 with link.

When I click on term1 **I want to display related products name, description, image with full details link.** I am currently displaying only term related product title with read more link only. \[!\[enter image description here\]\[1\]\]\[1\] Please Advice.

# Answer
You could install Views module, create a list of products, and filter based on taxonomy (Contextual filter).
> 1 votes

# Answer
Sorry, but I have no tutorial or other pages, you will have to look for each step by yourself in this forum or others. Basically you change the file: **/sites/all/themes/YOUR\_THEME/template.php**, in the function

**YOUR\_THEME\_preprocess\_page**, you set

```
if($variables["node"]->nid == ID_OF_PRODUCT_PAGE){
  $variables['theme_hook_suggestion'] = 'page__products';
  if(arg(1) == "") {
    $categories_view = views_embed_view('YOUR_VIEW1', 'block', "");
    $variables["categories_view"] = $categories_view;
  }else{
     $products_view = views_embed_view('YOUR_VIEW2', 'block', arg(1));
     $variables["products_view"] = $products_view;
  } // if
} // if

```

You must create, previously, a content node which will be a dummy node and where you can inject the blocks. You use the node id in the code. The content of the blocks is printed by using print $product\_views or print $categories\_view.

You can copy the page.tpl.php in that folder, rename to page--products.tpl.php and clear the cache, and then you are done. I hope it is useful to you, there are dozens of ways of doing the same thing, some better and some worse. Drupal can require 10x effort than PHP alone for complex projects which need a lot of customization.
> 1 votes

# Answer
Sorry my reputation not high enough to add a comment. Anyway here is the link might able to help you.

Create Views

Views Relationships and Contextual Filters
> 1 votes

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


# Question
Title: Installation showing only SQLite as database option
I using Windows 8.1, XAMPP 3.2.2 and Drupal 8.0.3.

When I install Drupal, it only gives an option for Database as SQLite and it stores the file in `drupal->sites->default->files`. Then inside the folder 'files' name of the SQLite DB is `drupal.ht.sqlite`.

I want to use MySQL as DB instead of sqlite, Please help me to get out of this problem. And I have add some content it is working fine.

# Answer
I think you need to have the `pdo-sql` PHP module activated if you want to use MySQL, otherwise the MySQL option will not appear. For more details, see no mysql option at install.
> 0 votes

# Answer
You won't be able to convert an existing site as far as I know; you'll need to build a new site and migrate the content over to it. It might be easier to just start a new site from scratch and export/import the data manually, depending on how far you've got.

Before you do that, you need to enable MySQL in PHP. If you only see SQLite as a DB option, it means you haven't installed the PDO MySQL extension. Consult your web server's documentation for instructions on how to do that.

Once you have, MySQL will appear as an option for installation.
> 2 votes

---
Tags: database, 8, installation
---


# Question
Title: How to set MINIMUM number of required fields?
I need to set the minimum number of required values for several file fields in Drupal 7. I can only find options to make the field required or set a maximum number of allowed values. Is there any way to set the MINIMUM number of required values?

# Answer
> 3 votes
You can use the Field validation module, and set up a validation rule using "number of selections".
The Field validation module has many validation rules you can set for any of your fields. It works by defining a set of validation rules at first, then you can assign that set to a field.

To answer your question, the validation rule you need to use is the "number of selections". You can define a minimum and a maximum number of values required. Just leave blank the "Maximum number of selections" parameter and set "Minimum number of selections" to your needs.

# Answer
> 2 votes
I found the field validation option resulted in a lot of form submission failure messages, the best was trying to add another field when I had only one complained that I did not have btwn 3 and 5, but did not give me another field.

**My solution using hook\_form\_alter():** Not the most elegant code now that I look at it...

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  /**
  * Make sure that there are at least 3 and at most 5 items
  */
  if ($form_id == 'content_type_container_node_form') {

    // Count how many items we have
    $item_count = 0;
    foreach ($form['field_name_items'][ LANGUAGE_NONE ] as $delta => $item) {
      if (is_integer($delta)) {
        $item_count++;
      }
    }

    // If it is a new node then make sure we start with 3 items
    if ($form['nid']['#value'] == NULL && $item_count < 3) {
      $item_template = $form['field_name_items'][ LANGUAGE_NONE ][0];

      // We are adding two items to the one we already have
      for ($i = 1; $i < 3; $i++) {
        $form['field_name_items'][ LANGUAGE_NONE ][ $i ] = $item_template;
        $form['field_name_items'][ LANGUAGE_NONE ][ $i ]['remove_button']['#delta'] = $i;
      }
    }

    // Re-Count how many items we have
    $item_count = 0;
    foreach ($form['field_name_items'][ LANGUAGE_NONE ] as $delta => $item) {
      if (is_integer($delta)) {
        $item_count++;
        // Remove the 'Remove' link for the first 3 items
        if ($item_count <= 3) {
          unset($form['field_name_items'][ LANGUAGE_NONE ][ $delta ]['remove_button']);
        }

      }
    }

    if ($item_count == 5) {
      // Remove add more link if there are 5 items
      unset($form['field_name_items'][ LANGUAGE_NONE ]['add_more']);
    }
  }
}

```

---
Tags: entities, files
---


# Question
Title: Execute jquery function if Ajax callback form complete
I got a custom ajax callback which replaces my checkbox options based on the select option.

Now after the checkboxlist get's updated i need to execute a jquery function on those checkboxes.

How can i execute this custom jquery function after the callback is done, so after the checkboxlist is updated.

Form element:

```
        $widget['select_box'] = array(
            '#type' => 'select',
            '#title' => 'Select bussen',
            '#options'  => $options,
            '#validated' => TRUE,
            '#default_value' => '_none',
            '#attributes' => array('class' => array('select-province')),
            //The callback
            '#ajax' => array(
              'callback' => 'ajax_select_callback',
              // 'wrapper' is the HTML id of the page element that will be replaced.
              'wrapper' => 'replace_select_div',
            ),
        );

        //Form element wich get updated
        $widget['select_box_2'] = array(
            '#type' => 'checkboxes',
            '#title' => 'Select bussen',
            '#options' => ...,
            '#prefix' => '<div id="replace_select_div">',
            '#suffix' => '</div>',
            );

```

Ajax callback function:

```
    function ajax_select_callback($form, $form_state) {
      // The form has already been submitted and updated. We can return the replaced
      // item as it is.
    return $form['line_item_fields']['field_bussen_select']['und'][0]['select_box_2']

    }

```

Jquery function i run on the checkboxes:

```
    jQuery("input[type='checkbox']").change(function () {
        jQuery(this).parent().siblings('ul')
            .find("input[type='checkbox']")
            .prop('checked', this.checked);
    });

```

# Answer
> 0 votes
I think if found the answer at :https://drupal.org/node/171213.

Section: JavaScript on your AJAX form

"Attach jQuery to Drupal.behaviors, that way it can be run anytime new DOM elements are inserted. One example, if you're using AJAX in Views, each time a section of the page reloads, it will reload/run jQuery."

Didn't test it, because i don't need it anymore :), but still good to know!

# Answer
> 0 votes
Wrap your JS function in Drupal.behaviours, it will work after section reloads

```
(function ($) {
  Drupal.behaviors.myModuleBehaviours = {
    attach: function (context, settings) {
      $("input[type='checkbox']").change(function () {
        $(this).parent().siblings('ul').find("input[type='checkbox']").prop('checked', this.checked);
      });
    }
  }
})(jQuery);

```

# Answer
> 0 votes
Work with ajax\_commands

your callback could be:

```
function ajax_select_callback($form, &$form_state) {
  $commands = array();
  // Replace the form element.
  $commands[] = ajax_command_replace('#edit-select_box_2-SELECTOR', render($form['select_box_2']), array());
  // Invoke any JavaScript func
  $commands[] = ajax_command_invoke(NULL, 'your_custom_js', array());

  // more commands...

  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}

```

And in JS:

```
jQuery.fn.your_custom_js = function () {
  ....
};

```

This is untested, its just the elegant way to go.

# Answer
> 0 votes
Please find below the nice and easy to understand tutorial for calling javascript function after ajax event in Drupal 7:

http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7

---
Tags: 7, forms, ajax, javascript, routes
---


# Question
Title: How to mirror product date attribute availability on the availability calendar?
I would like to mirror the available dates of the current product line item depending on the availability calendar of that specific product. The availability calendar is what the owner/admin of that product will fill up.

Then there is another date field that is on the line item (*add to cart*) of that product that will allow the customer to choose when to use/get/rent that certain product.

As you can see on the availability calendar, the 19th, 21th, 23rd, 26th, and 28th of Feb are fully booked. I want the same dates on the popup calendar to be disabled.

How can I achieve that?

These are modules I already tried:

* Rooms \- This is not fit for our website because of the forms/steps we are using.
* Commerce Availability \- This is exactly what I wanted but it's not working on my end. The date is still bookable on the line item even though my availability calendar is already fully booked. I already followed the instructions and fixed the settings of the module.

I also checked the demo of the Easy Booking, I had to guess which date is not available, which is not also good.

Thank you for the help in advance!

# Answer
> 2 votes
Unfortunately, there is not a particular bit of code that can be shared to fix your situation. But take heart! You're using libraries that are designed to be changed before display. That means with a little bit of custom php and javascript you can do this.

1. First you need to determine how to change your widget

Using Javascript: https://stackoverflow.com/questions/9742289/jquery-ui-date-picker-disabling-specific-dates

Using Drupal to send variables to Javascript: how to send variable from .php file to .js file?

2. Next you need to determine where your availability dates are stored

This is probably the most abstract issue. It sounds like you're storing the availability from within the node. I recommend you use the devel module and try to `$node = node_load(123); dpm($node);` to see what the availability field array looks like. We will do this in the next step. (Lynda series on the devel module)

3. Finally, you need to connect both your knowledge of how to tweak the calendar and where the availability is stored with your line item form.

Fortunately, this is quite straightforward. Unfortunately, it's not complete and will need a fair amount of trial and error to get to a working solution. Welcome to learning the hard way :)

```
<?php

/**
 * Implements hook_form_alter()
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Avoid bundle cart forms and other forms
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    $current_node = menu_get_object();
    // view the current node structure for your availability
    dpm($current_node);
    // view the current product's form array
    // you may not actually need to change the form here, but
    // I anticipate you needing to attach a javascript snippet to the
    // form so that it gets run each time the ajax loads a new
    // product
    dpm($form);

    // add your js to the php form
    $js_settings = "js array for your availability?";
    $form['#attached']['js'][] = array(
      'data' => array('module' => $js_settings),
      'type' => 'setting',
    );
  }
}

?>

```

---
Tags: 7, commerce, datetime, bookings
---


# Question
Title: read webforms fields in a mobile app and write submissions to the site database
I have a courses site where students take online courses and then take exams and get their certificates.

The courses content type has an entity reference to "Lessons" content type which has a further reference to Exams content type ( Webform).

The progress of user is being stored in a custom table in database.

Now we need to build a native mobile app with login / registration, and taking courses and exams features. (user registration / login and progress should be synced with site database)

Any ideas to start with? Custom API, web services or reading and writing to database directly.

thanks

# Answer
> 1 votes
I believe services will fulfill your needs. You can try with Services module.

You may require to customize the module for your custom made features in the site.

# Answer
> 1 votes
I would recommend DrupalGap for this situation. With it, and a few contrib modules, you'll have an app that can display and submit Webforms. Here are the key players in this scenario:

DrupalGap has built in support user login/logout/registration, and with the DrupalGap Webform module, it adds support for the display and submission of webforms in various application environments (mobile apps, web-apps, headless). The scenario you describe is attainable with probably 10 lines of custom code/terminal-commands or less.

---
Tags: services
---


# Question
Title: How can I exclude API keys, passwords, and so on from configuration management?
I am using Drupal 8 and `drush cex` to commit my configuration to my repository.

However, I want to keep passwords and API keys out of the repository. How do I do that? (selectively exclude sensitive information from configuration management).

For example, I'm using the SMTP module, but I noticed that in addition to the SMTP server and sender's name, etc., it also exports the API key to code, which should not be exposed. I want to manage module configuration with configuration management, but I don't want to commit the key.

# Answer
> 4 votes
You can't exclude specific keys easily from being exported.

However, you simply can not store the real keys there in the first place, and rely on local overrides through settings.php only, e.g.

```
$config['yourmodule.settings']['smtp']['api_key'] = '24ztsgfet';

```

And in the UI, you just store "dummy" or any other string. Note that there's currently no indication that a value is overridden in the backend, it will however display only the value that's actually stored in config, not overrides.

---
Tags: 8, security, configuration
---


# Question
Title: How to show related nodes in a view block based on taxonomy terms?
I have two Content Type, Apartments and Events. Both have a Term reference field (field\_location).

I want make a view block that displays in the nodes of Apartments Content Type some fields of Events Content Type based on field\_location term. If in Apartments the field\_location is Rome the block must display only the field of the nodes Events with field\_location Rome.

How I can do it?

Thank you in advance.

> **SOLVED**

# Answer
**SOLVED**

* Add a Contextual Filter-\>Has Taxonomy Term ID
* **When the filter value is NOT available:**
    + Provide default value Type: Taxonomy term ID from URL
    + Check only: Load default filter from node page, that's good for related taxonomy blocks; Limit terms by vocabulary; Vocabulary: my-vocabulary; Filter to items that share my term.
* **When the filter value IS available or default is provided:** Check only: Reduce duplicates.
> 0 votes

---
Tags: views, entities, taxonomy-terms, nodes
---


# Question
Title: Drupal custom Fullcalendar breaks jQuery version > 1.8
I have a project where I have created a pretty extensive (custom) fullcalendar implementation.

I am using fullcalendar 2.6 (the latest version at this point).

All is working like a charm untill i change the jQuery version (via jquery\_update) to anything that is higher than 1.8... Then the fullcalendar just dissapears completely (the div is empty)

No errors in the webdeveloper console (chrome), nothing!

I have tried to narrow down the fullcalendar js implementation to the bare minimum (just a title, prev & next buttons) but even that does not work.

Since i want to implement bootstrap into the project, I need to increase the jQuery version...

I have been googling around for this but can't seem to find a clear answer for this.

Anyone?

All suggestions are highly appreciated.

# Answer
> 0 votes
I have located the problem, sharing to whom it might concern.

Apparently there was a conflict between the contrib admin\_menu rc4 version and jQuery, causing the fullcalendar to fail.

After upgrading the admin\_menu to rc5, (latest release), all was fine.

---
Tags: javascript
---


# Question
Title: How can I fallback to one field in absence of another
How can I make one field show up, unless it has no value, in which case another field is shown? I want to do this on the default node view, I already know how to accomplish it in views. I'm assuming it will mean coding something in my theme, but where best to do that is a little confusing to me.

# Answer
I would checkout Field formatter conditions where you can set a whole variety of conditions of one field based on if another field is empty or not. You would set these conditions in whatever display mode you are in so in the case of a node, most likely the view mode will be full or default. (e.g. `admin/structure/types/manage/[MY_content_type]/display`

Alternatively, you could do some custom node template theming and set conditions there such as if one field is not empty do this, else, show the other field.

```
<?php if (!empty($content['field_foo'])): ?>
  <?php print render($content['field_foo']); ?>
<?php else: ?>
  <?php print render($content['field_bar']); ?>
<?php endif; ?>

```

This assumes there is a value with field\_bar so you may need to add conditions for that field too if it's empty. With per field theming, you may need to not render the general content variable as well, it just depends on the order and where things fall in the template.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How do I remove a system CSS file in a theme?
I am trying to remove Drupal CSS files (such as ajax-progress.module.css) from my custom theme YML. Here is what I tried:

```
name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
stylesheets-remove:
  - core/themes/stable/css/system/components/ajax-progress.module.css
libraries-override:
  system/base:
    css:
      theme:
        css/components/ajax-progress.module.css: false

```

Drupal's documentation about that is scarce at best...

Update: another version that also does not work:

```
name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
stylesheets-remove:
  - @stable/css/system/components/ajax-progress.module.css
libraries-override:
  system/base:
    css:
      component:
        /core/themes/stable/css/system/components/ajax-progress.module.css: false
        /core/themes/stable/css/system/components/autocomplete-loading.module.css: false

```

# Answer
> 3 votes
You can try with the unset method that drupal provides for css alter hook. Try the following code in your custom module

```
function hook_css_alter(&$css) {
unset($css[drupal_get_path('module','system').'/system.theme.css']);}

```

# Answer
> 2 votes
You are correct. This is what I have and it is working:

```
libraries-override:
  core/normalize:
    css:
      base:
        assets/vendor/normalize-css/normalize.css: false

```

# Answer
> 1 votes
Quote from https://www.drupal.org/node/2473869

> ```
> stylesheets-remove:
>   - core/assets/vendor/jquery.ui/themes/base/dialog.css
>
> ```
>
> In cases where a Drupal core asset is being removed (for example, a CSS file in jQuery UI) the full file path is needed. In cases where the file is part of a library that belongs to a module or theme, a token can be used. Note that when using the token it needs to be quoted because @ is a reserved indicator in YAML.
>
> ```
> stylesheets-remove:
>   - '@bartik/css/style.css'
>
> ```

As you are removing a stylesheet from the stable theme you should use the token `@stable`

# Answer
> 1 votes
The only way I managed to do it:

```
name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
base theme: false
libraries-override:
  system/base:
    css:
      component:
        /core/modules/system/css/components/align.module.css: false

```

---
Tags: theming, 8
---


title: Does Gmap work with geofield?

text:
# Question
Title: Does Gmap work with geofield?
I know Gmap is designed to work with the location module, but most spatial devs now suggest geofield as the "better" spatial data storage module.

I had to use geofield for an open layers map, and now I want to move away from the location module but I don't want to have to reimplement my other Google maps on the site.

So I can I painlessly switch?

# Answer
So, the simple answer is yes, the Gmap module will work with the Geofield module. What you have to do to get it to work is to add your Geofield field to the view, exclude it from display, and switch the location source in the views Gmap settings from Location to Geofield and then point it to your Geofield field.
> 0 votes

# Answer
Maybe you should investigate to what extend the IP Geolocation Views & Maps module could help you. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
>
> And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
>
> Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
>
> Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Its project page contains even more information ...
> 1 votes

---
Tags: google-maps, location
---


# Question
Title: Install Drupal with MS SQL Server 2008 R2
Is it possible in any ways to connect Drupal 6.x to MS SQL Server 2008 R2 on Windows Server 2008? I am really struggling to find a way out.

please let me know. Any help would be greatly appreciated!

# Answer
> 3 votes
The requirements clearly states that the supported databases in Drupal 6 are "MySQL 4.1 or higher, PostgreSQL 7.1."

You would have to write the database support yourself to get this working.

Drupal 7 does support MS SQL Server however.

# Answer
> 1 votes
Drupal 6 **cannot** use MSSQL as the storage engine

Drupal 7 and Drupal 8 **can** do so by means of the SQL Server Driver for Drupal:

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

The Drupal 8 version of the driver is a complete rewrite of the Drupal 7 driver and works like a charm.

To get it working you need to setup some other things, such as the MSSQL PDO PHP extension, a detailed tutorial can be found here:

http://www.drupalonwindows.com/en/blog/installing-drupal-windows-and-sql-server

> It's also still not likely to work as well as it does in MySQL.

I must object to this statement. We have found that MSSQL is better suited for big clusters and monster scaling thanks to features such as in-memory tables, always-on, etc. If you are using Drupal for brochureware this is meaningless though.

# Answer
> 0 votes
Well, Drupal 7 has an database abstraction layer that makes it possible to support MSSQL, but you still need modules like SQLSRV for it to work. It's also still not likely to work as well as it does in MySQL.

# Answer
> -1 votes
First use Godaddy as it only a short time with there help to setup the latest version of Drupal. I use 2008R2 with Drupal but you do need to write code to connect..

---
Tags: database
---


title: Link to a text file

text:
# Question
Title: Link to a text file
In Drupal 8, how do we make a link to a text file? The file is not managed by Drupal, but hosted within the same domain.

For example, I'm building a Drupal 8 module and on its help page I'd like to link to its `README.txt` file. I thought this would work:

```
$readmePath = drupal_get_path('module', 'my_module') . '/README.txt';
$readmeLink = \Drupal\Core\Link::fromTextAndUrl(
  t('README'),
  \Drupal\Core\Url::fromUri($readmePath)
)->toString();

```

This unfortunately does not work, and instead throws a 500.

# Answer
The API documentation for Url::fromUri() states the following regarding the $uri parameter:

> string $uri: The URI of the resource including the scheme. For user input that may correspond to a Drupal route, use internal: for the scheme. For paths that are known not to be handled by the Drupal routing system (such as static files), use base: for the scheme to get a link relative to the Drupal base path (like the HTML element). For a link to an entity you may use entity:{entity\_type}/{entity\_id} URIs.

So I think that you would need to do,

```
$readmePath = drupal_get_path('module', 'my_module') . '/README.txt';
$readmeLink = \Drupal\Core\Link::fromTextAndUrl(
  t('README'),
  \Drupal\Core\Url::fromUri('base:' . $readmePath)
)->toString();

```
> 3 votes

---
Tags: 8
---


title: Content types disappear

text:
# Question
Title: Content types disappear
In some lists my content types all disappear. This especially affects Apache Solr for me. But also Views and Rules dont show the content types in some lists.

Interesting is that:

1. One content type is shown("Rezept") which is created by a custom module
2. All content types are shown correctly the moment i clear the cache.

**Views:**

**Apache Solr Module:**

The moment i clear the cache they show up correctly. But as soon as the cache clearing is finished and i reload the page, they disappear again:

**Views while clearing the cache:**

**Apache Solr while clearing the cache:**

# Answer
> -1 votes
The problem was caused by Domain Access Module. Since i didnt needed it anymore, i deactivated it.

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


# Question
Title: CCK to Fields: content_migrate says missing widgets (image, matrix), but modules enabled
I am attempting an update from D6 to D7 on a site with multiple CCK types (yes, optimist me after reading lots of horror stories), I am following the CCK migration guide and have installed the cck module for D7. When accessing admin/structure/content\_migrate to migrate cck to fields, I get the following warnings for all image and matrix type fields.

This looks like a bug in the migration code, but where to report to, CCK content\_migrate, image or matrix module?

This is somewhat urgent as it affects the migration from d6 - d7 so I would be very grateful for any pointers.

## Details below:

> ```
> field_image   image
> RNAi
> Changed field type: The 'field_image' field type will be changed from 'filefield' to 'image'.
> Missing widget: The 'image' widget is not available for the field_image field, it will be set to the default widget.
>
> ```

Edit: the same for the matrix module: "Missing widget: The 'matrix' widget is not available for the field\_primer\_group field, it will be set to the default widget."

But the image and matrix modules are both enabled:

```
 Core        Image (image)                      Module  Enabled   7.41
Fields       Matrix Field (matrix)              Module  Enabled   7.x-2.4

```

-- php is 5.3.3 (centos) and postgres is 8.4 if that matters.

# Answer
> 0 votes
I can ignore the warning, it does not influence display or upload of images.

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


title: Alter results programmatically

text:
# Question
Title: Alter results programmatically
I'm using views data export module to output results as csv, xls, xml and txt files

I'm using Batched export (with Segment size 100) because there are many results.

I have some fields which I want to alter their values.

I have implemented hook\_views\_pre\_render to replace field values with ones I'm getting from webservice.

The problem that some values are correctly changed, others not

Is there a solution for that?

# Answer
> 1 votes
Instead of a pre-render function, I think the correct spot to modify values is actually hook\_views\_post\_execute(). This is invoked after the query has run, but before the data has been passed to rendering.

> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after. Altering the content can be achieved by editing the items of $view-\>result.

It has been a while since I've personally played with Views Data Export so I'm not 100% sure why you're seeing only some values change and not others, but I recall the rendering of the export being a little abnormal compared to the usual render process.

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


# Question
Title: Adding a #suffix to a Drupal Product Form Payment Method Radio
I have two radio buttons in my Drupal 7 product form. One for credit card and the other for 'send an invoice'. I'd like to add some text after each option but I don't know how.

In my hook\_form\_alter module this is what I'm attempting:

```
$form['commerce_payment']['payment_method']['#options']
['paypal_commerce_payment_paypal_wpp']['#suffix'] = 'text here';

```

However, this keeps throwing an error:

```
Warning: strlen() expects parameter 1 to be string, array given in
drupal_validate_utf8() (line 1599 of
/var/www/checkout/includes/bootstrap.inc).
Notice: Array to string conversion in format_string() (line 1550 of
/var/www/checkout/includes/bootstrap.inc).

```

And under the two radio options it just says 'Array' next to yet another radio button. Obviously not what I want. I want the text 'text here' to appear right after the 'Credit Card' radio option.

I also tried targeting the 'suffix' with '`#field_suffix`' to no avail.

Any idea how to make this happen?

# Answer
> 2 votes
The issue here could be the type of element `$form['commerce_payment']['payment_method']['#options']['paypal_commerce_payment_paypal_wpp']` is.

Is paypal\_commerce\_payment\_paypal\_wpp the key of one your options?

Have you tried #description?

---
Tags: forms
---


# Question
Title: Access control for announcement users to view via link
Is there a module available or anyone have a hint as to how one could create private links? I have a site that is locked down via access control, but I would like to send an announcement user a link to be able to view that piece of content.

Sort of like a Dropbox share. I can elaborate more on my use case if needed.

# Answer
Try Node authorize link.

> Generates link for view, edit, or delete content without login.
>
> Module maintains authorization key for every node and gives additional grants (view/edit/delete) to every user (anonymous too) who accesses page with correct key in URL. Module offers function node\_authlink\_get\_url($node, $op = 'view') for generate absolute URL to selected operation (e.g. for e-mail notifications).

Although the module is minimally maintained I used it two years ago and I did the work.

You can generate links that an anonymous user can use to get access to view a node, for example. I think it works with Conent Access, but not I'm not sure. May be you have to tweak precedence.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How do I get a javascript library to work inside the CKEditor module?
My content administrators want to be able to toggle back and forth between bootstrap nav-pills inside of the CKEditor instance. Out of the box, CKEditor doesn't seem to allow javascript to function in the editor. An example is below - I need to be able to click on the different pills to edit the associated content:

I have found an associated question that seem to answer this issue but I cannot get it to work in Drupal - I don't know how to implement the code. I would add a comment to that question but I do not have sufficient reputation points.

# Answer
> 0 votes
Using the code supplied in this associated question, I was able to get the javascript nav-pills to work in the CKEditor instance for Drupal 7. Unfortunately, it will only function in Firefox for PC. In addition, I had to add the following code to the ckeditor.config.js file as well as manually add the script to the admin theme's html.tpl.php file - this seems redundant but it will only work if both files have it.

```
CKEDITOR.on('instanceReady', function(ev) {
var jqScript = document.createElement('script');
var bsScript = document.createElement('script');

jqScript.src = 'http://code.jquery.com/jquery-2.0.2.js';
bsScript.src = 'http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js';

var editorHead = ev.editor.document.$.head;
editorHead.appendChild(jqScript);
editorHead.appendChild(bsScript);

jqScript.onload = function() { editorHead.appendChild(bsScript); };
});

```

---
Tags: 7, wysiwyg
---


# Question
Title: Configuration Manager or hook_update() to enable modules
In Drupal 7, if we wanted to push code to our environments enabling modules, we would call `module_enable()` in `hook_update_N()`. We no longer have that in Drupal 8, so how do we programmatically enable modules? Do we use Drupal 8's Configuration Manager or `hook_update_N()`?

A diff on the exported configuration yields this:

```
+++ b/cim/sync/core.extension.yml
@@ -10,6 +10,9 @@ module:
   config: 0
   contact: 0
   contextual: 0
+  ctools: 0

```

So it seems the module is enabled via code using Configuration Manager. We're also working with the idea of this:

```
function mymodule_update_8003() {
  $modules = array(
    'ctools',
  );
  \Drupal::service('module_installer')->install($modules);
}

```

What is the correct method?

# Answer
For site-specific changes, I would definitely go with using configuration deployments.

They have a very interesting advantage and difference to enabling modules in update hooks/through the API yourself. Config deployments can handle changed default configuration while installing the module.

A module might provide default configuration like views, settings and so on. They might also programatically do things during hook\_install() that you want to customize (like configuring default formatters/widgets for fields they add) Configuration deployment allows you install a module locally, customize it and deploy the result as an atomic operation (as much as is possible) to production.

I'd only use the API and hook\_update\_N() if it's a functional change in a module, e.g. when a module is split up into a new one and/or has a new dependency that is mandatory for it to work.

Also note that I would advice against doing both in the same deployment. Update hooks might run code and create config that will result in differences on every run (like creating a new configurable field). Running config deployments first isn't possible anyway and will soon be prevented explicitly in core and running after might result in the deployment removing and re-adding configuration due to different UUID's.
> 10 votes

# Answer
The code:

```
\Drupal::service('module_installer')->install($modules, TRUE);

```

Should be fine to use. This is how Drush enables modules and how they are enabled through /admin/modules. This should also create the configuration you need and it is best to stick to what core does. This will prevent any issues that hard-coding the config file might cause and if the way conf files are formatted changes, this will be updated to work with those changes.
> 4 votes

# Answer
I've yet to run into any issues just using configuration management, so I'd just stick with that for now.

The only thing that could be considered an issue is environment specific modules (i.e. Devel) can be tricky to manage. I tend to just deploy the configuration with them enabled and then disable them as part of my deployment scripts (either Flightplan.js or Acquia Cloud Hooks depending on environment).
> 0 votes

---
Tags: 8
---


# Question
Title: How to make taxonomy term name field work with 'Full HTML' text format?
As taxonomy term name field supports only plain text, all I want is to use non-breaking space (` `) for taxonomy name. Just to achive better html layout.

# Answer
> 1 votes
Try using the check\_plain function in your template file. Similar to what is shown in this example (which is for menu items though).

---
Tags: taxonomy-terms
---


# Question
Title: How to limit search results based only on OG group membership?
I followed the tutorial about How to Create Custom Search Pages Using Just Views in Drupal 7.

I have selected the blocks option instead of page option in views as I want to add it as a block in the organic group homepage.

How do I restrict the search using **relationship and context filtering** in the Views settings so each logged in user can only search for published content of their group only **(NOT SITE-WIDE)**?

**EDIT:** I have already tried the following:

Contextual filters \> (OG membership from node) OG membership: Group ID Relationships \> OG membership: OG membership from Node

(Which I got the idea from the default og\_content view that comes with OG Groups!)

Can this be done with hooks?

# Answer
> 3 votes
Editing my answer here as there seems to be a glitch in Views. Even with no contextual filters or relationships, just filtering by groups audience and exposed search doesn't work. The SQL query has both values but I don't know enough about sql to debug it.

> 1. Contextual filters \> (OG membership from node) OG membership: Group ID
> 2. Relationships \> OG membership: OG membership from Node

Instead, here's a hacky way of getting it to work by not using the search module.

1. Do the same as above to limit results by group.
2. If you only want to search by title for example, just add an exposed filter for the title and select "contains".
3. If you want to search by more fields which is likely, add the fields you want to search by (and maybe hide them) eg. Node title / Body. Then create a `Global: Combine fields filter (exposed)` and select the above fields with "contains".

That will let you search whichever fields but just not as nicely as with the search module.

If anyone else has a solution to the exposed search problem, post please.

# Answer
> 3 votes
# Group module as possible OG alternative

As per your (3rd) comment like "I personally think OG is ..." below the previous answer: be aware that the Group module is a possible alternative for Organic groups for Drupal 7 these days (and soon Drupal 8 also ...).

Refer to my answer to "How to create basic Organic Groups functionality with flags and references?" for way more details about the Group module.

Specific to this question here, some more details about the Group module, as mentioned on "Group - an alternative to Organic Groups":

> **Permission system**
>
> Group permissions are defined by the site builder and are then passed onto every group instance. This is done by configuring the “group type”, which is comparable to a node type for nodes. So you can configure a set of permissions for different types of groups, yet don’t have to worry about group members being able to fiddle with them.
>
> **Group roles**
>
> In order to make the above work, the Group module defines a concept called group roles. These behave exactly like user roles would globally, but can be defined on the group type level. Group provides three special roles to make your life easier too: Anonymous (no account on the site), Outsider (account on the site but not a member of the group) and Member (account on the site and a member of the group).

So with the above in mind, if you're willing to consider the Group module as a possible alternative, restricting the search results as you are trying to do seems much easier (if not automatically).

# Search configuration module for more configuration options

Another approach (which you might possibly want to combine with using the Group module) is to use the Search configuration module. Some details from its project page:

> This module has five main functions.
>
> 1. Alter the appearance of the core node search form.
> 2. Group content types for more meaningful searching.
> 3. Restrict search results by the content type. This is a role based restriction.
> 4. Restrict search results from showing individual items.
> 5. Alter the pager limit (aka number search item results per page).

Its project page contains many more details about what you can do with this module.

---
Tags: 7, search, organic-groups, views
---


# Question
Title: Content created using field and content created using <div>, and effect on website performance?
I am using the field collection module to create my Content. I have 10 text content. For ease of CSS class, I put each content in **separate fields** and apply the class using the `field formatter module`, So I have 10 fields and putting 10 text content in each one. Now same thing I can achieve by just making `<div></div>` 10 times in body of CKEditor (just one field), For example,

```
<div>Text content 1</div>
<div>Text content 2</div>
<div>Text content 3</div>
.
.
.
<div>Text content 10</div>

```

Now, in terms of performance will it affect the speed/loading of webpage of drupal 7 sites, if I go by 10 separate field or with one html code with 10 div? I am preferring 10 separate field method, because it is easy to handle editing and updating if needed.

**Kind Note:** To Moderators, please do not categories this question as opinion based, because i do not have experience with in-terms of performance of website, so I need suggestion/Comparison between this two methods from more experience Drupal developers. Thanks

# Answer
I'd recommend just using one field and changing the **"Number of values"** in the field settings. This will allow you to add as much as you want and yet only maintain one field.

In case you have different requirements, here's my opinion on the two approaches you are thinking of.

Here are the differences between the two approaches:

**10 fields**

* you have many fields that each go through the preprocess, process, field\_alter, and any other hook that might affect a field.
* Assuming they are similar fields any maintenance you would do would have to be done on each on individually.
* If the fields will eventually have different values then this approach allows you to easily modify them.

**1 text area**

* you only have 1 field that does through the whole hook process. Which makes things go faster.
* You only have 1 field to maintain.
* It does not make sense to store multiple values in one textarea since it makes curating difficult and prone to typos. Imagine missing a closing div. Boom, layout gone.
* Also, if in the future you have a case to migrate your content, you will have to make additional effort to migrate these since there are multiple values in the data.

All this said, the two options do not have a HUGE impact on performance if you're just loading them up for display and not doing massive preprocessing.
> 1 votes

---
Tags: entities, performance
---


title: Allow user to delete own account

text:
# Question
Title: Allow user to delete own account
In *admin/people/permissions* I checked the boxes next to the "Cancel own user account" and "Select method for canceling own account" but in the user profile (*user/NID/edit*) the **Cancel account** button is not present. Why? What could I have forgotten?

I have assigned the right role.

Thank You.

# Answer
* Make sure you are not using user 1, because you can't cancel user 1.
* Clear caches after changing permissions.

Update: Check for any modules you have which may affect Permissions. In this case Administer Users by Role may be lacking some permissions that you need to set.
> 2 votes

---
Tags: users
---


title: Drupal 7 and PageSpeed

text:
# Question
Title: Drupal 7 and PageSpeed
The Apache module PageSpeed provides various optimizations for HTML, JavaScript and such, which is great.

However, some of its features are redundant with Drupal's own aggregation and optimization methods. So has anyone tested which filters would be useful for a typical Drupal 7 website and which would be useless due to Drupal already providing support for it?

# Answer
> 9 votes
This is the PageSpeed section from my .htaccess:

```
<IfModule pagespeed_module>
    ModPagespeed on
    ModPagespeedEnableFilters extend_cache
    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters combine_css
    ModPagespeedEnableFilters move_css_to_head
    ModPagespeedEnableFilters remove_comments
    ModPagespeedEnableFilters inline_css
    ModPagespeedEnableFilters rewrite_javascript
    ModPagespeedEnableFilters insert_img_dimensions
    ModPagespeedEnableFilters rewrite_images
    ModPagespeedEnableFilters rewrite_css
</IfModule>

```

Whilst there is a little overlap with the js and css compression, I'm not seeing any negative results. I've set Drupal 7 to aggregate and compress CSS and JS.

The site isn't particularly high traffic though.

# Answer
> -1 votes
Here is my htaccess setup:

```
# -----------------------------------------------------------------------
# Enable keep-alive for faster pagespeed:
# -----------------------------------------------------------------------
<ifModule mod_headers.c>
    Header set Connection keep-alive
</ifModule>

# -----------------------------------------------------------------------
# Expire caching
# -----------------------------------------------------------------------
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 year"
    ExpiresByType application/x-font-woff2 "access plus 1 year"
    ExpiresByType application/x-font-ttf  "access plus 1 year"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresDefault "access plus 2 days"
</IfModule>

# -----------------------------------------------------------------------
# Cache Headers
# -----------------------------------------------------------------------
<ifmodule mod_headers.c>
  # Cache specified files for 31 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 31 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</ifmodule>

# -----------------------------------------------------------------------
# Defining MIME types to ensure the web server actually knows about them.
# -----------------------------------------------------------------------
<IfModule mod_mime.c>
    AddType text/css .css
    AddType application/javascript .js
    AddType application/x-javascript .js
    AddType text/html .html .htm
    AddType text/richtext .rtf .rtx
    AddType image/svg+xml .svg .svgz
    AddType text/plain .txt
    AddType text/xsd .xsd
    AddType text/xsl .xsl
    AddType text/xml .xml
    AddType video/asf .asf .asx .wax .wmv .wmx
    AddType video/avi .avi
    AddType image/bmp .bmp
    AddType application/java .class
    AddType video/divx .divx
    AddType application/msword .doc .docx
    AddType application/x-msdownload .exe
    AddType image/gif .gif
    AddType application/x-gzip .gz .gzip
    AddType image/x-icon .ico
    AddType image/jpeg .jpg .jpeg .jpe
    AddType application/vnd.ms-access .mdb
    AddType audio/midi .mid .midi
    AddType video/quicktime .mov .qt
    AddType audio/mpeg .mp3 .m4a
    AddType video/mp4 .mp4 .m4v
    AddType video/mpeg .mpeg .mpg .mpe
    AddType application/vnd.ms-project .mpp
    AddType application/vnd.oasis.opendocument.database .odb
    AddType application/vnd.oasis.opendocument.chart .odc
    AddType application/vnd.oasis.opendocument.formula .odf
    AddType application/vnd.oasis.opendocument.graphics .odg
    AddType application/vnd.oasis.opendocument.presentation .odp
    AddType application/vnd.oasis.opendocument.spreadsheet .ods
    AddType application/vnd.oasis.opendocument.text .odt
    AddType audio/ogg .ogg
    AddType application/pdf .pdf
    AddType image/png .png
    AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
    AddType audio/x-realaudio .ra .ram
    AddType application/x-shockwave-flash .swf
    AddType application/x-tar .tar
    AddType image/tiff .tif .tiff
    AddType audio/wav .wav
    AddType audio/wma .wma
    AddType application/vnd.ms-write .wri
    AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
    AddType application/zip .zip
    AddEncoding gzip svgz
    #AddEncoding gzip js
    #AddEncoding gzip  css
</Ifmodule>

# -----------------------------------------------------------------------
# Compressing output.
# -----------------------------------------------------------------------
<IfModule mod_deflate.c>
    # Enable compression
    SetOutputFilter DEFLATE

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|png|jpg|jpeg)$ no-gzip dont-vary
    Header append Vary User-Agent env=!dont-vary
</IfModule>

# -----------------------------------------------------------------------
#  PageSpeed. - TESTED with Mediacenter
# -----------------------------------------------------------------------
<IfModule pagespeed_module>

    # Turn on mod_pagespeed. To completely disable mod_pagespeed, you
    # can set this to "off".
    ModPagespeed on

    # Direct Apache to send all HTML output to the mod_pagespeed
    # output handler.
    AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html

    ModPagespeedLowercaseHtmlNames on
    ModPagespeedEnableFilters extend_cache
    ModPagespeedEnableFilters insert_dns_prefetch
    ModPagespeedEnableFilters add_head
    ModPagespeedEnableFilters add_instrumentation
    ModPagespeedEnableFilters make_google_analytics_async
    #ModPagespeedEnableFilters make_show_ads_async
    ModPagespeedEnableFilters flatten_css_imports

#
# Text / HTML
#

    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters convert_meta_tags
    ModPagespeedEnableFilters remove_comments
    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters elide_attributes
    ModPagespeedEnableFilters trim_urls
    ModPagespeedEnableFilters pedantic

#
# JavaScript
#

    ModPagespeedEnableFilters combine_javascript
    #ModPagespeedEnableFilters canonicalize_javascript_libraries
    ModPagespeedEnableFilters rewrite_javascript
    ModPagespeedEnableFilters defer_javascript
    ModPagespeedEnableFilters inline_javascript

#
# CSS
#

    ModPagespeedEnableFilters rewrite_css
    ModPagespeedEnableFilters combine_css
    ModPagespeedEnableFilters move_css_to_head
    ModPagespeedEnableFilters inline_css
    ModPagespeedEnableFilters inline_import_to_link
    ModPagespeedEnableFilters move_css_above_scripts

#
# Images
#

    ModPagespeedEnableFilters inline_preview_images
    ModPagespeedEnableFilters insert_img_dimensions
    ModPagespeedEnableFilters rewrite_images
    ModPagespeedEnableFilters convert_gif_to_png
    ModPagespeedEnableFilters recompress_images
    ModPagespeedEnableFilters recompress_jpeg
    ModPagespeedEnableFilters recompress_png
    ModPagespeedEnableFilters convert_jpeg_to_progressive
    ModPagespeedEnableFilters resize_mobile_images
    ModPagespeedEnableFilters sprite_images
    ModPagespeedEnableFilters lazyload_images
    ModPagespeedEnableFilters local_storage_cache
    ModPagespeedJpegRecompressionQuality 100
    #ModPagespeedEnableFilters responsive_images
    ModPagespeedEnableFilters resize_images

    # Disallow problematic files:
    #ModPagespeedDisallow "*/respond.js"
    #ModPagespeedDisallow "*/lightbox.js*"

</IfModule>

```

---
Tags: 7, performance
---


# Question
Title: Reset user password without using "Forgot password?"
I know that in Drupal 7 I could reset the user #1 password via code.

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$newhash = user_hash_password('newpass');
$updatepass = db_update('users')
  ->fields(array('pass' => $newhash))
  ->condition('uid', '1', '=')
  ->execute();

```

(`user_hash_password()` doesn't exist anymore in Drupal 8.)

Alternatively, I could use the following code.

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$edit['pass'] = 'newpass';
$account= user_load(1);
user_save($account, $edit);

```

What is the equivalent code for Drupal 8? What API should I use for this purpose?

# Answer
It's easier these days:

```
$account = \Drupal::entityTypeManager()->getStorage('user')->load(1);
$account->setPassword('new password');
$account->save();

```
> 12 votes

# Answer
Alternately, since you seem to be running this as a standalone script, there is a Drush (9.x) command

```
drush user:password admin mynewpassword

```

For Drush 8.x and earlier::

```
drush user-password admin --password=newpass

```
> 3 votes

---
Tags: users, 8
---


# Question
Title: How can I change a rendered user display to a combination of fields linking to the user?
I have a set of users on the site I'm building that have First and Last name fields in their profile. How can I create a display that will show the user link as "Last name value, First name value" all inline?

There are a number of places where this is how I want user references to show up. In some other places, it would be ideal to show those fields, and a couple of others along with the user's image. Then of course there is the full profile view. I had though this must be done with different display types, but can not see anyway to bring fields inline with each other, or adjust what text makes up the link.

# Answer
> 1 votes
Another option is to use **hook\_username\_alter**

then in your **template.php** file located in `/sites/all/themes/yourtheme`

add the following code:

```
function yourtheme_username_alter(&$name, $account) {
  if (isset($account->uid)) {
    $this_user = user_load($account->uid);//loads the custom fields
    $name = $this_user->field_first_name['und'][0]['value'].' '.$this_user->field_last_name['und'][0]['value'];
  }
}

```

replace **yourtheme** with your actual theme name.

You might not want to alter the user name when you're in the user profile page. So you could do something like this:

```
function yourtheme_username_alter(&$name, $account) {
if (    arg(0) != 'user' // test if you are on user page
) {
  if (isset($account->uid)) {
    $this_user = user_load($account->uid);//loads the custom fields
    $name = $this_user->field_firstname['und'][0]['value'].' '.$this_user->field_lastname['und'][0]['value'];
       }
     }
}

```

replace **yourtheme** with your actual theme name.

# Answer
> 1 votes
One option would be to use:

### Real Name

> The RealName module allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook\_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.

For Example:

> By default only the raw username is being shown, as you can see at the top of the page.
>
> Change this to:
>
> Result:
>
> source: Change Drupal Usernames with the Real Name Module

# Answer
> 0 votes
Your question is very similar to Combine two fields to be displayed together where you'll find several ideas, some of which are solving your problem even without custom code.

Hope will help

---
Tags: 7, users
---


title: Views as blocks - dropdown filters

text:
# Question
Title: Views as blocks - dropdown filters
On Drupal 7 I have a view with filters exposed to the user, which are dropdown lists. I want to use this View as a Block within a page. The only way to get this to work is the tick the "Use AJAX" checkbox in the Advanced section. However this means that the dropdown lists change to autocomplete fields, and I want to keep them as dropdowns. Is there any way to do that?

(Alternatively, is there any way to add the options that appear in the tabs at the bottom of a piece of content to a view page?)

# Answer
there is also a module Better exposed filters. Gives more options for the user. Maybe it is possible to do it with that module
> 2 votes

---
Tags: 7, views, blocks
---


title: Feed imports don't seem to trigger

text:
# Question
Title: Feed imports don't seem to trigger
The Feeds module is still in development for D8, but I'm trying to test it. I can set up Feed Types, but the actual imports do not seem to trigger.

Does anyone know how to do this on Drupal 8?

# Answer
> 1 votes
> **1.** Go to Administration \> Content \> Feeds (http://www.example.com/admin/content/feed)
>
> **2.** Add a Feed (http://www.example.com/feed/add).
>
> source: https://www.drupal.org/node/2604358#comment-10865318

---
Tags: 8, feeds
---


title: Two different views with common URL

text:
# Question
Title: Two different views with common URL
I want to have an URL which calls a View, for instance:

```
www.example.com/products

```

This will be the URL for a View called products\_list

If I want to filter the products by category, I could clone the View page, add a Contextual filter based on Taxonomy, and with a URL indicated as /products/% I could use

```
www.example.com/products/Brand-1

```

to filter the products of brand "Brand 1".

But what if I want to use a completely different View, with a layout different from the above, for just the special case of some brands, i. e.,

```
www.example.com/products/Special-Brand

```

I want the above URL to use a completely different View. How can I manage to do that in the simplest possible way?

# Answer
> Exactly, that is the point. I need just 2 Views, which one shows some completely different data than the other, and for different kind of brands. But all of these brands can be grouped in 2 big groups. Now I solve it by using views\_embed\_view in template.tpl.php, and using a View or other in the function via database logics, but I was not sure if there was an ideal way of doing without "hard code", via Rules, Context or something.

Here is an alternative.

### Create taxonomy terms.

go to `/admin/structure/taxonomy`

* Add Vocabulary, call it Products
* Then click on list terms (/admin/structure/taxonomy/products) and add terms
    + Brand A with url alias `/products/brandA`
    + Brand B with url alias `/products/brandB`

Then on your actual products content type (lets pretend it's Articles) add a **term reference** field of Bundle Type: Products.

Then edit your Article and select A or B for that node.

### Create 2 block views (one for each type)

* under advance, add relationship of terms on node

* Then Add a contextual filter of Taxonomy Term Name

+ Provide Default Value
        - Fixed Value
            * Brand A

Then go to blocks, and find your 2 view blocks and configure them.

I only showed A here, repeat steps for B.
> 1 votes

# Answer
You add a new view by clicking Add Page

This will clone your original view. Then click on fields and at the top select **this page override** as you don't want to affect all views.

Then click the remove button, to remove the fields.

Do this for everything, so you can remove everything and start from scratch.
> 0 votes

---
Tags: views
---