# Question
Title: Disable delete functionality on Webform submissions
I need to disable/hide the delete functionality of weform submissions.

Marked as yellow on the images below.

# Answer
> 3 votes
Webform provides the following permissions, which can be controlled via the standard page at /admin/people/permissions:

* Delete all webform submissions
> Allows deleting of any webform submission by any user. Generally an administrative permission.
* Delete own webform submissions

Once you have those set for the required roles, the delete tab will no longer appear for those users.

---
Tags: 7, webforms, forms
---


title: How do we theme node view component?

text:
# Question
Title: How do we theme node view component?
I've tried to theme a portion of a node by adding some values in to it using

1. hook\_theme and a twig template

I've used hook\_node\_view to add a few variables and then I have included the theme specified in hook\_theme and printed it in twig template.

Here is the code; nothing is working like nothing.

```
function content_statistics_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
    $node_count = some function called;
    foreach ($node_count as $key => $value) {
      $node_statistics = array(
        '#theme' => 'content_statistics_list',
        '#letter' => $value->letter,
        '#word' => $value->word,
        '#sentence' => $value->sentence,
      );
    }
  }
  $node->content['content_statistics_list'] = array(
    '#markup' => drupal_render($node_statistics)
  );
}

/**
 * Implements hook_theme().
 */
function content_statistics_theme($existing, $type, $theme, $path) {
   return array(
    'content_statistics_list' => array(
      'variables' => array('letter' => NULL, 'word' => NULL, 'sentence' => NULL),
      'template' =>  drupal_get_path('module', 'content_statistics') . '/templates/' . 'content-statistics-list',
    ),
  );
}

```

In content-statistics.html.twig, I have printed `{{ letter }}` but it is not showing anything on the node page. It is also causing an error.

> Warning: Attempt to modify property of non-object in content\_statistics\_node\_view()

# Answer
Your hook\_node\_view() is incorrect, check the documentation and example implementations. The first argument is a `$build array`. That's the new `$node->content`: What your code is adding to `$node->content` should be added to `$build`.

Also, never render things yourself: Just put your render array (`$node_statistics`) in `$build['content_statistics_list']`.

It's also recommended to implement `hook_entity_extra_field_info()` and expose that key as an extra field. Then it can be shown/hidden based on the view mode.
> 2 votes

---
Tags: hooks, 8
---


# Question
Title: You must include at least one positive keyword with 3 characters or more
Drupal 6.20 according to the changelog file.

We took over a site from another company who built the site in Drupal, and we'll be converting it over to Wordpress eventually but we need to resolve the search issue first.

I get the "You must include at least one positive keyword with 3 characters or more." error message whether I use the search bar (search module) which leads you to "search/node/KEYWORD" with KEYWORD being your search parameter or if I just go to /search after the URL.

I've read about this and have tried all the suggestions that I saw and none have resolved the issue. I re-indexed the site, and ran cron.php. After I ran cron.php I looked at the settings again and it shows that 100% of the site has been indexed.

I also manually changed the search module status in the database, but it only made the search bar disappear and after I changed the status back to active I got the same result. I tried that because it worked for another module that wasn't working on startup.

The entire site and DB was copied over, and the site that is on the other company server the search functions properly. I don't think it's php version related because I ran a script to revert back to PHP 5.3. Does anyone have any suggestions on what else I might try to possibly get the search working?

# Answer
> 1 votes
The search module is a little weird in Drupal, and can take some time to wrap your brain around. If you start reading from `node_search()`, you will see a call to `do_search()` which is the function that links the search indexes to the things you are searching over.

If you read that function, you will see that there is a variable `minimum_word_size`, that defaults to 3. If you need to be able to search on smaller words, you need to set this smaller. I believe you can set this on 'admin/settings/search', but I don't have any Drupal 6 sites to check against.

Change this value, then wipe the search index and rebuild it. These last two steps are most easily accomplished with Drush.

---
Tags: 6, search
---


title: URL Alias showing on checkout?

text:
# Question
Title: URL Alias showing on checkout?
Drupal 7.38 Organic Groups Drupal Commerce Commerce Node Checkout

I have everything setup and working well. There's one strange bug. On checkout, I have Title displayed so the logged in user can create a new group, but URL alias also shows up. I don't want this. I have pathauto handling all this automatically. Screen shot attached. I've dug through all display settings. I'm lost. Any help would be appreciated. Screen shot below.

Thanks

# Answer
It was a permission issue on the content type.
> 1 votes

---
Tags: commerce
---


title: Loop through array in Twig

text:
# Question
Title: Loop through array in Twig
I have this array

```
{% set icons = { 1: 'glyphicon glyphicon-asterisk',
                 2: 'glyphicon glyphicon-plus',
                 3: 'glyphicon glyphicon-minus',
                 4: 'glyphicon glyphicon-euro'
                 }
%}

```

I want to loop through it and print like this

```
<li{{ item.attributes.addClass('pos' ~ loop.index, icons[loop.index]) }}>

```

# Answer
Simple:

**Twig:**

```
<ul>
  {% for key, icon in icons %}
    <li{{ item.attributes.addClass('pos' ~ key, icon) }}>
  {% endfor %}
</ul>

```

**Source:**
http://twig.sensiolabs.org/doc/tags/for.html
> 1 votes

---
Tags: theming, 8
---


title: Randomizing nodes in a view display

text:
# Question
Title: Randomizing nodes in a view display
I've tried the solutions here:

Display random value from multi-value field in Views

And here

views... two random nodes to vote on

This is what I have: A content type (Inventory) involving a field collection of up to 10 items with a picture, price, description and a link.

I have a block view created filtered by category (so it shows up when users click on a particular category and a sort filter setup to randomize.

The block view shows field collection items.. but I only want it to show field collection items for one node at a time, then randomize the results.

Currently it's showing more than one nodes' field collection items.. When I refresh the page, it does randomize the results, but it's mixing nodes and field collection items together. I just want to randomize the node.

# Answer
> 1 votes
You could try the Views Field View module, which allows you to have a view as a field in another view.

So you would set up your view of nodes, filtering by taxonomy term and sorting randomly. Limit this to one result.

Then add another view that just shows the field collection items with a contextual filter for the parent entity id (I can't remember right now what filter you would use).

Then add the second view as a field on the first view.

---
Tags: views, nodes
---


# Question
Title: Taxonomy child terms list and product list view
I would like to ask about product category vocabulary and different page views for parent and child terms.

This is my use case: I have to build drupal 7 commerce based site, products are organised in taxonomy called "Product categories". Lets have these terms in here:

Category1

* Subcategory1-1
    + Product1
    + Product2
* Subcategory1-2
    + Product3

Category2

* Subcategory2-1
* Subcategory2-2
    + Product4
* Subcategory2-3

Category3

* Subcategory3-1

I need to make this behavior: Main category list page: contains list of main categories \[Category1, Category2, Category3\]

Main category detail page: after clicking on main category (e.g. Category1) and page contains list of child categories \[Subcategory1-1, Subcategory1-2\]

Child category detail page: after clicking on sub category item (e.g. Subcategory1-1) and page contains list of products \[Product1, Product2\]

so in general: if you click on category without products -\> display child categories list of particular parent category, and if you click on category with products assigned to them display list of products...

I was googling for a while and I don't find the right solution for my use case.

Can anybody help me with this?

# Answer
> 3 votes
Here's my tutorial video (I've published this step by step in many places): https://www.youtube.com/watch?v=y1jqu8JnLbU

**STEP BY STEP**

1. Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)
2. Create a Taxonomy View here: admin/structure/views/add

> You want to make sure that you choose "taxonomy" entities.

3. Add a contextual filter for "Taxonomy term: Parent term"

> Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

4. Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.
5. Save that view and create a new view here: admin/structure/views/add

> Make sure this view is a for "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).

6. Add a contextual filter for your taxonomy term, mine was called "Product Categories"

> Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

7. Add a "No results" item called a "View Area" and select "Page\_1" from your first view (this is the second page we created)
8. Save this view and go back to the first view.
9. Add a "No results" item called a "View Area" and select the second view that we just made.
10. Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/\[name\]" that way your catalog names are clickable :)
11. Profit!

# Answer
> 2 votes
A relatively easy way to do this, would be using Views. You would need two of them:
A) First you will need to have a view display products. This view has a contextual filter (taxonomy term) that filters based on the "Products Categories" field set on the products.
B) Secondly you would set up a view that displays taxonomy terms. You need a contextual filter (taxonomy parent term). This means that you expect a term as an argument to your view, and your view will display all children of the argument.
C) You need to configure View A to display View B when there are no results. That means that if View A does not deliver any products for a given taxonomy term, View B should display all children of the given term.

I tried this locally and it works as you described in the OP.

Hope this helps

---
Tags: views, taxonomy-terms, commerce
---


# Question
Title: How to specify a twig template for a custom Drupal 8 page?
I'm trying to create a custom Drupal 8 route with predefined content, like `/about-us`, which is not a node, just a standalone page.

The following tutorial is good only up to the point where I need to add the page content using `#markup`: https://www.drupal.org/node/2116767

How can I specify a twig template that I would like to use for page content?

# Answer
> 9 votes
I got that to work. Here's my solution.

Create a template in `path/to/your/module/templates/my-custom-page.html.twig`.

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path)
{
    return [
        'my_custom_page' => [
            'render element' => 'custom_page',
            'path' => $path . '/templates',
            'template' => 'my-custom-page',
            'variables' => [
                'var1' => 'default value for var1',
            ],
        ],
    ];
}

```

I couldn't figure out what `render element` is for, but it is required.

`variables` element defines the variables available in your template and provides default values for them. You can override them in your controller.

```
use Drupal\Core\Controller\ControllerBase;

/**
 * Class CustomPageController
 */
class CustomPageController extends ControllerBase
{

    public function getPage()
    {
        return array(
            '#theme' => 'my_custom_page',
            '#var1' => 'Actual value for var1',
        );
    }

}

```

Clear the cache and visit your custom page route. Everything should work.

Helpful links:

---
Tags: theming, routes
---


# Question
Title: Add a views with fields of nodes added from admin in the user profile
I describe my scenario:

the users in their profiles must display a view (views module) with a list of fields that the admin adds each time;

I assume that the admin must add this fields from a specific content type and display this fields with a views.

My question is: how I can associate the fields of this content type to an user and how I can display in the view only the fields of the nodes that the admin have associated to the user that are displaying the view?

Any help is appreciated. Also change my approach if need.

Thank you in advance.

**EDIT**

*Solve*

I solve the issue:

* Created a new content type;
* Added a user reference field to the new content type;
* Created a view that displays only this content;
* Added a filter in the view to reduce it to only nodes that reference the currently viewing user;
* Created a block in the view and place it to be only displayed on the user profile page;

# Answer
> 1 votes
With views you can display tables of items which are related to each other, like content users have created or fields of specific nodes of content.

Your question is not entirely clear. If you want to only show specific fields of a content type to a specific user those fields must be filtered by user ID, using a contextual filter.

If you want admins to be able to specify which fields are shown to which users you may want to use flags, and then filter your view of content on the flags which have been set.

If you can explain in more detail exactly what you are trying to do I may be able to help more.

---
Tags: users, entities, views
---


# Question
Title: How can I check if the current user is accessing his/her own user page?
I would like to print something in `page-user.tpl.php` only when the current user is accessing his own user page. (any URL starting with `/user/%uid/` but when %uid/ is the user id of the current logged in user)

For example, printing something like "Your are viewing your own user page now." in `page-user.tpl.php`

How can I make this condtion?

# Answer
> 3 votes
There are two paths a user could be visiting their own page: "user" and "user/UID" where their UID matches.

There is a global variable $user that stores the currently logged in user.

So in the variable preprocessor for the template you can determine whether or not a user is on their own user page and save it to a variable that you can reference in the template file, like below.
Note the use of `$variables['logged_in']`, which is an available variable as listed in the page.tpl.php documentation.

```
/**
 * Override or insert variables into the page templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function THEME_NAME_preprocess_page(&$variables) {
  // If we are on the 'user' page or a sub-page of it.
  if (arg(0) == 'user') {
    $variables['own_account'] = FALSE;
    // If we are on 'user' and are logged in then we are on our own user page.
    if (!arg(1) && $variables['logged_in']) {
      $variables['own_account'] = TRUE;
    }
    // If we are on 'user/UID' then check against the current user.
    else if (is_numeric(arg(1)) && !arg(2)) {
      global $user;
      if ($user->uid == arg(1)) {
        $variables['own_account'] = TRUE;
      }
    }
  }
}

```

Then you can use the variable `$own_profile` in your `page-user.tpl.php` template, which in this case might look something like this:

```
<?php if ($own_account): ?>
  <div class="own-account-msg">
    Here is some markup for the message a user sees when they are on their own account page.
  </div>
<?php endif; ?>

```

---
Tags: theming, 6, users
---


# Question
Title: Drupal 7.4.2 Can't Login after installing MySQL 5.7.9
I have a Mac with the following PHP 5.6 MySQL 5.7.9 Apache/2.4.16 (Unix)

Drupal 7.4.2

After upgrading to El Capitan and deleting MySql and then installing a new version of MySql, I can no longer login to Drupal.

I tried to update the user 1 password script, even though I did not forget my password. It said it was successful but I still cannot login.

When I go to my localhost /user/login I enter the username and password and submit the form. The page reloads, no messages are displayed.

Any suggestions?

httpd.conf Apache Configuration

```
ServerRoot "/usr"
Listen 80

LoadModule authn_file_module libexec/apache2/mod_authn_file.so
#LoadModule authn_dbm_module libexec/apache2/mod_authn_dbm.so
#LoadModule authn_anon_module libexec/apache2/mod_authn_anon.so
#LoadModule authn_dbd_module libexec/apache2/mod_authn_dbd.so
#LoadModule authn_socache_module libexec/apache2/mod_authn_socache.so
LoadModule authn_core_module libexec/apache2/mod_authn_core.so
LoadModule authz_host_module libexec/apache2/mod_authz_host.so
LoadModule authz_groupfile_module libexec/apache2/mod_authz_groupfile.so
LoadModule authz_user_module libexec/apache2/mod_authz_user.so
#LoadModule authz_dbm_module libexec/apache2/mod_authz_dbm.so
#LoadModule authz_owner_module libexec/apache2/mod_authz_owner.so
#LoadModule authz_dbd_module libexec/apache2/mod_authz_dbd.so
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
#LoadModule authnz_ldap_module libexec/apache2/mod_authnz_ldap.so
LoadModule access_compat_module libexec/apache2/mod_access_compat.so
LoadModule auth_basic_module libexec/apache2/mod_auth_basic.so
#LoadModule auth_form_module libexec/apache2/mod_auth_form.so
#LoadModule auth_digest_module libexec/apache2/mod_auth_digest.so
#LoadModule allowmethods_module libexec/apache2/mod_allowmethods.so
#LoadModule file_cache_module libexec/apache2/mod_file_cache.so
#LoadModule cache_module libexec/apache2/mod_cache.so
#LoadModule cache_disk_module libexec/apache2/mod_cache_disk.so
#LoadModule cache_socache_module libexec/apache2/mod_cache_socache.so
#LoadModule socache_shmcb_module libexec/apache2/mod_socache_shmcb.so
#LoadModule socache_dbm_module libexec/apache2/mod_socache_dbm.so
#LoadModule socache_memcache_module libexec/apache2/mod_socache_memcache.so
#LoadModule watchdog_module libexec/apache2/mod_watchdog.so
#LoadModule macro_module libexec/apache2/mod_macro.so
#LoadModule dbd_module libexec/apache2/mod_dbd.so
#LoadModule dumpio_module libexec/apache2/mod_dumpio.so
#LoadModule echo_module libexec/apache2/mod_echo.so
#LoadModule buffer_module libexec/apache2/mod_buffer.so
#LoadModule data_module libexec/apache2/mod_data.so
#LoadModule ratelimit_module libexec/apache2/mod_ratelimit.so
LoadModule reqtimeout_module libexec/apache2/mod_reqtimeout.so
#LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so
#LoadModule request_module libexec/apache2/mod_request.so
#LoadModule include_module libexec/apache2/mod_include.so
LoadModule filter_module libexec/apache2/mod_filter.so
#LoadModule reflector_module libexec/apache2/mod_reflector.so
#LoadModule substitute_module libexec/apache2/mod_substitute.so
#LoadModule sed_module libexec/apache2/mod_sed.so
#LoadModule charset_lite_module libexec/apache2/mod_charset_lite.so
#LoadModule deflate_module libexec/apache2/mod_deflate.so
#LoadModule xml2enc_module libexec/apache2/mod_xml2enc.so
#LoadModule proxy_html_module libexec/apache2/mod_proxy_html.so
LoadModule mime_module libexec/apache2/mod_mime.so
#LoadModule ldap_module libexec/apache2/mod_ldap.so
LoadModule log_config_module libexec/apache2/mod_log_config.so
#LoadModule log_debug_module libexec/apache2/mod_log_debug.so
#LoadModule log_forensic_module libexec/apache2/mod_log_forensic.so
#LoadModule logio_module libexec/apache2/mod_logio.so
LoadModule env_module libexec/apache2/mod_env.so
#LoadModule mime_magic_module libexec/apache2/mod_mime_magic.so
#LoadModule expires_module libexec/apache2/mod_expires.so
LoadModule headers_module libexec/apache2/mod_headers.so
#LoadModule usertrack_module libexec/apache2/mod_usertrack.so
##LoadModule unique_id_module libexec/apache2/mod_unique_id.so
LoadModule setenvif_module libexec/apache2/mod_setenvif.so
LoadModule version_module libexec/apache2/mod_version.so
#LoadModule remoteip_module libexec/apache2/mod_remoteip.so
LoadModule proxy_module libexec/apache2/mod_proxy.so
LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so
LoadModule proxy_ftp_module libexec/apache2/mod_proxy_ftp.so
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
LoadModule proxy_fcgi_module libexec/apache2/mod_proxy_fcgi.so
LoadModule proxy_scgi_module libexec/apache2/mod_proxy_scgi.so
#LoadModule proxy_fdpass_module libexec/apache2/mod_proxy_fdpass.so
LoadModule proxy_wstunnel_module libexec/apache2/mod_proxy_wstunnel.so
LoadModule proxy_ajp_module libexec/apache2/mod_proxy_ajp.so
LoadModule proxy_balancer_module libexec/apache2/mod_proxy_balancer.so
LoadModule proxy_express_module libexec/apache2/mod_proxy_express.so
#LoadModule session_module libexec/apache2/mod_session.so
#LoadModule session_cookie_module libexec/apache2/mod_session_cookie.so
#LoadModule session_dbd_module libexec/apache2/mod_session_dbd.so
LoadModule slotmem_shm_module libexec/apache2/mod_slotmem_shm.so
#LoadModule slotmem_plain_module libexec/apache2/mod_slotmem_plain.so
#LoadModule ssl_module libexec/apache2/mod_ssl.so
#LoadModule dialup_module libexec/apache2/mod_dialup.so
LoadModule lbmethod_byrequests_module libexec/apache2/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module libexec/apache2/mod_lbmethod_bytraffic.so
LoadModule lbmethod_bybusyness_module libexec/apache2/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module libexec/apache2/mod_lbmethod_heartbeat.so
LoadModule unixd_module libexec/apache2/mod_unixd.so
#LoadModule heartbeat_module libexec/apache2/mod_heartbeat.so
#LoadModule heartmonitor_module libexec/apache2/mod_heartmonitor.so
#LoadModule dav_module libexec/apache2/mod_dav.so
LoadModule status_module libexec/apache2/mod_status.so
LoadModule autoindex_module libexec/apache2/mod_autoindex.so
#LoadModule asis_module libexec/apache2/mod_asis.so
#LoadModule info_module libexec/apache2/mod_info.so
#LoadModule cgi_module libexec/apache2/mod_cgi.so
#LoadModule dav_fs_module libexec/apache2/mod_dav_fs.so
#LoadModule dav_lock_module libexec/apache2/mod_dav_lock.so
#LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
LoadModule negotiation_module libexec/apache2/mod_negotiation.so
LoadModule dir_module libexec/apache2/mod_dir.so
#LoadModule imagemap_module libexec/apache2/mod_imagemap.so
#LoadModule actions_module libexec/apache2/mod_actions.so
#LoadModule speling_module libexec/apache2/mod_speling.so
#LoadModule userdir_module libexec/apache2/mod_userdir.so
LoadModule alias_module libexec/apache2/mod_alias.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
#LoadModule php5_module libexec/apache2/libphp5.so
LoadModule php5_module /usr/local/opt/php56/libexec/apache2/libphp5.so
LoadModule hfs_apple_module libexec/apache2/mod_hfs_apple.so

<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User _www
Group _www
</IfModule>

ServerAdmin you@example.com
ServerName myself1mac.employerdomain.com:80

<Directory />
    AllowOverride none
    Require all denied
</Directory>

DocumentRoot "/Library/WebServer/Documents"
<Directory "/Library/WebServer/Documents">
    Options FollowSymLinks Multiviews
    MultiviewsMatch Any

    AllowOverride None

    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<FilesMatch "^\.([Hh][Tt]|[Dd][Ss]_[Ss])">
    Require all denied
</FilesMatch>

<Files "rsrc">
    Require all denied
</Files>
<DirectoryMatch ".*\.\.namedfork">
    Require all denied
</DirectoryMatch>

ErrorLog "/private/var/log/apache2/error_log"

LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "/private/var/log/apache2/access_log" common
</IfModule>

<IfModule alias_module>
    ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1"
</IfModule>

<IfModule cgid_module>
</IfModule>

<Directory "/Library/WebServer/CGI-Executables">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /private/etc/apache2/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
</IfModule>

TraceEnable off

# Server-pool management (MPM specific)
Include /private/etc/apache2/extra/httpd-mpm.conf

# Multi-language error messages
#Include /private/etc/apache2/extra/httpd-multilang-errordoc.conf

# Fancy directory listings
Include /private/etc/apache2/extra/httpd-autoindex.conf

# Language settings
#Include /private/etc/apache2/extra/httpd-languages.conf

# User home directories
#Include /private/etc/apache2/extra/httpd-userdir.conf

# Real-time info on requests and configuration
#Include /private/etc/apache2/extra/httpd-info.conf

# Virtual hosts
#Include /private/etc/apache2/extra/httpd-vhosts.conf

# Local access to the Apache HTTP Server Manual
#Include /private/etc/apache2/extra/httpd-manual.conf

# Distributed authoring and versioning (WebDAV)
#Include /private/etc/apache2/extra/httpd-dav.conf

# Various default settings
#Include /private/etc/apache2/extra/httpd-default.conf

# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
    Include /private/etc/apache2/extra/proxy-html.conf
</IfModule>

# Secure (SSL/TLS) connections
#Include /private/etc/apache2/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
#       starting without SSL on platforms with no /dev/random equivalent
#       but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
</IfModule>

Include /private/etc/apache2/other/*.conf

```

# Answer
> 1 votes
It could be a host of things, but it should as if the connection from your Drupal site to the DB is working - you mentioned that you cannot log in, so I am assuming your site is showing the login screen, which means that Drupal is connecting to the DB. If there was a DB connection issue you would get error message during bootstrap.

So it might just be that your admin account is locked. The password may be right, but the account is still locked. I had a situation a while back where password\_policy module locked the admin account.

I would try to add a new user (drush create user), assign this user to the admin roles, and then try to login with this user. If yo get access, you can 'reset' the admin account.

If you cannot log in with your new user, then there is something more sinister going on.

# Answer
> 0 votes
This is a good thing to use drush for, since you can reset the password for user 1 (`drush user-password`), or check for error messages (`drush ws`). Drush can also create a one-time-link to test.

You can access the user/login page, so I'm guessing you don't have a problem with clean URLs (which would make it hard to log in). The one thing that might cause problem, however, would be what's the exact link you're browsing to. Drupal handles its logins via a cookie that it sets, and cookies are tied to the exact site you're browsing to, even if you're just doing on your laptop. If the host name you log in on is different than the host name you get redirected to (say, you're using something like mysite.local to log in, but you browse to 127.0.0.1, then you'll be logged in only if the URL you're browing to is "mysite.local", even if mysite.local points to 127.0.0.1.

The other possibility is that your Apache configuration may be wrong. I don't think Apple has been using Apache 2.4 that long, and there are annoying differences in how you configure 2.4 as compared to Apache 2.2. You may want to edit your question to post your apache configuration, so folks can check if it's right for a local Drupal install.

---
Tags: database
---


title: AWS S3 Bucket - File Explorer Field

text:
# Question
Title: AWS S3 Bucket - File Explorer Field
I'm looking for a file field module that will allow me to select files from an AWS S3 Bucket, but not upload them.

A client of mine is going to be uploading csv files via ftp from a different location and he wants users of a lesser role to be able to select the files from within the website.

I know that Scald will probably serve those needs, but not without a lot of setup and headaches.

Anyone know of a way to accomplish this?

# Answer
You want to have a read only access for your users, correct? It's not so difficult to implement in Amazon S3.

First of all, you need to set up an IAM user and apply read only permissions for it. AWS provides pre-defined policy template. More information here: http://docs.aws.amazon.com/IAM/

Once you created a user, you can connect to your storage using tools such as CloudBerry Explorer. When you client authanticats using key pairs assigned to the read only user you created, they will be able only to download files. You can download CloudBerry Explroer here: http://www.cloudberrylab.com/free-amazon-s3-explorer-cloudfront-IAM.aspx

Regards, Vlad, CloudBerry Lab
> 0 votes

---
Tags: entities, files
---


# Question
Title: How do I find or set the apropriate form for base scheme fields?
In my custom entity I want to set a base scheme field, which is an integer. The field has a minimum of 0, a maximum of 360 and a default of 180.

I tried this so:

```
    $fields['pan'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('PAN'))
  ->setDescription(t('Horizontal Positioning'))
  ->setSettings(array(
    'default_value' => 180,
    'min_value' => 0,
    'max_value' => 360
  ))
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'default',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'number',
    'weight' => -3,
    'settings' => array(
      'default_value' => 180,
      'min' => 0,
      'max' => 360
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

Neither the form is limited nor the input is limited when I post.

How can I get the correct type for my form and the correct settings? How can I look for them? Where?

Edit: solution is the following:

```
    $fields['pan'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('PAN'))
  ->setDescription(t('Horizontal Positioning'))
  ->setDefaultValue(180)
  ->setSettings(array(
    'min' => 0,
    'max' => 360
  ))
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'number_integer',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'number',
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

# Answer
> 3 votes
You can always create a field with the desired settings in the field, widget and formatter settings in the UI. Then export the configuratio and use the settings from there. The field settings are in two files:

* field.storage.entity\_type.yourname.yml
* field.field.entity\_type.bundle.yourname.yml

For base fields, you can merge the settings together into a single array.

---
Tags: forms, 8, entities
---


# Question
Title: Why is Drupal urlencoding in tpl output?
In Drupal 7, I have

```
<?php print $some_content; ?>

```

in page.tpl.php and when the string `$some_content` contains a URL (i.e., \<a href="some-url?parameters=1|2|3|5"\> ... )

the URL gets urlencoded and parameters is shown as:

```
parameters=1%7C%7C2%7C3%7C5

```

where | is substituted by %7C. For aesthetic reasons I want Drupal to stop this conversion, but even if I try with urldecode(), it does not work, as it seems to be hard-coded on Drupal core itself.

How can I override this which is just a simple line in pure PHP?

# Answer
Drupal is not URL encoding in the template output, it doesn't try to make that sort of blind string replace anywhere.

If the URL was prepared using any of Drupal's `url()` function, which is likely if you're using well written modules, then you should expect the query parameters to be properly encoded.

Drupal tries hard to conform to standards, you're probably going to find it more trouble than it's worth to get it to produce an invalid URL (which your desired result would be); it would be easier to simply write your own invalid version of `url()` and use that to prepare the content.
> 3 votes

---
Tags: 7, uri
---


# Question
Title: How to send an email with a download link?
I had installed Webform Protected Downloads. But there are lot of things I don't like about this module:

1. Too many steps to download files.
2. The email's body content is only for plain text. You cannot use any HTML tag.

What options do I have to remedy these things I don't like?

# Answer
> 3 votes
The **Functional Overview** of the Webform Protected Downloads module seems to be like so (from its project page):

> This module provides protected downloads using webforms. When you create a webform you can select which of the attached files you want to protect. You need to specify the webform field used for the confirmation mail (this must be a mandatory email field) and how long the download should be accessible after the user has submitted the form. When a user submits a webform with protected files he will be sent an email with a link to the downloads page. The link contains an individual hash code that will be checked upon page load to verify the access. If verification fails access will be denied. If it succeeds the user will see the default private upload file listing with all protected files that are attached to the webform.

Pretty sure you can build something similar (or close) by using the Rules module instead, which integrates nicely with Webform via the Webform Rules module. By using the Rules module you can, for example:

What else would you need?

# 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, webforms, emails, files
---


# Question
Title: How do I implement a custom theme function?
I'm trying to print a markup in a peg. I've implemented a function passed the values through the variables. Also I've implemented a custom theme function with a markup.

But it is giving the error.

> Template "modules/custom/example/templates/example.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/custom/example/templates/example.html.twig" in the Drupal theme registry.).

Here is my code.

```
/**
 * Implements hook_theme().
 */
function example_theme($existing, $type, $theme, $path) {
   return array(
    'example' => array(
      'variables' => array('items' => array()),
    ),
  );
}
// Theme function
function theme_example($variables) {
   return 'hi'
}
// Preprocess implementation.
function template_preprocess_example(&$variables) {
  $value = 'hi how are you';
  return $value;
}

```

I've implemented both one after another, but they didn't work. Is the custom theme function format changed in Drupal 8?

# Answer
> 1 votes
From the description of valid parameters in the docs:

> **function**: (deprecated in Drupal 8.0.x, will be removed in Drupal 9.0.x) If specified, this will be the function name to invoke for this implementation. If neither 'template' nor 'function' are specified, a default template name will be assumed. See above for more details.

So if you must use a function, you need to be explicit:

```
function example_theme($existing, $type, $theme, $path) {
   return array(
    'example' => array(
      'variables' => array('items' => array()),
      'function' => 'theme_example',
    ),
  );
}

```

But considering that method is deprecated in favour of template files, it would be better to use one. You can do so by simply creating a template file at modules/custom/example/templates/example.html.twig

---
Tags: 8, theming
---


# Question
Title: Search api solr create a custom search link
I try to create a custom search link like this :

```
l(t('See our Job Ads'), 'search', array('query' => array('f[0]' => 'is_recruiter_nid:' . $nid )));

```

when i click on the link nothing get filtered. P.S : i have added the filter '`is_recruiter_nid`' in code using the `hook_search_api_solr_documents_alter()` Something like:

```
function MYMODULE_search_api_solr_documents_alter(array &$documents, SearchApiIndex $index, array $items) {
  foreach ($documents as $document) {
     ...
     $document->setField('is_recruiter_nid', $recruiter->nid);
  }
}

```

How I can do this? Is there any example ?

Thanks for your help.

# Answer
> 0 votes
f\[0\] param doesn't work directly. To allow ApacheSolr to filter results based on custom fields you will need to define them as facet (checkout FacetAPI module) or you can implement `hook_apachesolr_query_alter` and add your own filters in it.

---
Tags: search
---


# Question
Title: How to programmatically create entity with certain language applied to fields?
I am programmatically creating some content during profile installation and since Drupal uses "en" langcode during this period I am getting the language from config and it is working fine.

The issue I have is that I am creating a node and I will end up with it being in English. So I have set the "langcode" property of the node during creation which worked as expected. **But the fields are not responding to this fact**(I have only the body field attached).

So I have tried to key the value(s) by the langcode(Drupal 7 style) but it resulted in the field not being populated in DB at all.

The node entity nor field item list nor field item have methods for setting the langcode so I am unsure how to proceed with this.

Any ideas?

This is my code:

```
// Create 'terms of service' page
  $tos = entity_create('node', [
    'type' => 'page',
    'title' => t('Terms of service', [], ['langcode' => $langcode]),
    'uid' => 1,
    'status' => 1,
    'langcode' => $langcode, // this is working on node only
    'defaultLangcode' => $langcode, // no change on field
    'activeLangcode' => $langcode, // no change on field
    'body' => [
      $langcode => [ // this is not working
        [
          'value' => '<p>' . t('This is a placeholder. Please edit this page and use your own text.', [], ['langcode' => $langcode]) . '</p>',
          'summary' => '',
          'format' => FULL_HTML_FORMAT
        ]
      ]
    ]
  ]);
  $tos->save();

```

---

I have found setLangcode() method on the FieldItemList but that didn't work as well.

---

I have tried to save the node without body, then set the body and save the node again, but the field is in English again(and the node in installed language). Is it possible that this is kind of a (edge case)bug that relates to language manager?

---

I have checked the entity constructor and this is also not working:

```
'body' => [
      $langcode => [
        [
          'value' => [
            'value' => 'some text',
            'summary' => '',
            'format' => FULL_HTML_FORMAT
          ]
        ]
      ]
    ]

```

# Answer
I have found a solution. As I have mentioned this was during the profile installation process and it is related to How to get correct language code during installation?

The solution was to make sure the installed language exists before the modules are being installed and set it as default. Normally, translation are the last installation task. So I have copied the following code from `install_download_additional_translations_operations()` into a task in my profile that runs before modules are installed.

```
if ($langcode != 'en') {
    \Drupal::service('module_installer')->install(['language']);
    if (!($language = entity_load('configurable_language', $langcode))) {
      // Create the language if not already shipped with a profile.
      $language = ConfigurableLanguage::createFromLangcode($langcode);
    }
    $language->save();

    \Drupal::service('language.default')->set($language);
  }

```

I have also removed the $langcode from my code since translations were now working as expected.
> 0 votes

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


# Question
Title: Is there an easy way to adjust the block layout?
I have menus that are set to Sidebar First in the Bartik theme. When the screen size decreases, those menus are shown below the main page content. Which file in a copied version of the Bartik theme could I play around with to change around the block configuration as shown here:

# Answer
The page.tpl.php file within /themes/bartik/templates/ folder is the main layout for the theme.

So in your copied version of that you can edit that file. If you look for: `print render($page['sidebar_second']);`

That is the rendered content of sidebar second region. There's also 1 for sidebar\_first. So you can move these to a different location within this file if you want it to be displayed heigher/lower in the content
> 1 votes

---
Tags: blocks, 8
---


# Question
Title: Rule to update referenced node after customer completes checkout
I've got a rule which fires on "Customer completes checkout".

When it fires I would like to update a field in a node which is related to the one which was "checked out".

The node which is "checked out" has an entity reference field which relates it to another node, of a different content type.

So I have my Rule Event: "Customer completes checkout" And the condition: "Entity has field" which checks for the entity reference field

Under Actions, I have: "Fetch entity by ID" to fetch the referenced node. And I have provided a "Variable name" for the Fetched Entity.

I know this much works because I can print the Title of the referenced node as a status message on the site at this point. I can even print the contents of the field that I want to update using the token \[the-fetched-node:field-name\]

But when I add an Action: "Set Data value" and look for the field to update, **the-fecthed-node:field-name** is not available.

I can see things like the-fetched-node:body and the-fetched-node:title, but none of the fields of the node seem to be available to Set Data values on...

How can I get access to set the data in my required field?

I'm using the Rules (7.x-2.9) and Ubercart (7.x-3.9) modules.

# Answer
This question seemms to be a variation of Populate an entity reference field, which suggests a solution like so:

* Add **Condition**: “Entity has field”, checking for your reference field
* Add **Action**: “Fetch entity by id”, supplying your node/user id from another field in the dataset and providing a meaningful name (Note: This solution implies you get the id by a simple field value in your dataset; you might want to add another condition to register the id first)
* Add **Action**: “Set data value”, which you now can supply your entity object from the step before (hence a name you'll identifiy in the dataset)

Apart from some Rules "Event" you probably need to add to it (related to your "*After customer completes checkout*"), this should be pretty close to what you're looking for.
> 2 votes

# Answer
Under the hood, Rules 7.x-2.x keeps around something called a RulesState object, which you can think of as a sort of grab bag that keeps data around for conditions and actions of the rule to process later in the chain, if the Rules event you're triggering on does not make the data you want directly available.

@pierre.vriens' approach is not too bad. Somehow, you need to get grab the field you want so the field is available (i.e., stamped into RuleState) for the action you want to use.

I'm guessing the event you're trapping is defined as:

```
  $events['uc_checkout_complete'] = array(
    'label' => t('Customer completes checkout'),
    'group' => t('Cart'),
    'variables' => array(
      'order' => array(
        'type' => 'uc_order',
        'label' => t('Order'),
      ),
    ),
  );

```

The definition means you will get a uc\_order object, named as "order" as part of your RulesState. This is set up as an entity in uc\_order.module.

I haven't used Ubercart, but from reading the code, it looks like the uc\_order object has a "products" array, and that the "bid" node you want to access will be in that array. So:

* As the first part of the actions, do a Rules loop that uses the "products" array to pull out one of the products, and assign it to a variable via a data selector.
* At this point, the bid should be accessible, along with its fields. If all you need to do is update the content of another of the node's fields, it should now be possible.

If you can have multiple products in the cart's order but only want to operate on some one them, it gets a little trickier, although I think you can create a Rule Component that you will call for each of the items in the cart. The component can test if the component is of the "bid" type, and process just those. Since components can bundle conditions along with actions, this should give you the flexibility you need.
> 1 votes

# Answer
### Create a component

Plugin: Rule

Component Name: kewl

Data Type: Node \>\> Name: kewl \>\> Machine name: kewl

Add Condition \>\> Entity has field \>\> kewl \>\> \[select the field you want to update\]

Add Action \>\> Set a data value \>\> kewl:\[the field you want to update\]

### Create Rule

Add Loop \>\> node:field-\[your reference field name\]

* Add Action \>\> Under Components, Rule: Kewl \>\> list-item
> 1 votes

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


# Question
Title: How do I add repeating dates programmatically?
I have some JSON data I'm using to populate Drupal 7 database. This involves creating nodes with repeating dates.

This is a sample of the data.

```
 [field_event_date] => Array
    (
        [0] => stdClass Object
            (
                [value] => 2012-12-14 10:00:00
                [value2] => 2012-12-14 12:00:00
                [rrule] => RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20160422T215959Z;WKST=MO
EXDATE:20121221T000000,20130125T000000,20130222T000000,20130329T000000,20130426T000000,20130531T000000,20130628T000000,20130726T000000,20130830T000000,20130927T000000,20131025T000000,20131129T000000,20131220T000000,20140131T000000,20140228T000000,20140328T000000,20140425T000000
                [timezone] => Europe/London
                [timezone_db] => Europe/London
                [date_type] => datetime
            )

        [1] => stdClass Object
            (
                [value] => 2012-12-28 10:00:00
                [value2] => 2012-12-28 12:00:00
                [rrule] => RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20160422T215959Z;WKST=MO
EXDATE:20121221T000000,20130125T000000,20130222T000000,20130329T000000,20130426T000000,20130531T000000,20130628T000000,20130726T000000,20130830T000000,20130927T000000,20131025T000000,20131129T000000,20131220T000000,20140131T000000,20140228T000000,20140328T000000,20140425T000000
                [timezone] => Europe/London
                [timezone_db] => Europe/London
                [date_type] => datetime
            )
    )

```

How could I enter this data into the table which stores the date for this node type?

# Answer
Add \[\] to the end of the data field.

eg.

```
    foreach($vals->field_event_date as $fed){
        //notice the []!
        $node->field_date_of_event['und'][]= array(
            'data1' => $fed->data1,
            'data2' => $fed->data2
        )
    }

```
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: How to send a notification to a user at specified time (between 9am to 10 am) daily?
I have created a form which contains a CCK field **"send sms"** (checkbox) with two options:

1. Send sms between 9am to 10am (= option 1)
2. Or anytime (= option 2)

If the user selects **option 1**, then notification should send between time 9am to 10am to user.

If the user selects **option 2**, then notification should send at any time.

How to achieve this functionality?

# Answer
### Part 1: Rules

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", a question that is a variation of part of your question. It explains how you can use the Rules module for this (using the Rules Scheduler also).

### Part 2: Message Stack

Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

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

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

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

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.
> 2 votes

---
Tags: rules, notifications
---


# Question
Title: How to translate custom fields in taxonomy terms?
I would like to have custom **fields** with **translatable** content in **taxonomy** terms. Is this possible with existing modules?

I know that this is possible if I use *nodes* instead of taxonomy terms: I can make fields translatable using the entity translation module and edit the different versions of the field by switching the language on the node edit page.

I am also aware that the taxonomy translation module allows to "localize" a vocabulary in the sense that its terms can have a different name and description for each language. I want not only name and description to be localizable but also custom fields that I have attached to the vocabulary, in particular text and image fields. Is this possible with existing modules?

# Answer
Entity translation allows for translation of custom term fields either. You only need to enable taxonomy term as translatable entity type on the Entity translation settings page (admin/config/regional/entity\_translation).

But note that once you have enabled Entity translation for taxonomy terms, the name and description of a term cannot by localized anymore unless you have installed and enabled the Title module. It provides an option to replace the core name and description fields with field instances, which will be translatable through Entity translation.
> 0 votes

# Answer
If you use 'Localize' option for taxonomy translation mode, it is possible to add taxonomy custom fields to string translation:

```
/**
 * Implements hook_i18n_string_list_TEXTGROUP_alter().
 */
function YOUR_MODULE_i18n_string_list_taxonomy_alter(&$strings, $type, $object) {
  if ($type == 'taxonomy_term' && $object) {
    if (isset($object->FIELD_NAME)) {
      $term_FIELD_NAME = field_get_items('taxonomy_term', $object, 'FIELD_NAME');
      $strings['taxonomy']['term'][$object->tid]['FIELD_NAME']['string'] = $term_FIELD_NAME[0]['value'];
    }
  }
}

```

After clearing cache the field will be available in translation form.
> 2 votes

# Answer
In regards of andreyjan answer, this is a little more generic code to allow any textfield fields to be translated by using the "localize" mode:

```
function mymodule_i18n_string_list_taxonomy_alter(&$strings, $type, $object) {

  if ($type == 'taxonomy_term' && $object) {
    // Retrieve vocabulary and potential field instances
    // for this vocabulary.
    $vid = $object->vid;
    $vocabulary = taxonomy_vocabulary_load($vid);
    $field_instances = field_info_instances($type, $vocabulary->machine_name);

    // Iterate over each fields to check if textfield(s) exists.
    foreach ($field_instances as $field_name => $field_instance) {
      if ($field_instance['widget']['type'] == 'text_textfield') {

        // Retrieve data for the field.
        $term_data = field_get_items($type, $object, $field_name);

        // Add new entry into strings array to reflect
        // values from current processed field.
        $strings['taxonomy']['term'][$object->tid][$field_name] = array(
          'string' => $term_data[0]['value'],
          'title' => $field_instance['label'],
          'format' => NULL,
          'name' => array('taxonomy', 'term', $object->tid, $field_name),
        );
      }
    }
  }
}

```

You can easily add other tests on widget type to allow other kind of fields to be added in translation process.
> 2 votes

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


# Question
Title: Adding taxonomies to node gallery and using views to display
I think the most important piece of information I can give is I am doing a migration from Drupal 6 to Drupal 7 and I am resetting everything up. This gave birth to a few hiccups along the way. As a side note, all content was migrated using the drupal-to-drupal migration module.

I have a few taxonomies. Some of the vocabularies have terms. I am using Node Gallery to create and display galleries and I am also using views to display some views. Given this information, I have 2 problems:

1. The first is I do not know how to link node gallery to any of the terms. This would be the first thing I need to do. I need to link a gallery to a specific category or term.
2. The second problem might be a bit involved. I need to create a view, based on the taxonomy accessed. On the Drupal 6 website, the menu URL was say /category/vocabulary/term. When clicked it redirected to ex. /gallery-page/term where both terms are the same.

I know the Drupal 6 site used Taxonomy Views Integrator. Not sure if that was what created it. I haven't had any luck getting any of this to work.

I see the Drupal 6 version allows you to select a category when creating or editing the gallery, not sure if this is a custom module.

Any advice, module suggestions or anything like that would be greatly appreciated.

**Update:**

I think I have figured out how to set categories, was missing a field. Added it and can now select. Will edit again if fixed.

# Answer
> 0 votes
I have made a plan. I have ignored the redirection for now. What I did was set up a view for each gallery-page/term that there should be. Each view was linked to a specific term that each gallery item is associated with.

The term association was made by adding a field to the gallery content type using the field type term reference. This allowed me to set the terms required for each gallery.

After setting up each of the fields I wanted to display including the path and additional settings, I got it to work displaying only the galleries in a specific taxonomy.

The solution is actually pretty straight forward. I would have liked to have used arguments, however I couldn't get that working. At least the problems described above have been resolved.

---
Tags: 7, views, migrations, media
---


# Question
Title: Webform conditional calculation depending on selected options count
Users register for a conference via a webform. There are options for choosing a city \[mandatory\] *and* 1-4 dates \[at least 1 date has to be checked\]. E.g. user checks NYC + 2015-08-07 and 2015-09-01.

The price for the conference bases on the days count: if all 4 days has been checked = X USD; if 1, 2 or 3 of 4 days = Y USD/day.

Now, I have to calculate the price based on total count of checked dates and send it to the user in confirmation e-mail. How to do it?

# Answer
> 0 votes
You have to use javascript for this and multiply the price with the number of days (the number of checkboxes checked).

---
Tags: webforms
---


# Question
Title: Add a button that when clicked adds the user to the entity reference field
I have a Job content type (created only by a Client), with an Entity Reference field, "candidates".

Freelancers (user role) see a Views block of jobs created.

How do I add an "Express interest" button to each job so that the freelancer who clicks it gets referenced by the job?

# Answer
You can create a custom module dealing with the subscriptions. Implement hook\_menu(), and create a callback url that gets the NID (I suppose your content type is derived from the node entity, but it would work for custom entities as well) as parameter, e.g. 'node/%node/subscribe'.

Within the callback function you check whether the current user has already subscribed for this job and create the reference programmatically if not.

In your view make sure to read the NID property. You may hide it from display. Then you can easily add another field, and rewrite its output as link using the \[nid\] token from the previously hidden NID, in the above example, the URI would be 'node/\[nid\]/subscribe'.

Last not least you can CSS style your link to look like a button.
> 1 votes

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


# Question
Title: Aegir different site folder from site name
When you create a new site in Aegir it creates the a directory using the sitename in the corresponding platform. So if the site name is `example.com` the path for the site will be `/var/aegir/platforms/platform_name/sites/example.com/`.

Is there a way to create the site in a different directory, like: `/var/aegir/platforms/platform_name/sites/my_awsome_path/`?

# Answer
Using a different sitename would be your best option. You could then add an alias for the real sitename.
> 1 votes

---
Tags: multi-sites, aegir
---


title: Calling json from <a>

text:
# Question
Title: Calling json from <a>
in mt .tp file I have a loop that outputs Publish or something similar for each entry. I don't want it to refresh the page when clicking on the so I want to call some json instead to call a module and pass some parameters to update the Database but I am not sure how to go about it. Do I need a new module with something like this in it?

```
function menudemo_menu() {

    $menuitems['menudemo'] = array(

    'title' => 'My Menu',

    'page callback' => 'menudemo_mymenu_page_callback',

    'access callback' => TRUE,

    'type' => MENU_CALLBACK,

    );

    return $menuitems;

}

function menudemo_mymenu_page_callback() {

    return 'My Menu URL was hit';

}

```

And how do I pass the parameters

# Answer
> 0 votes
Thanks for the confirmation - I was on the right track. I just need to add in the sql update command now and will all be working.

---
Tags: 8
---


title: Email Attachment File Path

text:
# Question
Title: Email Attachment File Path
I am using Drupal 7 with the WebForm and MIME Mail modules.

I've got webform attachments being sent in the email working fine. However the email also contains a path to view the email in a directory on the server. Currently, it's set to `/sites/default/files/webform/sites/default/files/webform/ /`.

How can I change the directory where WebForm submissions are stored?

# Answer
> 0 votes
As far as I know they've got to stay within /sites/default/files/webform/ folder as /sites/default/files is the only folder that should be both writable and publically accessible

If you edit the file component you added to your webform you can then specify a folder within /sites/default/files/webform/ that you'd like them to be stored specifically for that form. Look for the "upload directory" field.

---
Tags: 7, webforms, emails
---


# Question
Title: Need Steps to Install multisite configuration using only drush. i.e multi-site install having different database
I need a help to install multi-site setup using only Drush that have multiple/different databases.I have already installed a site using drush but when I do the same steps for install another site into the sites folder using drush it gives me an error to delete previous database. I want instead to install another site that having same code base but different database.

1. Install site in /var/www/html/abc
2. Install another in /var/www/abc/sites/xyz.com

Gives error.

# Answer
Try:

`drush site-install --db-url=mysql://USER:PASS@localhost/DATABASENAME --sites-subdir=sitename`

You may also need to add `--db-su` and `--db-su-pw` if necessary to provide the right credentials to create the database if the user specified by `USER:PASS` does not have permissions to do this.

See `drush help site-install` for other useful optional options you might want to specify, e.g. site name, admin account details and so on.
> 2 votes

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


# Question
Title: Does Drupal.t() inside JS file has the same restrictions as the PHP t()?
I have read that the string parameter passed to t() function should be literal, which excludes:

* variables, even the parameters of a function: `t($description)`
* a concatenation of strings: `t('If you want to add a link, click on' . '<a href="http://example.com">this link</a>.')`
* the value returned from a function:`t(get_menu_description())`
* a constant: `t(MYMODULE_MY_WIDGET_TITLE)`, `t(MyClass::WIDGET_TITLE)`

as mentioned here Is it always bad to pass a variable through t()?.

So, does Drupal.t() inside JS file has the same restrictions? as I have find a string inside some module that is passed as a variable

```
 $(this).addClass('open').text(Drupal.t(settings.linkText));

```

This string `settings.linkText` can't be located at the translation interface and I tried to change it to

```
 $(this).addClass('open').text(Drupal.t('@txt',{@txt:settings.linkText}));

```

but still couldn't find it. Any Ideas?

# Answer
> 0 votes
The string will show up in the translation interface if it is found by the js code parser. And a variable can't be worked on by the parser, it has to be a string. So

```
$(this).addClass('open').text(Drupal.t(settings.linkText));

```

can't show up. It doesn't prevent the string to be translated though, if the js is aware by another way of the translation : if you write somewhere else in your js

```
Drupal.t('my_string');

```

then the parser will find 'my\_string' to translate, and the js will load it next time it's called, and if `settings.linkText` happens to equals `'my_string'`, then it will be translated.

You have to flush the js cache after the js code alteration, so the parser can look again for strings. It may be why the

```
$(this).addClass('open').text(Drupal.t('@txt',{@txt:settings.linkText}));

```

doesn't show `'@txt'` in the translation interface.

---
Tags: i18n-l10n
---


title: When not given a link, use URL node

text:
# Question
Title: When not given a link, use URL node
For a slideshow with banners, i've added the fields overlay-text and link-to. The link-to is the URL you go, if you click on the banner. It's al done & working in Views & Views Slideshow.

The user adds a node and has to set the URL by hand in the field link-to. Sometimes however, the banner has to point to a different URL or node.

How can i set the URL of the node when the field link-to is empty?

# Answer
You can use *No results behavior* on the field. Include the path field and use the field path token.

>

If there are no results, it picks the node URL.
> 1 votes

---
Tags: views, entities, uri
---


title: How do I create an Excel file?

text:
# Question
Title: How do I create an Excel file?
I'm developing a module. I need to give to the users the option to download the coupons in XLS (Excel) format.

How I can do this?

# Answer
I'm assuming you are using some content type for the content needed on your module. If so, then you can use Views with a module like Views Data Export.
> 0 votes

# Answer
As an alternative to the Views Data Export module (suggested in another answer here), you could also use the Forena module to create an appropriate report, and then save (export) the report data (= query results) in the desired format, of which XLS is one of the supported options (apart from CSV, HTML, DOC, PDF, etc). For an online example of this, refer to the Customized Simple Table of States, and its related annotations to explain the example.

For somebody who rather wants/needs a JSON or XML format, refer to my answer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

To integrate Forena in a custom module, use any of the hooks available to do so, as documented in Forena's Developers Guide.
> 0 votes

---
Tags: 7, importing-exporting
---


title: Insert or Update value in table mysql?

text:
# Question
Title: Insert or Update value in table mysql?
I just trying to save or insert data into a mysql from inside a custom module.

The table is 'my\_table'.

I use this to insert:

```
  db_insert('my_table')->fields(array(
    'name' => 'Andy',
    'last_name' => 'Moore',

  ))->execute();

```

and this to update:

```
  db_update('my_table')
  ->fields(array(
    'name' => 'John'
  ))
  ->condition('last_name', 'Moore')
  ->execute();

```

So far so good, but now I need to update or insert a value:

```
If 'name=George' exist then update its 'last_name=Niels'. Otherwise if  'name=George' doesn't exist then create insert it with this values 'name=George' and 'last_name=Niels'

```

# Answer
You can use db\_merge() function. Here is the example.

```
db_merge('my_table')
  ->insertFields(array(
    'name' => 'George',
    'last_name' => 'Niels',
  ))
  ->updateFields(array(
    'last_name' => 'Niels',
  ))
  ->key(array('name' => 'George'))
  ->execute();

```

If there is no key ("name") with value "George", "name" and "last\_name" values are inserted to the database table. If there is a record with key value "George", only the field "last\_name" is updated with the specified value.
> 2 votes

---
Tags: database
---


# Question
Title: How to create a Views based chart with time intervals and using Highcharts?
Is there any change to do time interval to Highcharts -module ?

Such as in this example: http://www.highcharts.com/stock/demo/compare

Or do I need to use different module for that?

# Answer
> 0 votes
The example in your question looks like a variation of this chart:

The above is a screenprint of a chart created with the Charts module, for which Highcharts is one of the supported charting engines (apart from Google Charts). So consider this module as a possible alternative to create such chart(s).

Head over to the Community documentation Create charts using Views for details about how to use the Charts module in combination with Views.

**Disclosure**: I'm a co-maintainer of Charts.

---
Tags: views, charts
---


# Question
Title: How to prevent Drupal export XML formatter adding paragraphs?
I'm exporting nodes as XML and with fields in most nodes set to "Plain text" format. Everything is fine when I'm editing them, but when exporting an extra paragraph (`<p>`) tag is added around text (using "Default" formatter).

The mentioned field has a variable length text (some are short like "Book" and some have long HTML). Some longer texts are exported fine, but those short ones all have extra paragraph around them (e.g. `<p>Book</p>`).

So is there some option I can check to disable adding those paragraphs or even disable any formatting? Or maybe I have to install/make some special module for formatting?

PS: I'm using Views data export (version 7.x-3.0-beta8).

# Answer
I don't think there is a need to ***make*** a "special module". Instead you could ***install*** the Forena module (with quite a few official D7 releases ...), as an alternative to what you're trying to do with the Views Data Export module (or the Views Datasource module as suggested in one of the comments to the question here).

You could use the Forena module to create an appropriate report. As per your comment like "*Full nodes, no. Only some choosen fields, but all of a single content type.*" such report should be straight forward to create. And then create an XML file from the report data (= query results). Similar solution for somebody who rather wants/needs a JSON format. Refer to my answer to "How to add a link to the CSV download to my module page, for a report created with Forena?" for more details about all sorts of export formats, and some online demo samples.

Using this alternative, you probably don't need your (*not ideal*) work-around anymore which is to *disable changing new lines to HTML new lines*.
> 0 votes

---
Tags: 7, importing-exporting
---


title: Description of entity type properties

text:
# Question
Title: Description of entity type properties
Description of entity type properties in code is very poor and I cannot find alternative resources. Could anyone explain those properties?

For example: "data\_table" is described as:

> The name of the entity type's data table.

But it doesn't explain anything.

I created a custom entity based on "examples" module, added "data\_table", "revision\_table", "revision\_data\_table", added revision entity key, but after `drush updatedb --entity-updates` only myentity\_revision table was added, and I still cannot see myentity\_data\_table, and other tables that "node" entity is using for example. Why is that?

Could someone explain those properties, what they are precisely for, and as a bonus - how they relates to "setRevisionable/setTranslatable" methods that we can invoke when creating field definition?

# Answer
I had to re-install to get it to work, AFAIK. The `data_table` is initially empty, but gets filled up as soon as you start creating a few of your custom entities. But the table itself should be there.

What exactly the `data_table` is for, I'm clueless as well, as pretty much everything worked without declaring it.

I couldn't however get the Entity Autocomplete ( see here for more info/example ) form element to work without declaring the `data_table`. As soon as I added the annotation, the autocomplete element worked by declaring `#target_type => 'my_custom_entity'`
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Add payment method surcharge on single page checkout
## Using Drupal 7, Drupal Commerce module.

I have a single page checkout on which the user enters Billing Info, selects one of two payment methods and enters their credit card or E-Check information (using the Commerce NMI payment gateway which utilizes a direct-post method), and ultimately submits the payment. The Review pane is empty and therefore skipped, so the checkout proceeds directly to the Third-party Payment Redirect pane.

**My issue:** I use a Rule to apply a fee (using Commerce Fees) depending on payment method, but it seems like the payment method isn't being set before the information is sent to the payment gatway--the payment method comparison always evaluates to false.

The rule *is* recognized after the fact, however, as the fee gets added after the payment has been submitted, resulting in an unpaid balance on the order.

The client is set on a single page checkout process, and so what I need is this:

**How can I grab and alter the order information after submitting the checkout form but before the third party redirect fires?** This would be very helpful as I would also like to add a custom code to the order ID this way.

# Answer
You need to be careful here. Obviously you want to share with your customer that their order total will change, even slightly, before they pay. Often, most payment gateways strongly discourage passing on their fee to the customer, or flat out do not allow it.

But let's assume you want to charge more for "Cash on Delivery."

According to the commerce\_fee documentation, you have to use two pages.

> Notice: if using fees based on payment type, be sure to move the payment type pane to a screen before the review pane on admin/commerce/config/checkout so that customers can see the fee before accepting.

This requirement would prevent nearly all normal payment gateways that require an off-site-payment-redirect step after putting payment details into a form from functioning correctly, if at all.

One way to create a single page, with ajax is the following recipe:

**Ingredients**

**Directions**

Add a payment method field to your order. Use field group and checkout field group to add this field to a checkout page. Use Rules to make only a pre-selected payment method available based on the field on orders (might require a custom rule condition?). Use Rules to calculate your fee based on that field selection and not on the actual payment gateway selected. Use Commerce Checkout Ajax to re-load panes as needed.
> 0 votes

---
Tags: rules, commerce
---


title: Custom title for facet display block

text:
# Question
Title: Custom title for facet display block
I am new to Search API and Facet API, any clue how to change the default Facet filter block title?

# Answer
> 1 votes
To change the title of the block provided by the Facet API, go to admin/structure/block and choose the block of which you want to chage the title. Click on the `Configure` link and then change the title of block from Block Title textfield.

---
Tags: search
---


# Question
Title: How to only allow a user to edit his/her own users?
For instance, my site contains two roles:

* employer.
* company.

Every company has to be able to add, edit and delete there own employees.

As you may understand, companies should not be able to edit or delete users created by other companies.

How can I achieve this?

# Answer
> 3 votes
The Organic groups module (as already suggested in another answer) is indeed a possible answer to your question. But you should also have a look at the (fairly new) alternative for it, which is the Group module (with it roots close to where Dries started Drupal ...). Some more details about it (from its project page):

> **Organic Groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
>
> **Groups** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.

The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

> ... you can already use Rules to:
>
> * Add a new Group
> * Create a new GroupMembership and save it (the equivalent of $group-\>addMember())
> * Add or remove a GroupRole from a GroupType
> * React on new GroupMembership or Group entities
> *
>
> What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
>
> Useful Rules we may add could be:
>
> * E-mail all members of a Group, optionally filtered by GroupRole
> * Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"
>
> ...

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

**PS**: Refer to How to implement an option for users to limit access to nodes/comments to users with the same role while posting it? for an interesting illustration of how this module can be used.

# Answer
> 2 votes
OG is one way to do this as others suggested. But for this particular use case you can get away without using it. However, you may find OG useful if it plays well with other parts of your application.

Here is what you can do:

1. Add an entity reference field (`field_company_ref`) to the user object. This field will store the company user id of an employer.
2. Use `hook_menu_alter` to alter the access callback of the `user/%user` and `user/%user/edit` pages. The result will be that the system will run your custom access functions before it displays the pages:

```
/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  $items['user/%user']['access callback'] = 'mymodule_user_view_access';
  $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
}

/**
 * Hook_menu access callback
 */
function mymodule_user_view_access($user) {
  // Add logic to determine if the user visiting the page  user/%user has permission to view it. Return TRUE or FALSE.
  // You may want to look this for the default access callback: user_view_access()
}

/**
 * Hook_menu access callback
 */
function mymodule_user_edit_access($user) { }

```
3. Additionally, you will want to do a `hook_form_alter()` to alter the properties of the user form page:

* Add you custom validation function in `$form['#validate']` array to make sure that the user submitting the user form is legit.
    * Add a custom submit function in the `$form['#submit']` array to set the value of the `field_company_ref` to the user id of the company creating the user.
    * Add a $form`['field_company_ref']['#access'] = FALSE` so that the user will not be able to view/change this field when editing his user details

# Answer
> 2 votes
When I asked this question I actually thought of an answer like Mike gave me, till I started experimenting with this really interesting group module a few hours ago.

Using the group module I was able to:

* Enable companies to edit fields of employees on special group member profiles.
* Give employees in a group, owned by a company, the permission to create, edit and delete certain nodes.
* Enable companies to add existing users to their company group.
* Enable companies to remove existing users from their company group

I wasn't able to:

* Enable companies to edit the basic account information of employees (username, e-mail and password).
* Enable companies to delete their employees.

It doesn't really matter to me that companies aren't able to edit and delete their employees as they are able to remove them from their group. This is why I 'll probably continue using the group module.

# Answer
> 1 votes
I would recommend using og module, with help of og module you can define a group(company as in your case) and then there can be members of the group(employers in your case) and with in group you can have group admin which can have permission to edit other members in the group.

---
Tags: 7, users
---


# Question
Title: How can I include a simple php in a Drupal 8 twig file?
I'm making a custom theme, and I just want to include this in my twig file.

```
<?php echo date("l H:i"); ?>

```

Do I need make a twig extension? How can I do it?

# Answer
> 4 votes
One way to do it would be to add the variable in a preprocess function, and print that out in the chosen twig template as `{{ your_variable }}`.

```
function yourtheme_preprocess_page(&$variables) {
  $variables['your_variable'] = \Drupal::get('date.formatter')->format(args);
}

```

I'm not sure where you are doing this, so your use case could be \_page, \_node, \_html, \_block for the preprocessor.

Since you are not passing a timestamp to date, it will assume current time and print that. If that is your intent, you should consider that when caching mechanisms are enabled, it won't show the current time anymore, and you should consider a Javascript based solution to keep that accurate (something like momentjs?). Again, don't know your full use case here.

edit: see https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/format\_date/8

and https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21DateFormatter.php/class/DateFormatter/8

---
Tags: theming
---


title: File upload is not working

text:
# Question
Title: File upload is not working
We are using the file upload field in a custom drupal form, it was working for one (1) year but now it's not. It is working for administrators but not for anonymous users.

I am using the following code.

```
$allowed_exts = array('jpg jpeg gif png txt doc xls xlsx pdf ppt pptx pps odt ods odp docx zip rar');

      $form['file1'] = array(
        '#title' => 'Attachments',
        '#description' => t('Allowed Files - jpg jpeg gif png txt doc xls xlsx pdf ppt pptx pps odt ods odp docx zip rar'),
        '#attributes' => array('id' =>'file_attachment'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => $allowed_exts,)
      );

```

# Answer
> 1 votes
try to set the location

```
'#upload_location' => 'public://',

```

---
Tags: files
---


# Question
Title: Configuring the new display modes in Drupal 8
I like very much that in Drupal 8 you can create your own display modes (i.e. not just have "Full" and "Teaser", but create your own) and that you can reference Content via Entity Reference fields within Content. It's really neat and allows me to add arbitrary lists of content on pages and have them render as I like. EXCEPT there seems to be one small issue - the rendered entities always start with the title linking to the Content. There doesn't seem to be any way of getting around it.

Apart from creating my own templates for my display modes, is there any way I can prevent the Title displaying when I render Content in another piece of Content using an Entity Reference? This seems to be an oversight with a very useful bit of functionality - or am I missing something?

# Answer
As you've found out through comments, the title is currently hardcoded.

The reason for that is that the title isn't controlled by the view mode in the default behavior. It's whether the node thinks he's on his own page vs. not. A behavior that's not easily configurable.

Would have been nice to fix that but like many other things, we didn't enough time.

Apart from using templates to do, you could also consider to use Display Suite, just like in 7.x, it allows you to control the title, pick from different layouts and so on.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How do I convert a string like node/1 into a RouteMatch or Url object?
I'm creating a text filter that modifies links. I am processing all the hrefs, and I want to load a RouteMatch or Url object for all valid urls like "/node/1". I need this to also handle i18n URLs. How do I convert a string like node/1 into a RouteMatch or Url object?

# Answer
One way is to use `PathValidator::getUrlIfValid()`, which returns a `Url` object, if if the path passed as argument is valid and accessible.

```
if ($url = \Drupal::service('path.validator')->getUrlIfValid($path)) {
  // The path is valid and it's accessible from the currently logged-in user.
}

```

I don't think it can handle a URL that prefixed with the language code, if that's what you mean. That's usually handled/stored separately.
> 2 votes

# Answer
You may want to look at a question I asked a few months back.

Berdir had the suggestion to take the URI and first feed it to file\_create\_url(), which seems to clean up some of the URLs that may make Drupal 8 blow up.

This isn't 100%, since the change record he refers to has since landed. My sense is that URL code is a lot better than it was, but can still occasionally blow up, rather than just give an error.
> 1 votes

---
Tags: 8, routes
---


# Question
Title: How to concatenate fields in Views with different separators (Settings)?
I have 4 fields : lastname, firstname, middlename, suffix

I selected TABLE Format. In the Settings tab, I put all fields together in the first column so I can have them together in one row, but I want the display to be:

Jones, John David Jr

instead I can get

Jones John David Jr

or

Jones, John, David, Jr

In other words, the separator is applied between **every** field, and I want it applied only after the first.

I tried the UNFORMATTED LIST but that didn't provide me with any way to concatenate.

# Answer
Solution 1:

As @rooby suggested here are the steps you can follow

1. Add the fields Last Name, First Name, Middle Name and Suffix to the view in the same order
2. For the first 3 fields Last Name, First Name, Middle Name select the option "Exclude from Display" and save.
3. In the settings of the field "Suffix" check the option "Rewrite the output of this field" under the section "Rewrite Results".
4. In the TextArea that gets displayed enter \[field\_last\_name\], \[field\_first\_name\] \[field\_middle\_name\] \[field\_suffix\]

For the exact field names you may click on the link "Replacement Patters" below the text area.

This approach works fine if the Suffix field is a required field and all the records for it. If not the complete value is not displayed if the suffix is empty.

Solution 2:

1. Add the fields Last Name, First Name, Middle Name and Suffix to the view in the same order
2. Add "Global: Custom text" field to the view at the bottom of all the fields.
3. For the fields Last Name, First Name, Middle Name and Suffix select the option "Exclude from Display" and save.
4. In the settings of the custom text field enter \[field\_last\_name\], \[field\_first\_name\] \[field\_middle\_name\] \[field\_suffix\] under "Text" and save
5. Look at the replacement patterns for the exact field names in your system

This approach works fine even if there are empty values for any of the fields.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How can I make my site stop adding <p> tags in textareas?
For a current project I have a content type’s textarea set to Full HTML. But where I’ve added a `<span>` tag, Drupal will go ahead and enclose it within a `<p>` tag which is definitely not what I want!

It’s also adding an empty `<p>` tag at the bottom of said container.

How and where can that be turned off? Where is the mechanism or module that is doing that?

# Answer
Sounds like maybe you need to disable the "Convert line breaks into HTML (i.e. `<br>` and `<p>`)" filter on your Full HTML text format.

This can be done by navigating to Configuration \> Content authoring \> Text formats and editors, then editing the Full HTML configuration and un-checking the box for "Convert line breaks into HTML (i.e. `<br>` and `<p>`)" under "Enabled filters". Assuming this is Drupal 8 anyway. Drupal 7 has the same setting but the exact location might be different.
> 1 votes

---
Tags: input-formats
---


title: How can I use tokens in my content

text:
# Question
Title: How can I use tokens in my content
I want to use tokens in my content but it seems like it doesn't let me. I've found an article about using the Token Filter module but I have not been able to configure it so that it would print. In the README.TXT it says,

> Go to /admin/settings/filters and enable the token\_filter for any of your existing filter type or if you wish, create a new one.

but my problem is, when I go to http://127.0.0.1/drupal-7.34/#overlay=%3Fq%3Dadmin%252Fsettings%252Ffilters (on my installation, I just get to see and I'm not sure how I can "enable the token\_filter for any of your existing filter type" - may anyone help me?

Thank you!

# Answer
Actually in order for this to work you need the token filter module:

https://www.drupal.org/project/token\_filter

Otherwise there is no option in text format config.
> 0 votes

# Answer
README file of D7 version of module seems to be outdated, couple of things to ensure here:

1. Token filter module is enabled.
2. Navigate to text format section: `Home » Administration » Configuration » Content authoring` (URL: `<DOMAIN-URL>/admin/config/content/formats`)
3. Either edit any of the existing text formats or else create new text format and select the option: `Replace tokens`
4. Now verify `Filter processing order` present just below this options, to make sure `Replace tokens` doesn't overridden by some other option.
5. Check permission for this updated/created text format (required user roles have permission to access this text format)
6. Try creating content, however ensure the text format is one update/create above.
> 0 votes

# Answer
On Drupal 7, you set the text formats at admin/config/content/formats; so, on your site it should be http://127.0.0.1/drupal-7.34/admin/config/content/formats. Click on *configure* for the format you want to change.
> -1 votes

---
Tags: nodes, tokens
---


# Question
Title: How to resize an image in a content type
I created an article and added an image field, but I don't know how to resize the image. Can anyone help me how to do it?

# Answer
> 2 votes
You can use image styles for this. Go to `admin/structure/types/manage/article/display` and change the respective image style you want to use for the image field under 'format'.

If the available image styles don't suit your need, then you can go to `admin/config/media/image-styles/add` and add new image style you want. For more information on using image styles, refer image documentation at https://www.drupal.org/documentation/modules/image

# Answer
> 0 votes
Image Resize Filter

> The easiest end-user solution for resizing inline images.
>
> This filter makes it easy to resize images, especially when combined with a WYSIWYG editor such as tinyMCE, CKeditor etc. Users never have to worry about scaling image sizes again, just insert an image and set it's height and width properties in HTML (this is done automatically by WYSIWYG editors) and the image is resized on output to match the HTML.

---
Tags: theming, media
---


title: How do I hook into t()?

text:
# Question
Title: How do I hook into t()?
Drupal uses t() in various places. I was wondering if there was a way to hook into this function. Basically, if Drupal calls:

```
t("some string");

```

I wanted to modify this string and add "BOOM" at the end. I was hoping it would be as easy as this

```
function mymodule_t($string)
{
   return $string.'BOOM';
}

```

But no luck... any ideas on how to get this right?

# Answer
> 2 votes
AFAIK Drupal's t() function does not provide any hooks for neither altering its input values nor its results.

However, if your intention is to override specific translations of the locale module, you can alter them within the translation interface of Drupal at '/admin/config/regional/translate/translate'.

If you don't want to alter the database stored locale translations, or don't have the locale module enabled, you can also provide according overrides within your settings.php by defining $conf\['locale\_custom\_strings\_' . TARGET\_LANGUAGE\]\[CONTEXT\]. Replace TARGET\_LANGUAGE with the target language shortcut, and CONTEXT with the context of the translation (usually an empty string):

```
$conf['locale_custom_strings_en'][''] = array(
  'some string' => 'some stringBOOM',
);

```

---
Tags: 7
---


# Question
Title: What is the difference between a page and a node?
What is the actual difference between a node and a page in Drupal 7? Why there is separate `page.tpl.php` and `node.tpl.php` pages. How is the theming applied for the actual page.

Any link for understanding all this would be greatly appreciated.

# Answer
**node.tpl.php**

> Default theme implementation to display a node.

**page.tpl.php**

> Default theme implementation to display a single Drupal page.

see image for more detail.
> 20 votes

# Answer
Page.tpl.php contains, header, footer, left block and content section, while node.tpl.php contains content section
> 1 votes

# Answer
Pages may hold nodes, blocks, modules.

In the other hand nodes holds only articles, news, pictures, bla, bla.
> 0 votes

---
Tags: theming
---


title: Feeds: Error Importing Node Reference

text:
# Question
Title: Feeds: Error Importing Node Reference
I am trying to import a node reference in my users's profile using feed and feeds profile modules and using a CSV file like this:

```
"Name","Email","Team"
"Pepe","Pepe@example.com","Team A"
"Juan","Juan@example.com","Team B"
"Pedro","Pedro@example.com","Team C"

```

My mapping configuration is like this:

```
SOURCE         | TARGET                                        | TARGET CONFIGURATION
Name             User name (name)                                Used as unique
Email            Mail                                            Used as unique
Team             team nid nid (profile2:main:field_team_nid_nid)

```

Team is a node reference to a content type that I had created. When I try the import y receive this error message:

```
Invalid data value given. Be sure it matches the required data type and format.

```

# Answer
> 0 votes
The feed was expecting a node id and I was delivering a text value. I replaced the text value for node id corresponding in the CSV file and it works. I had to looking for node id value using phpmyadmin.

---
Tags: 7, feeds, migrations
---


# Question
Title: How do you add a form to a content type?
I have a view that had a list of equipment. Each equipment node in the view needs a form so I can upload equipment drawings. I would like the form to belong to the node because it makes it easier for submission to understand it's context. Is there any way to do this?

I have webforms installed and I can create a webform for each node individually, but for some reason I can't find a way to add a webform for the content type.

Thanks!

# Answer
If you are ok with custom code.

* The form does not need to be inline to Content Type.
* Consider this example
* You have custom form. form builder of which takes an argument as nid.

function custom\_form\_builder($form, &$form\_state, $nid) { $form\['nid'\] = array( '#type' =\> 'hidden', '#value' =\> $nid, ); // form field goes here. }
* Now in your view add nid field along with other fields you need and an extra custom field.
* In your views you can define custom template for custom field.
* Implement template\_preprocess\_views\_view() to call drupal\_get\_form('form\_id',$nid) and make it available on the custom template.
* Print the form on the template.
* Now when the custom form gets submit you can get the nid to update in $form\_state\['values'\]\['nid'\].
> 0 votes

# Answer
Each webform is a node, so you can use a **node reference** field on your equipment nodes and render that within your View.
> 0 votes

---
Tags: views, webforms
---


# Question
Title: Email sent to customer from Drupal has RED LOCK icon in the email
I'm using Drupal Commerce. Overall it's working well. I have SSL setup and enforced so users HAVE to use 'https' (via .htaccess). I'm able to test fill out the form and it submits. PayPal gets the payment. We're happy. I get an email telling me a new purchase has been made (via Drupal at `site:mail` token).

**The issue is**, the user also receives an email from Drupal letting them know, you know, thanks for purchasing, etc. However, in the email to the person who purchased the product (in gmail specifically as that's all I've tested with) there is a **RED LOCK icon next to their name/email** at the top of the email. When hovered over it says '**bluehost.com did not encrypt this message**'.

Now, MAYBE it doesn't really matter because i'm not sending them their credit card info back to them or anything, but it does LOOK disconcerting and I'd like it not to be there in their email. **So I need their email to be encrypted**.

I talked to Bluehost and they said it was an **internal linking issue**. The only link in the form is their email address that they put in (it's a custom field we setup).

**Does anyone know how to encrypt their email address in the form before Drupal sends it to them**? Or tokenize it properly perhaps is another approach since `site:mail` doesn't have that issue.

Here's the token I'm using to send them the email from Drupal:

```
[commerce-order:commerce-customer-billing:field-email-address]

```

*Note: I'm using '**Send mail with Variable**' action to send this email, if that's worth noting.*

# Answer
> 5 votes
I've read both your questions regarding this issue posted here. IMHO the red lock is not a thing you can overcome by encrypting the contents of your mail before sending it via an unencrypted channel.

This issue is not directly connected to Drupal, but to your Drupals mail gateway. Obviously your mail relay is not supporting TLS mail forwarding.

I do suppose you are sending the mails using Drupals built-in mail functions. These functions do use the PHP mailing functions, which by default are set-up to use your hosts mail services.

If you are working with a root server and installed your mail server yourself (e.g. postfix on Unix), you have to digg into its configuration and make sure it is set-up to use TLS when connecting to other mail servers.

When you don't have direct access to these settings (e.g. on a shared hosting package), you can overcome this issue by creating a mail account with a third-party email provider that is using TLS (e.g. gmail itself). With this mail account you will also get SMTP credentials to use for sending mails from your desktops mail client.

In your Drupal, you can install and configure the SMTP module to use these credentials for letting Drupal send mails via this external mail provider. Please note that some mail providers have flood mailing prevention in place that do allow a certain amount of mails each time/per minute only. So you might additionally consider using Queue Mail and a Cron job to send your mails in batches.

**Edit:** Drawback of the second solution is, that the mails received by your sites visitors may have been flagged as "x-forwarded" or have the third-parties mail provider email address as sender. Some mail clients therefore may mark the mails as spam.

So another solution for shared hosting: Ask your hosting provider to change the default mail server settings.

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