# Question
Title: How to modify/add addition variable to service json after successfully register.json?
I am able to get the response after register using service register.json

Response:

```
    {
        "uid": "10",
        "uri": "http://example.com/apps_api/user/10"
    }

```

Input:

> { "name":"smart", "pass":"smart", "mail":"tushar@smalution.com", "status":"1", "roles":\[ "3" \] }

I get all the information `"uri": "http://example.com/apps_api/user/10"` . I just want to get the "name", "mail", "role" in response.

Do not need to go again `"uri": "http://example.com/apps_api/user/10"`.

# Answer
> 1 votes
I was never able to get back the raw text password without hacking on the logintoboggan / user modules themselves (similar to what is shown in my question).

However, I solved my same purpose of providing immediate-login-upon-registration for Services/API calls using the services\_token\_access module. This code only hooks onto a success registration then ads the services\_token to the response which is now the only thing my client now needs for validation.

```
function HOOK_services_request_postprocess_alter($controller, $args, &$result) {

if ( gettype($result) == 'array' && isset($result['uri']) && isset($result['uid'])) { // THIS CONDITION MATCHES THE DEFAULT RESPONSE OF A SUCCESSFUL REGISTRATION.
        $user = (object)$result;
        $user = user_load($user->uid);
        $user = HOOK_services_account_object_alter($user);
        $result = array('token'=>$user->services_token, 'user'=>$user);
    }
}

function HOOK_services_account_object_alter(&$user) {
    $user->services_token = services_token_access_update_token($user->uid, FALSE); // essential for logging in later
    $user->specialstuff = 'whatever else you need';
}

```

(The services\_token\_access module is not particularly popular and barely supported, but worked for me.)

# Answer
> 1 votes
Add custom code/module to modify the service response, check hook\_services\_endpoint\_response\_alter and all other similar alter hooks services alter hooks

e.g.:

```
function MODULENAME_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller->callback == '_user_resource_create') {
    if ($result->uid) {
      $user = user_load($result->uid);
      $result->user = $user;
    }
  }
}

```

---
Tags: 7, users, services
---


title: Fatal error: Cannot redeclare

text:
# Question
Title: Fatal error: Cannot redeclare
my website show a fatal error about 'cannot redeclare' \[1\]. In first moment I though that It was a concrete problem and I deleted some part of code though it was repeated. But the problem is yet, but now with other element.

I have tried updating some modules and the database by Drupal, but I can't. When database is updating happens an error \[2\]:

\[2\] *Fatal error: Class CToolsCssCache contains 1 abstract method and must therefore be declared abstract or implement the remaining methods.*

\[1\] *The messege that it's showing is: Fatal error: Cannot redeclare pa3173d21() (previously declared in /var/www/vhost/cdciconianegra.com/home/html/sites/all/modules/views/theme/views-view-fields.tpl.php:1) in /var/www/vhost/cdciconianegra.com/home/html/sites/all/modules/views/theme/views-view-fields.tpl.php on line 1*

Could someone help me? Thank you very much!

# Answer
> 0 votes
I'm assuming this is D8. What i'm assuming here is that you have duplicate code - how many views directories do you have on your website? First check your installation in terms of setup, i'd look there first.

# Answer
> 0 votes
Since Views is in sites/all/modules, I am guessing this is D7. I would:

* Verify that both CTools and Views are up to date.
* Check for copies of modules in `sites/default/modules`
* Run updates again

If it is still complaining about 'redeclare', I would try to flush APC or any server code caching and try Drush Registry Rebuild. Then try running updates again.

---
Tags: debugging
---


# Question
Title: Bootstrap CDN over-rides my custom CSS files
I have a modest site that I was hired to help customize with some CSS features, however I am noticing a problem.

Bootstrap has its own mini-file that tells it what to style its navigation bars with and at the moment, because of that, my nav bar text is grey. Its contrast compared what the site owner wants is very poor and so I attempted to change this to black.

However in doing so, because I am using CDN, bootstrap files seem to override my custom CSS template files. Is there a way to resolve this issue? I have searched for answers but have yet to find any, please help. Thank you.

# Answer
Your custom css needs to be more targeted to override the default boostrap css. On line 38 replace ".navbar-nav" with the following:

```
.navbar-default .navbar-nav>li>a

```
> 0 votes

---
Tags: theming
---


title: How do I handle special characters?

text:
# Question
Title: How do I handle special characters?
I use the Display Suite module and I enabled the Display Suite Format module. I use a code field to display a node/edit link, with the following code:

```
  if (node_access('update', $entity)) {
    print l(t('Modifier'), 'node/' . $entity->nid . '/edit?nid=' . [node:field-construction-fdr-ref:nid]);
  }
?>

```

The resulting URL is `http://localhost/node/11430/edit%3Fnid%3D11419`, leading to a *Page not found* error. I wish to get `http://localhost/node/11430/edit?nid=11419`.

I tried */* before *?* and *=*; I tried *&\_#63;* for *?* and *&\_#61;* for *=*.

How can I get the URL I need?

# Answer
Query params should be passed to the function in a keyed array:

```
$query = array(
  'nid' => 123,
  'foo' => 'bar',
);
$params = array('query' => $query);

print l(t('Modifier'), 'node/' . $entity->nid . '/edit', $params);

```
> 0 votes

---
Tags: display-suite
---


# Question
Title: Theming login form just for specific user registration / Auto Assign Role Page
On this page users gets automatically a role assigned by the Auto Assign Role module.

For a better user experience i added the login form also to this page. This works great:

In `user--register.tpl.php` I added the following code to print the login-form `<?php print(drupal_render(drupal_get_form('user_login_block'))); ?>`

But how do i THEME this login form on this specific page? So it doesn't affect the original form on `/user/login`?

# Answer
> 0 votes
You are rendering the *user\_login\_block* within your template, which is not rendered on the `/user/login` page.

As long as you have not placed a login-block, that you don't want to be affected, you should not have any problems.

You can use the template file `block--user--login.tpl.php` to theme this block or even use a `form_alter` hook to alter the form.

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


# Question
Title: How I can include Commerce SKUs in search result?
How I can include Commerce SKUs in search result?

I am using “Search API and Search API Solr” modules.

Any suggestions?

# Answer
> 0 votes
**Add a field or attribute to your index**

Most likely, you need to add the SKU field to your index. Since most search api implementations of Commerce index display nodes AND their connected products, you will need to use: https://www.drupal.org/project/commerce\_search\_api for connecting referenced product properties with your display nodes.

Then, you will need to add the SKU field to your product display index. A good step-by-step for this is here (search for "define index fields" on the page): http://www.webwash.net/drupal/tutorials/intro-search-api-part-1-how-create-search-pages

**Add an indexed field or attribute to search results**

Finally, if you want to managed the fields that appear in search results, you will need to modify the view and/or the display mode being used to render the results.

Commerce allows "field injection" for display nodes that allow you to inject default product properties on display. But note that if you search for "Red Shirt" and the display node that has this product is by default "Blue Shirt" then, when that node is rendered, it's likely going to render the "Blue" and not "Red" SKU.

Probably need to create a hook\_form\_alter() that can determine if the add to cart form is being generated inside search results and trying to make it understand which SKU should be a part of the result.

---
Tags: 7, commerce, search
---


title: Override favicon output

text:
# Question
Title: Override favicon output
Some of search engines (yandex in my case) want me to output favicon with type image/x-icon.

But drupal 7 outputs it without this type. How could i override this through template.php or any other suggestion? Thanks!

# Answer
> 1 votes
The following code in your `template.php` should do the job.

```
function MYTHEME_preprocess_html(&$variables) {
  $favicon = theme_get_setting('favicon');
  $type = 'image/x-icon';
  drupal_add_html_head_link(array('rel' => 'shortcut icon', 'href' => drupal_strip_dangerous_protocols($favicon), 'type' => $type));
}

```

# Answer
> 5 votes
To alter or remove the favicon URL Drupal 7 points to by default (not just add another favicon link) try this:

```
function YOURTHEME_html_head_alter(&$head_elements)
{
  // Search the head elements for the Favicon
  foreach ($head_elements as $key => $element) {
    if (!empty($element['#attributes'])) {
      if (array_key_exists('href', $element['#attributes'])) {
        if (strpos($element['#attributes']['href'], 'misc/favicon.ico') > 0)
        {
          // Change the URL
          $head_elements[$key]['#attributes']['href'] = '/'.drupal_get_path('theme', 'YOURTHEME').'/path/to/favicon.ico';

          // Or, delete the favicon link entirely
          unset($head_elements[$key]);
        }
      }
    }
  }
}

```

# Answer
> 2 votes
Another Simple Solution to this problem would be using a contributed module https://drupal.org/project/favicon.

Using this module, you can avoid getting 404 on those browsers which make a call to \<\>/favicon.ico to retrieve sites fav ICON. This behavior will cause a 404 Entry to show up in drupal logs.

# Answer
> 1 votes
In **Drupal 8** you could use the following to remove the Icon Link (Don't remove the favicon.ico itself) as a Link is depreciated.

in the file: *themes/YOUR\_THEME/YOUR\_THEME.theme*

```
/**
 * Implements template_preprocess_html().
 *
 * Search the head elements for the Favicon and remove it.
 * See: http://realfavicongenerator.net/faq#why_ico_not_declared.
 */
function YOUR_THEME_page_attachments_alter(&$page) {
  foreach ($page['#attached'] as $key => $element) {
    if ($key === 'html_head_link' && !empty($element)) {
      foreach ($element as $k => $item) {
        if (isset($item[0]['rel']) && $item[0]['rel'] === 'shortcut icon') {
          unset($page['#attached']['html_head_link'][$k]);
        }
      }
    }
  }
}

```

---
Tags: 7
---


# Question
Title: Writing a migration from non a non Drupal site
How can I translate this in a migrate query?

```
SELECT t.name FROM tags t
    join tag_types tt on (tt.id = 3)
    join story_tags stg on (stg.tag_id = t.id) WHERE story_id = $row_id'

```

I tried this, but it doesn't work.

```
->select('story_tags', 'tags')
->fields('tags', array('tag_id'))
->leftJoin('tag_types', 'tt', '(tt.id = tag.tag_type_id)')
->condition('tag_type_id', '3', '=' )
->condition('story_id', $row->id, '=')
->execute()
->fetchCol();

```

What am I missing?

# Answer
It might not be the answer you are looking for, as it is not Migrate, but when I did this a couple years ago for a large client this is how I did it.

First, I set up the Feed Import module and a map of column names to desired fields. Second, on the various non-drupal sites that I was migrating to a single drupal install I exported the data to csv files paying careful attention to the column aliases so they matched the map. Also, as it totalled a lot of rows, I broke it into several files to run them in batches. Using an anchored feed import, I was able to run them in batches and subsets of data, to purge and re-import any set as needed, and to group all the difficult international names together by sorting my csv files.

It took a day for every 10,000 nodes I imported.
> 0 votes

---
Tags: 7, database, migrations
---


title: Disable theme css via module

text:
# Question
Title: Disable theme css via module
I'm using Drupal 7.

I want to disable css defined by theme because I want to use my custom css that is defined by my custom module. What I mean is, I want to disable `sites/all/themes/custom_theme/css/custom.css` and use `sites/all/modules/custom_module/css/custom.css` instead.

Is there any way to do that?

Thanks!

# Answer
Yes.

What you want is to include call drupal\_add\_css() for example:

```
drupal_add_css(drupal_get_path('module', 'your_module') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));

```

What that does is that it adds the css file on every page load. You can read more about adding css files here: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_css/7

In your theme's .info file you will find a section describing where to find the css file e.g:

stylesheets\[all\]\[\] = css/style.css

simply switch it off by placing a ; at the start of that line. This works particularly well if your theme is a subtheme, that is based off some other theme that you don't want to change directly in case you may need to upgrade it later.

Lastly, should you decide to remove the css file from your template.php file or module, you can do that via hook\_css\_alter()

for example:

```
function hook_css_alter (&$css) {

    if (isset ($css[path_to_theme() . '/css/custom.css'])) {
        unset ($css[path_to_theme() . '/css/custom.css']);
    }

}

```

Hope it helps.
> 1 votes

# Answer
Chiko's answer is spot-on. You can also tweak the css\_alter so that you can switch css off and on again by using TRUE and FALSE, such as this:

```
function MYTHEME_css_alter(&$css) {
$exclude = array(
    'modules/syslog/syslog.css' => FALSE,
    'modules/system/admin.css' => FALSE,
    'modules/system/maintenance.css' => FALSE,
    'modules/system/system.css' => FALSE,
    'modules/system/system.admin.css' => FALSE,
    'modules/system/system.maintenance.css' => FALSE,
    'modules/system/system.menus.css' => FALSE,
    'modules/system/system.messages.css' => FALSE,
    'modules/system/system.theme.css' => FALSE,
    'modules/taxonomy/taxonomy.css' => FALSE,
    'modules/tracker/tracker.css' => FALSE,
    'modules/update/update.css' => TRUE,
    'modules/user/user.css' => FALSE,
);
$css = array_diff_key($css, $exclude);

```

}
> 0 votes

---
Tags: theming
---


# Question
Title: How to remove panel-separator CSS in mini-panels?
I have an issue with a mini-panel which prevents me from aligning social buttons:

I tried to set:

```
.panel-separator { height: 0px; width: 0px; }

```

in my CSS, but the Google +1 button is still under the ShareThis buttons, rather than next to it. The only difference is that FireBug displays the div line as shaded. There is enough space on the right of the ShareThis buttons for the Google +1 button.

How can I solve this? Thanks. If it matters, I am using `Panels Everywhere` with the `Versatile` theme.

**UPDATE**

I tried `.panel-separator { display: none; }`. It improved the situation, but did not solve it:

I am including more requested information:

**UPDATE II**

I asked another question and the issue is now solved.

# Answer
Your question is a little thin on specifics (like what the existing css is for .panel-separator) but you could try simply to set your css to this:

```
.panel-separator { display: none; }

```

I'm guessing that although you set height and width to 0, .panel-separator still has one or the other (or both) of padding and margin that are non-zero, and/or there's a cascade where the height is being overridden.
> 1 votes

# Answer
All you need is to override the **panels\_default\_style\_render\_region** function.

1. Open your **template.php** file that can be found here: **/sites/all/themes/YOURTHEME/**
2. Create a new function in end of the file

```
function YOURTHEME_panels_default_style_render_region($vars) {
    $output = '';
    $output .= implode('', $vars['panes']);
    return $output;
}

```
> 6 votes

# Answer
In the file /sites/all/modules/panels/plugins/styles/default.inc remove in line 23.

```
$output .= implode('<div class="panel-separator"></div>', $vars['panes']);

```

to

```
$output .= implode('', $vars['panes']);

```
> 1 votes

# Answer
It would be helpful to see more of the html including the placement of the buttons and the separator area fully expanded. ALso show us the specific CSS that is controlling the display by copying the relevant CSS from Firebug include in your question. The specific CSS is determined using a scoring system and without seeing more it is difficult to make suggestions to raise the score. The first thin I would try is changing the open class identifier `.panel-separator` to the specific html reference `div.panel-separator`. and see if that helps. Of course it may be that the browser is forcing padding between regions. If that is the case, you can try some negative values for padding. Depending upon the location, that may help you solve this. Another thing to play with is editing the settings for the panel layout. If you select to edit the layout from the panel dashboard pick the canvas drop down and edit the settings there. At the bottom of the form are settings for minimum spaces between various areas of the panel. One of these may be affecting your display as well.
> 0 votes

# Answer
I was in the same situation once. Here's what solved my problem:

**You can also choose the "style" setting on the region and choose "No markup at all". This will remove the panel separator.**

For more info: https://www.drupal.org/node/579020#comment-8163459
> 0 votes

---
Tags: 7, theming, panels, social-network
---


title: Is there a way to remove node titles?

text:
# Question
Title: Is there a way to remove node titles?
When I make a node such as a basic page I have to give it a Title by default. However, the Title also appears on the page when I am viewing it, but I do not want every node I have to come with a title tacked unto it. For example, on some of my nodes, they are linked to the navigation bar, so it looks funny to see the same name twice when visiting the page.

Is there a way to remove the Title being represented on the page?

# Answer
Have a look at the Exclude Node Title module.

> This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers. It provides a checkbox on node-edit pages for easier exclusion, or you can use the admin page to manually enter a list of node id's to exclude title. Also provides the option to hide all titles of a certain Content type.
> 5 votes

---
Tags: 7, nodes
---


# Question
Title: Override module javascript file in theme or custom module
Is it possible to override a single javascript file from a module within a theme or custom module? My specific use would be for `Views/js/ajax_view.js` \- I've had to apply multiple patches to get ajax views to work properly with BEF and panels, and though I'm including documentation for future developers, it seems more foolproof to override within the theme or a custom module.

# Answer
`hook_js_alter()` allows you to modify any JS before it is written to the page.
The documentation includes a snippet to replace a core file with an alternate from a module:

```
function hook_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
}

```
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Is there a way to use File Field but have it’s directory path be different for different instances of content, instead of the same?
I’m selling mp3’s via Commerce File/File Field modules and i need these files to reside in different directories based on artist name and album name, etc. For example:

```
mp3s/some_artist/album_name/some_song.mp3.

```

so typically a catalog would have numerous dirs.

but by default a Drupal content type only allows a single directory to be specified.

so far the only way to achieve this is to have to continually make changes to the product variation content type. i have to keep changing the file directory setting

this is not a good solution and limits the amount of bulk uploading i can do at one time.

is there a way to get Drupal to just accept these file references as i input it? to accept any number of different file paths, in the context of bulk import?

(i hope i’ve asked this question clearly…

# Answer
> 4 votes
You can define your file paths with node tokens. File (Field) Paths module provides the functionality that you are looking for.

> The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.

---
Tags: files, commerce
---


title: Apache Solr server URI problem

text:
# Question
Title: Apache Solr server URI problem
I rebulding solr server after VPS crash, so I'm not completely newbie, but this time something went wrong and I can't manage the problem:

I configuring Apache Solr to use with Drupal. Acoording to may manuals Solr server URI should look like **xx.xx.xx.xx:8983/solr/corename**

but my Solr ULR looks like

**xx.xx.xx.xx:8983/solr/#/~cores/corename**

However, Drupal reports "The Solr server could be reached", but when indexing I get errors:

1. SearchApiException while deleting items from server New SOLR server: "400" Status: Bad Request HTTP Status 400 - HTTP method POST is not supported by this URL The request sent by the client was syntactically incorrect.
2. SearchApiException: Could not index items since important pending server tasks could not be perfor

med.

System info: Ubuntu 14, solr 4.7.2, tomcat 7

# Answer
The URL that the Drupal modules need is different than the one on which you browse the Solr server as an admin. Thus, for you, assuming 8983 is server port, it should be:

xx.xx.xx.xx:8983/solr/corename
> 3 votes

# Answer
The solution is to put "/solr/corename" in **Solr path** field ignoring "#/~cores/" part of URL on the Drupal Searh API server configuration page. Then you should press "Clear all indexed data" button on index page, then reindex.
> 1 votes

# Answer
For Solr 4.x the server's path should also contain the Solr core name.

E.g. when using default example application, set the path to `/solr/collection1` instead of `/solr`, then it should work.

Related: Upgrade - The Solr server could not be reached at d.o.
> 1 votes

---
Tags: search
---


# Question
Title: Theming site name in mayo over Flexslider slideshow header?
I asked this originally in the Mayo support on drupal.org but got directed here.

Continuing my development of my main work website has continued to use Mayo as I find it brilliant and simple.

This week I've managed to implement the Flexslider module using views slideshow and views to construct a new header.

The issue I have which i could do with some support with and that is theming the sitename and slogan to overlay on the left to match the title on the right. Ultimately I will link the title on the left to content of that service but first i need to get this sitename issue sorted.

No matter what i do, i cannot get the sitename to display in front of the flexslider?

I have managed to theme the title of the image within the view fine so i dont think its a flexslider issue but wondered if there is any thing i need to over ride with additional css within the mayo theme itself using css?

I currently have the sitename off until i sort this issue out but see the attached picture which shows the inspected code and where the div is currently via chrome inspect tool.

# Answer
Ok I've sorted it.

Use the Module: Views variable field

Add the field to the View for the slideslow / flexslider.

Add the site\_name variable to the field.

Rewrite as Link and type in

Rearrange the fields so that it is Site name then Slideshow then Caption

Save.

Rewrite the CSS to grab the site name div and place it where you want.

Remove some annoying div whitespace

Be happy!
> 0 votes

---
Tags: javascript
---


# Question
Title: hook_menu() with a query string parameter?
I have a module that loads at path `module/1/view` and then when user clicks a button they are redirected to another site and then redirected back to the same URL they left from with a querystring that looks like `module/1/view?code=123`

How do I implement a hook\_menu to catch this slight difference in url/querystring param? I essentially want the hook\_menu for `module/1/view` and `module/1/view?code=123` to be different.

# Answer
`hook_menu()` doesn't handle query parameters, so the behaviour will have to be within a single page callback.

```
function MYMODULE_generic_page_callback() {
  $query = drupal_get_query_parameters();
  if (empty($query['code'])) {
    return MYMODULE_without_code_page_callback();
  }
  return MYMODULE_with_code_page_callback();
}

```

---

If you need dynamic behaviour for some of the other `hook_menu()` options, many provide a callback option. For example "title callback" would also let you use a function to change the page title based on the presence of the query parameter in the same manner as the page callback.

For access control, it's probably better to return MENU\_ACCESS\_DENIED or MENU\_NOT\_FOUND from your page callback. "access callback" will be called when rendering links to the path to determine if the user has access and the link should be shown, so the query parameter will not be available on the page that contains the link.
> 3 votes

---
Tags: 7, routes
---


# Question
Title: Menu item with update text (title) in real time
I have a menu where one of the items (menu links) is a link to a view where I can see all comments that I have to moderate. Which I need is (if it is possible) to have the title of this link that change in realtime (or every time I load a page/node).

Think to my situation where I don't know how many comments I need to moderate so in this moment every X minutes I reload the page with all comments that I have to moderate. But this is frustating. So my necessity is to have a menu item like "Comments to moderate: FOO" where FOO is a number (from 0 to infinite) that I can calculate in realtime at every page load or every BAR minutes.

M.

# Answer
This is how I solved a similar problem:

You need implement the `hook_menu()` and use the '`title callback`'

```
function YOUR_MODULE_menu() {
    $items = array();

    $items['perfil-usuario'] = array(
        'title' => 'perfil',
        'description' => t('User Profile'),
        'title callback' => 'change_title_profile_link',
        'page callback' => 'go_to_profile',
        'access callback' => 'user_is_logged_in',
        'expanded' => TRUE,
        'weight' => 100,
        'menu_name' => 'main-menu',
        'options' => array('attributes' => array('class' => array('perfil-usuario'))),
        );

    return $items;
}

```

In this function you can change the link title

```
function change_title_profile_link() {
    return rand();
}

```

Here you can redirect to the desire url, if the url change you can implement this function

```
function go_to_profile() {
}

```
> 2 votes

---
Tags: 7
---


title: 8 - How to configure system link

text:
# Question
Title: 8 - How to configure system link
I'm new to drupal, I'm trying to change the link structure and still did not get.

For example, when I create a basic page, it uses a standard link "node/drux"

but I want the link to be the title of the page, without having to create an alternative URL.

How can I change this structure?

# Answer
> 1 votes
You're looking for Pathauto I think. It allows you to define patterns for how the aliases should be created automatically.

# Answer
> 0 votes
Drupal saves its own url, usually node/nid (nid is the id of the node), but you can create an alias in node edit -\> URL path settings.

---
Tags: 8, uri
---


# Question
Title: how to make a content type that ties to the user and user can only add one?
Drupal 8

So I want users to add a actor profile or crew profile or both. I am thinking both would be content types. The user should only be able to add one of each and it ties to the user.

Anyone know how I would do this?

# Answer
Instead of creating content types, I think you're better off using the profile module.

For Drupal 8 use the Profile Module

> The Profile module provides configurable user profiles.
>
> Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those. Optionally, profile forms are shown during user account registration. Fields may be configured to be private - thus visible only to the profile owner and administrators. Profile types are displayed on the user view page, and can be configured through “Manage Display” on account settings.

Formerly known as Profile2 in drupal 7. Here is a video tutorial. Perhaps it's similar in Drupal 8?
> 3 votes

---
Tags: users, 8
---


# Question
Title: Can I assign a taxonomy to a content type's term_reference field at runtime?
I need to manage a few different types of objects, let's say "car", "pickup", and "van". These are similar enough (for my purposes) that I can define a single content type and associated code for "vehicle" and use it for all of them, along with a field that specifies the exact type of the object. This allows me to do things like have one page that shows all the cars, one page that shows all the pickups, and so on. I have this code running; everything is fine.

I now want to add an OPTIONAL tag field to these items, using the taxonomy / term\_reference stuff in Drupal. The catch is that I want to have a separate tag taxonomy for each of my different kinds of vehicles, so that "car" tags don't show up in the truck's autocomplete suggestions. (Trust me -- in the context of my app, this makes sense.) The question is how to do it; the complicating factor is that the vocabulary for a tag field has to be defined when the field is added to the content type, and, remember, my content type is generic across all the types of vehicles.

So:

* Ugly possibility #1: Define a single tag field -- field\_vehicle\_tags? -- in the content type and write some magical code in a form\_alter or theme or after\_build hook or somesuch that, when building the edit form for the node, checks to see what kind of vehicle is being created (this is known upon entry to the form) and bashes the appropriate vocabulary into the field's autocomplete process. I don't know that this is actually possible, and I suspect the opportunities for screwing myself are endless.
* Ugly possibility #2: Define one tag field for each kind of vehicle -- field\_car\_tags, field\_pickup\_tags, etc -- each of which is connected to its own taxonomy. Then, use the theming hook to throw away (= not render as part of the form) all the tag fields except for the one that matches the kind of thing being edited. This is stupid and wasteful in all sorts of ways, but I'm pretty sure it would work.

Any thoughts or alternatives? I'm currently leaning towards #2, but if there's a better alternative, I'd love to hear about it.

# Answer
> 2 votes
You can create a Content Type named Vehicle and make inherits his fields to your Cars, Van with the help of the Bundle Inherit module. Then you can create a Taxonomy for each kind of Vehicle then you will have.

```
Vehicle (color, number_of_seats, etc)
 - Car (field_car_tags)
 - Van (field_van_tags)

```

With this you don't need to write lines of code and you can reuse the fields of the Vehicle Content Type.

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


# Question
Title: How do I theme (add extra markup to) menu links in Drupal 7?
I have a secondary menu that displays like:

```
<ul class="secondarynav">
<li class="menu-428 first">
<a href="/content/page">PAGE</a>
</li>
...

```

I would like to change that so it displays a `<span>` on the links like:

```
<ul class="secondarynav">
<li class="menu-428 first">
<a href="/content/page"><span>PAGE</span></a>
</li>
...

```

According to the Drupal 7 theme\_menu\_link documentation and this answer on theming Drupal 7 menu links, I should just be able to declare a hook like `THEMENAME_menu_link__MENUNAME($variables)`.

I've declared the following two functions in my `template.php`, but neither of them is being called:

```
function MYTEMPLATE_menu_link__system_secondary_menu(array $variables) {die;}
function MYTEMPLATE_menu_link__secondary_menu(array $variables) {die;}

```

I'm using Framework, and there's a section like:

```
if (isset($vars['secondary_menu'])) {
    $vars['secondary_menu'] = theme('links__system_secondary_menu', array(
        'links' => $vars['secondary_menu'],
        'attributes' => array(
        'class' => array('secondaryNavigation'),
    )
    ));
}

```

What's the cleanest / best practice-y way of printing an extra `<span>` in the menu links for this menu only?

I can write a function to theme the entire menu at once with `function MYTEMPLATE_links__system_secondary_menu(array $variables)`, but theming the entire menu just to get a `<span>` in each link seems like overkill.

# Answer
It calls `theme('links__system_secondary_menu')`. By default, there is no `theme_links__system_secondary_menu`, so I guess it is calling theme\_links. Looking at the function, all you have to do is copy it to your theme as `THEMENAME_links__system_secondary_menu`, then change the call to l() to something like:

```
$link['html'] = TRUE;
$output .= l('<span class="whatever">' . $link['title'] . '</span>', $link['href'], $link);

```

The `html => true` is required or `l()` will strip the html out of its first parameter.
> 3 votes

# Answer
For custom menus (created by you) the MENUNAME is the machine name of the menu (obtainable by visiting the menu edit page) with dashes converted to underscores. So for a menu called 'Secondary Menu' the machine name should be 'secondary-menu' (make sure to check) which converts to 'secondary\_menu'. So you should implement THEMENAME\_menu\_link\__secondary\_menu(array $variables).
> 1 votes

---
Tags: 7, theming, routes
---


# Question
Title: Is it possible to patch a non-dev version of a module?
I can create patches from dev copies of modules just fine thanks to this documentation, but when I try to create a patch from a non-dev version I get troubles. If possible, How do I do this?

# Answer
There would be a few differences from the process described on that documentation page.

1. In Step 1, when creating the topic branch, specify the commit from which to create the branch. You can do this by appending a commit ID, a tag name, or an existing branch name to your `git branch` command. Tag name should work, because Drupal project releases are tagged with the project version number. So if you wanted to patch off of the 7.x-1.5 version of a module, instead of this:

> git branch \[issue-number\]-\[short-description\]

You would do this:

> git branch \[issue-number\]-\[short-description\] 7.x-1.5
2. You would skip Step 4 and 5, since those steps are for making apply to the most recent dev version.
3. In Step 6, when using the `git diff` command to create your patch file, you now want to diff against the commit that represents the unmodified version. Again, we can use the tag/version name.

> git diff 7.x-1.5 \> \[project\_name\]-\[short-description\]-\[issue-number\]-\[comment-number\].patch
> 2 votes

---
Tags: 7, version-control
---


title: Access denied after installation

text:
# Question
Title: Access denied after installation
I just finished the installation, everything went fine but when I go to view my site I can not login. I cant get to /user

have a look: www.huf.co.nz

all worked fine on my local before I tried to make live

I have cleared all cookies and cache

# Answer
Checking your URL, I see that going to http://www.huf.co.nz/user gives a 404 (page not found) from your web server, but http://www.huf.co.nz/?q=/user render's Drupal's login page. This means that for some reason, "clean URLs" -- i.e., URLs that don't have the "?" in them -- aren't set up right.

It isn't clear what web server you're using from the 404 page. If you're using Apache, then just look at the README file in the base of the Drupal install, or go to https://www.drupal.org/documentation/install/beginners, since looking at your HTML you appear to be using Drupal 7.42. Apache is the easiest web server to set up, since Drupal ships with a .htaccess file that sets things up for clean URLs.

Drupal 7 also ships with a web.config file for using IIS, if you are serving Drupal from that web server.

If you're using something like nginx, you need to add a bit of configuration in order to get the web server to properly turn your URLs into the format that Drupal needs to see; nginx won't read a .htaccess file. If you are using nginx, Google "perusio drupal", or go to https://github.com/perusio/drupal-with-nginx.

If you're using anything other than those 3, you'll need to find someone who knows how to translate an Apache type configuration into that web server's configuration.
> 1 votes

---
Tags: users, installation
---


# Question
Title: Turning on aggregration causes a SQL error
I would like to create a view to display the number of nodes (later I'd like to also sum some numeric fields, but let's not run before we can walk).

In my view, I've turned on aggregation (under advanced settings), set the display type to fields, and added the title field with an aggregation type of "COUNT". However, in the view preview I'm getting the following error:

> SQLSTATE\[42000\]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no `GROUP BY` clause: `SELECT node_field_data.nid AS nid, COUNT(node_field_data.title) AS node_field_data_title FROM {node_field_data} node_field_data WHERE (( (node_field_data.status = :db_condition_placeholder_0) )) LIMIT 10 OFFSET 0; Array ( [:db_condition_placeholder_0] => 1 )`

What do I need to do to fix this error?

# Answer
> 2 votes
Aggregation can be sort of a pain in Drupal 8's Views implementation. Part of this is due to limitations in how MySQL handles GROUP BY.

As @Jonathan points out, for an aggregation function to work at all, you need to have *at least* one group by expression. And if you want a function like COUNT or MIN to work as you expect, you *only* want the one group to be listed in the GROUP BY.

To get this to work right just now, you need to:

* Under Advanced, you need to set Aggregation to "yes".
* Under Format \> Settings, you need to choose your Group by field.
* You may **not** sort by anything other than the field you chose under Format \> Settings, or your aggregation functions will give you bogus answers.

This is a bit limiting for some things you'll want to do, but as of 8.0.2, it's tricky to get better than this.

If anybody knows how to do better than this, I'd love to hear how :-)

# Answer
> 1 votes
Counts only make sense when you have a group to count. You need to add a field that you want to group by and set its aggregation setting to "Group similar results".

---
Tags: views, 8
---


title: Display results of a form

text:
# Question
Title: Display results of a form
I am trying to find a simple way to display the results of a simple checkbox form on the same page after submit. I know you can use the `drupal_set_message`, but I want to display the results formatted on the page, not in the message box.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message($this->t('Your favorite car is @fav_car', array('@fav_car' => $form_state->getValue('fav_car'))));
      }
    }

```

Full code for form here;

```
/**
 * @file
 * Contains \Drupal\cars\Form\FavoriteCarForm.
 */

namespace Drupal\cars\Form:

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\cars\CarsStorage;

/**
 * Class FavoriteCarForm.
 *
 * @package Drupal\cars\Form
 */
class FavoriteCarForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'favorite_car_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['fav_car'] = array(
      '#type' => 'radios',
      '#title' => $this->t('What is your favorite Car!'),
      '#options' => array('Toyota' => $this->t('toyota'), 'Ford' => $this->t('Ford'), 'Subaru' => $this->t('Subaru')),
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your favorite car is @fav_car', array('@fav_car' => $form_state->getValue('fav_car'))));
  }
}

```

# Answer
> 4 votes
This is not different from what is done in Drupal 7:

* When building the form, you verify in `$form_state` a value is present; if it is present you show its value
* In the submission form handler, you tell Drupal to rebuild it

What changes is the code you actually use, since Drupal 8 introduces new classes Drupal 7 doesn't have.

```
class FavoriteCarForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'favorite_car_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['fav_car'] = array(
      '#type' => 'radios',
      '#title' => $this->t('What is your favorite Car!'),
      '#options' => array('Toyota' => $this->t('toyota'), 'Ford' => $this->t('Ford'), 'Subaru' => $this->t('Subaru')),
    );

    if ($form_state->getValue('fav_car')) {
      // Show the value the user entered.
    }

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }
}

```

Calling `$form_state->setRebuild()` causes Drupal to call `buildForm()` again, passing in `$form_state` the values the user submitted and the values added from validation and submission handlers.

I didn't add the code to write the submitted value. You could:

* Show it as description of the form element
* Show it in a #markup element

I would rather not implement such code for just showing the selected value, though. I would use it to show the result of an elaboration done from the input given from users, for example showing a map of the town entered from users.

# Answer
> 1 votes
If you only need to display it on the same page as the form, then you can check the value in form state and put it in another render array, for example with the `ProcessedText` class that extends `RenderElement`.

```
if ($form_state->getValue('fav_car')) {
  $form['something'] = [
    '#type' => 'processed_text',
    '#text' => $form_state->getValue('fav_car'),
    '#format' => filter_default_format()
  ];
}

```

---
Tags: 8, forms
---


# Question
Title: How to manage form display non programmatically?
In Drupal 8, using `admin/structure/types/manage/article/form-display`, you can manage the form display for your content type. You don't have to rely anymore on contributed modules or on the implementation of the `hook_form_FORM_ID_alter()` or `hook_form_alter()` to hide an element in your form when you go to edit or add a node.

But in Drupal 7 we don't have this functionality, at least not yet. So, how to manage form display in Drupal 7 non programmatically?

# Answer
> 2 votes
The most close approach that I was found is the Display Suite module.

Display Suite allows you to manage the display of content editing forms for entities (such as nodes, views, comments, users, et cetera). This can be useful if you want to provide the users of your website with a customized edit form (*and you don't need to implement the hook\_form\_alter()*).

When enabled Display Suite Forms takes over the Drupal core functionality that let you arrange the fields via the "Manage fields” tab.

**Manage display of an editing form**

1. Enable the sub module Display Suite Forms at Administration \> Modules (admin/modules)
2. Go to Administration \> Structure \> Display Suite (admin/structure/ds)
3. Click "Manage form" for the entity (e.g., "User") that you like to change
4. At the bottom of the page, in the vertical tab "Layout for ... in form" choose "One column" and click "Apply"
5. Chose the Hidden option in the field.
6. Save the changes

Another way is the use of the Rules Forms module, but you need make a rule for this after enable the module.

1. Go to the "Form events" page in the Rules administration menu (admin/config/workflow/rules/forms).
2. Select the checkbox "Enable event activation messages on forms" and hit the "Save settings" button.
3. Go to the form on your site that you would like to customize with Rules, e.g. go to 'node/add/article' to enable events on the "Create Article" form.
4. On the top of the page you see a drupal message with a link to activate events for the form, click it.
5. Enter a human-readable label for identifying the form.
6. In some cases you may want to enable events for individual buttons on the form. To do so, check the checkbox labeled "Enable button level validate/submit events".
7. Confirm the activation by clicking the "Activate" button.
8. Go to the "Triggered rules" admin page (admin/config/workflow/rules) and click the "Add a new rule" link.
9. Fill out the label, choose a form event by selecting one in the "Rules Forms" group and confirm with "Save changes".
10. Now you can select "Hide an element in the form" and select the element to hidde.

Reference:

---
Tags: 7, forms
---


title: Missing sub-menu

text:
# Question
Title: Missing sub-menu
I have configured my main menu to have several sub-menu entries but unfortunately they don't show up. The menu is rendered using a custom template (menu--main.html.twig) but I don't think that this is the problem because when I print the menu using kint item.below is an empty array.

Unfortunately I have no idea how to find out what the problem could be. Do you have any suggestions?

# Answer
In the block settings there are settings for menu levels, check those first, also you may need to expand items in the actual menu configuration, e.g./admin/structure/menu/manage/main edit each item and set to expanded.
> 2 votes

# Answer
Like Jeff stated, make sure your parent menu item is configured to "Show as expanded"
> 2 votes

---
Tags: theming, routes, 8
---


title: How to start view chart on last page

text:
# Question
Title: How to start view chart on last page
I am using the Charts module and Google Charts API with Views. I want my view to display with the last page of the view showing on page load. How can this be accomplished? For more explanation of what I'm trying to do: I have a view displaying a line chart with historical data, but I want the view to load with the most recent data first and the pager to allow the user to go back (using previous button) to view data in the past.

Thanks in advance.

# Answer
> 0 votes
Not familiar with charts, but in views SORT you could try using the opposite.

Ex: Sort Descending instead of Ascending. (so it reverses the order).

Then all you would have to do is override the pager so it says previous instead of next. I found some documentation here.

---
Tags: views, charts
---


# Question
Title: How do I implement Entity Reference Behaviour Plugins?
1. Do Entity Reference behaviour plugins exist for Drupal 8? Please see: https://www.drupal.org/node/1803064#comment-10717088
2. Are there any existing examples; documentation or code?

I would like to upgrade *entityreference\_prepopulate* but I am unsure about these behaviour plugins.

# Answer
> 1 votes
Answer on IRC via ***berdir***: "no, that doesn't exist". So it simply does not exist yet in D8.

Supplementary info provided for field settings in D8 =\>

***berdir***:

> note that fields, like all config entities have a concept of third party settings. you can use that to store per-field settings. didn't check the other parts
>
> see https://www.drupal.org/project/allowed\_formats for a projects that uses third party settings on fields

---
Tags: entities, 8, plugins
---


# Question
Title: What are the nfs values seen in the Strongarm seciton of features
When preparing a feature I see that there are a number of values beginning nfs\_ in the Strongarm section.

What are these nfs\_ values and do I need them in my feature?

# Answer
Gonna go out on a limb and guess that they come from the Node and Comments Form Module, which uses `nfs` as a prefix for variables.

Failing that, have a look through your contributed modules and see what you have that can be shortened to NFS - that's probably the culprit.
> 1 votes

---
Tags: features, strongarm
---


# Question
Title: Why can't I programatically create a location field in a node?
I'm trying to programmatically create a node with a location field, but I'm not able to do it. I have done it in a similar project and it works fine. I use the Entity API module to create the nodes, with this code.

```
 $localizationmap = array(
   'latitude' => $item['field_mapa']['latitude'],
   'longitude' => $item['field_mapa']['longitude'],
   //other elements added here (province, postal_code, country [es, en,...],additional, ...)
 );
 $entity->field_mapa->set($localizationmap);

```

I checked the values that are given to the array and they're OK. Drupal log contains the following error:

> EntityMetadataWrapperException: Unknown data property field\_mapa. en EntityStructureWrapper-\>getPropertyInfo() (línea 335 de /var/www/vhosts/drupal/litoral.interdigital.biz/sites/all/modules/entity/includes/entity.wrapper.inc).

`field_mapa` exists and it is the name of the location field I'm trying to fill.

What am I doing wrong?

# Answer
It's simply because the stable version of the Location module doesn't support Entity API.

There's a patch here that claims to provide the missing support, obviously use with caution on a dev version of the site first.
> 2 votes

---
Tags: nodes, entities, location
---


title: How to create a subsite

text:
# Question
Title: How to create a subsite
I have a drupal website where on the existing one we need to create a subsite. More specifically, we need to access the subsite through the existing one. Both sites (main and subsite) as far as i can understand will use the same database but whatever changes regarding the configuration of the subsite, such as Themes, Blocks etc, will not affect the main site. In other words, we need two sites (a main and a subsite) that will share the same database, but each one will have its own configuration. Is it possible with Drupal and how?

Thanks in advance

# Answer
> 0 votes
Here's a guide on how to create a sub site within drupal. You can do it so the main site's theme/modules are used on the subsite or you can overwrite them.

https://www.drupal.org/documentation/install/multi-site

You can share the 1 database but have separate tables (this means spearate user,content and config) by adding a prefix when you first setup drupal under the advanced settings when entering the database name, username and password.

E.g. you could prefix the main site with "main\_" so "main\_node" and prefix the subsite tables with "sub\_" and that would have tables like "sub\_node"

Or alternatively you don't use the drupal multisite functionality mentioned above and you just put a whole new drupal install within the root of the main site.

e.g. /html/subsite

---
Tags: subsites
---


# Question
Title: How to resolve the SSL error with local copy of site on Dev Desktop?
I am running a local copy of my site on Acquia Dev Desktop and everything is working fine.

The site is set to enforce SSL connection when logging in to the sitename.com/admin page. However, since it is now installed on my localhost, it does not have an SSL certificate and throws the error like so:

```
SSL connection error
Unable to make a secure connection to the server. This may be a problem with the server,
or it may be requiring a client authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR

```

What can I do in order to get around this, and log in to my page administratively?

# Answer
> 2 votes
DevDestop now supports this. https://docs.acquia.com/dev-desktop2/sites

Acquia Dev Desktop now provides simulated HTTPS support using a self-signed SSL certificate, which supports local testing and development of websites that rely on SSL. Learn more.

Just download a new version of DevDesktop. I'm currently on Version 2, Control panel rev: 032976b and have it working with sites that use SSL.

# Answer
> 2 votes
On the Config settings from Acquia Dev Desktop \>\> Preference \>\> Config:

Now Select Apache Module (mod\_php) and hit OK Button. That's All the SSL Connection Error has Fixed.

# Answer
> 1 votes
DevDesktop doesn't have mod\_ssl included in its version of Apache.

The only way to go about it is to disable the site configuration that enforces SSL. If it's .htacess, you can edit the root .htaccess file to remove the HTTPS redirect rules. If it's a module like securepages, you can disable it directly in the system database ("UPDATE system SET `status` = 0 WHERE `name` = 'securepages' AND `type` = 'module' ), or better, use Drush to disable it from the console (e.g. "drush dis securepages").

---
Tags: ssl, acquia-dev-desktop
---


title: Uploading and deleting unused images

text:
# Question
Title: Uploading and deleting unused images
I have a custom form with manage file input where users can upload their profile images. Upload looks like this:

```
 $acc = user_load($state['user_id'], TRUE);

 // upload profile image
 if ($state['values']['image'] != '0') {

   //check if this file is already in use, if not, save new file
   $res = db_select('users', 'u')
       ->condition('uid', $state['user_id'], '=')
       ->fields('u', array('picture'))
       ->execute()
       ->fetchAssoc();

   if ($res['picture'] != $state['values']['image']) {

     $img = file_load($state['values']['image']);

     file_usage_add($img, 'user', 'user', $state['user_id']);

     $img->status = FILE_STATUS_PERMANENT;
     $acc->picture = $img;
     file_save($img);

   }

 } else {
   $acc->picture = NULL;
 }

 user_save($acc);

```

This approach is piling up unused files if user's change their images multiple times. It is because of `file_usage_add` function that is logging files in database, therefore drupal won't delete files that are logged in `file_managed` database.

I think I could manually change old file status in database before new log is inserted by `file_usage_add` and let Drupal automatically remove this unused file. **Is this statement right?**

Even if it is true, I have strong feeling this is not optimal Drupal way of managing files. Is there a better way?

# Answer
> 1 votes
You can achieve your requirement by using Audit Files module.

> Audit files is designed to perform audits of your upload directory and the corresponding database records. It will cross check that all files in the database have a corresponding physical file, or it will check that all files in the upload directory have a corresponding entry in the database.

---
Tags: users, files
---


# Question
Title: What to do with hidden files in Drupal 8 minor core upgrade?
Step 3 of https://api.drupal.org/api/drupal/core!UPGRADE.txt/8 says

> Also remove all of the files in the top-level directory, except any that you added manually.

it doesn't exclude or include hidden files explicitly, so my logic would say 'all' includes hidden files.

later it says

```
cp -R drupal-x.y.z/* drupal-x.y.z/.htaccess /path/to/your/installation

```

which does not copy any hidden files except `.htaccess`.

This would suggest *not* to delete the old hidden top level files. On the other hand the new version/patch of Drupal 8.y.z comes with (new?) hidden files.

So my question is: what is the correct way to handle top level hidden files other than `.htaccess` while upgrading Drupal 8?

# Answer
> 1 votes
TL:DR;
You should delete all files hidden and not hidden that you didn't place there yourself.

Drupal core has a lot of hidden files, which are used when developing Drupal itself (git, lint and possibly more) but none of those are needed or relevant for running a Drupal site in production. They are highly relevant when you are working on Drupal itself.

The only hidden file you need for a production site is the .htaccess, if you have more than that they are safe to delete.

---
Tags: 8, updating
---


# Question
Title: How to import/add translated strings having inline styles?
I've imported a .po file having Spanish translations. The import was successful but some translation strings were skipped because they contain disallowed HTML.

From UI, I found that some translations were not translated. So I tried them adding those via the translate admin interface (Administration » Configuration » Regional and language » Translate interface)

I could see the original text having inline style like following.

But when I tried to add a Spanish (Latin American) Translation and hit 'Save translations' getting the following error.

> The submitted string contains disallowed HTML:`<span style="color:#0098CF">Hola</span>`

I've enabled Translatable all *HTML text formats* under multilingual settings (Administration » Configuration » Regional and language » Multilingual settings)

It's working when I remove inline style add translation like the following. So I guess it's not supporting inline styles and classes.

```
<span> Hola </span>

```

What could be the problem? I found a function in `function locale_string_is_safe($string)` under includes/locale.inc file. Do I need to do any tweaks with that?

Any suggestions would be much appreciated.

# Answer
> 1 votes
Yes your guess is correct,`locale_string_is_safe` "Check that a string is safe to be added or imported as a translation." if you want to ignore your job you should patch it for a while , change it to

```
function locale_string_is_safe($string) {
  return TRUE:
}

```

after your job revert it.

# Answer
> 2 votes
Here's an alternative without hacking the core. You simply could unset the validation for the translation interface form:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  // That's the form ID of the translation interface.
  if ($form_id == 'i18n_string_locale_translate_edit_form') {

    // Let's check at least for a user's role first.
    global $user;
    if (in_array('administrator', $user->roles)) {

      // Simply unset the validation. Done.
      unset($form['#validate']);
    }
  }
}

```

---
Tags: 7, i18n-l10n
---


# Question
Title: How often i should re-build and re-submit xml sitemap for news website?
I have an website that get news from RSS Feeds. I build every day 2-3k articles and now i have almost 160k links.

So, how often i should re-submit the xml sitemap; (currently i do this job every hour)

# Answer
Depending on your server configuration you can setup your site to run cron more often.

You can also use Rules module, To write a rule for resubmitting site map which can be trigger after certain time or on new content published.

It is also important to mention that search engines takes time to index - no matter whether through external links, internal links or sitemaps.

So don't think submitting site map more often will help.
> 1 votes

---
Tags: cron, xml-sitemap
---


title: How to translate dates?

text:
# Question
Title: How to translate dates?
I have a calendar view in my Drupal 7 website, that looks like this:

And I also have a date field in a Webform:

All of these appear in english, of course. But, I want to translate all dates to portuguese.

How can I do that easily?

Thanks a lot.

# Answer
Most of Drupal contributed modules have their translation under Drupal Translations

If you visit the site and search for Date, you will notice list of countries and languages.

I notice Portuguese translations for Date module.

1. Portuguese, Brazil
2. Portuguese, International
3. Portuguese, Portugal

Download the correct language translation file by selecting the version of Date module your using.

Go to http://\[your\_site\]/admin/config/regional/translate/import . To import the downloaded file.

For more information about Translation and how to build multi language site please refer to my answer in https://drupal.stackexchange.com/a/184623/24038
> 1 votes

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


title: How do I integrate postal code search?

text:
# Question
Title: How do I integrate postal code search?
How to integrate number search along with string search in drupal 7? As of now,I was able to implement string search i.e a user can search via name,place etc but I want to implement number search so that users can search via postal code, date of birth, etc.

# Answer
You can use Postal code module to integrate postal code in your site.

Please note at the moment the module only support:

USA, Canada, UK, Germany, France, Italy, Australia, Netherlands, Spain,Denmark, Sweden, Belgium, India, Poland
> 1 votes

---
Tags: 7, search
---


# Question
Title: What's the difference between Drupal 8.0.x and 8.1.x?
On the drupal core download page I see two development branches, 8.0.x and 8.1.x.

I'm sure in the old days it just went linearly 8.0 then next would be 8.1 etc. but this suggests development is now parallel as if 8.0 and 8.1 are really different.

I'm interested to learn why this is this way. Why, for instance, as a developer would I work off 8.0.x and not 8.1.x?

# Answer
> 2 votes
The answer is semantic versioning. The "1" in 8.1.x, represents a branch that can contain new features as well as bug fixes. Backwards-compatibility to code written for 8.0.x is inherent in the numbering system. So, if your code requires features in 8.1.x, you should develop against it, but note you won't be able to deploy your code until 8.1.0 releases.

# Answer
> 2 votes
See http://semver.org/

X.Y.Z

* "Patch version Z (x.y.Z | x \> 0) MUST be incremented if **only backwards compatible** bug fixes are introduced."
* "Minor version Y (x.Y.z | x \> 0) MUST be incremented if **new, backwards compatible** functionality is introduced to the public API."
* "Major version X (X.y.z | X \> 0) MUST be incremented if any **backwards incompatible** changes are introduced to the public API."

---
Tags: 8
---


# Question
Title: Fresh install of COD: Anonymous users get "Access denied" on homepage
## Problem

I created a clean VM & installed COD. Unfortunately, when people aren't logged in they see:

How should I go about diagnosing further and/or resolving this issue?

## Things tried

* I thought this might be because the first conference wasn't published but the published flag was set, and I ticked the 'Promoted to front page' option.
* That did not resolve the issue, so I created a basic page and applied the same options. No change to the homepage.
* The homepage was set to `node/1` so I changed it to no extension so that it could use the default homepage. No change.
* UPDATE: Ticked *Grant content access* and *Grant own content access* for anonymous users in admin/people/permissions
* UPDATE: Tried to use the rebuild option (/admin/reports/status/rebuild) to no avail

# Answer
The permission required is `View published content`.

It turns out the content access module has **a lot** of different permissions that can be assigned to roles and this one is not selected by default for anonymous users.

This is a really easy permission to miss. It sits deep within `nodes` permissions and if you use the search facility for words like view or access you won't get it in the search result. Heck, if you search `View published content` it isn't returned.
> 0 votes

---
Tags: users
---


# Question
Title: Drupal for Bloggers: How can I achive getting such a little FB, Twitter, etc. Box on the left of my homepage?
How can I achive getting such a little, sticky FB, Twitter, etc. Box on the left of my homepage, like one can find on this site: http://www.marieforleo.com/2010/04/real-online-paid/

Any ideas - or is there a module for that? Sorry I don't know what this little box is called ...

Many thanks! Soezkan

# Answer
> 1 votes
You want to try something like the ShareBar in Drupal 7.

> The Drupal Sharebar module lets you easily add a "floating" social media submission bar on your website (like that found on Mashable) that includes share buttons for the most popular social media websites online such as Facebook, Twitter, and Google +1 Buttons.

---
Tags: social-network
---


title: Hide the title of a form element?

text:
# Question
Title: Hide the title of a form element?
I'd like to use placeholders instead of labels for a form built with the form API.

I can get placeholders working well with the Elements module, but now I want to hide the labels. If I just set `['#title'] = NULL;` then form errors don't have descriptive names, and it ruins accessibility.

In Drupal 7, you could set the `#title_display` to `invisible` (documentation). Was something like this backported in a contrib module somewhere?

Or is there a way I can set my own class on the `label` element?

# Answer
> 1 votes
Drupal 6 is a lot more limited than 7 or 8 in this regard, and I'm not aware of any effort to backport this functionality.

However, Drupal 7 and 8 use the .visually-hidden CSS class to hide the label, and it's not very hard to make Drupal 6 do the same.

It's possible to add classes to a form element label with a theme function, but I've found this hard work. A much easier approach is the use the #prefix and #suffix attributes to wrap the element in a div tag. For example:

```
$form['test'] => array(
  '#type' => 'textfield',
  '#title' => 'Test'
  '#prefix' => '<div class="hide-label">',
  '#suffix' => '</div>'
);

```

Then you just need to add the following CSS:

```
.hide-label label {
  position: absolute !important;
  clip: rect(1px,1px,1px,1px);
  overflow: hidden;
  height: 1px;
  width: 1px;
  word-wrap: normal;
}

```

The contents of this class are copied from Drupal 8's .visually-hidden.

Hope this solves your problem.

James

# Answer
> 0 votes
You could override the theme\_form\_element() function in your theme's template.php so that the label does not output:

```

// Remove  from output

function THEMENAME_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

$output = '\n";
  $required = !empty($element['#required']) ? '*' : '';

if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required));
    }
    else {
      $output .= '$t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required));
    }
  }

$output .= " $value\n";

if (!empty($element['#description'])) {
    $output .= ' ' . $element['#description'] . "\n";
  }

$output .= "\n";

return $output;
}

```

Alternatively, you could target the form id \> label and set it to display:none without modifying the theme function.

---
Tags: forms, 6
---


# Question
Title: Commerce Paypal WPP Sandbox: cURL error: SSL connect error
EDIT: Appears it is related to this issue: https://www.drupal.org/node/2616730#comment-10782646 . Still awaiting a fix though, as the patch in the issue doesn't fix it for me.

Our staging site was successfully using the Paypal sandbox with WPP for taking payments. As of three days ago, with seemingly no changes it is no longer working. The front end returns the error: "We encountered an error processing your payment. Please verify your credit card details or try a different card." Under reports all it says is cURL error: SSL connect error. Any idea how to fix this?

EDIT: I've tried to add CA certificate as per these instructions:

```
  // Commerce PayPal requires SSL peer verification, which may prevent out of
  // date servers from successfully processing API requests. If you get an error
  // related to peer verification, you may need to download the CA certificate
  // bundle file from http://curl.haxx.se/docs/caextract.html, place it in a
  // safe location on your web server, and update your settings.php to set the
  // commerce_paypal_cacert variable to contain the absolute path of the file.
  // Alternately, you may be able to update your php.ini to point to the file
  // with the curl.cainfo setting.

```

But now I get the error cURL error: Problem with the SSL CA cert (path? access rights?). I've tried restarting Apache with no effect. Please help!

More info on the request below:

```
Message PayPal API request to https://api-3t.sandbox.paypal.com/nvp:

Array
(
    [METHOD] => DoDirectPayment
    [PAYMENTACTION] => Sale
    [NOTIFYURL] => http://website.com/commerce_paypal/ipn/paypal_wpp%7Ccommerce_payment_paypal_wpp
    [BUTTONSOURCE] => CommerceGuys_Cart_PPP
    [CREDITCARDTYPE] => Visa
    [ACCT] => XXXXXXXXXXXX0331
    [EXPDATE] => 032016
    [AMT] => 126.00
    [CURRENCYCODE] => USD
    [CVV2] => XXX
    [INVNUM] => 5355-1453684794
    [CUSTOM] => Order 5355
    [DESC] => 1x product
    [EMAIL] => test@test.com
    [IPADDRESS] => [IPADDRESS]
    [FIRSTNAME] => test
    [LASTNAME] => test
    [STREET] => test
    [STREET2] => test
    [CITY] => test
    [STATE] =>
    [COUNTRYCODE] => HK
    [ZIP] =>  -
    [USER] => pro_api1.website.hk
    [PWD] => XXXXXXXXXXXXXXXX
    [SIGNATURE] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    [VERSION] => 76.0
)

```

# Answer
> 1 votes
Ran this past some Paypal support personnel. They echoed both the author of the question and Nick in the comments.

Paypal reviewed the error and offered a link to this resource, which I will quote in part:

> PayPal is upgrading the protocols used to secure all external connections made to our systems. Transport Layer Security version 1.2 (TLS 1.2) and Hypertext Transfer Protocol version 1.1 (HTTP/1.1) will become mandatory for communication with PayPal in 2016. You will need to verify that your environment supports TLS 1.2 and HTTP/1.1, and if necessary make appropriate updates.
>
> PayPal is in the process of upgrading the SSL certificates used to secure our web sites and API endpoints. These new certificates will be signed using the SHA-256 algorithm and VeriSign's 2048-bit G5 Root Certificate. You will need to ensure that your environment supports the use of the SHA-256 signing algorithm and discontinue the use of SSL connections that rely on the VeriSign G2 Root Certificate.
>
> If you are using PayPal’s Instant Payment Notification (IPN) service, you will need to ensure that HTTPS is used when posting the message back to PayPal for verification. HTTP postbacks will no longer be supported.

Related Drupal.org Issue: https://www.drupal.org/node/2616730#comment-10782646

So, it seems, Paypal is upgrading lots of their security requirements for 2016. I highly recommend you investigate deeper with Paypal's support service to see if they can make a recommendation on next steps for you.

---
Tags: commerce, payment-gateways
---


# Question
Title: How can I store the user agent string and referrer for Webform 4.x submissions?
In Webform 3.x, I have a "Give me feedback" webform that I embed in various places throughout my site using Panels. This form contains two *hidden* fields:

Referer / Default value: `%server[HTTP_REFERER]`

User agent / Default value: `%server[HTTP_USER_AGENT]`

This is extremely helpful because I can get the details of users' machines without having to ask them as well as get the page the user came from (because the webform is embedded on a number of pages throughout my site with Panels). However, `%server\[\]` tokens apparently no longer work in Webform 4.x:

> Most tokens will be upgraded for you, however some tokens do not have equivalents and no longer work. These include %post, %request, %cookie, and %session. The %get token (which maps to PHP's $\_GET variable) has the equivalent token \[current-page:query:key\].

Is there an alternate way to somehow include the user agent string and referer in a 4.x webform?

# Answer
This issue is Closed (won't fix) on Drupal.org

If you want them back, you basically need to create a module that implements hook\_tokens() and hook\_token\_info(), as described in the API. I don't think anyone did it already.

Here is how I'd do it:

```
function yourmodule_token_info() {
  $type = array(
    'name' => t('Server'),
    'description' => t('Tokens related to $_SERVER superglobal.'),
  );
  $tokens = array();
  foreach($_SERVER as $key => $val) { //discard $val now
    $tokens[$key] = array(
      'name' => $key,
      'description' => "\$_SERVER['$key']",
    );
  }
  return array(
    'types' => array('server' => $type),
    'tokens' => array('server' => $tokens),
  );
}

function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'server') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
        $replacements[$original] = (string)$_SERVER[$name];
    }
    return $replacements;
  }
}

```

Of course code above is **not production ready**, it ignores proper type handling, security issues and so on. It's meant to set you on the right track, but you need to apply your own sanity before deploying it. I take no responsibility for abuse. Read about the reasons it was removed in the first place before you decide to add it back, and be careful to restore only what you really need.
> 4 votes

# Answer
For people ending up here via a search engine (like me). If you don't want to open up these globals as tokens and you only want to use this info from these globals as a default value for a webform component, you can also use this code:

```
/**
 * Allow modules to modify a webform component that is going to be rendered in a form.
 *
 * @param array $element
 *   The display element as returned by _webform_render_component().
 * @param array $component
 *   A Webform component array.
 *
 * @see _webform_render_component()
 */
function hook_webform_component_render_alter(&$element, &$component) {
  if ($component['cid'] == 10) {
    if (!empty($_SERVER['HTTP_REFERER'])) {
      $queryString = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY);
      parse_str($queryString, $queryParams);
      if (!empty($queryParams['persons']) && is_numeric($queryParams['persons'])) {
        $element['#default_value'] = (int) $queryParams['persons'];
      }
    }
  }
}

```

In my case I wanted to use values as were entered by the visitor in a Views exposed filter. It is an availability search and the visitor can select one of the results to make a booking. The dates were already passed to the webform by the availability calendar module (booking formlet sub module), but the number of persons I had to extract from the query string from the referrer URL which can be done in a secure way with this code.

You can find the cid value in the URL when you are editing the component you want to give a default value.
> 1 votes

---
Tags: webforms
---


# Question
Title: Twig dump not working (PHP Warning: Leaked 2 hashtable iterators )
I'm trying to create a custom markup for a views-block. What I want to do is similar to what someone is trying to do here (How to create a custom markup for a views-block?).

My view-block has 3 items and I want to create a template where I can individually place them using HTML code. At the moment it just gets rendered from `{{ content }}` in my `block--views-block--latest-block-1.html.twig`. I guess I'd need to check how the three elements are stored in the content so that I can individually place them in my HTML markup.

The Twig dump function however doesn't seem to work. I get the following error message when loading my webpage:

```
PHP message: PHP Warning: Leaked 2 hashtable iterators in Unknown on line 0

```

What's going on?

# Answer
Probably because there are some recursive data structures in there. Try installing kint from the devel project, I'm not sure right now if it replaces dump() or if it provides an alternative kint() but one of those should give you much better output.
> 3 votes

# Answer
It might be easier to add the html in another twig. Look for `#type` and `#template` keys in content. Each array with this keys inside will invoke other templates, which will then after they are processed invoke at least a another level of templates. You can see this, if you enable twig debugging and look in the html source in your browser:

Locating Template Files with Debugging
> 0 votes

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


# Question
Title: Form API: Autocomplete Field in Chrome and Safari
I'm working on a custom webform component to essentially look up entity properties in an autocomplete field.

All works perfectly in Firefox, but I'm just seeing an plain old textfield in Chrome and Safari. Nothing is printed to the console, and nothing is printed to watchdog.

This is what the field looks like on Chrome/Safari:

This is what is looks like in Firefox:

I'm wondering if this has something to do with my code, so I've extracted the relevant snippets below:

**Form Definition:**

```
  $ac_field_id = drupal_html_id('field_autocomplete');
  $element['field_autocomplete'] = array(
    '#type' => 'textfield',
    '#title' => $component['name'],
    '#description' => t($component['extra']['description']),
    '#default_value' => $value['field_autocomplete'],
    '#required' => $component['required'],
    '#autocomplete_path' => 'entity-auto-comp/' . $field_entity_type .
                                '/' . $field_entity_prop . '/' . $field_number_of_items_to_return .
                                '/' . $search_type . '/autocomplete',
    '#attributes' => array(
      'data-entity-auto-id' => $ac_field_id,
    ),
  );

```

**How Autocomplete Path is being Handled:**

```
 /**
  * Implements hook_menu() - this provides a URL route for our
  * entity data source
  */
 function entity_auto_comp_menu() {
    $items['entity-auto-comp/%/%/%/%/autocomplete'] = array(
      'page callback' => 'entity_auto_comp_autocomplete',
      'page arguments' => array(1, 2, 3, 4),
      'access arguments' => array('view published content'),
      'type' => MENU_CALLBACK,
    );
    return $items;
}

/**
 * Implements hook_autocomplete() - which allows us to return data
 * to the form field as JSON.
 */
function entity_auto_comp_autocomplete($entity_type, $entity_prop, $max_results = 5, $search_type = 'STARTS_WITH', $string = '') {

  //Get all relevant entity IDs
  $efq = new EntityFieldQuery();
  $efq->entityCondition('entity_type', $entity_type, '=');
  $efq->propertyCondition($entity_prop, $string, $search_type);
  $efq->range(0, $max_results);
  $efq_result = $efq->execute();
  $efq_keys = array_keys($efq_result[$entity_type]);

  //Load entities from database
  $entities = entity_load($entity_type, $efq_keys, false);

  $prop_values = array();
  foreach($entities as $entity){
    $prop_values[$entity->$entity_prop] = $entity->$entity_prop;
  }

  //If we couldn't find anything, say so
  if(count($prop_values) == 0){
    $prop_values[""] = "No results were found...";
  }

  drupal_json_output($prop_values);

}

```

**Some JS I'm using to detect changes and populate a hidden form field:**

```
(function ($) {
    Drupal.behaviors.ol_webform_manage_map_default = {
        attach:function (context, settings) {

          //Get the autocomplete field as a jQuery object
          var $autocomplete_field = jQuery('input[data-entity-auto-id="'+Drupal.settings['ac_field_id']+'"]', context);
          var $autocomplete_value = jQuery('#'+Drupal.settings['ac_field_id'], context);

          //Event listener for option selection
          $autocomplete_field.bind('autocompleteSelect', function(event) {
            $autocomplete_value.val(jQuery(this).val());
          });

        }
    };
})(jQuery);

```

I'm stumped. So I would appreciate any help you can provide!

Thanks,

Strainy

## Update

Scratch that. Nothing to do with browsers. It's got something to do with how I'm handling permissions at either the form field level or the autocomplete path. Realised that I can only use autocomplete if I'm logged in!

# Answer
> 0 votes
The problem was with my menu hook. I was using 'view published content' as an access argument, where the argument should have actually been 'access content'.

```
 /**
  * Implements hook_menu() - this provides a URL route for our
  * entity data source
  */
 function entity_auto_comp_menu() {
    $items['entity-auto-comp/%/%/%/%/autocomplete'] = array(
      'page callback' => 'entity_auto_comp_autocomplete',
      'page arguments' => array(1, 2, 3, 4),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK,
    );
    return $items;
}

```

This, and more about access arguments, can be found in the Drupal documentation: https://www.drupal.org/node/553368

# Answer
> 0 votes
If it works on Firefox, I suspect that the issue is with the javascript. Here, the question you should be asking is: do you really need to write your own.

In Drupal 7, there's a default implementation of the javascript you need for this in `misc/autocomplete.js`. In fact, by defining your callback via `'#autocomplete_path'`, you are likely asking for trouble: both your javascript handler from your .js file and the javascript from `misc/autocomplete.js` may well be completing with each other to handle the textfield. I would not be in the least surprised if the behavior you saw was browser dependent.

Unless there's a specific reason you need the javascript you've written, I'd just use the default javascript, which will get automatically loaded for you when you use the `'#autocomplete_path'` Form API key. AFAICT, your callback and your `hook_menu` definitions are just fine.

However, you can find a nice sample in the Examples Module (https://www.drupal.org/project/examples). Where your implementation differs, the simpler implementation in the Examples code may well be more cross-browser compatible.

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


title: Automatically clear cache

text:
# Question
Title: Automatically clear cache
Theme: Basic 8.x-1.x-dev

I am trying to clear theme data after any change is done to twig files. I see that rebuildThemeData is here: https://goo.gl/EA2YL4

Currently have this within my .theme file.

```
\Drupal::service('theme_handler')->rebuildThemeData();

\Drupal::service('theme.registry')->reset();

```

Does anyone have this sort of implementation complete and working for an example? https://www.drupal.org/node/2608470

# Answer
> 4 votes
There are some defaults that ship with D8 in your `sites/default` configuration files that you can configure during development.

The application portion:

```
Open development.services.yml in the sites folder
and add the following block (to disable twig cache)
        parameters:
          twig.config:
            debug : true
            auto_reload: true
            cache: false

```

There is more information on this Drupal.org node.

---
Tags: 8, caching
---


# Question
Title: Views Search Terms not working correctly for taxonomy terms with multiple words
I'm having a bit of an odd issue. I have a Search Terms filter set up on a view and it's not working quite correctly for taxonomy terms in the view. For example, if one of the Terms is 'International Harvester' and it returns the correct results if I enter *International* or *Harvester* or *"International Harvester"*, but if I put in *International Harvester* without quotes then no results are returned. Any ideas?

using Drupal 7.41, Views 7.x-3.7

# Answer
> 0 votes
This turned out to be a bug with the search score feature discussed here https://www.drupal.org/node/1615438.

This comment details that checking the "Remove search score" checkbox under the **Search: Search Terms** filter fixes that problem.

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


# Question
Title: 7 - How can I add a region inside another region?
I'm surprised I can't find the answer to this online.

I'm currently creating a custom header for my drupal site, so I've created a custom\_header region in the .info and a region--custom-header.tpl.php file. Inside the region, I need to add another region.

I've tried to print the other region inside the header region, but nothing is showing up.

Good practise or not aside, how can I do this?

# Answer
You cant do it that way. But its drupal and it spread true love, so worry not, heres a solution.

1. Activate php filter under modules
2. Create a custom block
3. add `<?php print views_embed_view(yourviewname, block); ?>`
> 1 votes

# Answer
No You cant do that. Whatever use case you're looking for can be achieved through blocks
> 0 votes

# Answer
It's possible, but it'll get hacky and fragile. This sounds like a 'golden hammer' problem, a different tool would likely work better.

Have you considered using Panels or Display Suite to accomplish what you're doing? Panels are better if you want a more WYSIWYG type interface, Display Suite is better if you're comfortable coding.
> 0 votes

# Answer
If you don't want to mess with template files or lack coding skills, you can use

## Panels

> **An Overview of Panels** The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

With Panels, you can add more regions to your nodes.

With mini panels, you can add blocks with regions inside them.
> 0 votes

---
Tags: 7, theming
---


title: drupal 7 link taxonomy term with users

text:
# Question
Title: drupal 7 link taxonomy term with users
How can i add all my users to a taxonomy term author so that when you start typing an author name it will suggest you names of all users with those letters?

# Answer
> 1 votes
Use the entity Entity Reference Module.

* Add a field with **Entity Reference** and a widget of **Auto complete (tag style)**

For example: I named mine lalala (click picture below to enlarge)

**4)** In your field settings:

* Select User as your target type

After you click save field settings you are taken to another screen, scroll down and find **Number of values** and change it to **Unlimited** and Save Changes.

On your entity reference field since we are using Autocomplete (tag style) you start to type a user name and select the user. Then add a comma `,` to add more users

Ex:

# Answer
> 1 votes
If i understand your question correctly, you can simply select all the users from users table and create a taxonomy term.
Ex. `select * from users;`
then use `taxonomy_term_save()` reference here to create a term.

And if you want to create a term for every user creation. use `hook_user_insert()` then create a term by `taxonomy_term_save()`.

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


# Question
Title: Menu link that uses title from router item's title callback?
In the user menu, I would like the menu link for the "user" path to use the dynamic link title from the title callback, instead of a custom link title.

I know I could alter this on the theme layer, e.g. with hook\_preprocess\_menu\_link(). But somehow I have the feeling there must be something simpler, that works out of the box..

Any ideas?

# Answer
> 1 votes
Menu links that are registered through hook\_menu() do this already, so if you are using the system-provided menu link, it should pick up whatever you have altered "title callback" to be instead.

The system-provided 'user' menu link is being altered by user.module to prevent it from showing up to anonymous users (see `user_menu_link_alter()`, `user_translated_menu_link_alter()`). That might be getting in the way of what you want, in which case you could bypass/unset the user module implementation in a `hook_module_implements_alter()` function.

If you're using a custom menu link created through the UI, I don't believe you will be able to make that link title dynamic short of implementing `hook_menu_link_alter()` and `hook_translated_menu_link_alter()`. That's probably more work than intercepting it at the theme layer, though.

---
Tags: routes
---


# Question
Title: On a module Issue page, how do you tell what version the patch has been applied in?
Much of the time, take this field collection migration issue for example, when I find an issue with a drupal module, there has already been an issue filed, and in some cases the issue has a status of Closed (fixed). In the sidebar there is a version mentioned. It seems likely that that version is the one you set when you file the issue, specifying which branch of the code you saw the issue in.

When the issue has been Closed (fixed), does that mean that if you grab the specified version, that the code will include the patch? Is there any way of knowing when a fix has reached the stable branch?

# Answer
> 2 votes
As mentionned by Eyal a patch is always applied to the -dev version of the module. That's already a good stuff to know. So yes, if a patch is committed you can download the -dev version specified in the issue (or apply the patch separately if needed).

Usually the patches included in a new release are listed in the changelog: .

note: normally once a patch is committed the issue status becomes "closed (fixed)" and you will ind this kind of details in the latest issue comments:

In the sidebar of the presentation page of the module the "View pending patches" can be helpful to check if the issue you are looking for is still opened or fixed. There is also the "Views commits" link for a quick overview. this page provides a detailed list of the patches implemented (issue date, version , description, id).

--

The official doc https://www.drupal.org/issue-queue/status could also help you to understand the process.

# Answer
> 1 votes
**Patches are not always applied to the dev branch**. This is not the case always although it would be. For example there may be 2.x and 1.x version or maybe the stable release is 1 year ahead from the dev branch etc.

The official rules for submitting patches can be found here: Submitting patches.

In reality the patches refer to the version (release or branch) that issued the patch. See the example. And the naming rules say that you should add the project branch in the patch name too!

When you create an issue on D.O. you are obligated to enter the project version that issued the issue. **So any patches submitted there refer to the "version of the issue"**. When the branch is the dev branch which changes often the patch need to change often too! That's why you see so many patches for an issue if it is not closed soon.

Also, D.O. has a special bot that takes patches from issues and apply them to the project so every patch has a **pass** status. See more at Drupal.org Testbots.

D.O. : Drupal.org

---
Tags: community-official-site
---


# Question
Title: How to overcome a database error on field deletion
I have read the other SQLSTATE\[42S22\] questions here, and they seem to all be about modules that have not completed setup properly, but I think my issue is different.

Whenever I try to delete a field the following error shows up:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'field_data_field_doc_file0.field_doc_file_value' in 'where clause':
SELECT field_data_field_doc_file0.entity_type AS entity_type,
field_data_field_doc_file0.entity_id AS entity_id,
field_data_field_doc_file0.revision_id AS revision_id,
field_data_field_doc_file0.bundle AS bundle FROM
{field_data_field_doc_file} field_data_field_doc_file0 WHERE
(field_data_field_doc_file0.field_doc_file_value = :db_condition_placeholder_0)
AND (field_data_field_doc_file0.deleted = :db_condition_placeholder_1) ;
Array ( [:db_condition_placeholder_0] => 61531 [:db_condition_placeholder_1] => 0 )
in field_sql_storage_field_storage_query()
(line 652 of /path/to/drupal/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

It seems that perhaps some previous field deletion went awry or something? If I hit the back button it does appear that my field has been deleted, but I fear that if I keep deleting fields, I may be digging myself into a much worse problem to untangle. What would be the best course of action to resolve this issue, and get rid of these db errors? I'll start by looking at the field\_sql\_storage module, but suspect I'm not familiar enough with drupal yet, to quickly ascertain what is going wrong via that route.

**UPDATE:** Line 652 of that module is the last line of the `field_sql_storage_field_storage_query` method:

```
return $query->finishQuery($select_query, $id_key);

```

**UPDATE 2:** I found the entity with the id in `[:db_condition_placeholder_0]` in a table called `field_deleted_data_143`, but I haven't find a column named `field_doc_file_value` anywhere yet (The deleted table has a `field_doc_file_title_value` table). The FROM portion of the query is `FROM {field_data_field_doc_file} field_data_field_doc_file0`, but I don't know what table `{field_data_field_doc_file}` represents here. Is it `field_data_field_doc_file` (which is an empty table), or are do those curly brackets mean that name is being replaced with something else?

I guess maybe the next step is to try adding the column to the table.

# Answer
> 0 votes
I tried manually adding a column with the missing name to the table in question. Now a cron run spits out a series of 20 sets of error messages like this:

```
Notice: Undefined property: stdClass::$fid in file_usage_list() (line 649 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$status in file_field_delete_file() (line 363 of /path/to/drupal/modules/file/file.field.inc).
Notice: Undefined property: stdClass::$fid in file_usage_delete() (line 728 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1273 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1274 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1278 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1280 of /path/to/drupal/includes/file.inc).
The specified file could not be deleted, because it is not a valid URI. More information is available in the system log.

```

At the same time I notice the number of rows in my various deleted\_data tables seems to decrease by 10 with each run. Deleting a field likewise triggers 20 errors and a decrease in the number of rows in the deleted\_data tables.

I'm hoping that this has been the fix. It makes sense that it can't delete the files as they come in via a migration, and I've started bringing the files in on a different field, so I rolled back and imported. I'll update this once cron has run enough times that I can see if my deleted data logjam has cleared and fields can be deleted again.

**UPDATE:** It seems like there was a tremendous amount of backlog building up behind this database error. I set a system cron job to trigger drupal cron once a minute (dev site, so no performance concerns) and over the course of many hours, the rows in the deleted\_data and deleted\_revision tables have started to go away, followed by the tables themselves. A few empty tables and one with three rows in it remain, and I'm not sure if they will eventually be cleared, or if they aren't in whatever queue is being run through. If someone knows how to check what tasks drupal has queued up to run in the background, please do comment and let me know.

**IN CONCLUSION:** In this particular case, where the system was trying to make a selection and not finding the column it expected to find, it seems like the only possible solution was to add the column in, so the select would return 0 rows instead of an error that stopped things from moving on. I'm not sure what caused the discrepancy between expected columns and actual database schema, but I suspect it has something to do with an earlier struggle to get the media module working for me, that involved switching back and forth between the 7.1.x and 7.2.x branches of that module. Somewhere along the way I think drupal lost track of what version was currently installed, and stopped being able to properly run the right database upgrades on install and update. I'll read up some more on how to check if this is something I need to address, but if you've had a similar experience, that may be a place to start on debugging the source of your woes.

---
Tags: 7, database
---