# Question
Title: Why does Drush Make usually skip large sections of my .make file with no errors or explanation?
This felt like a bug to me, but I was told it was technical support, so I'm asking here.

Running Drush 6.2 on OSX Mavericks, drush make usually skips most of our .make file for some unknown reason. If we keep running the command, eventually it works. The only difference in the output is the missing section.

Linux users running the same command (with the same .make file) are not seeing the same issue.

The command we are issuing is: drush make --working-copy --no-core --no-cache -y -v --contrib-destination=. profilename.make

I don't feel like it's the .make file itself, because it works elsewhere.

Here's output with the --debug flag from a failed session (with the repo URL replaced), up to the point it checks out the first module.

```
Bootstrap to phase 0. [0 sec, 1.87 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 1.99 MB] [bootstrap]
Cache HIT cid: 6.2.0-commandfiles-0-b2a725c613aec072d6594b2001dc5c79 [0.01 sec, 2 MB]                                                [debug]
Bootstrap to phase 0. [0.05 sec, 5.25 MB]                                                                                [bootstrap]
Bootstrap to phase 0. [0.07 sec, 5.26 MB]                                                                                [bootstrap]
Found command: make (commandfile=make) [0.07 sec, 5.26 MB]                                                                       [bootstrap]
Loading release_info engine. [0.11 sec, 5.28 MB]                                                                                [notice]
Calling hook drush_make [0.11 sec, 5.38 MB]                                                                                [debug]
Make new site in the current directory? (y/n): y
Beginning to build profilename.make. [0.12 sec, 5.66 MB]                                                                     [ok]
Backend invoke: /usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off                       [command]
/usr/local/Cellar/drush/6.2.0/libexec/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2  make-process /tmp/make_tmp_1395944498_53346c3280189 2>&1 [0.23
sec, 6.17 MB]
/usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off                                        [notice]
/usr/local/Cellar/drush/6.2.0/libexec/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2  make-process /tmp/make_tmp_1395944498_53346c3280189 2>&1 [0.23
sec, 6.18 MB]
Bootstrap to phase 0. [0.35 sec, 5.25 MB]                                                                                [bootstrap]
Bootstrap to phase 0. [0.38 sec, 5.25 MB]                                                                                [bootstrap]
Found command: make-process (commandfile=make) [0.38 sec, 5.25 MB]                                                               [bootstrap]
Loading release_info engine. [0.42 sec, 5.26 MB]                                                                                [notice]
Calling hook drush_make_process [0.42 sec, 5.37 MB]                                                                                [debug]
Returned from hook drush_make_process [0.42 sec, 5.37 MB]                                                                            [debug]
Command dispatch complete [0.42 sec, 5.35 MB]                                                                                [notice]
Peak memory usage was 7.02 MB [0.42 sec, 5.34 MB]                                                                                [memory]
Cache MISS cid: 6.2.0-alias-path--0df1237dd975a845493d7a49d0e0a21f [0.42 sec, 5.34 MB]                                               [debug]
Undefined property: DrushMakeProject_Library::$type make.project.inc:147 [0.43 sec, 5.7 MB]                                         [notice]
Executing: svn --force checkout https://repo.example.com/repos/wms/vendor/contrib/7.x/libraries/CAS/tags/1.3.2 /tmp/make_tmp_1395944498_53346c3280189/__build__/libraries/CAS

```

Here's output with the --debug flag from a successful session (with the repo URL replaced), up to the point it checks out the first module. Again, all we have to do is keep running the same command on the same make file, and it eventually works.

```
Bootstrap to phase 0. [0 sec, 1.87 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 1.99 MB] [bootstrap]
Cache HIT cid: 6.2.0-commandfiles-0-b2a725c613aec072d6594b2001dc5c79 [0.01 sec, 2 MB]                                                [debug]
Bootstrap to phase 0. [0.05 sec, 5.25 MB]                                                                                [bootstrap]
Bootstrap to phase 0. [0.08 sec, 5.26 MB]                                                                                [bootstrap]
Found command: make (commandfile=make) [0.08 sec, 5.26 MB]                                                                       [bootstrap]
Loading release_info engine. [0.12 sec, 5.28 MB]                                                                                [notice]
Calling hook drush_make [0.12 sec, 5.38 MB]                                                                                [debug]
Make new site in the current directory? (y/n): y
Beginning to build profilename.make. [0.13 sec, 5.66 MB]                                                                     [ok]
Backend invoke: /usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off                       [command]
/usr/local/Cellar/drush/6.2.0/libexec/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2  make-process /tmp/make_tmp_1395944871_53346da723049 2>&1 [0.27
sec, 6.17 MB]
/usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off                                        [notice]
/usr/local/Cellar/drush/6.2.0/libexec/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2  make-process /tmp/make_tmp_1395944871_53346da723049 2>&1 [0.27
sec, 6.18 MB]
Bootstrap to phase 0. [0.43 sec, 6 MB]                                                                                [bootstrap]
Bootstrap to phase 0. [0.46 sec, 6 MB]                                                                                [bootstrap]
Found command: make-process (commandfile=make) [0.46 sec, 6 MB]                                                                  [bootstrap]
Loading release_info engine. [0.5 sec, 6.02 MB]                                                                                [notice]
Calling hook drush_make_process [0.5 sec, 6.12 MB]                                                                                [debug]
navigation404 svn --force checkout %s %s from                                                                                [ok]
https://repo.example.com/repos/wms/vendor/contrib/7.x/modules/navigation404/tags/7.x-1.0. [1.02 sec, 6.15 MB]

```

It then checks out all the modules the failed build missed.

Just as we get to the point where the failed build starts, in the successful build we see the same messages:

```
Returned from hook drush_make_process [200.02 sec, 7.01 MB]                                                                          [debug]
Command dispatch complete [200.02 sec, 6.99 MB]                                                                                [notice]
Peak memory usage was 7.71 MB [200.02 sec, 6.98 MB]                                                                                [memory]
Cache MISS cid: 6.2.0-alias-path--0df1237dd975a845493d7a49d0e0a21f [200.02 sec, 7 MB]                                                [debug]
Undefined property: DrushMakeProject_Library::$type make.project.inc:147 [200.05 sec, 5.97 MB]                                      [notice]
Executing: svn --force checkout https://repo.example.com/repos/wms/vendor/contrib/7.x/libraries/CAS/tags/1.3.2 /tmp/make_tmp_1395944871_53346da723049/__build__/libraries/CAS

```

Any ideas on how to make it succeed all the time? Any more info I can give?

**Edit:** here's a (URL-replaced) copy of the .make file.

# Answer
I kept coming back to this question while running Drush 6 on a mac. In the meantime it seems there is an answer on the original bug post: update to Drush 7 or greater. See: https://github.com/drush-ops/drush/issues/549#issuecomment-101353376 and https://github.com/drush-ops/drush/pull/1049 I'm doing fine now with Drush 8.0.1.
> 0 votes

---
Tags: drush
---


# Question
Title: How can I set a Feeds Importer to accept multiple values for a field?
I created a Feeds Importer for commerce products. One such product is an album which contains multiple mp3 files. So in the files field of the content type, this is set to unlimited.

but my feeds importer isn’t accepting multiple values. Ive tried using the the pipe char (|) but it’s not working.

my CSV looks like this. fyi - having one commerce mp3 file reference in the csv does work. but when adding another and separating w/ the pipe symbol, it does not.

How can this be achieved?

my csv file so far -

```
SKU,Title,Album cover front,Price,Files
SKU_ALB#8_CD_SOME_TITLE,http://staging.MYSITE.com/feeds/album_artwork/cd_cover_front.jpg,1000,private://albums/Killer Track.mp3|private://albums/Heavy Groove.mp3

```

# Answer
> 3 votes
Have a look at feeds tamper.

Using the pipe symbol is alright. The next step would be to enable Feeds Tamper and chose to "Explode" the "Files" with the pipe character as separator.

# Answer
> 2 votes
You need to use Feeds Tamper to take a single value and make it into an array. Examples: multiple columns to a single, multi-valued field or a whole node importer using it.

tl;dr - You're looking for the "explode" tamper plugin.

---
Tags: commerce, feeds
---


# Question
Title: How to add Google Maps data overlay to Openlayers map?
So, for data purposes I want to use OpenLayers for my maps presentation but I want to use Google Maps as my data overlay or base layer. I know this is possible, but the UI isn't exactly friendly to new users.

As always, any advice is appreciated.

# Answer
If you find OpenLayers for Drupal too daunting you could have a look at https://www.drupal.org/project/leaflet. It's easier to configure and more lightweight.

As for OpenLayers:

1. Create a view that provides an OpenLayers Data Overlay Display.
2. Then you may want to checkout: "admin/structure/openlayers/layers" and configure a Google Maps layer.
3. Then create a map over here "admin/structure/openlayers/maps". Make sure you enable your Google Maps layer as base and your Views Data Overlay as the Overlay for this map.
4. If you want to "show" the map also with Views create a new display (not an overlay) and use the OpenLayers Map formatter. You can then select your OL map created in step 3.
> 1 votes

---
Tags: google-maps, javascript
---


# Question
Title: How to configure or style an Openlayers source?
I'm just getting started with Drupal Openlayers. I've created a simple map consisting of one views geojson view. What I want to know is how to customize the display of the layer, such as the type of marker for the points, etc. I'm just not sure where these setting are.

Any advice would be appreciated.

# Answer
You won't find any options in Views to customize the display. Have a look under "admin/structure/openlayers". Markers are defined under "styles" -\> admin/structure/openlayers/styles.
> 1 votes

---
Tags: views, javascript
---


# Question
Title: Ability to separate between levels in vocabulary hierarchy
In the frontend visualisation of vocabularies, is One in Drupal able to specify from which level in the vocabulary hierarchy one should display terms from?

If yes, how do you do this?

Thanks,

Espen

# Answer
> 0 votes
Yes, you could use a module like taxonomy\_menu to show a list of taxonomy terms.

Alternatively, you could use a code solution like `taxonomy_get_tree` that allows selecting terms by parent tid and depth.

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


# Question
Title: Unable to collect end date after field is saved
I've been running a d7 site for a couple months and one of the content types has a date field. Initially I opted not to collect and end date but the need for it has arisen. As you may know, there's a design decision in d7's field api that forbids you from changing field settings after it's been saved.

The problem is that I have a very considerable amount of data on a fairly live site, which means it's extremely hairy to do something like deleting the field and then somehow herding all the data back in. Has anyone ran into this? How did you solve it? Any insight at all? Thank you :)

# Answer
When I did this, I created a new date field and set it as hidden on the page. I configured it the way I wanted, then duplicated the existing information in the new field, manipulating the database directly. As you will have two date values (...\_value and ...\_value2) you should begin by setting them the same.

Once you are sure that the correct values are in place, you must then change all your views, rules etc that use the date field to use the new field.

Then set the new field to display and hide the old field. Make sure everything is working before you delete the old field.

There is no short cut that I am aware of. Best to do all this on a copy, with extensive backups. Good luck.
> 3 votes

# Answer
I use a different approach. I:

* back up my database table for my field, for example field\_data\_field\_event\_date. Back up entire database as well for good measure.
* Delete my field from the field manager (admin/structure/types/manage/yourcontenttype/fields).
* Add field back with field manager, using exactly the same machine name (field\_event\_date in my example).
* set the field settings to allow you to collect an end date.
* import your field table backup file into the field\_data\_field\_event\_date table. This brings back your previous date values.
* Now try and edit a content item. You should be able to edit the date and provide an end date too.
> 2 votes

# Answer
The easiest way, if you don't mind patching, is to review the patch in the following Date module issue: https://www.drupal.org/node/2581013

The patch unlocks the "Collect End Date" option when there is already data in the field and allows you to change it.
> 1 votes

# Answer
I once wrote an update script that converted a date field from using only a start date to collect both a start and an end date. Here it is as a sample. Be warned, I haven't looked at this sample in 3 years, so review with caution. Basically, delete the field in your local dev environment, then recreate it and export it using the Features module. Once that's done, push your code to your dev/stage/prod environments. This update hook will save all the values for a given date field to a variable, delete the field, recreate it using the Features module, then re-add the saved data. This might fail with enormous data sets as it doesn't make use of the batch API (a large data set might cause a PHP to run out of memory and error).

```
/**
* The following was used as in an update hook to convert a date field from using
* a single date value to a date field that uses both begin and end dates.
* The date field in question here was for an "event" content type
*
*/
function hook_update_700X(&$s){

//Get the current event date field data
$query = db_select('node', 'n');
$query->condition('n.type', 'event', '=')
    ->fields('n', array('nid'));

$result = $query->execute();

//Save the dates
$dates = array();
foreach ($result as $row) {
    $node = node_load($row->nid);
    $dates[$node->nid] = $node->field_date;
}

//Delete the field, this destroys data
field_delete_field('field_date');
field_purge_batch(5);//5 Should cover this field and any others to be purged (which is probably 0)

//Create new date formats, we are moving away from regenerating the dates in the views templates
$formats = array(
    array(
        'type'    => 'date_selector_class',
        'format'  => 'm-Y',
    ),
    array(
        'type'    => 'event_selector',
        'format'  => 'l, F j',
    ),
 );

 foreach ($formats as $format) {
     variable_set('date_format_' . $format['type'], $format['format']);
 }

//Use features to recreate the field with the end date option
features_revert(array('cloud_events' => array('field')));

$counter = 0;

 //Set the dates, use the start date for the end date for now.
foreach ($dates as $nid => $date) {
    $counter++;
    $node = node_load($nid);
    error_log('Repopulating node '.$node->nid,0);
    $node->field_date = $date;
    $node->field_date[$node->language][0]['value2'] = $date[$node->language][0]['value'];
    node_save($node);
}

return $counter . " Events updated.";

}

```
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Views Exposed Filters: how to get functionality shown in this image?
I'm wondering how hard it would be to get the functionality shown in the image, and at the associated webpage, with Views Exposed Filters. How would you go about it? Thanks in advance!

I notice 3 main things:

1. Entering text in the autocomplete search box causes the select list options to filter. (The matching letters are also underlined, which is fancy but not necessary.)
2. Selecting an option causes it to fill the search box.
3. A number after each select list option tells the user how many pieces of content are available.

The actual search box can be seen on this webpage: https://properties.aplaceinthesun.com/AP1724897/Beautifully-Maintained-Four-Bedroom-Villa-For-Sale

# Answer
> 1 votes
You would need to configure the Select2 or Chosen JQuery component to do this.

Create the list of object with count and apply the one of the above library.

For Drupal use Select2 module

# Answer
> 1 votes
Chosen

> By default the module will automatically apply itself to any select elements that have more than 20 options, which is a reasonable default for which having Chosen will be useful. To change or disable this automatic enhancement, you can change the selectors (or remove all selectors) from the Apply Chosen to the following elements field on the Chosen administration page.

---
Tags: 7, views
---


# Question
Title: Updating a drush command from drush 7 to drush 8
what to do if there is a drush command file worked with drush 7 but doesn't work with drush 8. The official docs seem not to have an upgrade guide for this.

# Answer
> 1 votes
Drush makes an attempt to never run any code associated with a module or theme unless that module or theme is enabled. This protection is often more conservative than necessary, as some Drush extensions do not exercise any code that requires a Drupal bootstrap.

None the less, Drush 8 is more rigorous than Drush 7 was. Drush 7 would search for extensions in all of the theme folders regardless of whether the corresponding themes were enabled. Drush 8, on the other hand, ignores extensions stored with disabled themes.

Include paths provided specifically via the --include option are always searched, though; Drush makes no attempt to determine if the specified path happens to correspond to a disabled theme. This is why the workaround you found works.

---
Tags: drush
---


title: Block Regions in node.html.twig

text:
# Question
Title: Block Regions in node.html.twig
How can i use block regions in my node.html.twig in drupal 8 ?

i tried this :

```
block_get_blocks_by_region

```

but function not found

# Answer
Fixed by adding this function to my theme

```
function YOURTHEME_preprocess_node(&$variables) {

$block = \Drupal\block\Entity\Block::load('views_block__sidebar_meetings_group_page');
$variables['block_output'] = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);

}

```

thanks @ivan jaros and @berdir
> 1 votes

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


# Question
Title: After every cron job, the Media tags in WYSIWYG markup change to https upon a robot crawl
My site doesn't use https certificates.

The Media WYSIWYG markup changes the images protocol and caches them as https and therefore they don't display as there is no certificate on the website!!

The only thing I could do is re-save the affected pages if I spot them and then it's all good until another robot crawls them again in https after a cron job, which will revert the Media WYSIWYG markup from http to https and we are back to square one.

What is the solution for this?

Can the Pathologic module solve this?

# Answer
If you don't want HTTPS, simply turn it off. And if, for some reason, you want HTTPS links to still work, you should redirect HTTPS to HTTP \- but that's out of scope of this site. Just **never leave https on without proper certificate**.

That said, you have some serious bug in your caching configuration, and data you provided is not enough to identify it. Luckily, there is no need to do so.
> 3 votes

# Answer
While you could try rewriting images to HTTP, perhaps easiest to add a free valid SSL certificate from Let's Encrypt.
> 1 votes

---
Tags: theming, media, cron, wysiwyg, input-formats
---


title: Add fields to feeds importer

text:
# Question
Title: Add fields to feeds importer
I want to import the fields "alt", "title" and the custom field "copyright\_notice" via feeds using the following code:

```
function budg_eu_projects_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {

    $info = field_info_field($name);

    if ($info['type'] == 'file') {
      $targets[$name . ':alt'] = array(
        'name' => t('@label: Alt', array('@label' => $instance['label'])),
        'callback' => 'budg_eu_projects_set_target',
        'description' => t('The alt tag of the @label field.', array('@label' => $instance['label'])),
        'real_target' => $name,
      );
      $targets[$name . ':title'] = array(
        'name' => t('@label: Title', array('@label' => $instance['label'])),
        'callback' => 'budg_eu_projects_set_target',
        'description' => t('The title of the @label field.', array('@label' => $instance['label'])),
        'real_target' => $name,
      );
      $targets[$name . ':copyright_notice'] = array(
        'name' => t('@label: Copyright Notice', array('@label' => $instance['label'])),
        'callback' => 'budg_eu_projects_set_target',
        'description' => t('The title of the @label field.', array('@label' => $instance['label'])),
        'real_target' => $name,
      );
    }
  }

  return $targets;
}

```

As a callback function I use

```
/**
 * Callback for mapping file fields.
 */
function budg_eu_projects_set_target(FeedsSource $source, $entity, $target, array $values) {

  list($field_name, $sub_field) = explode(':', $target . ':uri');
  $info = field_info_field($field_name);

  // Populate entity.
  $field = isset($entity->$field_name) ? $entity->$field_name : array(LANGUAGE_NONE => array());
  $delta = 0;

  foreach ($values as $v) {
    if ($info['cardinality'] == $delta) {
      break;
    }

    if (!isset($field[LANGUAGE_NONE][$delta])) {
      $field[LANGUAGE_NONE][$delta] = array();
    }

    $field[LANGUAGE_NONE][$delta][$sub_field] = $v;

    $delta++;
  }

  $entity->$field_name = $field;
}

```

I managed to add the fields as a mapping target but the data of the fields are not saved. What is missing?

Thanks Rainer

# Answer
> 1 votes
AFAICT the code you've posted *will* populate the entity with the values from the CSV file - but nothing's set up to persist those values. The Field API itself can persist values it knows about. Look at `file_field_schema()`

```
/**
 * Implements hook_field_schema().
 */
function file_field_schema($field) {
  return array(
    'columns' => array(
      'fid' => array(
        'description' => 'The {file_managed}.fid being referenced in this field.',
        ...
      ),
      'display' => array(
        'description' => 'Flag to control whether this file should be displayed when viewing content.',
        ...
      ),
      'description' => array(
        'description' => 'A description of the file.',
        ...
      ),
    ),
    ...
  );
}

```

Through this, the Field API knows to store the file ID, whether or not to show the file when viewing content, and a description of the file. Image field is very close to file field, and shares mostly the same code. And looking at `image_field_schema()` you can see where the title and alt fields come from.

```
/**
 * Implements hook_field_schema().
 */
function image_field_schema($field) {
  return array(
    'columns' => array(
      'fid' => array(
        'description' => 'The {file_managed}.fid being referenced in this field.',
        ...
      ),
      'alt' => array(
        'description' => "Alternative image text, for the image's 'alt' attribute.",
        ...
      ),
      'title' => array(
        'description' => "Image title text, for the image's 'title' attribute.",
        ...
      ),
      'width' => array(
        'description' => 'The width of the image in pixels.',
        ...
      ),
      'height' => array(
        'description' => 'The height of the image in pixels.',
        ...
      ),
    ),
    ...
  );
}

```

I think the right way forwards depends on your data model. In the example below there are two nodes with file fields, each referring to the same file. Note that they can have different `alt` and `title` fields even though they're referring to the same file.

```
Node 1:
  file_field:
    fid: 1
    alt: A beautiful beach
    title: Wish you were here?

Node 2:
  file_field:
    fid: 1
    alt: Great swimming
    title: Fun for all the family

```

The alternative I suggested in a comment was to add the fields to the entity itself.

```
File 1:
  alt: A beautiful beach
  title: Wish you were here?

Node 1:
  file_field:
    fid: 1

Node 2:
  file_field:
    fid: 1

```

This means the `alt` and `title` will always be the same for a given file. It's obviously for you to decide which model meets your needs more appropriately. If you want to store the data per-field (the first example) you have two choices:

1. Use an existing field and alter its schema with `hook_schema_alter()` \- a bit painful as there's no `hook_field_schema_alter()`. **Only do this if conceptually *every* instance of this field should have that extra data.**
2. (I'd prefer this personally) Create a new field that stores the extra columns you're interested in. Image field is the perfect place to look for inspiration, because its functionality's based on file field and it has extra columns.

If you want to store the data per file entity, then you can use fieldable files and I'm fairly sure you should be able to set everything up through the feeds UI. (IE no need for the feeds code above.)

---
Tags: 7, files, feeds, importing-exporting
---


# Question
Title: How to implement and install Icomoon and Fontello icon packs in Drupal 7?
**I am trying to get Fontello and Icomoon icon packs installed properly.**

I look in the backend and it says import for Fontello and Icomoon.

I have downloaded the packages, but importing creates an error.

I have manually downloaded and extracted them, put them in my libraries and:

```
Renamed folder: Fontello

```

And

```
Renammed folder:  Icomoon

```

But not found under status report, not even as missing. I have installed the Icon API module and enabled it.

Additionally, Fontawesome installed correctly and is showing ok in status report but it stil shows this error:

```
The Font Awesome library could not be found.Please make sure that     fontawesome was download & extracted at sites/all/libraries/fontawesome directory.Please check README.txt for more details.

```

# Answer
Ok, got it figured out.

1. Go to Fontello website.
2. Drag and drop Icons you need in the box on top.
3. Save file as Zipped, don't do any renaming or extracting.
4. Go to admin/config/media/icon/import
5. Give it a title and import the zipped file you just downloaded.

The icons will then show up on the drop down when adding them to articles or wherever.

Additionally, the help files for Fontello are here.
> 2 votes

# Answer
Are you using the Icon API modules for Fontello and Icomoon? This should be easy to set up.

First you install Icon API module, then the provider modules (linked above). Then you go the respective websites (http://www.fontello.com/ and/or https://icomoon.io) and select the icons you need for your project. Basically you create an own "font" with this selection and download it as an archive. Which is the one you upload in the import dialog of the Icon API configuration page (admin/config/media/icon).
> 0 votes

---
Tags: theming
---


title: Referencing another node's field values

text:
# Question
Title: Referencing another node's field values
I have created a "Customer" node-type. In that, I have a multi-valued field "Addresses" for taking customer's address.

I have another node-type "Order". While creating a new "Order", I want to select the customer from my existing customers. I can do this using entity or node reference. Now, while selecting the customer, I also want to select the customer's address which is present in the "Customer" node-type.

So, how do I do this? How do I reference another node's field values?

Or, is there any other way for this use-case?

# Answer
Entity Reference Autofill does exactly what you want.

> > The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: Hide admin email address in user's from field (Webform)
I am using the Webform module. So far the user can send an email via a form to my admin email.

However when I reply to the user my admin email address shows in their 'from' field! - How do I hide that to the site's name (but still pointing to my admin email address)?

# Answer
After saving the new component, visit the emails tab. Select the newly created component from the "Component value" select list and select add. The final results will look similar to this.
> 0 votes

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


# Question
Title: How to override code of module in custom module?
I am using Content Taxonomy module and trying to override some code, when I tried to modify in my custom module then the module functions also keeps running. And by modifying module file my purpose get solved but is there any way to do it in my custom module, please suggest:

CODE NEED TO MODIFIED:

```
/**
 * Form element validate handler for taxonomy term autocomplete element, which denies any new terms.
 */
function content_taxonomy_autocomplete_validate_deny_new_terms($element, &$form_state, $form) {
  $values = $form_state['values'];
  foreach ($element['#array_parents'] as $parent) {
    $values = $values[$parent];
  }
  foreach ($values as $delta => $value) {
    if ($value['tid'] == 'autocreate') {
      form_error($element, t('%name: new terms are not allowed. Please choose from the given list.', array('%name' => $element['#title'])));
    }
  }
}

```

DOING LIKE BELOW:

```
function custom_overrides_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  // Add validation function to taxonomy_autocompletes, if necessary.
  $instances = field_info_instances($form['#entity_type'], $form['#bundle']);
  foreach ($instances as $instance) {
    if (($instance['widget']['type'] == 'taxonomy_autocomplete' || $instance['widget']['type'] == 'autocomplete_deluxe_taxonomy')
      && isset($form[$instance['field_name']])
      && isset($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'])) {

      // Use the language that is used in this form (which doesn't necessarily
      // be the default language in $langcode).
      $lang_key = $form[$instance['field_name']]['#language'];
      if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'moderate') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'content_taxonomy_autocomplete_validate_moderate_new_terms';
      }
      else if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'deny') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'custom_content_taxonomy_autocomplete_validate_deny_new_terms';
        var_dump($form[$instance['field_name']]);
      }
    }
  }
}

/**
 * Form element validate handler for taxonomy term autocomplete element, which denies any new terms.
 */
function custom_content_taxonomy_autocomplete_validate_deny_new_terms($element, &$form_state, $form) {
  global $user;
       if($element['#title'] == "Topic"){
          if (!$user->uid) {
                $values = $form_state['values'];
                foreach ($element['#array_parents'] as $parent) {
                  $values = $values[$parent];
                }
                foreach ($values as $delta => $value) {
                  if ($value['tid'] == 'autocreate') {
                     form_error($element, t('%name: new terms are not allowed. Please choose from the given list.', array('%name' => $element['#title'])));
                  }
                }
            }
      }else{
            $values = $form_state['values'];
            foreach ($element['#array_parents'] as $parent) {
              $values = $values[$parent];
            }
            foreach ($values as $delta => $value) {
              if ($value['tid'] == 'autocreate') {
                form_error($element, t('%name: new terms are not allowed. Please choose from the given list.', array('%name' => $element['#title'])));
              }
            }
      }
 }

```

By Doing this now I have my custom validator running and my custom module weight is 1000 and contrib module weight is 0 but still its not working because I think second validator function as shown below in output of var\_dump need to be unset by some way:

```
'#element_validate' =>
        array (size=3)
          0 => string 'taxonomy_autocomplete_validate' (length=30)
          1 => string 'content_taxonomy_autocomplete_validate_deny_new_terms' (length=53)
          2 => string 'custom_content_taxonomy_autocomplete_validate_deny_new_terms' (length=60)

```

# Answer
In addition to Shabir A. you can also unset the original validation function.

For this, your module needs to run after the contrib module. You can achieve this by altering your module's weight.

```
/**
 * Implements hook_field_attach_form().
 */
function YOUR_MODULE_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  // Add validation function to taxonomy_autocompletes, if necessary.
  $instances = field_info_instances($form['#entity_type'], $form['#bundle']);
  foreach ($instances as $instance) {
    if (($instance['widget']['type'] == 'taxonomy_autocomplete' || $instance['widget']['type'] == 'autocomplete_deluxe_taxonomy')
      && isset($form[$instance['field_name']])
      && isset($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'])) {

      // Use the language that is used in this form (which doesn't necessarily
      // be the default language in $langcode).
      $lang_key = $form[$instance['field_name']]['#language'];
      if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'moderate') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'content_taxonomy_autocomplete_validate_moderate_new_terms';
      }
      else if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'deny') {
        // Loop through existing validation functions.
        foreach ($form[$instance['field_name']][$lang_key]['#element_validate'] as $key => $val) {
          // If we find the old one, unset it.
          if ($val == 'content_taxonomy_autocomplete_validate_deny_new_terms') {
            unset($form[$instance['field_name']][$lang_key]['#element_validate'][$key]);
          }
        }

        // Add your own validation function.
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'YOUR_VALIDATION_FUNCTION';
      }
    }
  }
}

```
> 1 votes

# Answer
You can use hook\_field\_attach\_form(). function much like it has been done in content\_taxonomy\_autocomplete module and replace the validate function to the one you want.

```
function MODULENAME_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
 // Add validation function to taxonomy_autocompletes, if necessary.
  $instances = field_info_instances($form['#entity_type'], $form['#bundle']);
  foreach ($instances as $instance) {
    if (($instance['widget']['type'] == 'taxonomy_autocomplete' || $instance['widget']['type'] == 'autocomplete_deluxe_taxonomy')
      && isset($form[$instance['field_name']])
      && isset($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'])) {

      // Use the language that is used in this form (which doesn't necessarily
      // be the default language in $langcode).
      $lang_key = $form[$instance['field_name']]['#language'];
      if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'moderate') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'content_taxonomy_autocomplete_validate_moderate_new_terms';
      }
      else if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'deny') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'YOUR_NEW_VALIDATOR_NAME';
      }
    }
  }

}

// add your validater function here

```
> 1 votes

---
Tags: 7
---


# Question
Title: Is it possible to create a menu item with first argument as wildcard?
I have created a menu item using hook\_menu() with the following structure.Unfortunately, when i access the given link, it returns not found error? Can anyone give a solution for this?

```
$items['%/doctors/department/%/%'] = array(
  'title'=>'Search a Doctor by Department  - Thumbay Hospital',
  'page arguments' => array(0,3,4),
  'page callback'=>'location_find_doctor_by_dept',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

```

# Answer
> 2 votes
From the `hook_menu()` docs:

> Note that wildcards may not be used as the first component.

So by design, no, it's not possible.

---
Tags: routes
---


# Question
Title: Create View with 2 rows of diferent Content
Can someone help me on whow can i create a View Like This? I Found this view a a theme template at http://demo.megadrupal.com/?theme=md-thenews .

This view is composed by 2 rows. The first one has an image, a title and a teaser and the other rows has a list of articles. I've also tried the views\_field\_view plugin, but the output is not the same. Thanks for you help.

Code behind the view in the image:

```
<div class="view view-category-news view-id-category_news view-display-id-block_1
 view-dom-id-9b65677b6b3b4229321f21719157d144 view-content">
  <div class="rows-first rows-inner row">
        .... //Views Fields
  </div>
  <div class="rows-others rows-inner">
    .... //Views Fields
  </div>
</div

```

# Answer
Views Node Split module does what you are trying to achieve.

> This module allows site administrators or builders to have a different view mode for the first nodes of a view result
> 2 votes

---
Tags: views
---


title: Redirect to "Access denied" page?

text:
# Question
Title: Redirect to "Access denied" page?
Is there a path with which I can call the "Access denied" page?

I'm trying to implement a rule that redirects to such a page because I want to prevent users and search robots from visiting certain nodes.

This is for Drupal 6.

# Answer
> 3 votes
If you simply need to add some logic to prevent nodes from being viewed on their own, there are a few well-known solutions. If you search here, you will find the various options.

After trying a few different methods, using the Rabbit Hole module is my new preferred solution. One, you don't need to roll your own solution in a custom module anymore. Two, the configuration is rather flexible and supports multiple behaviors within a single site. I don't see myself going back the method I used to promote.

# Answer
> 6 votes
You don't need to redirect to any page; you can produce the access denied page by calling drupal\_access\_denied().

# Answer
> 0 votes
You can create your own action in hook\_rules\_action\_info() Here is sample what you can do in your\_module.rules.inc file.

```
/**
 * @file your_module.rules.inc
 * Contains custom code for Rules module.
 */
/**
 * Implements hook_rules_action_info().
 */
function your_module_rules_action_info() {
  return array(
    '_your_module_access_denied' => array(
      'label' => t('Access Denied'),
      'group' => t('Nodeex Rules'),
    ),
  );
}
/**
 * Rule action _your_module_access_denied.
 */
function _your_module_access_denied() {
  return drupal_access_denied();
}

```

---
Tags: rules, users
---


# Question
Title: How to make billing cycles available as product attributes?
On our current billing system (from which we are trying to switch to Drupal Commerce) customers can select a product and then easily select between monthly, quarterly and yearly payment periods. In other words, billing cycles can be selected as product attributes.

And I can't figure out how to make billing cycles available as product attributes on a DC setup. According to the instructions on Commerce License Billing products are bound to billing cycle types. Does that mean I have to create three different products (for each monthly, quarterly and yearly billing cycles) for every single good or service product we offer on our website to customers? Doesn't make much sense for websites selling tens different types of services. I would appreciate if someone could point me to the right direction of configuring this.

# Answer
> 1 votes
Yes, you need to create different products that are linked to the billing license configurations you want. This means that if you want monthly, quarterly, and yearly billing options, these would each be tied to products and then available via a dropdown.

---
Tags: commerce
---


# Question
Title: Get content types field in another content type with the entity reference relationship
I have two content types. Person and Projects. I use a entity reference for the persons name on the project node so people can select the person that is involved in the project. Now using that reference I also want to get another field from the persons content type, and display this. I can't figure out how to do this. I thought I could do it with a views. I created a view with a relationship and filter with NID but it just doesn't seem to work. Whats the simplest way (view or not) to do this?

# Answer
With Entity Reference Autofill You can achieve something like you specified.

> > The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to add Tags to images being uploaded?
Is there a way to add tags to uploaded images (stored in vocabulary under *admin/structure/taxonomy/tags/edit*)

There is just alt and title fields as default at the moment....

I want users to add/ search tags that relate to images and not nodes (e.g. term reference)

I have found this module Taxonomy Images but it stops at D6 and I have D7

Ideally I would like something like this:

# Answer
> 4 votes
You can use a combination of the modules File Entity and File Entity Inline. File Entity will allow you to add fields to different file types, including images, and File Entity Inline will display all those added fields after clicking "Upload" whenever a user creates or edits content.

In order to make this work with Multiupload Imagefield Widget, you will need to apply two patches, one patch to multiupload\_imagefield\_widget.module, and one patch to file\_entity\_inline.module.

These patches are simple enough that they can be applied manually.

1. First install the modules File Entity and File Entity Inline. Go to Structure \> File types \> Image \> Manage field and add the Term Reference field you want and any other fields you desire for the Image file
2. Apply the patches. For the sake of convenience I'm pasting below the lines that need to be replaced.

In the directory where your drupal installation lives in the server, find the file `multiupload_imagefield_widget.module`, usually located under the path sites/all/modules/multiupload\_imagefield\_widget. Add the following lines at the very end of the file:

```
/**
 * Implements hook_file_entity_inline_widgets().
 */
function multiupload_imagefield_widget_file_entity_inline_widgets() {
  $widgets = array();
  $widgets['image_miw'] = array(
    'element_type' => 'mfw_managed_file',
  );
  return $widgets;
}

```

Save.

Then find the file `file_entity_inline.module`, usually in the path sites/all/modules/file\_entity\_inline/. Find the line:

`if (empty($element['fid']['#value']) || !isset($element['#entity_type']) || !isset($element['#field_name'])) {`

and replace it for:

`if (empty($element['#value']['fid']) || !isset($element['#entity_type']) || !isset($element['#field_name'])) {`

and find the line:

`$file = !empty($element['#file']) ? $element['#file'] : file_load($element['fid']['#value']);`

and replace it for:

`$file = !empty($element['#file']) ? $element['#file'] : file_load($element['#value']['fid']);`

Save.

Go back to your site, clear the cache. Then you should be good to go. Be sure to select `Multiupload` as the widget for the Image field. After selecting the files and clicking Upload, the page will show thumbnails for each file and whatever fields you have added to the image file entity in step 1.

ONE BIG CAVEAT: If you ever install an update or upgrade for either patched module, you will lose your patches, unless they are "committed" to the new module versions. The maintainers of both modules seem to be dragging their feet committing these patches. Multiupload Imagefield Widget has had two new versions without this patch being committed. File Entity Inline hasn't been updated in at least 3 years...

# Answer
> 0 votes
Try using field collections, create a field collection with Image field and Taxonomy Term field and use it instead in the content type.

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


# Question
Title: How can I automatically apply a shipping service and skip shipping selection during checkout?
In certain circumstances, you may want to automatically add a particular shipping rate to an order. For instance, you might want to:

* use a particular service for estimation purposes
* force a particular shipping service based on business logic (e.g. it might be free or fixed cost)
* have the customer skip the shipping pane in checkout

# Answer
> 2 votes
You can use Rules for this. You can modify the rule export below and either import it directly into Drupal or include it in `MYMODULE.rules_defaults.inc`:

```
/**
 * Implements hook_default_rules_configuration().
 */
function MYMODULE_default_rules_configuration() {
  $configs = array();

  $configs['rules_auto_add_shipping_service'] = rules_import('{ "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "TAGS" : [ "Commerce Shipping" ],
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : "standard_shipping"
          }
        }
      ]
    }
  }');

  return $configs;
}

```

In the example above, the rule fires when an order is updated. When an update occurs it:

1. Removes all shipping line items from the order. (`commerce_shipping_delete_shipping_line_items`)
2. Collects rates for the specified shipping method. You can edit the `shipping_method_name` from `flat_rate` to any service you are using (it doesn't have to be Flat Rate).
3. Applies a particular rate. This rate must be collected during the previous step.

Now, your order will always have a shipping rate applied to it.

To skip checkout, you can disable the shipping pane using the UI or use something like the snippet below to handle it in code:

```
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // No need for shipping since it's auto-selected.
  $checkout_panes['commerce_shipping']['enabled'] = FALSE;
}

```

---
Tags: 7, commerce
---


# Question
Title: Add link to call by Skype in a message - relative reference
I have rules' module and in the last part I set an action to show a message. In that message I want to add a link to call one user by Skype, I am using this:

```
     $message = "<a href='skype:echo123?call'>Click to call to your student</a>";

     echo $message;

```

That only works in php (You can try it http://phptester.net/).

But the problem is that Drupal is using that reference as a relative url so when I click it, it takes me to "http://www.example.com/yyyy/echo123?call". How can I do to do a reference to Skype?.

Thank you so much for your help.

# Answer
your link contains "skype" protocol that is filtered out by filter\_xss\_bad\_protocol() Drupal core function.
You can install Filter Protocols module which allows you to configure allowed protocols. Skype protocol is not included in configuration by default, you'll have to add it yourself - then your skype link will work.
> 2 votes

# Answer
I don't really know about the skype stuff so this might not be ideal but can't you use: $message = "Click to call to your student";

That should still open up in skype if you've got it as the default. Also means people without skype e.g. mobile phone users can click it directly and make a call via their phone
> 0 votes

---
Tags: rules, users
---


# Question
Title: view's query "was not run" while getting results
I'm working with drupal 7 and views module (7.x-3.11 version) and I'm getting a strange problem.

In the Views admin, when I run the query, I get a message **no query was run** while I actually get expected results. Moreover, if I add a filter criteria and run the query, the results are affected by this new criteria while I still get **no query run** message.

Secondly, I have created a custom module to use `views_query_alter` to modify view's queries. It never comes into the function on this particular view while it does for other views.

So, to summary, I have a **no query was run** message and nothing is passing by the `hook_views_query_alter` but query is run somewhere because I get some results and it is sensitive to filter criteria changes.

I really need to find this query and to override but I just can't find it.

Do you have any idea of what's going on here?

# Answer
> 0 votes
If your views having contextual filter using relationship, then you should check if correct relationship set in contextual filter.

---
Tags: views
---


title: Configuration Form Access Denied

text:
# Question
Title: Configuration Form Access Denied
I am porting a module to Drupal 8. I have correctly setup the path in routing.yml but it always says access denied even I am logged in with user 1.

routing.yml

```
flood_control.flood_control_config_form:
  path: '/admin/config/flood-control'
  defaults:
    _form: '\Drupal\flood_control\Form\SettingsForm'
    _title: Flood Control
  requirement:
    _permission: 'administer site configuration'

```

.links.menu.yml

```
flood_control.flood_control_config_link:
  title: Configure Flood Control
  description: 'Configuration Form for flood control'
  parent: system.admin_config
  route_name: flood_control.flood_control_config_form

```

What am I missing wrong?

# Answer
> 3 votes
Can be just a typo, look at requirement, you missed a 's'.

```
  requirements:
    _permission: 'administer site configuration'

```

Look at here for a complete skeleton. (or a collection of modules examples here)

---
Tags: users, 8, routes
---


title: Install module via Drupal Console fails

text:
# Question
Title: Install module via Drupal Console fails
I'm trying to install a module via the new Drupal Console on Drupal 8.

I chmodded my modules directory to 777 without success.

```
drupal module:install admin_toolbar

[ERROR] Unable to install modules admin_toolbar due to missing modules admin_toolbar

```

# Answer
Try to download it first and then install.

```
drupal module:download admin_toolbar
drupal module:install admin_toolbar

```
> 3 votes

---
Tags: 8
---


# Question
Title: Twig/Drupal caching and dynamic variables
I have a template with a list of recent articles and an article itself. I want to check in the list of recent articles if the article currently viewed is there and if yes add a class to the div. This works all fine on a development environment but as soon as I turn on caching it goes haywire. The class is stuck on one item instead of switching to the active one.

How can I solve this?

My template:

```
<a class="news-block {{ node.id == current_id ? 'news-block--active' : '' }}" href="{{ url }}">
    ...
</a>

```

My preprocess:

```
function theme_preprocess_article(array &$variables) {
    $currentNode = \Drupal::routeMatch()->getParameter('node');
    $variables['current_id'] = $currentNode->get('nid')->getValue()[0]['value'];
}

```

# Answer
My understanding is that this doesn't vary on the same URL, so both page\_cache and dynamic\_page\_cache should be fine. However, each node is also cached on its own, a and that's your problem here.

As 4k4 said in the comment, you should be able to vary the cache with this: `$variables['#cache']['contexts'][] = 'url'`.

That's rather problematic however, because it means that every node needs to be cached differently on every page, which results in a huge amount of variations that fill up your cache tables.

You could define your own cache context for whether you are on the node page of a given node. Core actually should provide a cache context for that, since it has a similar problem when you'd e.g. use the default view mode somewhere else than on the node/N page. But it doesn't, there's an open issue for that.

As mentioned, the easiest fix is probably to use JS for this.
> 4 votes

---
Tags: 8, caching, theming
---


# Question
Title: Set boolean (single on/off checkbox) value while creating a user
I am creating a user programmatically and there is a boolean field (single on/off checkbox) being used as a terms of use inside the users profile.

How do I set the value of it when creating a user object? I need it to be checked or 1.

```
$new_user = array(
                'name' => $username,
                'mail' => $email,
                //'pass' => $pass,
                'signature_format' => 'full_html',
                'status' => 1,
                'access' => 0,
                'timezone' => 'America/New_York',
                'init' => $email,
                'field_user_account_terms' => array(
                    'attributes' => array(
                        'checked' => 'checked',
                    ),
                ),
              );

$account = user_save(NULL, $new_user);

```

i've also tried

```
                    'field_user_account_terms' => array(
                    'und' => array(
                        0 => array(
                            'value' =>  1,
                        ),
                    ),
                ),

```

I've also tried setting the default value and a bunch of other syntax. Nothing seems to be working for me.

**is this even possible? What is the correct syntax for setting the value of a checkbox, to be saved in a users profile?**

# Answer
> 0 votes
The help message for this field says: **If left empty, "1" will be used** and **if left empty, "0" will be used**. So I left this field blank and assumed you could programmatically set the value while creating a user. This doesn't work at all for me.

You actually have to explicitly define the *On* and *Off* values in order to be able to set them while creating a user.

Then you can set the value in the user object.

```
'field_user_account_terms' => array(
                'und' => array(
                    0 => array(
                        'value' =>  1,
                    ),
                ),
            ),

```

---
Tags: entities, users
---


# Question
Title: what is the difference between a load callback and list callback in the i18n hook_i18n_object_info() function?
I am learning how to use the i18n module to translate a module. In `hook_i18n_object_info()` implementations, I have noticed other modules using list callback or load callback.

What is the difference?

# Answer
> 1 votes
A list callback is a callback that returns all the objects of a specific type; for example, for content types, the list callback is `node_type_get_types()`.
A load callback is a callback that loads a single object of that specific type; for content types, the load callback is `node_type_get_type()`.

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


title: Chosen module present but inactive

text:
# Question
Title: Chosen module present but inactive
To replicate the issue:

Install and enable Chosen module -\>

(Apply Chosen to exposed filter)

Add `.views-widget-filter-title` to /config/user-interface/chosen under "Apply Chosen to the following elements"

Why is my chosen element present but inactive? (See picture)

# Answer
The selector added to "Apply Chosen to the following elements" section would be

```
.view-filters .views-exposed-form select

```

in order for Chosen plugin to be applied to Views exposed filter with select drop-down widget.
> 0 votes

---
Tags: views
---


# Question
Title: How to skip creating records with blank fields when migrating from csv file?
I have created a migration with the **Migrate** module that migrates data from a csv file into a custom entity. There are some rows in my csv file that don't have any data for the entity that I'm importing into, so I would like to skip the creation of those entities.

Is there a way I can do this?

# Answer
> 2 votes
in your prepareRow function test to see if a field is empty and if it is, return FALSE. For example:

```
public function prepareRow($row) {
  if ($row->data == '') {
    return FALSE;
  }
}

```

---
Tags: migrations, importing-exporting
---


# Question
Title: Checking what user a migration is running as
I have a single migration out of a larger group, that needs to be run as the administrator or an entity reference fails to map the User entity properly. I'd love ideas on what I might change so that I wouldn't have to be an administrator to entity reference users, but failing that:

How can I check what user the migration is currently running as? Basically I want to be sure that drush has been invoked with --user=1 or throw an exception with a reminder that this migration needs to be run as administrator.

# Answer
In the interest of trying to up the percentage of Drupal Questions that have an answer, I'll post the solution that I came to as a result of Clive's comment.

I added a preImport and postImport method to my migration class as follows:

```
  public function preImport() {
    parent::preImport();
    $GLOBALS['user']->previousid = $GLOBALS['user']->uid;
    $GLOBALS['user']->uid = 1;
    if ($GLOBALS['user']->uid != 1) {
      throw new MigrateException('Run Staff Contributor Migration as user 1.');
    }
  }

  public function postImport() {
    parent::postImport();
    $GLOBALS['user']->uid = $GLOBALS['user']->previousid;
  }

```

This ensures that this particular migration is run as user 1 and returns the user value back to whatever it had been at the end of the migration. It also throws an exception if for some reason the user switch failed.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: How to skip (not ignore) some rows in migration?
I want to skip some rows in my migration, so that rows will imported on the 2nd attempt. for this am returning false in the prepare row function.

```
public function prepareRow($row) {
if($parent) {
      return TRUE;
    }
    else {
      return FALSE;
    }
}

```

but this ignore that rows and then I am unable to import the data again. Is there any option to skip some rows so that I can import them on 2nd attempt?

# Answer
> 2 votes
Migrate doesn't work with attempts, so it always performs one migration (that you can update with the latest content).

Considering the fact you need some parent do be defined first, it might be easier to apply some sorting, so the parent is always created before the child (and you would not need several attempts). If you are migrating from a Drupal (7) site you can use the `menu_links` table for this. See the section about book hierarchies here: Migrating Book module nodes for a similar situation.

If you are not migrating from Drupal, but some other system you might want to look for a similar table.

As an alternative, you might be able to use the `handleSourceMigration()` function to see if the old parent id is already migrated (function returns NULL otherwise) and skip rows based on that, then re-run the migration. But I have never used this method and it might not work.

# Answer
> 1 votes
You don't specify *why* you want to skip some rows, but one likely scenario is that you are wanting to test if some row that this row relies on has been created before creating this row. In this case, the easiest option when it is possible is to order your query so that you ensure the initial requirees are created before the requirers.

I have also done this by restricting the where clause in my query to make sure I only get the items I want (perhaps the parents from your variable name) in one migration, and then create another migration with a query that gets the rest.

The other option is to create a stub for the required row, that will act as a placeholder until the migration has the actual data. This allows you to create the reference and associate properly first, and add the actual data later. This is documented in the migrate module documentation on using stubs

---
Tags: 7, migrations
---


title: Get all managed file usage by id

text:
# Question
Title: Get all managed file usage by id
Is there a way to get all the managed files used by a particular entity, i.e. a node or other module item?

Looking in the file\_usage table there is an `id` column and this is what I want to retrieve fid's by.

Seems like something that there would be a function for, but I haven't found it yet...

# Answer
I don't think there is such a function. However it's not hard to create your own. Here's an example:

```
function load_files_by_type($type, $id) {
  // Select all used files by type and id.
  $query = db_select('file_usage', 'fu')
    ->fields('fu', array('fid'))
    ->condition('fu.type', $type)
    ->condition('fu.id', $id);

  // Load all file ids in an array.
  $fids = $query->execute()->fetchCol();

  // Return the file objects.
  return file_load_multiple($fids);
}

```

You can call it like this: `load_files_by_type('node', 64);`

Of course you can alter the query to your liking, you could even add a module check.
> 4 votes

---
Tags: 7, files
---


# Question
Title: How can I assign users different profile pictures upon registration based on gender?
My setup: I am on Drupal 7 but not using the default user profile pictures; instead, I have a custom image field, profile\_picture, which is attached to the user profile. When users register, they must select their gender (Male/Female/Prefer not to say).

I would like to assign a different default picture to this profile\_picture field based on the value each user selects for gender. I tried using *Set a data value* with Rules but I can't figure out how to get these three specific pictures (one for each gender choice) to be options.

If it helps, each user also has a role based on their gender. I'm not committed to using Rules for this; I will accept any solution that allows me to reliably set the picture based on the value of the field in their profile. There is no opportunity for users to change their gender so this needs only be set once.

EDIT: Users are later able to replace this with their own custom profile picture, so I need to keep this as an Image field.

# Answer
A simple approach might be to retheme the gender field itself so that it displays an image based upon its value, eg, instead of displaying `male`, it displays an image with path `sites/default/files/male.png`.

In D6, this would mean copying CCK's `content-field.tpl.php` to your theme directory and then creating `content-field-field_gender.tpl.php` and jiggering things up in there, eg...

```
print theme('image', 'sites/default/files/' . $item['view'] . '.png')

```

...instead of just `print $item['view']`.

My quick look at D7 here suggests that copying Field's `field.tpl.php` to `field--gender--profile.tpl.php` in your theme's directory would be basic starting point there and instead of render()ing $item, doing something similar with its value.

Then, in either version, just make sure you have three images in your files directory called `male.png`, `female.png` and `unknown.png` (or files based upon whatever the values of your gender field are.)

With this approach, you only have three files to deal with instead of a file uploaded and stored for each and every user. Another side benefit is that they will be easily cached by your users' browsers.

ADDITION:

Based upon new info from comments and other answers, you could do something like this in your `user-picture.tpl.php` template:

```
if (!empty($account->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($account->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
} else {

  $file_path = 'sites/default/files/' . $account->field_gender[LANGUAGE_NONE][0]['value'] . '.png';
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file_path));

}

```

where the new stuff is the `else ....` Pardon my D6ism if `sites/default/files` is wrong in D7, but basically you just want a path on your system to where you've stuck `male.png`, `female.png` and `unknown.png` and you display them when your profile\_picture field is not set.
> 2 votes

# Answer
One way is to add a custom submit handler for user registration form.

```
   function yourmodule_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'user_register_form') {
            $form['#submit'][] = 'mycustom_user_profile_form_submit';
        }
    }

```

And then assign value to your profile\_picture field programmatically as below.

```
function mycustom_user_profile_form_submit($form, &$form_state) {
    if ($form ['field_gender']['und']['#value'] == "Male") {
        $image_path = 'public://pictures/male.jpg';
    } else if ($form ['field_gender']['und']['#value'] == "Female") {
        $image_path = 'public://pictures/female.jpg';
    } else if ($form ['field_gender']['und']['#value'] == "Prefer not to say") {
        $image_path = 'public://pictures/other.jpg';
    }
    $result = db_query("SELECT f.fid FROM {file_managed} f WHERE f.uri = :uri", array(':uri' => $image_path));
    $record = $result->fetchObject();
    $image_info = image_get_info($image_path);
    $fid = 0;
    $account = user_load($form_state['values']['uid']);

    //check if file is already in file_managed table
    if ($record) {
        $fid = $record->fid;
    } else {

        //create new file
        $file = new StdClass();
        $file->uid = $account->uid;
        $file->uri = $image_path;
        $file->filemime = $image_info['mime_type'];
        $file->status = 0;
        $file->filesize = $image_info['file_size'];
        file_save($file);
        $fid = $file->fid;
    }

    //create file array
    $file_array = array();
    $file_array['fid'] = $fid;
    $file_array['display'] = 1;
    $file_array['height'] = $image_info['height'];
    $file_array['weight'] = $image_info['width'];

    $account->field_profile_picture['und'][0] = $file_array;

    user_save($account);
}

```
> 2 votes

# Answer
You can use hook\_field\_attach\_submit() as **this hook is invoked after the field module has performed the operation**.

A fully implemented code is as follows

```
/**
 * Implements hook_field_attach_submit().
 */
function MODULE_NAME_field_attach_submit($entity_type, $entity, $form, &$form_state) {

    // First find the image fields. This proces is much more complicated than
    // it probably should be.
    // 1. Grab the name of the entity bundle
    // 2. Grab the list of fields for the given entity type and bundle
    // 3. Loop through all fields in that type and bundle and get the image
    //    fields names.
    $entity_info = entity_get_info($entity_type);

    // User entity doesn't have a bundle. So you just pass the type into the
    // bundle field.
    if (empty($entity_info['entity keys']['bundle'])) {
        $field_instances_info = field_info_instances($entity_type, $entity_type);
    }
    else {
        $field_instances_info = field_info_instances($entity_type, $entity->{$entity_info['entity keys']['bundle']});
    }

    $image_fields = array();

    foreach ($field_instances_info as $field_name => $field_instance_info) {
        if($field_name == 'field_profile_picture') {
            $field_info = field_info_field($field_name);
            $image_fields[$field_name] = $field_instance_info['settings'];
            $image_fields[$field_name]['uri_scheme'] = $field_info['settings']['uri_scheme'];
            $image_fields[$field_name]['empty'] = ($form[$field_name]['und'][0]['#value']['fid'] > 0)? FALSE:TRUE;
            $image_fields[$field_name]['default_images_path'] = "default_images";
            $image_fields[$field_name]['gender'] = $form['field_gender']['und']['#value'];

        }
    }
    // The list of image fields is now available. If the instance setting of that
    // field has random_default set and the image field is empty choose a random
    // file of the supported file type in the directory.
    foreach ($image_fields as $field_name => $field_instance_info) {
        if ($field_instance_info['empty']) {

            if($field_instance_info['gender'] == 'Male') {
                $file_selection = cf_get_image_info("public://default_images/avatar-male.jpg");
            }
            else {
                $file_selection = cf_get_image_info("public://default_images/avatar-female.jpg");

            }

            // 2. Check if a file id exists for it
            $result = db_select('file_managed', 'fm')
                ->fields('fm', array('fid'))
                ->condition('fm.uri', $file_selection['uri'])
                ->execute()
                // Fetch as array
                ->fetchAll(PDO::FETCH_ASSOC);

            // 3. If it does not create a new one
            if (empty($result)) {
                GLOBAL $user;
                $file = new stdClass();
                $file->uid = $user->uid;
                $file->filename = $file_selection['filename'];
                $file->uri = $file_selection['uri'];
                $file->filemime = file_get_mimetype($file_selection['uri'], $mapping = NULL);
                $file->status = 1;

                file_save($file);
            }
            else {
                $file = file_load($result[0]['fid']);
            }

            // Add a fake file usage to prevent files pulled form the random directory
            // from being deleted when they are no longer referenced.
            $usage = file_usage_list($file);
            if (!isset($usage['profile_default_image'])) {
                file_usage_add($file, 'profile_default_image', 'profile_default_image', 0);
            }

            // 4. Identify this file for the field
            $entity->{$field_name}['und'][0] = (array) $file;
        }
    }
}

function cf_get_image_info($path) {
    $image1 = image_get_info($path);
    $image2 = pathinfo($path);
    $image_info = array_merge($image1, $image2);
    $image_info['uri'] = $path;

    return $image_info;
}

```
> 1 votes

# Answer
How about overriding template\_preprocess\_user\_picture()?

--\> Here's the default implementation: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/template\_preprocess\_user\_picture/7

Notice this is where the decision is made to use an image supplied by the user or to fall back to a default picture:

\[...\]

```
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}

```

\[...\]

You could simply extend that to interrogate the gender field present in the $account object (which is available at that time) and provide a user\_picture\_default\_male and user\_picture\_default\_female.

Does that make sense?
> 0 votes

# Answer
Another Solution: ( using profile 2 ) create user-picture.tpl.php in your theme folder then try the below code.

```
<?php if ($user_picture) {?>
<div class="<?php print $classes; ?>">
    <?php print $user_picture; ?>
</div>

    <?php

} else {
$profile = profile2_load_by_user($account->uid);

global $language ;
$curr_lang = $language->language;

if ($profile['main']->field_user_gender) {
$field_user_gender = $profile['main']->field_user_gender['und'][0]['value'];
$uid = $profile['main']->uid;

}
if($field_user_gender=="female"){
?>

        <div class="user-picture">
            <a href="/<?=$curr_lang?>/user/<?=$uid?>" class="active"><img src="/sites/all/themes/xxx/img/f.jpg"></a>

        </div>
        <?php }else{?>
            <div class="user-picture">
                <a href="/<?=$curr_lang?>/user/<?=$uid?>" class="active"><img src="/sites/all/themes/xxx/img/m.jpg"></a>
            </div>
            <?php
}
} ?>

```
> 0 votes

---
Tags: users, rules
---


# Question
Title: tabledrag submit - $form_state missing values
I have built a draggable table using this tutorial (halfway down page is the Drupal 8 code):

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

In the submit function I would like to look through all the rows and create an array for each row. I am using the following code:

```
foreach ($form_state->getValues(['mytable','rows']) as $tablerow) {

```

And then running db\_update on each item using this:

```
$tablerow['label']

```

But this returns an error "undefined index". Is there something wrong with the foreach line?

UPDATE: My table is generated using this code:

```
  foreach ($entities as $id => $entity) {
    // TableDrag: Mark the table row as draggable.
    $form['mytable'][$id]['#attributes']['class'][] = 'draggable';
    // TableDrag: Sort the table row according to its existing/configured weight.
    $form['mytable'][$id]['#weight'] = $entity->get('weight');

    // Some table columns containing raw markup.
    $form['mytable'][$id]['label'] = array(
      '#plain_text' => $entity->label(),
    );
    $form['mytable'][$id]['id'] = array(
      '#plain_text' => $entity->id(),
    );

    // TableDrag: Weight column element.
    $form['mytable'][$id]['weight'] = array(
      '#type' => 'weight',
      '#title' => t('Weight for @title', array('@title' => $entity->label())),
      '#title_display' => 'invisible',
      '#default_value' => $entity->get('weight'),
      // Classify the weight element for #tabledrag.
      '#attributes' => array('class' => array('mytable-order-weight')),
    );

    // Operations (dropbutton) column.
    $form['mytable'][$id]['operations'] = array(
      '#type' => 'operations',
      '#links' => array(),
    );
    $form['mytable'][$id]['operations']['#links']['edit'] = array(
      'title' => t('Edit'),
      'url' => Url::fromRoute('mymodule.manage_edit', array('id' => $id)),
    );
    $form['mytable'][$id]['operations']['#links']['delete'] = array(
      'title' => t('Delete'),
      'url' => Url::fromRoute('mymodule.manage_delete', array('id' => $id)),
    );
  }

```

I have run `dpm($form_state->getValue(['mytable','2']));` on submit for each of the rows, but only the operations and weight column values appear in $form\_state. How do I get the `id` and `label` columns to appear?

# Answer
The answer is quite simple - markup doesn't make it into $form\_state. Place the item id ($entity-\>ref in the below code) in a textfield or number field instead and use the following to hide and disable it (not sure if disabling is necessary):

```
    $form['mytable'][$id]['label'] = array(
    //'#plain_text' => $entity->ref,
    '#type' => 'number',
    '#title' => "",
    '#default_value' => $entity->ref,
    '#disabled' => TRUE,
    '#access' => FALSE,

```
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How to import the node class into a title field of a view?
I installed the Node Class module. I have a view, where the node class should be imported into the title field of the view.

How can I achieve this?

# Answer
As far as I understand, you want to add a class name to the title field of your nodes listed in a view. (1) Views provide this functionality by default:

Adds the class to the selected html element, `<span>` is by default. It can be used as a field wrapper.

(2) In case this is not suitable for you, you may very well use view's "rewrite results" :

It can be used to wrap the field's text.

(3) Lastly there is always the preprocess\_views\_view\_fields solution where you can edit your field's attributes:

```
if($view->name == 'view-name') {
  $vars['fields']['title']->wrapper_prefix = '<div class="views-field views-field-title my-class">';
}

```

It can be used as a field wrapper.
> 2 votes

---
Tags: views
---


# Question
Title: Help with basic hook for my first module
I am having problems with understanding if my hook is activating/running. I have watched and read many things about hooks but until I get something to work I am very confused.

I'm trying to use the hook here: http://api.drupalcommerce.org/api/Drupal%20Commerce/sites!all!modules!commerce!modules!checkout!commerce\_checkout.api.php/function/hook\_commerce\_checkout\_pane\_info\_alter/DC

```
/*  Hello World
*/
function commerce_admam_commerce_checkout_pane_info_alter(&$checkout_pane)
{
dpm("hi");
}

```

All I want to have happen on checkout is to see if that message shows up. I have tried other hooks as well. MY filename is commerce\_admam.module and it's enabled in the backend. I can move the dpm() out of the hook and it fires off the message (everywhere though because its running it all the time)

# Answer
> 2 votes
`dpm` and `dsm` can be a little tricky in some hooks, and you may need to time a cache clear with a page reload to see them fire.

Better to use something like `watchdog` or actually alter the page content.

Your function looks good, so try this from the example module. More chance of seeing the effect:

```
function checkout_pane_example_commerce_checkout_pane_info_alter(&$panes) {
  if (!empty($panes['cart_contents'])) {
    // Change the title of the "Cart Contents" pane.
    $panes['cart_contents']['title'] = t('Your big wonderful shopping cart brimming over with shopaholic nonsense');
  }
}

```

---
Tags: 7, commerce
---


# Question
Title: How to display records in table programmatically?
I'm using Drupal 8.0.1. I'm starting to develop a new custom module for learning purpose. Just I have created one form. From the form, the values are stored in my custom table. Now I want to show the records in separate page.

In drupal 7, I have used

```
  $query = db_query('SELECT id,name,email,age,gender FROM {learning}');
  $rows = array();
  while ($data = $query->fetchAssoc()) {
      // Fill the table rows
    $data['operation'] = l(t('Delete'), 'admin/people/survey/' . $data['id'] . '/delete');
    $data['operation'] .= "|";
    $data['operation'] .= l(t('Edit'), 'admin/people/survey/' . $data['id'] . '/edit');
    $rows[] = array('data' => $data , 'style' => 'word-break:break-all;' , );
  }
  //Number of records shown in per page
  $per_page = 4;
  $current_page = pager_default_initialize(count($rows), $per_page);
  $chunks = array_chunk($rows, $per_page, TRUE);
  // Prepare table header
  $header = array(t('ID'), t('Name'), t('Email'), t('Age'), t('Gender'), t('Operations'));
  // Output of table with the paging
  $output = theme('table',
    array(
      "header" => $header,
      "rows" => $chunks[$current_page],
      "attributes" => array(),
      "sticky" => TRUE,
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("No Survey Records has been found")
    )
  );
  //return pager with limited number of records.
  return $output .= theme('pager', array('quantity', count($rows)));;

```

And this was working fine in drupal 7. I just want to do same in the Drupal 8. When I put this code in drupal 8 it shows error **theme() not found**. How can I create the table to show the list of records from my custom table.

# Answer
In order to achieve this you need to do the following

* Inject the database service as db\_query is not working in Drupal 8 anymore
* Use of theme() was discouraged in Drupal 7 as well, instead you need to use render array #theme key
* Use Drupal 8 Database API db\_select and chaining stuff and extend a special class `Drupal\Core\Database\Query\TableSortExtender` for rendering the data in tabular form
* Finally form a render array with #theme key, #header, #rows.

The following example from my custom module display the data in table along with pager

```
      // Prepare _sortable_ table header
      $header = array(
        array('data' => t('ID'), 'field' => 'id'),
        array('data' => t('Name'), 'field' => 'name'),
        array('data' => t('Email'), 'field' => 'field1'),
        array('data' => t('Age'), 'field' => 'field2', 'sort' => 'desc'),
        array('data' => t('Gender'), 'field' => 'field3'),
        array('data' => t('Operations'), 'field' => 'field4'),
      );

      $query = $this->database->select('location','loc');
      $query->fields('loc', array('id', 'name', 'field1','field2','field3','field4'));
      $query->addField('loc','name','name_alias');
      $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
      $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
      $result = $pager->execute();

      foreach($result as $row) {
          $rows[] = array('data' => (array) $row);
      }

      $build = array(
          '#markup' => t('List of All locations')
      );

      $build['location_table'] = array(
        '#theme' => 'table', '#header' => $header,
          '#rows' => $rows
      );
     $build['pager'] = array(
       '#type' => 'pager'
     );

```
> 7 votes

# Answer
Its not a simple question, there is couple of things that you need to change for your module working properly in Drupal 8. Remember Drupal 8 now uses OOP and achitecture is modernized. Here you can check a nice presentation about this.

Here you can check a bunch of module examples, look at one called 'dbtng\_example' this is exactly that you want.
> 1 votes

---
Tags: forms, theming, 8
---


# Question
Title: How to show nodes where the user is (not) in the reference field with Views?
I have a content type with a multiple-values user entity reference field.

I need a view that shows (as two pages or within one view) (a) **all the nodes where the user IS referenced** and (b) all the **nodes where the user is NOT** referenced.

There is a relationship to the user reference field and a contextual filter (uid of the logged in user). This "positive" works and shows the nodes where the logged in user is referenced

But the view where the user is not referenced does not work. Is there a way to "negate" the contextual filter (uid of the logged in user)?

I have tried it in one view with an exposed filter (current user), but I could not solve the problem of having multiple user references. I tried the VIEWS distinct feature and the views\_distinct modules.

# Answer
You can use exactly the same you did for positive reference but with a single exception. You will see a checkbox contextual field setting names "**Exclude**". You can check that and the views will exclude the records which have not referenced.
> 2 votes

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


# Question
Title: Set restriction on user by country for language translation content
How do I restrict individual user by country to see a restricted list of languages in the Internationalization module? For example, I would like to restrict users from China, to see only Chinese translations.

I'm trying to get the country by `global $user;` but it is not working.

# Answer
You can use Translation Access module.

This module provides per-language access control for creating and updating nodes by adding a list of checkboxes for each available language to the user add/edit form (only visible to users with 'administer users' permission).
> 1 votes

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


# Question
Title: How to use summary field conditionally for display?
I have created a content type **Band** with a Description field (as Long Text and Summary). When I am viewing the Band page, I want to see the full description field. And when I am viewing a listing of bands, I want to see a summary description or the first hundred characters if the summary description is missing.

How do I show appropriate Description for the Band page and the listing pages?

# Answer
The *Description* text field needs to be of type `Long text and summary`.

With view modes (**admin/structure/types/manage/band/display**) you can configure how the fields must be rendered.

In the view mode `Teaser` you could set the format to `Summary or trimmed` and in other view modes to `Default`.

When viewing the content type *Band* as a full page you can render the view mode `Default`. When rendering a list of *Bands* with views you can set the view mode to `Teaser`.
> 1 votes

---
Tags: views, nodes
---


title: Get configuration settings not working

text:
# Question
Title: Get configuration settings not working
I am writing this Drupal 8 module. I am setting up some configuration settings here

But when I retrieve it here using `$this->config()->get()` it is not giving anything. Any idea what am I doing wrong?

# Answer
The problem is in your `flood_control.settings.yml`.

```
flood_control:
  user_failed_login_ip_limit: 50
  ...

```

This way, to get `user_failed_login_ip_limit` you must use `$this->config(flood_control.settings)->get('flood_control.user_failed_login_ip_limit')`. Or just remove `flood_control:` on first line for better use.
> 1 votes

# Answer
I was stupid enough to not include the schema for the settings. I have made it working by including schema file like this.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: Custom service returns "401 (Unauthorized : Missing required argument merchant_id)"
I'm trying to call a custom service module, but it shows 401.

resource:

```
$resources =  array(
    'get_contacts' => array(
      'operations' => array(
        'index' => array(
          'help' => 'Get customers and their contacts',
          'file' => array('type' => 'inc', 'module' => 'sync_contacts', 'name' => 'resources/sync_contacts.resource'),
          'callback' => '_get_customer_contacts',
          'args' => array(
            array(
              'name' => 'merchant_id',
              'type' => 'int',
              'description' => t('Get customers and their contacts by merchant_id.'),
              'source' => array('data' => 'merchant_id'),
              'optional' => FALSE,
            ),
          ),
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'drupalgap',
            'name' => 'drupalgap.resource',
          ),
          'access callback' => '_sync_contacts_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );

```

Service function:

```
function sync_contacts_get_customers_list(options) {
  try {
    options.method = 'GET';
    options.path = 'get_contacts.json';//'.json' removed and tested also
    options.service = 'sync_contacts';
    options.resource = 'get_contacts';

    Drupal.services.call(options);
  }
  catch (error) {
    console.log( error);
  }
}

```

Service function call:

```
try {
    var my_args = {
        merchant_id: 1
    };
    sync_contacts_get_customers_list({
      data: JSON.stringify(my_args),
      success: function(result) {
        drupalgap_alert("SUCCESSSS");
        $("#contactList").append(JSON.stringify(result, null, 2));
      }
    });
  } catch (error) { console.log(error); }

```

POSTMAN:

This is how I used the custom service. when I execute it, it shows "401 (Unauthorized : Missing required argument merchant\_id)".

How can I fix this issue?

`SOLUTION:` Used Tyler's resource in his answer below and service call modified as below(changed GET to POST and path modified accordingly).

`Note:` To test, in POSTMAN also we have to call with POST and pass the `merchant_id` as `Raw` ie. `{"merchant_id": 1}`

```
function sync_contacts_get_customers_list(options) {
   try {
     options.method = 'POST';
     options.path = 'sync_contacts_resources/get_contacts';
     options.service = 'sync_contacts';
     options.resource = 'get_contacts';

     Drupal.services.call(options);
  }
  catch (error) {
    console.log( error);
  }
}

```

# Answer
> 1 votes
You have to use the `POST` method in the `sync_contacts_get_customers_list` function:

`options.method = 'POST';`

Without this, you aren't "posting" anything up to Drupal Services, so your resource in Drupal will not be delivered the `merchant_id`.

If you want to use a `GET` request, then I'd recommend using a Views JSON (from Views datasource) and a contextual filter(s), otherwise custom resources in Services always use `POST` *AFAIK*, unless you're building a CRUD interface for an Entity (e.g. Services Entity API).

Also the way you are defining your custom resource in Drupal is incorrect, use `actions` instead:

```
  $resources = array(
    'sync_contacts_resources' => array(
      'actions' => array(
        'get_contacts' => array(
          'help' => 'Get customers and their contacts',
          'file' => array('type' => 'inc', 'module' => 'sync_contacts', 'name' => 'resources/sync_contacts.resource'),
          'callback' => '_get_customer_contacts',
          'args' => array(
            array(
              'name' => 'merchant_id',
              'type' => 'int',
              'description' => t('Get customers and their contacts by merchant_id.'),
              'source' => array('data' => 'merchant_id'),
              'optional' => FALSE,
            ),
          ),
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'drupalgap',
            'name' => 'drupalgap.resource',
          ),
          'access callback' => '_sync_contacts_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );

```

---
Tags: javascript
---


# Question
Title: Assign menu programmatically upon saving node
I'm using Superfish module for my menu. I have product parent menu where I need to display the 3 categories as sub-menu. Those 3 categories has been added to the menu with the help of Taxonomy menu module.

I would like to assign a menu automatically based from the nodes category.

For example:-

"Node 1" has "Category 1" term, then the node menu will be assigned to "Category 1". Something like below:-

```
-Product
 --Category 1
    ---Node 1
    ---Node 2
  --Category 2
    ---Node 3
    ---Node 4

```

# Answer
**Please try this**

```
/**
 * Implements hook_node_insert().
 */
function YOUR_MODUEL_node_insert($node){
  create_node_menu($node, 'insert');
}

/**
 * Implements hook_node_update().
 */
function YOUR_MODUEL_node_update($node){
  create_node_menu($node, 'update');
}

function create_node_menu($node, $action_type){
  if($node->type == 'YOUR_NODE_TYPE'){
    $category = $node->field_category[LANGUAGE_NONE][0]['value'];
    $menu_name = '';
    switch($category){
      case "A":
        $menu_name = 'menu-menu-a';
        break;
      case "B":
        $menu_name = 'menu-menu-b';
        break;
      case "C":
        $menu_name = 'menu-menu-c';
        break;
    }
    if(!empty($menu_name)){
      $item = array(
        'menu_name' => $menu_name,
        'link_title' => $node->title,
        'link_path' => 'node/'. $node->nid,
      );
// update already created menu link
      if($action_type == 'update'){
        $mlid = db_select('menu_links' , 'ml')
            ->condition('ml.link_path', 'node/'.$node->nid)
            ->condition('ml.menu_name', $menu_name)
            ->fields('ml' , array('mlid'))
            ->execute()
            ->fetchField();
        $item['mlid'] = $mlid;
      }
      $mlid = menu_link_save($item);
      menu_cache_clear_all();
    }
  }
}

```

Hope this will help.
> 2 votes

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


# Question
Title: Changing default domain in domain access causes 'access denied' for admin
I'm using Drupal 7 with the Domain Access module version 7.x-311. I've successfully configured a bunch of subdomains running sites correctly, with one subdomain as default.

All worked well until I swapped out the default domain with a new one. Now, every login attempt for admin including user 1 hits an 'access denied'.

I've updated the domain access settings to set the new domain as default. I've also ensured that the default domain is not set in the settings.php file, plus set the domain cookies settings reflects the top-level domain.

I've also cleared cache and cleared browser cache and cookies, still I get an access denied. I cannot work it out.

Has anyone got advice on where to look next?

N

# Answer
Caching would be my first thought, make sure to clear cache (through drush since you can't log in). Also if you have any heavy caching like Varnish - clear that too. You may have an active session still in Drupal for the admin account, try removing that via - **drush sql-query 'TRUNCATE TABLE sessions;'**
> 0 votes

---
Tags: 7, domain-access
---


# Question
Title: Use multifield values to create new nodes
I have a multifield **field\_staff\_required** of unlimited cardinality containing two subfields: **field\_staff\_category** and **field\_staff\_quantity**.

Example: I have an event node containing the staff\_required multifield to which I add the following values:

Category: Manager / Qty: 1

Category: Steward / Qty: 5

Category: Security / Qty: 3

On saving the node I would like it to automatically generate new 'staff booking' nodes for each of the staff required. The staff booking node will contain a 'Staff\_category' field which would be auto populated with the category from the multifield, and an entity reference field to refer each staff booking node back to the event node.

So the result in the example above is that I end up with 9 new nodes created, one with category set to Manager, five set to Steward, and three set to Security, all referring back to the event node.

Can the above be achieved using Rules? The multifield subfields don't seem to be accessible to Rules. I assume it will be necessary to write a custom module to achieve this. Any suggestions gratefully received!

# Answer
I managed to solve this by swapping the Multifield for a Double Field which does play nicely with Rules.

I was then able to use Rules Action: generate a list from an integer to loop through the quantity for each category and create a new node for each, populating the required fields.

The only downside is that Double Field does not allow to populate a select list from a taxonomy vocabulary, and I could not get the **Field Remove Item** or **Multiple Fields Remove Button** modules to work with it.
> 1 votes

---
Tags: rules, entities
---


# Question
Title: How to switch language on login based on user profile?
Is there a way when a user login to automatically switch him in then language setup in his user profile.

# Answer
In "Configuration -\> Regional and language -\> Languages -\> Detection and Selection" enable detection method "User -\> Follow the user's language preference." and drag it to the top of the list. Do same in both sections: User interface & Content language detection.

**UPDATE:** As an alternative to GUI method you can add the code pasted below in your theme's template.php file (*but first, disable detection of user language in Language settings*).

The code below uses hook\_user\_login which runs when the user successfully logs in and passes the user object as an argument. User language is then used for a redirect (`drupal_goto`).

```
function yourthemename_user_login(&$edit, $account)
    {
      // get current user's language from the user account
      $user_language = $account->language;

      // if account has no preferred language set - do nothing
      if (!$user_language) {
          return;
      }
      // if the language is set - do additional checks and then redirect
      else {
        // get a list of installed languages
        $languages = language_list();
        // check if language retrieved from user account exists
        if (!isset($languages[$user_language])) {
            return;
        }
        else {
          // verify if language is enabled
          if (!$languages[$user_language]->enabled) {
              return;
          }
          else {
            // if enabled - redirect to user profile in preferred language
            $user_profile_url = drupal_get_path_alias('user/' . $account->uid);
            drupal_goto($user_profile_url, array(
                'language' => $languages[$user_language],
            ));
          }
        }
      }
    }

```
> 2 votes

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