# Question
Title: Change the Default " - Choose -" text in Ctools Jump menu?
I've created a Ctools jump menu in a block in a module. The default text which Ctools provides for their jump menu is "- Choose -". Is there a way to change this in the module? I'm guessing it should happen somewhere in this line of code but not quite sure how to do it;

```
$form = ctools_jump_menu(array(), $form_state, array($url => t('Classified Ad'),$url2 => t('Places'),$url3 => t('Facility')), array());

```

# Answer
> 1 votes
Just had a look at the ctools\_jump\_menu function's code here.
I would try the following:

```
$options = array( 'choose' => 'CUSTOM TEXT' );
$form = ctools_jump_menu(array(), $form_state, array($url => t('Classified Ad'),$url2 => t('Places'),$url3 => t('Facility')), $options);

```

Hope this helps!

---
Tags: blocks, chaos-tool-suite, 7
---


# Question
Title: Features - keeping Git up to date when changing features on production
I have a Drupal 7 site with a UAT version and Production version. Most of the features on production have been overridden. I want to keep my repository up to date in case anything happens to my database I can redeploy with the most current (overridden) changes.

My question is: what is the best way to go about updating my Git repo without a lot of unnecessary work?

My thinking is that I could just download the features off of production, overwrite the features on my local and commit / deploy to remove the overrides. Is this a viable strategy? Is there any risk involved with this strategy?

I appreciate any help / nudge in the right direction.

# Answer
> 0 votes
Great question. I work in a Drupal agency where we see this all the time.

Imaging this scenario:

Locally you've made some amends to a site that overrides a bunch of features. Locally you can run feature updates, placing the changes from the database into the code and then get ready to push live. But when you go to push live, you see there are feature overrides existing on the live site. There can be feature overrides for a number of reasons but the most often one is fields and blocks moving. If there are additions in your code they will be ok, but if you need to revert one of the features to say, move a field, then it gets a bit tricky.

My personal solution to this is to download the latest live database and run feature updates from that database locally, then merge the code changes. Then when you push your code you will have your changes and your live sites overrides in the code.

This isn't perfect, but it's workable.

Why not just run feature updates on the live server and pull that code change locally for a merge? Most, usually all, servers don't allow write permissions in live environments. So cloning the db locally is often necessary for this.

It's also worth trying to structure you features well, it's an art not a science! I usually leave ALL blocks out of features as they always get overridden. Also don't make a feature for all content types or all views as that will easily be overridden. Yes you can make too many feature, this is where your experience will come into play and it gets easier the more you do it.

Our senior dev also hook\_update\_N which may be worth looking into.

---
Tags: features, workflows, version-control
---


# Question
Title: How to access jQuery plugin added through libraries API
I'm working on a Drupal 7 module to integrate an existing jQuery plugin (smallworld.js). I've added it successfully through the Libraries 2.x API in my module:

```
$libraries['smallworld.js'] = array(
    'name' => 'SmallWorld.js',
    'vendor url' => 'http://mikefowler.me/smallworld.js/',
    'download url' => 'https://github.com/mikefowler/smallworld.js',
    'version' => '1.0', //no version actually defined in code
    'files' => array(
      'js' => array('src/smallworld.js'),
      'js' => array('src/smallworld.jquery.js'),
    ),
  );

```

and have confirmed that the files are loading correctly. However, when I try and access the file in my Drupal jQuery, ex:

```
(function ($) {

  Drupal.behaviors.smallworld = {
    attach: function (context, settings) {
      $.getJSON('/sites/all/libraries/smallworld.js/dist/world.json', function (data) {
        $('.map').smallworld({
          geojson: data,
        });
      });
    }
  };
}(jQuery));

```

It doesn't trigger, giving me the console error message "Smallworld is not a constructer."

The two files it is loading are the Smallworld library and a smaller jquery wrapper that registers the library as a jquery plugin:

```
  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {
        $(this).data('smallworld', new Smallworld(this, opts));
        return this;
      });
    }
  });

```

Does this wrapper also needed to be added to the same Drupal jquery namespace? If a jquery library is added through Libraries API, is there special namespacing to consider when accessing it?

# Answer
Found the problem - this library comes with two separate files, one that is a straightup javascript library and another in jquery that registers the file as a plugin (smallworld.jquery.js)

```
  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {

      $(this).data('smallworld', new Smallworld(this, opts));
      return this;
    });

```

To get this to work, I had to take the whole 'register' script and add it to the jquery file script I created for the module, ex:

```
(function ($) {

  Drupal.behaviors.smallworld = {
    attach: function (context, settings) { ...

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How do I change the name of the "view" node tab for a specific content type?
I am using Drupal 8. I have a content type "hotel". I would like to change the default tab name "View" only for this content type "hotel". I can change the default tab name "View" by mymodule.links.task.yml (please see below code), but it applies to all content types.

```
entity.node.canonical:
  route_name: entity.node.canonical
  base_route: entity.node.canonical
  title: 'Summary'

```

So how do I change the default tab name "View" ONLY for a content type?

# Answer
In your theme open file THEMENAME.theme, and the add code below:

```
function MYTHEME_preprocess_menu_local_task(&$variables) {
  if (isset($variables['element']['#link']['title']) && $variables['element']['#link']['title'] == 'View') {
    $node = \Drupal::request()->attributes->get('node');
    if ($node && $node->getType() == 'hotel') {
      $variables['link']['#title'] = t('Hotel View');
    }
  }
}

```

Clear all cache and see result.
> 4 votes

---
Tags: 8
---


# Question
Title: Using webform 4.x values in other fields/descriptions on multi-page webforms
Is there a way to output values of other field values in a multi-page webform? Say I have a 3 page webform. First page is name, email, then address. How can I reference the name value in the last page of my webform? I tried \[webform:val-name\] and it doesnt work in the description field.

Or is there a way I can call it via javascript? Are these values stored somewhere?

# Answer
Once you complete an specific field in one page, it can be used ONLY in the next page. The variables are stored into -\>

```
$form_state['input']['submitted']['your_field_machine_name']

```

One trick I did, I saved that submitted variable into a hidden input in the next page.
> 0 votes

---
Tags: webforms, tokens
---


title: How can I disable a troublesome module?

text:
# Question
Title: How can I disable a troublesome module?
I've been playing around with D8 and have managed to break a few things I can't figure out how to fix. Most recently, after installing (via manually adding the module code to the modules folder) the Name Field module and subsequently enabling it in the Admin panel, my Drupal 8 instance started throwing fatal PHP errors. No problem, I thought, apparently the module has a bug and I'll just remove it for now. Not so easy. I removed the module folder from my instance, but the errors are persisting.

Not that the specific error matters as this question is not about troubleshooting the module, but here's an example of something I get *after* removing the module code:

> Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginException: "Plugin (name) instance class "Drupal\name\Element\Name" does not exist." at /srv/http/drupal.protestan.org/core/lib/Drupal/Component/Plugin/Factory/DefaultFactory.php line 87

Is there a way to disable a malfunctioning module without being able to load the control panel? I've looked around but all the hacks for D6/D7 including tweaking the database manually don't seem to apply any more. At the very least the layout has changed and I was unable to find the corresponding bit to toggle. Likewise the current version of `drush` does not seem to be able to cope with D8 yet.

Is my whole database borked? Is there a secret URL or other way to load the Admin panel with no modules enabled (i.e. some sort of safe mode)?

# Answer
We were having the similar issue. We were not able to uninstall the module from Drush or from Module Uninstall interface as it was throwing errors due to code in hook\_uninstall().

The 'acquia\_search\_multi\_subs' module was giving error in our case during uninstall and data in table looks like below,

```
drush sqlq "select * from config where name='core.extension'"

core.extension  a:2:{s:6:"module";a:74:{s:16:"acquia_connector";i:0;s:13:"acquia_search";i:0;s:24:"acquia_search_multi_subs";i:0;s:13:"admin_toolbar";i:0;s:19:"admin_toolbar_tools";i:0;s:5:"block";i:0;s:13:"block_content";i:0;s:10:"breakpoint";i:0;s:8:"ckeditor";i:0;s:6:"coffee";i:0;s:7:"comment";i:0;s:16:"composer_manager";i:0;s:6:"config";i:0;s:7:"contact";i:0;s:15:"contact_storage";i:0;s:10:"contextual";i:0;s:6:"ctools";i:0;s:8:"datetime";i:0;s:5:"dblog";i:0;s:18:"dynamic_page_cache";i:0;s:6:"editor";i:0;s:26:"entity_reference_revisions";i:0;s:6:"facets";i:0;s:5:"field";i:0;s:8:"field_ui";i:0;s:4:"file";i:0;s:6:"filter";i:0;s:5:"image";i:0;s:13:"layout_plugin";i:0;s:4:"link";i:0;s:17:"menu_link_content";i:0;s:7:"menu_ui";i:0;s:7:"metatag";i:0;s:18:"metatag_open_graph";i:0;s:7:"migrate";i:0;s:14:"migrate_drupal";i:0;s:12:"migrate_plus";i:0;s:13:"migrate_tools";i:0;s:15:"migrate_upgrade";i:0;s:4:"node";i:0;s:7:"options";i:0;s:10:"page_cache";i:0;s:12:"page_manager";i:0;s:15:"page_manager_ui";i:0;s:6:"panels";i:0;s:10:"paragraphs";i:0;s:4:"path";i:0;s:9:"quickedit";i:0;s:3:"rdf";i:0;s:11:"rdf_builder";i:0;s:5:"rdfui";i:0;s:16:"responsive_image";i:0;s:10:"search_api";i:0;s:15:"search_api_solr";i:0;s:15:"security_review";i:0;s:9:"sharethis";i:0;s:14:"simple_sitemap";i:0;s:6:"system";i:0;s:8:"taxonomy";i:0;s:9:"telephone";i:0;s:4:"text";i:0;s:5:"token";i:0;s:7:"toolbar";i:0;s:6:"update";i:0;s:4:"user";i:0;s:10:"zzz_common";i:0;s:11:"zzz_migrate";i:0;s:11:"zzz_zipcode";i:0;s:5:"views";i:0;s:8:"views_ui";i:0;s:20:"workbench_moderation";i:0;s:7:"youtube";i:0;s:8:"pathauto";i:1;s:6:"aaazzz";i:1000;}s:5:"theme";a:6:{s:5:"stark";i:0;s:6:"stable";i:0;s:6:"classy";i:0;s:5:"seven";i:0;s:6:"bartik";i:0;s:11:"zzzmagazine";i:0;}}

-

```

To uninstall the module, we run following sql statement on d8 database. Basically we removed s:24:"acquia\_search\_multi\_subs";i:0; from 'data' field and reduced the length of the array to 73 in our case.

```
drush sqlq "update config set data = 'a:2:{s:6:\"module\";a:73:{s:16:\"acquia_connector\";i:0;s:13:\"acquia_search\";i:0;s:13:\"admin_toolbar\";i:0;s:19:\"admin_toolbar_tools\";i:0;s:5:\"block\";i:0;s:13:\"block_content\";i:0;s:10:\"breakpoint\";i:0;s:8:\"ckeditor\";i:0;s:6:\"coffee\";i:0;s:7:\"comment\";i:0;s:16:\"composer_manager\";i:0;s:6:\"config\";i:0;s:7:\"contact\";i:0;s:15:\"contact_storage\";i:0;s:10:\"contextual\";i:0;s:6:\"ctools\";i:0;s:8:\"datetime\";i:0;s:5:\"dblog\";i:0;s:18:\"dynamic_page_cache\";i:0;s:6:\"editor\";i:0;s:26:\"entity_reference_revisions\";i:0;s:6:\"facets\";i:0;s:5:\"field\";i:0;s:8:\"field_ui\";i:0;s:4:\"file\";i:0;s:6:\"filter\";i:0;s:5:\"image\";i:0;s:13:\"layout_plugin\";i:0;s:4:\"link\";i:0;s:17:\"menu_link_content\";i:0;s:7:\"menu_ui\";i:0;s:7:\"metatag\";i:0;s:18:\"metatag_open_graph\";i:0;s:7:\"migrate\";i:0;s:14:\"migrate_drupal\";i:0;s:12:\"migrate_plus\";i:0;s:13:\"migrate_tools\";i:0;s:15:\"migrate_upgrade\";i:0;s:4:\"node\";i:0;s:7:\"options\";i:0;s:10:\"page_cache\";i:0;s:12:\"page_manager\";i:0;s:15:\"page_manager_ui\";i:0;s:6:\"panels\";i:0;s:10:\"paragraphs\";i:0;s:4:\"path\";i:0;s:9:\"quickedit\";i:0;s:3:\"rdf\";i:0;s:11:\"rdf_builder\";i:0;s:5:\"rdfui\";i:0;s:16:\"responsive_image\";i:0;s:10:\"search_api\";i:0;s:15:\"search_api_solr\";i:0;s:15:\"security_review\";i:0;s:9:\"sharethis\";i:0;s:14:\"simple_sitemap\";i:0;s:6:\"system\";i:0;s:8:\"taxonomy\";i:0;s:9:\"telephone\";i:0;s:4:\"text\";i:0;s:5:\"token\";i:0;s:7:\"toolbar\";i:0;s:6:\"update\";i:0;s:4:\"user\";i:0;s:10:\"zzz_common\";i:0;s:11:\"zzz_migrate\";i:0;s:11:\"zzz_zipcode\";i:0;s:5:\"views\";i:0;s:8:\"views_ui\";i:0;s:20:\"workbench_moderation\";i:0;s:7:\"youtube\";i:0;s:8:\"pathauto\";i:1;s:6:\"aaazzz\";i:1000;}s:5:\"theme\";a:6:{s:5:\"stark\";i:0;s:6:\"stable\";i:0;s:6:\"classy\";i:0;s:5:\"seven\";i:0;s:6:\"bartik\";i:0;s:11:\"zzzmagazine\";i:0;}}' where name='core.extension'"

-

```

Please make sure to take the backup of the table before executing such commands as if something goes wrong then you won't be able access the site.
> 3 votes

# Answer
You seem to be having two issues: this module (i.e. PHP Fatal Errors resulting from something that's broken in the module) and Drush.

Let's start by the easiest fix, Drush.

Make sure you have Drush 8 (or 9-dev), which is the only version compatible with Drupal 8. Run `$ drush --version` to know for sure. If you're not running Drush 8, then, read the documentation and install it via Composer.

As to your module issue, my best bet at this point would be to put the module back in place where it was so that Drupal can see it, else, it'll never be in a position to trigger the uninstall process if the module isn't there. Once it's back (under the `/modules` directory at the root of your Drupal install), run the `$ drush pm-uninstall -y` command which will **not** disable the module (this has been removed completely from D8) but **uninstall** it completely. If it doesn't fail during the process, then, chances are that everything will be fine. If you do have issues during the uninstall phase, try to visit the `/admin/modules/uninstall` page to uninstall the module from the UI (assuming something didn't work well with Drush).

If nothing works, try to rebuild the cache (`/admin/config/development/performance` or `$ drush cr`) and repeat the above operation. Finally, if you're still stuck, I'd advise you report your bug (at the very least the PHP error message) in the module's issue queue. Note that it should not be the error you mentioned earlier since you got it *after* you removed the module from its original location.
> 2 votes

---
Tags: 8
---


title: How to show download count of a product

text:
# Question
Title: How to show download count of a product
I am using drupal commerce for an e-commerce site. I have a view for listing the product. I want to show download count oof each product in product listing page as mentioned in the screenshot. How can I achieve this?

# Answer
You can do it by setting up a view of product line items, adding both the product and order relationships, filtering by order state, turning on aggregation, grouping by Product ID and summing on the line item's quantity field.

Else try the https://www.drupal.org/project/commerce\_reports commerce reports module.
> 0 votes

---
Tags: 7, files, commerce
---


# Question
Title: Multiple choice question - Able to have the question correct with any correct answer
I am using the *Quiz* and the *Multiple choice* modules. In a question, I have two answers correct and I'm hoping to have the question marked right, if any of the answer is chosen.

Right now, if both answers are chosen, only then the question is marked as correct by the module.

# Answer
There is an option " Score if chosen and Score if not chosen " in multichoice question.

Set `Score if not chosen = 1 and Score If chosen = 1`

I hope, It would fix the issue.
> 0 votes

---
Tags: 7, quiz
---


title: Organic Groups -- Load group from gid

text:
# Question
Title: Organic Groups -- Load group from gid
This seems like it should be a simple operation, but I must be completely blind because I can't find anything about it in the API docs at http://www.drupalcontrib.org/api/drupal/contributions!og!og.module/7.

I have a $gid. I need to check if it really is the gid of a valid group, and have access to the group information if it is.

I did find an old post somewhere saying to use og\_load(), but that is out of date -- that function does not exist in the current API. Nor can I find a function with similar functionality.

There has to be a simple way to do this; it's hardly an outlier use-case. What am I missing?

# Answer
You don't need to use `group_load` anymore! Use `node_load` instead. You gid is equivalent to nid.
> 3 votes

# Answer
you could use og\_get\_group() http://api.drupalhelp.net/api/og/og.module/function/og\_get\_group/7 API to get the og group. It Return a loaded group entity if exists or create a new one.
> 0 votes

---
Tags: organic-groups
---


title: Link which leads to comments

text:
# Question
Title: Link which leads to comments
I simply wish to put a link at the head of node, which leads at the beginning of comments.

I did not find clear answer on this subject.

I try this, but does not work :

```
<?php print l('<p>title</p>', '#comments', array('html' => TRUE)); ?>

```

Is there a solution under drupal?

# Answer
Creating a link like this will not create the desired output. When looking at the `l()` function comments on the Drupal API page, the following is suggested to make internal anchors work:

```
l(t('Comments'), $_GET['q'], array('fragment' => 'comments'));

```

What happens is you tell Drupal to create a link to the current page, and add `#comments` as an anchor (fragment).

This means you can also link to the comments from other pages, by simply changing the `$_GET['q']` parameter to the desired path.
> 0 votes

---
Tags: 7, theming
---


title: Dependency injection in a custom class

text:
# Question
Title: Dependency injection in a custom class
I have a custom module (my\_module); Inside this module I have a custom class (MyClass), where I want to use a Drupal service (file\_system).

This is my code.

### src/MyClass.php

```
namespace Drupal\my_module;

use Drupal\Core\File\FileSystem;

class MyClass {
  public function __construct(FileSystem $file_system) {
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('file_system')
    );
  }
}

```

When I instantiate this class (in a controller for example), I get an error.

```
$my_class = new MyClass();

```

> TypeError: Argument 1 passed to Drupal\my\_module\MyClass::\__construct() must be an instance of Drupal\Core\File\FileSystem, none given

What is wrong in my code?

# Answer
DI requires a bit more effort than that - you haven't told the system about your class; the DI container doesn't know that you've called `new MyClass()`, and it can't get involved.

You need to create a Service, which you can make depend on other available services, instances of which will be passed to your class using the static `create` method pattern you're already using.

In this case, that's probably as simple as providing your mymodule.services.yml and adding:

```
my_service:
    class: Drupal\my_module\MyClass
    arguments: ['@file_system']

```

When you've correctly registered the class with the system, you'll get an instance of it like so (if you need it in a global function):

```
$foo = Drupal::service('my_service');

```

Or if you're consuming it in a container aware class, then you can inject it just like any other service.
> 18 votes

---
Tags: 8, dependency-injection
---


# Question
Title: Term reference field - print as other format
I'm using term reference field, which is displaying as entity.

I want to print this in the other place of node.tpl, not full entity but only names.

Is this possible?

I've tried

```
<?php print render($content['event_speakers']['und'][0]['value']); ?>

```

But it doesn't print anything

# Answer
EDIT: I didn't completely get your question initially. To do this you will need to fetch the term names yourself, and make them available to your node template file. This means you'll have to use `hook_preprocess_node()` implementation.

Here's the code you'd use:

```
function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['node']->type == 'YOUR_CONTENT_TYPE' && isset($variables['node']->field_event_speakers[LANGUAGE_NONE][0]['tid'])) {
    $event_speakers = array();
    foreach ($variables['node']->field_event_speakers[LANGUAGE_NONE] as $event_speaker) {
      $term = taxonomy_term_load($event_speakers['tid']);
      // Just to display the name:
      $event_speakers[] = $term->name;
      // To display linked name instead, use this:
      // $event_speakers[] = l($term->name, 'taxonomy/term/' . $term->tid);
    }
    // This will separate names with a comma, and a space.
    $variables['event_speakers'] = implode(', ', $event_speakers);
  }
}

```

You can then use this as many times as you want in the template; example:

```
<div class="speakers-top"><?php print $event_speakers; ?></div>
<div class="speakers-bottom"><?php print $event_speakers; ?></div>

```
> 0 votes

---
Tags: theming, nodes, taxonomy-terms
---


# Question
Title: How to allow anonymous user for checkout process?
When users buy one of our offers (premium offer), the site will create a user account, send a link to his/her account to reset the password, etc.

How to achieve this?

# Answer
You may need to check the permission, under `Admin > People > Permissions : "Access checkout"` for anonymous users.

If the user does login, their anonymous order will be added to their authenticated user cart.
> 1 votes

---
Tags: commerce
---


title: Context and Page Caching

text:
# Question
Title: Context and Page Caching
Just started a gigantic Drupal build and I'm trying to validate if the Context Module is the correct option for a segmented content delivery system. It appears to be and I am optimistic.

The project calls for about 100 custom "variables" that the site administrators can segment content with. As a test, I've created a custom context condition of time of day. If the condition is set for \>= 2PM for example with a reaction of showing the Powered By Drupal block in the footer, everything works as expected - Before 2PM, no block and after 2PM, block. So the context condition is working as expected.

Now, I've enabled page caching with lifetime and expiration set to 1 day. If I clear the cache before 2PM and hit the page, the block does not show as expected. If I hit the page (which is previously cached) after 2PM, still no block.

I have used a "preboot" method to modify the cache key, but in my example above, the cache key would include the hour and the minute, effectively reducing the cached copy of a page to 1 minute. I might as well turn page caching off in that case!

Is it possible to run the context conditions on a cached page? Has anyone found a way to make this happen?

# Answer
> 0 votes
If you have access to your ssh console, you can use cron

```
crontab -e

```

Then you put inside, at the bottom:

```
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 14 * * * cd /var/www/drupal && drush cc all

```

the above will clear the cache with drush everyday at 2pm.

A few notes:

* replace cd /var/www/drupal with the actual path to your drupal.
* I believe the default runs at UTC time.
* You need to install drush if you haven't already.

An alternative to using Drush, you could create a PHP or Python or NodeJS etc.. file that uses mysql to delete the row that holds the page cache in your DB, and run the file with cron at 2pm.

---
Tags: caching, 7
---


# Question
Title: Allow access for anonymous to custom user view mode
I made a custom view mode with display suite for the user entity. It is called "user\_teaser" and shows some fields that may be visible for Anonomous user. Unfortunately currently anonymous users cannot see it because of the general "View user profiles" permission which they have no access to.

Which hook should I use to bypass this permission and allow anonymous to see my custom view mode?

I tried hook\_entity\_view\_alter() as below, but this is called already too late I think as it is not even called when the access to the user profile is blocked.

```
function MODULE_entity_view_alter(&$build, $type) {
  if ($build['#view_mode'] == 'user_teaser') {
    $build['#access'] = TRUE;
    $build['user_image']['#access'] = TRUE;
  }
}

```

So I would need a hook\_entity\_access\_alter or hook\_user\_access\_alter or a hook\_entity\_access\_query\_alter, but they don't exist.

(edit) I found now some lead that might have a solution: How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)

# Answer
As you already guessed the permission is checked before building the content, so you will never be able to display any user data without that permission. (At lest not without some programming.)

You could try to grant the `View user profiles` permission to all user and then use the Field Permissions module and grant access per field. So you can show anonymous users only the fields they should have access to.

UPDATE:

As you have pointed out the above solution introduces some problems with privacy and some additional fields not being hidden on the user profile.

So another suggestion; Remove the Views access check. Views by default bypasses access checks on content (so Views without access checks are considered unsafe). Which might be of benefit to you here. As an alternative you can set a more generic permissions such as `View published content` to prevent errors from modules like Security Review.

Then under display choose `Display Suite` and your custom view mode.

You will end up with a View that shows the custom View mode with all selected fields, even for anonymous users. Yet the user profile at `example.com/user/1` shows access denied for anonymous users.
> 0 votes

---
Tags: users, entities
---


# Question
Title: How to get value of Textarea in node add form?
In my node add form I have added one text area :

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == "contenttype_node_form") {
         if (!isset($node->nid) || isset($node->is_new)) {
             $form['extra']['#title'] = t('Title (Extra)');
             $form['extra']['#type'] = 'textarea';
             $form['extra']['#required'] = TRUE;
             $form['extra']['#cols'] = '15';
             $form['extra']['#resizable'] = FALSE;
             $form['extra']['#rows'] = '5';

             $form['#submit'][] = 'my_trans_submit';

        }
    }
}

function my_trans_submit(&$form, &$form_state){
  $swed_title = $form['extra']['#value'];
}

```

Above code display one textarea just after title field in my node form. I Need the value entered in this text-area when user click on **save node** and then I want to use that value and save translation by running node save function. I can get this on form submit, but at that time node is not created and nid is not available.

How can I get value entered by the users in the above textarea once the node is saved and the node ID will be available, allowing me to use `node_save()`? Do I have to use a form field? I was not using a form field as it creates a new entity table.

# Answer
Shortly put, you need to do the following:

* Use hook\_form\_alter, the way you do already
* Use hook\_node\_submit, to update the field\_title field on the node object, before it gets saved. In your hook implementation you will have access to both $form and $form\_state, which should carry your custom textarea submitted value. Even if the nid is not there, your changes should still get stored in the new node.

Hope this helps!
> 2 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Create a percentage discount coupon with a maximum value
Need to have a coupon that follows this basic logic:

```
IF (Commerce % Coupon Granted amount > Max Value) THEN
    Commerce % Coupon amount = Max Value
ELSE
    Commerce % Coupon amount = % of ORDER

```

For example:

10% with a max of $100.

> Order value = 500, Discount = 50 (10% of 500)
> Order value = 1000, Discount = 100 (10% of 1000)
> Order value = 1500, Discount = 100 (flat 100)

# Answer
> 2 votes
If you're using the latest version of Commerce Discount and Commerce Coupon, you can accomplish this with just two rules connected to a single coupon code.

1. Create a Coupon Code by going to Admin→Store→Coupons-\>Create Coupon Code. Save it.
2. Create a new Discount (Admin→Store-\>Discounts-\>Create). Set it to **Order Discount** and add a **Total amount** condition. Set the condition to **less than** and the amount to **2000**. Set the percentage discount as you desire. Finally, add the coupon code from step 1 to this discount and save it.
3. Create a another Discount. Set it to **Order Discount** and add a **Total amount** condition. Set the condition to **greater than or equal to** and the amount to **2000**. Set the flat discount as you desire. Finally, add the coupon code from step 1 to this discount and save it.

Now, when a customer checks out, the coupon will attempt to apply both discounts, but because of the condition, only one will apply: $200 if the order is $2000 or over, and 10% if the order is $1999.99 and under.

---
Tags: commerce
---


title: Date format problem in view

text:
# Question
Title: Date format problem in view
hello I encounter difficulties to display a date in the correct format in a view.

I souhaire display my dates like this 2009-07-19T03:00:00+01:00

I created a new format here / admin / config / regional / date-time / formats here that `Y-m-d\TH:i:sP`

Then I created a new type of date and selected my new format. When I go to my view, I select my new date format but the field shows a different format 2016-03-17+01:00 +01:00

So I have a time zone more and I miss the hour, minutes and seconds. Do you have a solution ?

# Answer
Try doing it like this, which works fine for me:

For date format select `Custom` and then enter `Y-m-d\TH:i:sP`
> 1 votes

---
Tags: 7, views
---


# Question
Title: Show the node creation date in admin/content
In Drupal 7, I can show the creation date for the single nodes, in their pages. The creation date isn't shown in admin/content, though.

>

Is there a way to add a creation date column to the node list on admin/content?

# Answer
> 9 votes
I believe the purpose of this module Administration Views is exactly what you are asking for. Once you install it, it will allow you to override your "content" page.
This way you can add extra columns, sorting and filters to that page, using the Views UI.

The View you are looking for is called Administration: Nodes (at least in D7) and if you edit that and add fields, they will show up on the content overview page. (comment by @Neograph734)

* You would need to edit this view, by navigating to the admin/structure/views/view/admin\_views\_node URL.
* Add the "Content: Post date" to the field of that view
* Configure the new field; set the Date format to "Short" and possible renaming its label to sth like "Created".
* You can optionally rearrange your columns and also make the new "Created" column Sortable in the Table format setting
* Save your view and visit the admin/content URL, it should now look similar to this:

Hope this helps!

# Answer
> 0 votes
If for some reason you don't want to use the Administration Views module as suggested previously, you can create a View of your content with the field you want. If you use the Views Bulk Operations module, you can also add operations that include the actions you can do on on admin page.

---
Tags: nodes, 7
---


# Question
Title: Why do my files get lost when migrating a CCK Filefield?
I'm just getting stuck in to migrating D6 to D7 (please note: migrating, NOT upgrading). I'm using the Drupal-to-Drupal data migration module and its UI to define what I need to bring across.

One of the content types is "Issue": an issue of an online publication which just has a title, some body text (optional) and a file attachment for the PDF version of the publication.

To prepare the migration, I set up a corresponding content type in the D7 database, making sure that the field name was the same in D6 and in D7.

I have run a migration reasonably successfully (except for the major issue of Book structure which doesn't get handled), and all the "Issue" content has come across. However, none of the files in the "File Field" fields have been copied across. I'm trying to get my head round this: do I need to extend the Node Migration class, and if so how do I go about this?

# Answer
> 0 votes
Have a look at the Video about Upgrade Drupal6 to Drupal7 using the MIGRATE module. You're probably familiar already with many of the things shown in it, but it also provides some other interesting tips about things like:

1. Before starting the migration, make sure your current Drupal 6 site is in good shape (like update your contributed modules to the most recent D6 version first).
2. If you have a lot of files (attachments) to be upgraded also, it might be possible to do that part without using the migrate module.
3. If you have a possibility to create a (temporary) subdomain for your Drupal 7 version, that will speed up the migration execution quite a lot.

Especially bullet nr '2.' above may be worth experimenting with. In the video it is shown starting from about 12:05 (and the "Step 4: Files" screen provides some more details about what your options are here). Later on in the video, starting from about 15:45, you can see that the "image placeholders" (pointing to some files) are already OK. So afterwards you just need to copy those files to the right spot, using FTP or something.

So try running migrate with that option for Step 4 "unchecked" (turned off)!

# Answer
> 0 votes
When you map content types using the UI, complex field mappings like file fields and term references are not automatically set up - you need to do this manually by editing the migration containing the fields.

1. In the migration dashboard, click your node migration name.
2. Click the Edit tab at the top.
3. Make sure you have your source and destination file fields mapped to each other.
4. For the file field mapping, in the "source migration" column at the right, select the migration for the actual files.
5. Below that there should be a destination field like "field\_file:file\_class".
6. Fill in the "default value" column with the string MigrateFileFid.

See the documentation (https://www.drupal.org/node/1819704) and feature request to have this happen automatically (https://www.drupal.org/node/2154015).

---
Tags: 7, migrations
---


# Question
Title: What's the default workflow for layouts in Drupal Bootstrap theme?
Panels/Page Manager and Display Suite are probably the two most popular approaches to layout of items in Drupal. Both, however, are officially not supported by the popular Bootstrap theme (as opposed to Zurb Foundation, which actively recommends both Panels and Display Suite).

I've been right through the Drupal Bootstrap documention, and beyond this "what not to do", I can't find anything on what *to* do. I know how to work with vanilla-Bootstrap's rows, columns etc using classes; I'm just struggling to find the standard, going-with-the-flow expected approach to doing this in the context of Drupal.

Is there any official guidance on best-practise layout in Drupal Bootstrap, or failing that, what's the expected approach to applying the row and column classes to elements?

I've seen Views Bootstrap, which is kinda-sorta supported. It's the next step up from that I'm not sure about, and I'm wary of just attempting something then finding I'm going against how the theme is designed and expected to work.

# Answer
I see your concern with the "unsupported" classification, just because that's an immediate red flag when looking for a module to provide some sort of core-like functionality. Since Bootstrap is really a frontend tool, I'm less concerned, since I'm generally just using it for its responsive behavior. In the past, I've simply used templates and preprocess functions to wrap or 'bootstrap' my content. Also, I've always used Display Suite Bootstrap layouts, which has been helpful in previous projects that are handed off to clients. Since it's a theme of choice, I'm interested to hear other comments.

**EDIT**

Before anything, you'll need to reference the Bootstrap CDN in your header **OR** install a Bootstrap Starter theme. Then, you'll need to install Display Suite and the Bootstrap layouts (linked above). You can then manage the display of a content type and choose a Bootstrap grid layout to add responsive behavior to your content type. If you prefer to use a template file e.g., you can copy the page.tpl.php from the core systems folder to your theme's template folder and add Bootstrap classes and elements to the markup. For more specific elements, such as menus and images, use preprocess functions in your template.php file to alter the markup. See the example below:

Bootstrap a menu:

```
function THEMENAME_menu_tree__MENU_MACHINE_NAME($variables) {
    return '<ul class="wrapper clearfix col-sm-12 col-md-6">' . $variables['tree'] . '</ul>';
}

```

Bootstrap a block:

```
function THEMENAME_preprocess_block(&$variables) {
    $elements = $variables['elements'];
    $classes = &$variables['classes_array'];
    if ($elements['#block']->subject == 'BLOCKNAME') {
         $classes[] = 'col-sm-6' . ' ' . 'col-md-3';
    }
}

```

Hope that's helpful.
> 1 votes

---
Tags: theming
---


title: Sort handler for pseudo field in views

text:
# Question
Title: Sort handler for pseudo field in views
I have made a custom views field handler by the following instruction:

http://www.interactivejunky.com/blog/database-independent-views-3-custom-field-handlers

The problem is that, I cannot sort the values of the created pseudo field in view. I know the reason is that my pseudo field basically doesn't exist in query of the corresponding view, and cannot exist there as it doesn't exist in any tables and it's just a computed field for that view.

Any ideas about making this field sortable?

# Answer
you should pass 'click sortable' =\> TRUE parameter together with 'handler':

```
...
  'field' => array(
    'handler' => 'views_handler_my_custom_field',
    'click sortable' => TRUE,
  ),
...

```

Then you can override click\_sort($order) in your views\_handler\_my\_custom\_field class, e.g. you can explicitly override the 'orderby' array of query object:

```
function click_sort($order) {
  ...
  $this->query->orderby[] = array(
    'field' => '...', // here may be a field, or some SQL clause e.g. FIELD(str, str1, ...)
    'direction' => strtoupper($order),
  ...
);

```

See also click\_sort($order) in views\_handler\_field class.

HTH, Alexander
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I prevent Drupal raising a segmentation fault when using a Node.js theming workflow?
# Symptoms:

Some drush commands fail; Some Drupal pages are blank.
The failing drush commands report "Segmentation fault: 11"
The Apache log (e.g. php-error.log in MAMP) also shows the same error.

# Background:

If you use a gulp or grunt workflow - to compile your theme's SASS etc. - you may run into a problem where drush commands throw a segmentation fault 11 as does Apache whilst serving Drupal pages as blanks (WSDs).

# Probable cause

This is because files from your `grunt` or `gulp` workflow environment in `node_modules` are erroneously being registered by Drupal itself as a bi-product of `drush cache-clear all` for example. There are dozens of these .js files and Drupal can't handle them ... it's possibly a PCRE regex that is the root cause as this is known elsewhere. Anyway ...

# It doesn't always happen

It's not clear whether some modules (like Browser Sync for example) induce this error as a node.js style (i.e. gulp or grunt) workflow can work perfectly before failing in this way.

# Answer
Here is the solution you're looking for. Much more elegant and less work:

```
"scripts": {
  "postinstall": "find node_modules/ -name '*.info' -type f -delete"
}

```

Just a slight alteration on @iamcarico's answer above.

note: you may need a .npmrc with just the following content:

```
unsafe-perm = true

```
> 26 votes

# Answer
So, I have a slightly more elegant solution, that will just remove the .info files after npm install. None are needed, so this *Should* be safe.

Add the following to the end of your package.json:

```
"scripts": {
  "postinstall": "find node_modules/ -name \"*.info\" -type f -delete"
}

```
> 7 votes

# Answer
This works for me:

(With many thanks to @jorgegc for identifying the cause in this thread at d.o. I thought the topic deserved a more general title here.)

1. Move `gulpfile.js` and `package.json` to the new "hidden" directory `.npm`
2. `cd .npm` and `npm install` (after having deleted theme root level `node_modules` directory of course)
3. edit `gulpfile.js` base directory for source and destination file paths.e.g. In the snippet bellow "../" were prepended to paths
4. in turn, invoke `gulp` command from within the `.npm` directory

### Example directory structure for ihit theme

`.
├── .editorconfig
├── .git
│   ├── HEAD
│   ├── ...
├── .gitignore
├── .jshintrc
├── .npm
│   ├── gulpfile.js
│   ├── node_modules
│   └── package.json
├── assets
│   ├── images
│   ├── js
│   └── sass
├── css
│   ├── ihit.hacks.css
│   └── ihit.styles.css
├── ihit.info
├── ihit.sublime-project
├── ihit.sublime-workspace
├── images
│   ├── logo.png
│   ├── search-icon.png
│   └── sprite.png
├── js
│   └── ihit.behaviors.js
├── php
│   ├── ihit_breadcrumb.inc
│   ├── ihit_form_search_form_alter.inc
│   ├── ihit_menu_link.inc
│   ├── ihit_menu_tree.inc
│   ├── ihit_preprocess_html.inc
│   ├── ihit_preprocess_region.inc
│   └── ihit_process_page.inc
├── research
│   └── Refills
├── screenshot.png
├── template.php
└── templates
 ├── html.tpl.php
 ├── node--image_gallery.tpl.php
 ├── node.tpl.php
 └── page.tpl.php`

### Head of gulpfile.js

`// project-specific
var project = {
 path: {
 sass: {
 source: '../assets/sass/**/*.scss',
 css_dest: '../css'
 }, // sass
 .
 .
 .`
> 5 votes

# Answer
You can avoid all of this by installing your workflow tools in the root of the Drupal site. It won't scan a top-level `node_modules` folder.

Installing at root-level also has other benefits, like allowing you to lint your entire project in a uniform fashion (your custom modules, Features, and themes can share this root-level config). Provided you group `sites/all/modules` into `contrib` and `custom` subdirectories, you can easily ignore contrib and other vendor folders.
> 3 votes

# Answer
It still seems to be a problem and I also got the following error: `Segmentation fault: 11` after running `npm install`.

I use `gulp` version `3.8.11` and `node` with the version `0.12`.

I usually (in this case too) use `aurora` as base theme and use an own `package.json` and `gulp.js` file. My `package.json` file contains iamcarrico's postinstall script:

```
  "scripts": {
    "postinstall": "find node_modules -type f -name '*.info' | xargs rm;"
  }

```

Hmm, at this point I just recognized that the postinstall script is slightly different which might have caused my Segmentation fault error. Anyway.

What I did was I removed the `node_modules` directory within my theme with `rm -rf ./node_modules`. Cleared the cache with drush `drush cc all`. Then I followed the above instructions of iainh ... until no. 3 (3 not included), ran `find node_modules -type f -name '*.info' | xargs rm;` inside the `.npm` folder and moved the `gulp.js`, `package.json` and the `node_modules` folder one level up to the original theme folder. I could run `gulp` without segmentation errors and even `browsersync` worked as expected.
> 1 votes

# Answer
Here is the issue on drupal.org which addresses this problem, including patch https://www.drupal.org/node/2329453
> 1 votes

# Answer
my solution was in the past to move the node stuff inside of a hidden folder like ".npm" for example.
> -1 votes

---
Tags: theming, drush
---


# Question
Title: Is there a way to change content in 1 master node and have it changed in hundreds of others?
I have searched for quite a while but with no success. Using D7.41, Views 3.

I have a lot of nodes of the same content type (~50 nodes) and all of these nodes have images and some text, plus 4-6 blocks of views in each (different text, different images and in some cases different blocks).

Task: to let the content manager edit this master template (change text, images, change blocks for all these 50 nodes), but the changes would then be replicated 20 times - I have exactly same structure replicated for 20 different regions - the same content, different paths. So that would be some kind of "Master template".

I do understand, that all of this could be managed with blocks, when all the content of the page is done via blocks, but maybe there is some other more clever way to achieve this?

**Updated**: one of the ways to reduce the amount of blocks used, I guess (as per user comment below), would be solution to have fieldable blocks. But in that case there is another question - how to do that?

# Answer
> 1 votes
If you have so many blocks, then you should try to find ways/techniques to reduce the amount of them. Below are some possible modules to help you on that.

# BEAN

You should have a look at the Bean module, which potentially can help you to answer this question. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

**Remark**: this module (a raising star!) has been moved to core in D8 ...

# Rules and Rules block visibility

Another module to have a look at (to help reduce the number of your blocks), is the Rules block visibility module. Here is a quote from its project page:

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

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


# Question
Title: Can I deploy my Content on drupal using scripts?
If suppose I have a drupal application in Github and I have automated drupal installation using chef. Now I want to deploy that application content such that i can see it on my content page. I am unable to put php and drupal tags due to reputation.

# Answer
If you would like to automate your deploys of content, just like you automate your code deploys, you'll probably want to look into the migrate module. This model is best for sites where the content is managed by a content-generation team; it is less applicable for sites that have a lot of user-generated content. This is a viable model that some people use, though, and is a very compelling workflow if your use-case supports it. One good extant site that uses this technique and has a public GitHub repository is Gizra's Negawatt.
> 0 votes

---
Tags: commerce, drush
---


# Question
Title: display data (taxonomy terms) after uploading it directly to the database
I have created a taxonomy vocabulary and then uploaded via mysql all the needed tables for the different fields.

I have created a view where I can see all the terms of the vocabulary, but if I go to `/admin/structure/taxonomy/myvocabulary` I can only see the terms that I have edited and saved, where, which table I have to modify for the terms to be displayed at the vocabulary page?

# Answer
From what I can tell those are all the taxonomy tables, but none of them seem to contain the term (url) path; thus, they must be in the **url\_alias** table. Also, don't forget to flush your cache to see the changes.

I think it's better/safer if you use feeds to import your taxonomy terms.

## Feeds

> **Import** or aggregate data as nodes, users, **taxonomy terms** or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * **Import or aggregate CSV files**
> * Import or aggregate OPML files
> * PubSubHubbub support
> * **Create** nodes, users, **taxonomy terms** or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

Video Tutorial
> 1 votes

---
Tags: entities, taxonomy-terms, database
---


# Question
Title: Can View content be filtered to what's new since user's last login?
We have a View that displays recently created content of a specific custom type – currently, it's showing the titles of the most recent 3 items. The site requires login, so can identify unique individuals. So how might we get this View to display only the items that are new since a particular user's last login? Or is there another way to display such a content list, other than by Views?

# Answer
> 3 votes
In your view, add a new filter criteria for "Content: Has new content." This should do exactly what you want.

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


# Question
Title: Conditionally apply CSS class to a conditionally-rewritten View field?
\[This will require some background explanation.\] We have a View (D7) displaying a custom content type. Flag Lists provides the option to select items via checkboxes and add them to a personal list. However some items are excluded from being available to add to such lists, and that it established by a boolean checkbox ("allowed" if checked) in the creation of the node. If NOT checked, the Flag List Operations checkbox in the View is rewritten by something else – currently, replaced by a simple text "X".

Now we want to provide a tooltip message explaining why this item is not available to be selected – using Tipsy, Q-tips or something like that. To display such a message only for the ones where the checkbox has been rewritten with X or something else, I believe it needs to have a unique class that also applies to all other such instances. SO: Is there a way to make those instances have a unique class so they can trigger the tooltip message only when it's relevant?

# Answer
Generally, every field has a unique selector already. If the defaults are not giving you enough control, I would recommend the Display Suite module which will allow to you add classes (and many other things) to individual fields.

You might also be able add the tip with the same method that you are using to rewrite with the X right now.
> 1 votes

---
Tags: views, theming, entities, tooltips
---


# Question
Title: Can you export a list of registered users who've registered for an event via the registration module?
Sorry if this is a duplicate. I tried to make sure it wasn't before I posted this.

In Drupal 7, does anyone know if there is "out of the box" functionality (that comes with the Entity Registration module) to export a list of people who've registered for an event via the registration module? Ideally, without using views, etc. Something that an end user/site editor could do.

I had a client ask if that were possible. I couldn't find an answer anywhere else and I've never used it before.

# Answer
Out-of-the-Entity-Registration-box you will (to my knowledge) not get such export facility that you are asking for, so the short answer is **NO**.

But *Sales starts when the customer says **no** ...*: have a look at the Community documentation of the Entity Registration module, especially to this part of it:

> Not happy with the default tabular list of registrations? No problem, registrations and their fields are all Views friendly. You can override the default event registrations list, create additional ones, etc.

In other words, if you're willing to accept, as a compromise, to get other modules involved, then it should be pretty forward. However with only views you still don't have the "export" function yet, and you'd need another module on top of that, like the Views data export module (or any of the "similar modules" mentioned on that project page).

**Unless** you're open to an alternative module for this views-and-some-other-module(s) approach ... I.e. if you'd be willing to only consider the Forena module (disclosure: I'm a co-maintainer), you'd have your 1 stop solution (only 1 extra module, that can do everything you are asking for). Have a look at it's community documentation to get the idea about it (or look at the answers to some of the questions). Or post a followup question like "**How can I do this with the Forena module?**" (to avoid you'd have to change your question here to a *chameleon* question).
> 1 votes

---
Tags: 7, users
---


title: View Bulk Operation page Customization

text:
# Question
Title: View Bulk Operation page Customization
i have created on view page which have option to update the node values but as a default behavior of VBO i first need to check the checkbox form my table and then click on update button then it goes to another page where i can select which value to be added

After click on update button next page will come for selection of value

after this selection and next is clicked the value get updated...

here i need to change this whole process to first page only i need my select box (i.e. Workgroup & Project Type dropdown) should come to first page only where i have my list to select the value and update button on click of that the node values should update and i return back to the same page..

# Answer
It's quite hard to understand exactly what you mean but I think an answer I wrote before might help since VBO doesn't really do what you want it to.

How to bulk delete selected content/nodes?

Follow the link if that "one page" functionality is what you need. It's limited but it works.
> 1 votes

---
Tags: views
---


title: Run Simpletest tests on Jenkins

text:
# Question
Title: Run Simpletest tests on Jenkins
I am trying to run a group of tests(Simpletest) for my custom modules through Jenkins.

1. Firstly I tried `drush test-run (...)` which has been removed from drush.
2. Then I tried `php scripts/run-tests.sh --xml logs_tests [GROUP_NAME]`, but for every test class it returns `/usr/bin/daemon: unrecognized option '--url'`. I haven't defined any URL, maybe is something Simpletest specific.
3. Finally, I created a fairly simple Phing task `<exec command="php scripts/run-tests.sh --xml logs_tests ${group_name}" error="build_error"/>` only to get the response `Unknown argument: --url`, from Phing this time.

# Answer
I was having the same issue you're mentioning in #2, getting this error:

```
/usr/bin/daemon: unrecognized option '--url'

```

# Solution

I found that the solution to this is specifying the PHP binary to `scripts/run-tests.sh` as such:

```
php scripts/run-tests.sh --php /usr/bin/php --url http://127.0.0.1

```

# Explanation

This is due to the way that jenkins starts programs, something like:

```
daemon program --parameters...

```

But run-tests.sh (lines 256-258) pulls the command that was run (falsely pulling `daemon php --parameters`) and thinks that the php binary is `daemon`.

The culprit code is:

```
 elseif ($php_env = getenv('_')) {
    // '_' is an environment variable set by the shell. It contains the command that was executed.
    $php = $php_env;
  }

```
> 1 votes

# Answer
It seems like you have tried everything except to supply the URL.

You must supply a --url argument to execute simpletest. This is what I use, where "IAS" is the test group I have selected to execute:

```
php scripts/run-tests.sh --url http://localhost/drupal7 --concurrency 4 IAS

```

It follows that you must have a Drupal install to do this.
> 1 votes

---
Tags: testing, deployment
---


# Question
Title: Multiple owners for commerce order [or] Allow non-owner to pay for an commerce order
Scenario:

* Drupal site with "Member" and "Spouse" roles.
* For any given married couple, Member and Spouse each have their own user accounts.
* entity reference field from spouse defines the relationship between the 2 users
* an order exists, belonging to Member user (order-\>uid)

Desired functionality:

* Regardless of the uid value for order, allow either Member *or* Spouse to proceed through checkout and payment for the order.

**I realize this is not possible through vanilla Drupal Commerce.** I'm looking for any ideas that will help me figure out how to implement this via existing Drupal techniques, or a custom module.

Specific questions:

* Has anyone achieved this successfully?
* Are the any specific ways (Drupal techniques) that could help solve this?
* What specific hooks or overrides should I be looking at?

Bonus points for elegant workarounds or shortcuts like a simple hook\_access override, or a clever way to just-in-time reassign the order uid.

# Answer
> 0 votes
You may want to look at https://www.drupal.org/project/masquerade module for some ideas to see how it does the switching since it allows:

> "...(anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time."

You can then write a custom module.

---
Tags: commerce
---


# Question
Title: How do I change a field type from integer to decimal?
I have some fields type integer that are already populated, is possible to change the fields from integer to decimal?

# Answer
Ok, I found a good solution to solve my problem.

**Modules required**

**Steps**

* Enable Helper module;
* Enable Devel module;
* Enable the block Execute PHP;
* Paste and execute this code in the block: `FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');`
* Edit display format for node where the field is being used;
* Edit Views where the field is being used to fix the format settings (If necessary);

If you don't want use Devel and can use Drush:

* Enable Helper module;
* create a new file in root Drupal folder, i.e. name it: intToField.php

`<?php
FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
?>`
* launch the drush command: drush src intToField.php
* Delete the file;
* Edit display format for node where the field is being used;
* Edit Views where the field is being used to fix the format settings (If necessary);
> 3 votes

# Answer
Changing the field type as you asked is not possible I think (fear).

However a possible alternative to achieve a similar result is like so (in the order specified):

* Create a new field, so that "from now on" any future node updates (or new nodes being created) will use that new field.
* Use the Rules module to create a rule like so:
    + Rules event: `before saving content`.
    + Rules conditions:
        - `entity has field`, with field = the old field.
        - AND NOT (`entity has field`, with field = the new field).
    + Rules Action: `set Drupal message`, which contains some instructions that the old field must be blanked out, and the new field should contain the appropriate value(s.

Obviously, this approach will take "some" time if this has to be done manually, 1 node at a time. But using Views (to build a list of similar nodes to be updated) and VBO (to mass update such lists) you might (should!) be able to speed up this process quite a bit. Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that.
> 1 votes

# Answer
You would have to go to your database and export your field as a CSV file. Then open file with excel.

> **Note:** If you're using php my admin for your export, do not use CSV for MS Excel. **Use the CSV option**. As CSV for MS Excel displays the values in a comma format rather than columns.

In Drupal delete the field and create a new decimal field. Go to a node and enter a value for your decimal field.

Go back to your database and find the decimal field, export as CSV. Then open on excel.

Use the values from your 1st excel to copy the node id's and the field value and paste them onto your 2nd excel and save.

Import 2nd excel to your decimal field and check-mark replace table data with file.

Clear/flush the cache to see changes.
> 0 votes

# Answer
you can do that by hook\_form\_alter.
> -2 votes

---
Tags: nodes, entities
---


# Question
Title: RouteNotFoundException when trying to delete a custom entity
I am building a custom component in Drupal 8 that has an entity with child entities i.e., TeamEntity has one or more MeetEntity objects.

When I navigate to the "Delete" link for a given MeetEntity, I get the following error:

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

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.meet_entity.collection" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 191 of core/lib/Drupal/Core/Routing/RouteProvider.php).
Drupal\Core\Routing\UrlGenerator->getRoute('entity.meet_entity.collection') (Line: 285)
Drupal\Core\Routing\UrlGenerator->generateFromRoute('entity.meet_entity.collection', Array, Array, 1) (Line: 110)
Drupal\Core\Render\MetadataBubblingUrlGenerator->generateFromRoute('entity.meet_entity.collection', Array, Array, 1) (Line: 754)
Drupal\Core\Url->toString(1) (Line: 161)
Drupal\Core\Utility\LinkGenerator->generate(Object, Object) (Line: 99)
Drupal\Core\Render\Element\Link::preRenderLink(Array)
call_user_func(Array, Array) (Line: 384)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 451)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 451)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 200)
Drupal\Core\Render\Renderer->render(Array) (Line: 471)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 43)
__TwigTemplate_4a2ed85f2bf4ceab0412cdb1168c80023104264819c7f1db9b016550543c33e9->doDisplay(Array, Array) (Line: 381)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 355)
Twig_Template->display(Array) (Line: 366)
Twig_Template->render(Array) (Line: 64)
twig_render_template('core/themes/classy/templates/form/confirm-form.html.twig', Array) (Line: 389)
Drupal\Core\Theme\ThemeManager->render('confirm_form', Array) (Line: 438)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 200)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 231)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 577)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 232)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 122)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 95)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 116)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 62)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 53)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 103)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 82)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 51)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 55)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 632)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

I have a "collection" link defined in my MeetEntity class like this:

```
 *   links = {
 *     "canonical" = "/meet/{meet_entity}",
 *     "add-form" = "/team/{team_entity}/meet/add",
 *     "edit-form" = "/meet/{meet_entity}/edit",
 *     "delete-form" = "/meet/{meet_entity}/delete",
 *     "collection" = "/team/{team_entity}/meets",
 *   },

```

I don't have that route defined in my routing.yml file because that "collection" path defined in the links in my Entity class points to a view called "views.view.meets.yml". However, when I do add a route for that in my routing.yml file, I get a `MissingMandatoryParametersException` on the {team\_entity}

I imagine I need to override some method somewhere but I can't figure out where. Can someone please help?

# Answer
I finally figured it out. I had to override both `Drupal\Core\Entity\EntityDeleteFormTrait::getRedirectUrl()` and `Drupal\Core\Entity\EntityDeleteFormTrait::getCancelUrl()` in my `MeetEntityDeleteForm` class. Here's my code:

```
public function getRedirectUrl() {
    $entity = $this->getEntity();
    return Url::fromRoute('view.meets.page_1', ['arg_0',$entity->getTeamId()]);
}

public function getCancelUrl() {
    return $this->getRedirectUrl();
}

```

`arg_0` in the call to `fromRoute` is the Team ID defined in the view's contextual relationship to the Team entity.

I was able to keep the `meet_entity.collection` route **out** of my routing.yml file. And my delete\_form route was very simple:

```
entity.meet_entity.delete_form:
  path: '/meet/{meet_entity}/delete'
  defaults:
    # Calls the form.delete controller, defined in the team entity.
    _entity_form: meet_entity.delete
    _title: 'Delete Meet'
  requirements:
    _entity_access: 'meet_entity.delete'

```
> 1 votes

---
Tags: 8, entities, routes
---


# Question
Title: Is there a way to filter blocks by vocabulary instead of NID or CT?
Each time I set the block visibility, I can do it only by node ID or content type.

Is there a way to set the block visibility using a taxonomy term?

# Answer
> 1 votes
Have a look at my answer to "How to make "Page specific visibility settings" for blocks more flexible?". It explains how the Rules block visibility module can be used to answer that question.

Your question here seems to be a variation of it. You could use a similar approach, so that in the end you'd only have to write a Rules Component related to your criteria here, ie to intercept your condition about "***if at least one term of a given vocabulary is in the node***" (in which case the Rules block visibility module should take care of "***showing the block in whatever region***". Done!

**Note**: for this to work, do not have to enable the PHP Filter module (always a good thing if you can avoid that).

# Answer
> 0 votes
You can use the PHP block visibility setting to return true when the node has any of the terms you want

```
<?php
  if (condition) {
    return TRUE;  // block will be shown
  }
  return FALSE;
?>

```

Edit: You need PHP Filter module enabled for that

---
Tags: blocks
---


# Question
Title: How to rebuild the theme registry on every page?
I returned to Drupal 7 after a short absence, and couldn't find the option to "Rebuild the theme registry on every page", which is useful while editing templates on a development site. I thought it was in the Performance options but I can't find it there, and searching for it gives unclear or out of date results, mostly around the Zen theme which I haven't used for years. I've definitely used this setting without using Zen.

Where's the Drupal option to rebuid the theme registry on every page?

# Answer
This isn't included in stock Drupal 7.

If you're not using Zen, the most common way to access this feature is via the module Devel.

Then it's accessible from `/admin/config/development/devel`, right down the bottom of the page.
> 3 votes

---
Tags: 7, performance
---


title: Comment Form Missing

text:
# Question
Title: Comment Form Missing
I'm baffled by this issue on my new site. I have double checked permissions to verify that authenticated users can post so I'm just getting that out of the way first off.

However, what is odd is that each node (where I rely off of the default Drupal node template, and those in which I have created a custom template) has a "Login or Register to Post Comments" div and appropriate links, however, when I login as a test user, there is no comment form.

I'm not sure where to go from here, as even my Admin account cannot see the comments form.

EDIT-----------

Also, all comment settings are set to "Open" for all content types and individual content postings.

EDIT-----------

I have rebuilt the permissions as well, just in case. Nothing has changed.

EDIT-----------

I happened to remember that I had previously posted a test comment on one of the pages, and now I can't see that comment, even if I go through the admin panels. I can see that there is a comment, but I cannot see the comment itself.

# Answer
Turns out the solution was to Disable Panels

or you could add the comment form to the Panel.
> 1 votes

---
Tags: comments
---


# Question
Title: Meaning of Error: Cannot redeclare bootstrap_preprocess_region()
I'm setting up a Drupal Bootstrap subtheme, and ran into this fatal error when trying to clear my cache. Something seemed to want to redeclare a bootstrap preprocess function:

> Error: Cannot redeclare bootstrap\_preprocess\_region()

This caused the whole site to go down and Drush to fail any time I tried to clear or rebuild the cache.

Why is this happening?

# Answer
> 0 votes
This was happening because I'd copied `.func.php` files from the templates folder of the Bootstrap parent theme into my base theme alongside `.tpl.php` files. Bootstrap is relatively unusual in that it has files in the templates folder alongside `tpl` files that will break the site if they're treated like standard theme `tpl` files.

While the `.tpl.php` files are to be copied as normal, to override the contents of the other files, you are expected to copy their appropriate *contents* into your subtheme's `template.php` file or into a new `.func.php` file, and substitute your subtheme name for the `bootstrap` part of the function name.

There's some more information on the theme registry docs page.

---
Tags: theming
---


# Question
Title: Webform with File upload field throwing "... field is required" error
I have created a Webform, which has two file fields (i.e. Attach document 1 and Attach document 2). Both of them are mandatory and files are to be uploaded in the "Private" folder.

Now when someone attaches the files and submits the form, it throws error messages "Attach document 1 field is required" and "Attach document 2 field is required". If I invoke the validation, then it works. I have checked in the server and the files are uploaded properly. So I think it is "Webform" or "Form" issue.

# Answer
> 1 votes
This can be solved by applying the patches found here:

This will hopefully be resolved just by updating for future versions of drupal core and webform.

# Answer
> -1 votes
I experience the same problem (using Webform 4.1). I found out that this issue only appears when I have the File entity (7.x-2.0-beta1) module enabled.

---
Tags: forms, webforms, files
---


# Question
Title: Why am I getting a 200 status header when the page is being served from cache?
Been running into a weird issue with all of our Drupal 8 websites, hosted on different servers.

The pages are caching correctly, x-drupal-cache header shows a HIT as well. The page however has it's headers set to 200, instead of 304. None of the sites are live yet, so i can't provide a link.

Request Headers:

* HTTP/1.1 200 OK
* Date: Fri, 18 Mar 2016 20:09:41 GMT
* Server: Apache/2.4.7 (Ubuntu)
* Cache-Control: max-age=900, public
* Expires: Sun, 19 Nov 1978 05:00:00 GMT (Dries' birthdate? O.o)
* Last-Modified: Fri, 18 Mar 2016 19:49:21 GMT
* Vary: Cookie,Accept-Encoding
* X-Drupal-Cache: HIT
* Keep-Alive:timeout=5, max=100
* Connection: Keep-Alive
* Content-Type: text/html;
* charset=UTF-8

Debugging the code Drupal uses to serve pages with 304 headers ( lines 165 to 170 of PageCache.php ) I have found that HTTP\_IF\_MODIFIED\_SINCE and HTTP\_IF\_NONE\_MATCH are not being set.

Thanks!

# Answer
> 1 votes
A Page cache hit just means that Drupal doesn't have to rebuild the HTML but can deliver it from the cache.

That doesn't make any difference at all for your browser. The browser requests the page and gets a HTML response. As far as he's concerned, there's no caching involved.

The built in Page cache has not support for returning 304 responses. Varnish does, but I don't know too much about when that works and when it doesn't. It depends on how you refresh/request the page for example, check if your browser really sends a If-Modified-Since header and if that's in the right form (see some of the answers in the linked stack exchange issue).

---
Tags: 8, caching
---


# Question
Title: How does a module tell Drupal which mail plugin should be used?
How does a module tell Drupal which mail plugin should be used? The SMTP Authentication Support module uses the following code in the submission handler of its settings form.

```
$values = $form_state->getValues();
$config = $this->configFactory->getEditable('smtp.settings');
$mail_config = $this->configFactory->getEditable('system.mail');
$mail_system = $mail_config->get('interface');

// Updating config vars.
if (isset($values['smtp_password'])) {
  $config->set('smtp_password', $values['smtp_password']);
}
$config->set('smtp_on', $values['smtp_on'])
  ->set('smtp_host', $values['smtp_host'])
  ->set('smtp_hostbackup', $values['smtp_hostbackup'])
  ->set('smtp_port', $values['smtp_port'])
  ->set('smtp_protocol', $values['smtp_protocol'])
  ->set('smtp_username', $values['smtp_username'])
  ->set('smtp_from', $values['smtp_from'])
  ->set('smtp_fromname', $values['smtp_fromname'])
  ->set('smtp_allowhtml', $values['smtp_allowhtml'])
  ->set('smtp_debugging', $values['smtp_debugging'])
  ->save();

// If an address was given, send a test e-mail message.
if ($test_address = $values['smtp_test_address']) {
  $params['subject'] = t('Drupal SMTP test e-mail');
  $params['body'] = array(t('If you receive this message it means your site is capable of using SMTP to send e-mail.'));
  $account = \Drupal::currentUser();
  // If module is off, send the test message with SMTP by temporarily overriding.
  if (!$config->get('smtp_on')) {
    $original = $mail_config->get('interface');
    $mail_system['default'] = 'SMTPMailSystem';
    $mail_config->set('interface', $mail_system)->save();
  }
  \Drupal::service('plugin.manager.mail')->mail('smtp', 'smtp-test', $test_address, $account->getPreferredLangcode(), $params);
  if (!$config->get('smtp_on')) {
    $mail_config->set('interface', $original)->save();
  }
  drupal_set_message(t('A test e-mail has been sent to @email via SMTP. You may want to check the log for any error messages.', ['@email' => $test_address]));
}

```

This code is not working, since in the log set with the `mail.log` directive I see the following, where it is evident that Drupal is still using the mail plugin definined in PhpMail.php.

> \[11-Mar-2016 06:36:14 UTC\] mail() on \[/home/domain/public\_html/core/lib/Drupal/Core/Mail/Plugin/Mail/PhpMail.php:101\]: To: edited@email.org -- Headers: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes Content-Transfer-Encoding: 8Bit X-Mailer: Drupal Sender: edited@email.org From: Edited `<edited@email.org>`

I cleared the log before sending the test email from the administrative page of the *SMTP Authentication Support* module; so, I am sure the log is caused from sending the test email.

Since the method used from this module doesn't seem to work, what is the correct way to set the plugin Drupal uses to send emails?

### Update

To make my question clearer, there are two things that are not clear to me in the code being used.

1. The code is setting the mail plugin Drupal should use, just for the test email, but as I can see that method doesn't work, since Drupal still uses the default plugin.
2. Apart from setting the mail plugin for the test email, the module doesn't change the mail plugin set by Drupal. How can Drupal know to use the mail plugin implemented by the module, then?

# Answer
Basing on Mail backends are now annotated plugins, drupal\_mail\_service() has been removed and the documentation for the `MailManagerInterface` interface, a module implementing a mail plugin should not set its own plugin as default plugin because `MailManagerInterface` interface doesn't document any configuration key the classes implementing it should use; only the site maintainer eventually know which mail manager is being used, and which configuration keys that mail manager is using. This is similar to setting the cache handlers, which is done in the settings.php file.

The *SMTP Authentication* module is doing the correct thing when it doesn't set its plugin as default plugin for sending emails.

As for the code to send a test email, the correct one should not directly set the configuration keys, if it wants to be independent from the current implementation of the mail manager. Eventually, code similar to the following should be used.

```
$mailer = \Drupal::service('plugin.manager.mail')->createInstance($plugin_id);
$bool = $mailer->send($mailer->format($message));

```
> 0 votes

---
Tags: emails, plugins
---


# Question
Title: Simplest way to create a Commerce shopping cart icon showing the number of items
I'm looking for the simplest way to implement something similar to Amazon's shopping cart icon which shows the number of items in the cart, which then links to the cart:

I've found several options through browsing various support requests etc, most of which are at least 3 years old and sound surprisingly complex in terms of overheads relying on many features (e.g. this suggestion from 2012 of creating an entire custom Views view to generate one number and one static link).

Obviously, the icon is the easy part, can be done in CSS very easily, it's the number of line items that I'm most interested in. Particularly having it integrated such that it updates when a new item is added to the cart.

I thought this would be something Commerce would do out of the box, or with an add-on module, but if it is I can't find it.

Is there any simple way?

# Answer
The way I would do it, is that I would make the total number of products in the shopping cart available in the `page.tpl.php` file, and print it there directly.

Here's example code:

```
function YOUR_THEME_preprocess_page(&$variables) {
  $cart_count = 0;
  $order = commerce_cart_order_load($variables['user']->uid);
  if ($order) {
    $wrapper    = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $cart_count = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
  }
  // Make the number of products in the shopping cart available to our template.
  $variables['products_in_shopping_cart'] = $cart_count;
}

```

Then in your `page.tpl.php` you would use this code to show the number of products in current user's cart:

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

```

Note: second argument passed to the `commerce_line_items_quantity()` is updated per Clive's note.
> 4 votes

---
Tags: 7, commerce
---


# Question
Title: Webform, rename files to a constant name and bypass validation
I have a webform where users can upload one pdf file. I'd like to have this pdf file always the same name *foo.pdf*.

To avoid conflicts I save each upload to a different directory with the pattern *foo/\[random:hash:md5\]*.

When trying to save these settings I get the error message *To create unique file names, use at least one token in the file name pattern.* I understand that this error makes sense to avoid naming conflicts but the conflicts should be avoided with the custom directory.

Is there a way to bypass the validation check?

**Edit:** For clarification. I need to *bypass* the validation check in the settings page for the field of the file upload not the validation for the form submission itself

# Answer
By looking at the source in `/components/file.inc` (in Webform module), you will see that the Webform declares a custom element validation callback that performs the check you want to avoid. In order to override this, you will have to hook into the settings form, and provide your own callback for this element.

Below is the code you would use to achieve that. Pay attention to the comments.

```
function YOUR_MODULE_form_webform_component_edit_form_alter(&$form, &$form_state) {
  // Override the element validation callback for renaming the file uploads.
  if (isset($form['extra']['rename'])) {
    // Loop through the validation callbacks and remove the one we want to
    // override. This way we will not affect any other module that alters this
    // part of the form.
    foreach ($form['extra']['rename']['#element_validate'] as $key => $validation_callback) {
      if ($validation_callback == '_webform_edit_file_rename_validate') {
        unset($form['extra']['rename']['#element_validate'][$key]);
      }
    }
    // Note: since the original validation callback provided in Webform module
    // only makes sure that the file names are unique, you don't need to provide
    // your own element validation callback. However, I would recommend doing so
    // just in case you have other webform nodes that will need this validation.
    //
    // Add our custom element validation callback.
    $form['extra']['rename']['#element_validate'][] = 'YOUR_MODULE_edit_file_rename_validate';
  }
}

function YOUR_MODULE_edit_file_rename_validate($element, &$form_state, $form) {
  // I recommend still limiting this only to specific nodes, content types, and
  // not disabling completely.
  if ($form['#node']->nid != YOUR_NODE_ID) {
    $rename = trim($form_state['values']['extra']['rename']);
    form_set_value($element, $rename, $form_state);
    if (strlen($rename) && !count(token_scan($rename))) {
      form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
    }
  }
}

```
> 1 votes

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


# Question
Title: Adding CSS and JS to form with attachments
I need to add some external and local CSS and JavaScript files to a form, but I can't seem to find the right way to do this. Do I simply add the paths and URLs for the JS and CSS files?

I assume `$form['#attached']['css'][]` and `$form['#attached']['js'][]` are the correct places to do this, so they get reloaded on form rebuilds. I seem to be missing something.

# Answer
> 73 votes
Have you looked at the documentation?

**Attach CSS and JS to form**

http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#attached

```
$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';

$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';

```

**External files**

http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_process\_attached/7

External 'js' and 'css' files can also be loaded. For example:

```
$build['#attached']['js']['http://code.jquery.com/jquery-1.4.2.min.js'] = array('type' => 'external');

```

# Answer
> 12 votes
Here's the method for adding *inline CSS* to forms...

```
$form['#attached']['css'][] = array(
  'data' => '.my-example-element { display: none; }',
  'type' => 'inline',
);

```

Note that you should *add* to the css array *rather than replace it*. Meaning you should use: `['css'][] =` rather than `['css'] =` to avoid squashing other additions.

# Answer
> 6 votes
Here is one way to do this that is via. calling a function using `#after_build` property. Just pass in your form id in switch case.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_form':
      $form['#after_build'][] = 'mymodule_after_build';
      break;
  }
}

function mymodule_after_build($form, &$form_state) {
  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js ("$path/mymodule.js");
  return $form;
}

```

Also you can follow this good tutorial Adding css and js to drupal forms

Hope this helps. :)

---
Tags: 7, forms
---


# Question
Title: Is there a wait-list functionality planned or already implemented?
I just took a first look on the RNG Module. In the Readme, it is called the successor of the Drupal Entity Registration Module.

Is there a wait-list functionality planned or already implemented? Maybe I'm not getting it right and its already implemented via Rules?

Any help would be welcome...

# Answer
There is no support for wait lists at this time, however the API has a tagging system not exposed via UI, which is designed to support a list systems.

I encourage you to take a look at RNG Ecosystem, and give some feedback on your requirements for wait lists.
> 0 votes

---
Tags: 8, rng
---


# Question
Title: Creating section with static image and text with dynamic link
I want to create a section with a static image and text but with a dynamic link and place it in one content type in Drupal 8. What would be the best way to approach this? Every approach seems to have some problem.

If I try using views to make a block and use the default values to populate the static content, the default value of the text field is not shown while default image and dynamic link are displayed.

Another approach I tried is to create a custom block, override its template with static images and text but getting the dynamic links to this block is a problem as I don't know how to access the current node fields in such block.

Is there any way to make the default value of a text field that we create in our content type to be printed through a view? Or in the alternative how would I access the node fields (specifically a link field) in a custom block?

Also, any other approach will be appreciated. I have no experience of working with the .theme file and don't really know the ins and outs of that.

# Answer
> 0 votes
Found a way around - To use it as a view with some static content, create a label for a field in the view and style in template file.

---
Tags: theming, nodes, 8, blocks
---


# Question
Title: Image preview thumbnail does not display
Drupal 7.

When adding a core image field to a content type to display an image, the preview thumbnail does not display on the edit page when uploading an image.

What appears after clicking on the "Upload" button is a placeholder for the image and an image icon. The placeholder then quickly disappears to leave the icon and the name of the file. It looks like the link is broken and the image cannot be found. However, the uploaded image and it's preview (thumbnail image style) are in the right folders. This is confirmed when the edit page is reloaded (browser refresh or a new visit to the page) because the preview image then displays properly on the edit page..

Clicking the Save button displays the image in the content.

However, if I do not click the Upload button and click on the Save button directly instead after selecting an image with the Browse button, the content image is not displayed either unless I click on the browser Refresh (or go to another page and come back.)

A few people have had this issue.

In this Youtube tutorial, the issue is reproduced (the thumbnail does not show up.) The instructor notices it but gives no solution: Drupal Tutorials #9 - Custom Content Types Part 2 Manage Display

Does anyone know what's going on and how to fix this?

Any and all help will be greatly appreciated. :)

# Answer
Try removing any space, empty line before

https://www.drupal.org/node/2195311

Hope this helps.
> 0 votes

---
Tags: 7, nodes, media
---


# Question
Title: Site shows themeless and blockless front page
I've installed a brand new Drupal 8 site (http://www.edcint.co.nz/tmp/drupal8\_problem\_new.PNG) with next to no configuration, default theme etc. I then ran Drupal Update against a Drupal 7 site (http://www.edcint.co.nz/tmp/drupal8\_problem\_existing.PNG). The content/users all came across but the front page shows without any theme or blocks, only the 3 articles/pages marked as "published to the front page" appear.

I've migrated another more simple Drupal 7 site to Drupal 8 and this did not happen.

Have I hit some limitation of the Upgrade module? How can I make the theme and blocks reappear on the front page?

# Answer
> 0 votes
I would check your watchdog logs (/admin/reports/dblog) after refreshing your homepage a few times.

This may give you some clues to what the problem is. For example...

I ran in to a similar issue with my D7 -\> D8 migration, where my nodes were imported with a 'filtered\_html' input\_format. I was storing my node body content as markdown.

My front page had no blocks or theme. When I looked in my logs, I was seeing `Missing text format: filtered_html.`

I ran the following to update the input\_format of my nodes, which fixed my problem.

`UPDATE `node__body` SET `body_format`='full_html' WHERE `body_format`='filtered_html';`

To then get things displaying properly, I installed the markdown module (and one of the required libraries, I opted for commonmark).

`drush en markdown
composer require league/commonmark`

I then went to `/admin/config/content/formats/manage/full_html` and enabled markdown for that content type.

---
Tags: 8, blocks
---


# Question
Title: Permanent Cookie Contains Sensitive Session Information
I have a cookie question in regards to a security scan (via IBM Rational AppScan) conducted on a drupal(7.43) site. The security scan failed with the following error: (Permanent Cookie Contains Sensitive Session Information) is POSITIVE on: http://site-name/user/login?ModPagespeed=noscript (cookie = SESSa020b17496f7fb76f92dd28c8d8341be).

How to resolve this?

# Answer
> 1 votes
Your app scanner is alerting you that cookie session data is being sent over an insecure channel (http://site-name/user/login?ModPagespeed=noscript) and is susceptible session hijacking.

One way to resolve this is to force your website to use HTTPS only, thus preventing anyone from sniffing out session data.

---
Tags: security
---


title: Multilevel Categories & Menu - How To?

text:
# Question
Title: Multilevel Categories & Menu - How To?
I would like to be able to create content of a particular type but be able to set multi-level categorisation. But I would like a menu where I can select a category and see all content including child categories as well.

e.g.

1. Fruit
    * Local
        + Apples
        + Pears
    * Tropical
        + Pineapple
        + Bananas

'Fruit' menu would show all fruit

'Local' Menu would show all local, apples and pears

'Apple' Menu would only show Apples

I am trying to achieve some thing like this side menu: http://learningexchange.ptc.com/tutorials/by\_product/ptc-creo/product\_id:1

# Answer
> 1 votes
There won't be a definite answer to this question as this can be achieved in a lot of possible ways. Depending on your knowledge in drupal you could start with the built-in drupal taxonomy system that enables you to classify your content as needed (e.g. with a tree-like-hierarchy or even related terms). To build the menu you can try the taxonomy menu module or use Views to create this manually.

For a start i recommend reading through this overview: https://www.drupal.org/documentation/modules/taxonomy

---
Tags: nodes
---


# Question
Title: Update existing field collections with Migrate module
How can I update existing field collection entities using Migrate module? I wasn't able to find any examples at the official documentation page, nor anywhere else.

When I'm migrating nodes, I can do something like:

```
$this->addFieldMapping('nid', 'nid');
$this->systemOfRecord = Migration::DESTINATION;

```

What's the alternative in this case?

# Answer
> 1 votes
There's no current support in field\_collection for this (a destination plugin must explicitly support Migration::DESTINATION, merging mapped fields with pre-existing values for the unmapped fields). I'd suggest submitting a feature request at https://www.drupal.org/project/issues/field\_collection.

---
Tags: migrations, entities
---


# Question
Title: During migration D6->D7 I get an error message "Integrity constraint violation"
I use Migrate and Migrate\_D2D in my process of migrating from D6 into D7 and I get this message for each an every node when using "MigrateFileUri":

```
    SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://instrument/instrumentbilder/63379742-s_1.jpg' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri … and so on…

```

The strange thing is that on another computer with the same development environment (WAMP) most of the nodes are imported without problem with exactly the same code. Something must be different though… Some mysql setting in WAMP maybe?

I have searched for the "duplicate files" in the table "file\_managed" and I can confirm that these files are not present in that table. So the duplication must happen during the import. For some reason the node must be saved twice?

I should mention that when importing all files in a separate migration and using MigrateFileFid as file class, there is no problem. The thing is that I need to use urlencode to clean file names and also I want to decide where different files from different node types are to be saved (different destination\_dir for different file types), and as far as I understand those options are not available with MigrateFilFid.

# Answer
> 0 votes
The error message indicates that your underlying database is having a problem. It looks like you've tried the migration multiple times, and that parts of it were successful previously. What the error message is stating is that you are attempting to insert duplicate records into the database, or at least duplicate keys for an existing record. You need to reset/empty the NEW database prior to running migrate and migrate\_d2d to remove the problem.

# Answer
> 0 votes
Also note that you can set file\_replace to MigrateFile::FILE\_EXISTS\_REUSE - with this setting, if the file already exists in file\_managed the migration will simply point to that existing file entity rather than attempt to create a new one. See the documentation at https://www.drupal.org/node/1540106.

---
Tags: migrations
---


# Question
Title: How to migrate tables in nodes from D6 to D7, created with the tablefield module
I am 90% done with my migration from D6 to D7. The last thing to figure out is how to map a table in certain nodes, created with the tablefield module in D6, into a table in D7, also created with tablefield. Just mapping the fields does not do the trick.

```
$this->addFieldMapping('field_D7_table', 'field_D6_table');

```

With the above mapping there are no error messages, the table is just empty after the migration. I can see that the data is stored in serialized form in the legacy database. Can anyone point me in the right direction?

# Answer
Tablefield does not currently include migration support - there is a patch to add it at https://www.drupal.org/node/2317245. If you try out the patch and report on your results there, you may help move it forward.
> 0 votes

---
Tags: 7, migrations
---


title: Put form labels left of the fields?

text:
# Question
Title: Put form labels left of the fields?
This is an age-old debate in Drupal, and I am surprised this has not been asked before on Drupal Answers. Maybe I missed it.

By default, Drupal form labels are always displayed at the top of form elements.

How can I display form element labels to the left (or right) of the element, instead of at the top?

I am talking about entity edit forms, but also other forms.

I am sure I will find a solution with hook\_form\_alter() or on the theme layer. But the question is, what is a convenient and maintainable way to do this?

I am personally working with Bootstrap theme, but a generic answer is preferable, so others can benefit too.

EDIT: It also would be nice to have an elegant way to control which forms this should apply to, and where it should not. Since I added this later, it should be considered optional.

## UX background

The main argument for labels at the top is that they are supposedly easier to read. E.g. here, http://www.wunderkraut.com/blog/why-top-aligned-labels-are-better-in-drupal-forms/2010-12-28

I personally think this is an answer to the wrong question. The form labels might be easier to read this way. But if you look at a pre-filled form, e.g. when editing an entity, then usually the field values are far more interesting than the labels. Often the labels are already evident from the field value. E.g. a street name looks like a street name. An email looks like an email.

And of course with labels on the side the form will look more compact and less cluttered, and more of it will fit "above the fold".

Another design option would be in-field labels. But with these, the label is completely gone when the field is filled out. You may still want the labels to make sure that every value is in the correct field.

So having labels on the side is a valid design goal..

# Answer
> 1 votes
As when it comes to theming stuff, you should always ask your self: Can I do this with CSS? The answer in this case is yes.

`label { float: left padding-right: 3px; }`

**Example**

OR (probably best to go with)

```
label { display: inline }
input { display: inline }

```

**Example 2**

You will need to add the css code to your **administration theme** .css file.

---
Tags: 7, forms, theming
---