# Question
Title: How to change File field icons (without changing core)?
The generated markup for displaying a file field is (PDF in this example):

```
<img src="/modules/file/icons/application-pdf.png" title="application/pdf" alt="" class="file-icon">

```

I'd like to use a different icon image. How could I do this without changing the content of /modules/file/icons?

I guess I could hide the default image and display a different one with CSS, but seems a bit messy.

# Answer
> 11 votes
You can override `theme_file_icon` in your theme, and specify different icon images. See `file_icon_path` for reference regarding how core determines which icons to use.

You can also set the "file\_icon\_directory" variable to the path to your icons, as the `file_icon_path` function looks for the path in that variable.

# Answer
> 4 votes
Two additional notes on this:

1. It is not necessary to copy all of the default icon files to your theme directory.
2. If you are using a custom icon, it must be appropriately named in order for it to be found.

As an example, I had a need to use a custom icon for a .bib (bibtex) file. This type is mapped in file\_default\_mimetype\_mapping(), but it defaults to the default text icon since there isn't an icon specifically defined for that mime type (text/x-bibtex).

I overrode theme\_file\_icon() in my theme's template.php, but I did it so that the icon path is only modified as needed, and I didn't have to copy the default icons directory to my theme directory:

```
function mytheme_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);

  if ($mime == 'text/x-bibtex') {
    $icon_directory = drupal_get_path('theme', 'mytheme') . '/images';
  }

  $icon_url = file_icon_url($file, $icon_directory);
  return '<img class="file-icon" alt="" title="' . $mime . '" src="' . $icon_url . '" />';
}

```

The second thing is that you have to name the icon appropriately. If you just keep the use of file\_icon\_url(), this code from that function will determine the file name for the icon:

```
// For a few mimetypes, we can "manually" map to a generic icon.
$generic_mime = (string) file_icon_map($file);
$icon_path = $icon_directory . '/' . $generic_mime . '.png';
if ($generic_mime && file_exists($icon_path)) {
  return $icon_path;
}

```

So in my case, I needed to name my file text-x-bibtex.png. Of course, if you want to just name it whatever you want (bibtex.png in this case), you could just set the file name manually:

```
$icon_url = $icon_directory . '/bibtex.png';

```

Either one will work, but this method allows you to keep the default icons where they are and only tweak things as needed.

# Answer
> 1 votes
Me and tregis got this File Field Icons module done a while ago. Hope this helps

> This modules adds the ability to change default file field icons. You can use core icon packages (included in this module), or you can define a custom icon package.

# Answer
> 0 votes
You can (usually) preprocess theme functions. So if you:

1. Are okay with copying all the icons into your theme to override one or more icons.
2. Don't care to override `theme_file_icon()` in your theme.

Copy the entire `modules/file/icons` directory to your theme (I used `file_icons`) and add this preprocess function to your theme's template.php:

```
/**
 * Implements hook_preprocess_HOOK() for theme_file_icon().
 *
 * Change the icon directory to use icons from this theme.
 */
function MYTHEME_preprocess_file_icon(&$variables) {
  $variables['icon_directory'] = drupal_get_path('theme', 'MYTHEME') . '/file_icons';
}

```

You could also do conditional overrides this way ala @wonder95 but I wanted to keep things simple.

# Answer
> 0 votes
While not being as clean as some of the solutions given, a really simple way of dealing with this is to make use of the CSS3 'type' attribute selector. You can use this to quickly add your custom icon as background image to your link. The result that both are linked to the target file. You can then hide the original image. I did this to get the following appearance:

This is the CSS I used to achieve the results above:

```
.views-field-field-image-files img.file-icon {display:none;}
.views-field-field-image-files a {padding-left: 100px; height: 80px; display: block; margin-bottom: 20px;}
.views-field-field-image-files a[type*="application/pdf"] {background: url(../img/icons/file-icon-pdf.gif) no-repeat; }
.views-field-field-image-files a[type*="application/zip"] {background: url(../img/icons/file-icon-zip.gif) no-repeat; }
.views-field-field-image-files a[type*="application/ppt"] {background: url(../img/icons/file-icon-ppt.gif) no-repeat; }
.views-field-field-image-files a[type*="application/pptx"] {background: url(../img/icons/file-icon-ppt.gif) no-repeat; }

```

In my example I was showing the file fields using views.

---
Tags: 7, files
---


# Question
Title: How to strip all array keys appended with :protected?
I'm trying to replicate `entity->export()` using Entity Metadata Wrappers. When I call `value()` on entity\_metadata\_wrapped entities (in this case a field collection), I get everything `entity->export()` give me, plus a bunch of `entity_key:protected` fields. I'd like to strip these out, as everything not protected gives me identical values to that provided in export.

Example `wrapper->value()` result:

```
Object
(
    [fieldInfo:protected] =>
    [hostEntity:protected] =>
    [hostEntityId:protected] =>
    [hostEntityRevisionId:protected] =>
    [hostEntityType:protected] =>
    [langcode:protected] => und
    [item_id] => 9
    [revision_id] => 9
    [field_name] => field_treatment_categories
    [default_revision] => 1
    [archived] => 0
    [entityType:protected] => field_collection_item
    [entityInfo:protected] => Array
        (
            [label] => Field collection item
            [label callback] => entity_class_label
            [uri callback] => entity_class_uri
            [entity class] => FieldCollectionItemEntity
            [controller class] => EntityAPIController
            [base table] => field_collection_item
            [revision table] => field_collection_item_revision
            [fieldable] => 1
            [redirect] =>
            [entity keys] => Array
                (
                    [id] => item_id
                    [revision] => revision_id
                    [bundle] => field_name
                    [uuid] => uuid
                )

            [module] => field_collection
            [view modes] => Array
                (
                    [full] => Array
                        (
                            [label] => Full content
                            [custom settings] =>
                        )

                    [token] => Array
                        (
                            [label] => Tokens
                            [custom settings] =>
                        )

                )

            [access callback] => field_collection_item_access
            [metadata controller class] => FieldCollectionItemMetadataController
            [bundles] => Array
                (
                    [field_treatment_categories] => Array
                        (
                            [label] => Field collection field_treatment_categories
                            [admin] => Array
                                (
                                    [path] => admin/structure/field-collections/%field_collection_field_name
                                    [real path] => admin/structure/field-collections/field-treatment-categories
                                    [bundle argument] => 3
                                    [access arguments] => Array
                                        (
                                            [0] => administer field collections
                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                )

                        )

                    [field_treatments] => Array
                        (
                            [label] => Field collection field_treatments
                            [admin] => Array
                                (
                                    [path] => admin/structure/field-collections/%field_collection_field_name
                                    [real path] => admin/structure/field-collections/field-treatments
                                    [bundle argument] => 3
                                    [access arguments] => Array
                                        (
                                            [0] => administer field collections
                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                )

                        )

                )

            [static cache] => 1
            [field cache] => 1
            [load hook] => field_collection_item_load
            [translation] => Array
                (
                )

            [schema_fields_sql] => Array
                (
                    [base table] => Array
                        (
                            [0] => item_id
                            [1] => revision_id
                            [2] => field_name
                            [3] => archived
                            [4] => uuid
                        )

                    [revision table] => Array
                        (
                            [0] => revision_id
                            [1] => item_id
                        )

                )

            [token type] => field_collection_item
            [apachesolr] => Array
                (
                    [indexable] =>
                    [status callback] =>
                    [document callback] =>
                    [reindex callback] =>
                    [bundles changed callback] =>
                )

            [configuration] =>
            [uuid] => 1
        )

    [idKey:protected] => item_id
    [nameKey:protected] => item_id
    [statusKey:protected] => status
    [defaultLabel:protected] =>
    [uuid] => c1d3982f-31c8-4640-89b4-2f54334e4803
    [field_tc_short_description] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => short desc 2
                            [format] =>
                            [safe_value] => short desc 2
                        )

                )

        )

    [field_tc_short_title] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Short title 2
                            [format] =>
                            [safe_value] => Short title 2
                        )

                )

        )

    [field_tc_title] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Treatment Category 2
                            [format] =>
                            [safe_value] => Treatment Category 2
                        )

                )

        )

    [field_treatments] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 10
                            [revision_id] => 10
                        )

                    [1] => Array
                        (
                            [value] => 11
                            [revision_id] => 11
                        )

                )

        )

    [rdf_mapping] => Array
        (
        )

    [entity_view_prepared] => 1
)

```

The `[fieldInfo:protected]` fields I'd like to remove, but I haven't found an options/methods to do so. Any thoughts?

# Answer
> 0 votes
For anyone looking to do this, the answer is pretty simple.

entity\_metadata\_wrapper-\>value() returns an object, complete with protected properties. To get only the values from the result, you can use php's get\_object\_vars() function.

This returns data equivalent to a normal entity-\>export() call in terms of data, although I believe export returns JSON instead of the array you get here.

So:

```
// Wrap an existing entity.
$wrapper = entity_metadata_wrapper('entity_type', $entity);

// Get the object representation of that entity.
$entity_data = $wrapper->value();

// Strip all properties (including :protected),
// and get an array representation of that data.
// This is the same data you get from entity->export(),
// but in array form.
$final_data = get_object_vars($entity_data);

```

Hope this helps someone.

# Answer
> 0 votes
use `array_walk` and scan the entity array to see if the `key` has the substring `:protected` in it. If yes, then `unset()` the array key.

# Answer
> 0 votes
You can't, because what you're seeing it's not an array, but an object, so you can't simply unset protected properties, because they're **protected** for the reason.

> Members declared protected can be accessed only within the class itself and by inherited classes.

This is how PHP OOP visibility works. So you should find appropriate getter/setter method to change that member of class or extend that class and define one.

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


# Question
Title: How to get field value having stdClass from views?
I am attempting to retrieve a value in a Fivestar rating field using views PHP. So far nothing I have attempted has been successful.

Here is the output from `print_r($data)`:

```
PHP: stdClass Object ( [entityform_created] => 1448480841 [entityform_id] => 2 [field_data_field_rating_entityform_entity_type] => entityform [_field_data] => Array ( [entityform_id] => Array ( [entity_type] => entityform [entity] => Entityform Object ( [uid] => 1 [entityType:protected] => entityform [entityInfo:protected] => Array ( [label] => Entityform Submission [entity class] => Entityform [controller class] => EntityformController [base table] => entityform [fieldable] => 1 [entity keys] => Array ( [id] => entityform_id [bundle] => type [revision] => ) [bundles] => Array ( [current_feelings_about_job] => Array ( [label] => current feelings about job [admin] => Array ( [path] => admin/structure/entityform_types/manage/%entityform_type [real path] => admin/structure/entityform_types/manage/current_feelings_about_job [bundle argument] => 4 [access arguments] => Array ( [0] => administer entityform types ) ) [rdf_mapping] => Array ( ) ) [job_test] => Array ( [label] => job test [admin] => Array ( [path] => admin/structure/entityform_types/manage/%entityform_type [real path] => admin/structure/entityform_types/manage/job_test [bundle argument] => 4 [access arguments] => Array ( [0] => administer entityform types ) ) [rdf_mapping] => Array ( ) ) ) [bundle keys] => Array ( [bundle] => type ) [view modes] => Array ( [full] => Array ( [label] => Full content [custom settings] => ) [email] => Array ( [label] => Email [custom settings] => ) [confirmation] => Array ( [label] => Confirmation [custom settings] => ) [download] => Array ( [label] => Downloads [custom settings] => ) [table] => Array ( [label] => Submissions Table [custom settings] => ) [review] => Array ( [label] => Review [custom settings] => ) [token] => Array ( [label] => Tokens [custom settings] => ) ) [label callback] => entity_class_label [uri callback] => entityform_uri [creation callback] => entityform_create [access callback] => entityform_access [module] => entityform [admin ui] => Array ( [path] => admin/structure/entityforms/list [front path] => entityform [file] => entityform.admin.inc [controller class] => EntityformUIController [menu wildcard] => %entityform ) [metadata controller class] => EntityformMetadataController [metatags] => [static cache] => 1 [field cache] => 1 [load hook] => entityform_load [translation] => Array ( ) [base table field types] => Array ( [entityform_id] => serial [type] => varchar [language] => varchar [created] => int [changed] => int [data] => blob [uid] => int [draft] => int ) [schema_fields_sql] => Array ( [base table] => Array ( [0] => entityform_id [1] => type [2] => language [3] => created [4] => changed [5] => data [6] => uid [7] => draft ) ) [token type] => entityform [configuration] => ) [idKey:protected] => entityform_id [nameKey:protected] => entityform_id [statusKey:protected] => status [defaultLabel:protected] => [wrapper:protected] => [entityform_id] => 2 [type] => current_feelings_about_job [language] => [created] => 1448480841 [changed] => 1448480841 [data] => [draft] => 0 [field_rating] => Array ( [und] => Array ( [0] => Array ( [rating] => 100 [target] => ) ) ) [field_please_tell_us_why_optiona] => Array ( [und] => Array ( [0] => Array ( [value] => good day at work [format] => [safe_value] => good day at work ) ) ) [field_job_your_industry] => Array ( [und] => Array ( [0] => Array ( [tid] => 5 ) ) ) [field_job_title] => Array ( [und] => Array ( [0] => Array ( [value] => sales [format] => [safe_value] => sales ) ) ) [rdf_mapping] => Array ( ) ) ) ) [field_field_rating] => Array ( [0] => Array ( [rendered] => Array ( [#attributes] => Array ( [class] => Array ( [0] => clearfix ) ) [#theme_wrappers] => Array ( [0] => container ) [user] => Array ( [#theme] => fivestar_formatter_percentage [#instance_settings] => Array ( [stars] => 7 [allow_clear] => 1 [allow_revote] => 1 [allow_ownvote] => 0 [target] => none [user_register_form] => ) [#display_settings] => Array ( [widget] => Array ( [fivestar_widget] => default ) [expose] => 1 [style] => user [text] => average ) [#item] => Array ( [count] => 1 [user] => 100 [average] => 100 ) ) [#access] => 1 ) [raw] => Array ( [count] => 1 [user] => 100 [average] => 100 ) ) ) )

```

The field I am attempting to retrieve data from is field\_rating. Any ideas on how to accomplish this?

# Answer
Since `$data` is a stdClass object which seems to contain your entityform (based on your `entityform_x` values), you can load it as a metadata wrapper and then get the value of it via `value()` method, e.g.:

```
$wrapper = entity_metadata_wrapper('entityform', $data->entityform_id);
$rating = $wrapper->field_rating->value();

```

See: Entity metadata wrappers.
> 1 votes

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


# Question
Title: How to add js code in the head using a function? For a single page
How can I add a js code in the `<head>` **for a single page** using a function?

I found this module https://www.drupal.org/project/js\_injector but it seems overkilling just for this.

# Answer
> 1 votes
Please consult function drupal\_add\_js

> **$options:** (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'/'external'), or an associative array. JavaScript settings should always pass the string 'setting' only. Other types can have the following elements in the array:
>
> **type:** The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'. **scope:** The location in which you want to place the script. Possible values are 'header' or 'footer'. If your theme implements different regions, you can also use these. Defaults to 'header'.

Note scope option in the text above.

Consult this post: Load JS & CSS Files on Specific Pages in Drupal 7 for direction on using a template preprocess function wherein to add the js.

---
Tags: 7
---


# Question
Title: Caching Views: Query results Vs Rendered Output
Can you think of an example when it would be beneficial to have the Query Results cache time be longer than the Rendered Output time? or vice versa?

# Answer
> 4 votes
First some explanations:

Caching your query results, means you store the results. So the next page load you don't have to perform your heavy time consuming SQL query again.

Caching the rendered output means you cache the generated HTML output; the system does not have to render the page again.

It would make sense to have most of these exipire at the same time, after all, if the data changes, you'd want to show the changes to the user.

The only situation I can think of to cache the query results longer than the SQL data, is in a situation where the template file changes very often. Your theme might for instace randomly change the color of each table row, or show the current time (provided via a theme variable and a preprocess function) on the display. You might want to keep this out of the cache to give the user the impression the data is current, while still being able to serve the page relatively fast.

Caching the rendered output longer than the query seems like a bad idea. You'd be performing the resource intensive SQL query for new data, yet discard the data directly because you choose to display the old data instead. So I'd recommend against doing that.

# Answer
> 1 votes
# Query results

Below are some situations (cases) that are impacting the choices you'd make for Query results cache time:

* ### Case 1 - Your resources are not unlimited

A query that is extremely expensive to execute (eg the number of server resources you'd need for it, like memory, etc). And those resources that you'd need for it are limited.
* ### Case 2 - Your data only change periodically

A query of which you are sure that the data to which these queries only get updated once a day, week, month, year.
* ### Case 3 - Up-to-date information is not free

Assume your data are about current values (market values) of stocks, goods, whatever. Users who are willing to pay a premium price get updates every X seconds / minutes, while users not willing to pay that price only get those updates every day or so.

# Rendered output

A sample could be that you're using this view on a site where you're trying to implement the BigPipe technique, similar what is done in Drupal 8's BigPipe module. Here is a quote from its project page:

> Sends pages in a way that allows browsers to show them much faster. First sends the cacheable parts of the page, then the dynamic/uncacheable parts.

Refer to the great videos on this project page to get the idea, and/or to these related links:

# Conclusion

IMO selecting a value for either of those 2 caching options should be done independent from the other caching options. And even though their values may be set the same, there is no real reason why they should be the same.

---
Tags: views, 8, caching
---


# Question
Title: How to attach/upload a file to node using restws?
I've got a content type with "File" field and "File" widget. I am **successfully** able to create a node **without** a file using **restws**. But, if I want to attach a file to it, it just doesn't allow me to do that. I've tried many different things, but with failure.

Also, when accessing a node with file already attached to it, using get request (e.g. {domain\_name}/node/219.json), the file field is displayed as an empty element, even though file is existing and is displayed fine when viewing the node in edit mode from admin area.

E.g.

JSON:

```
"field_simple_file":[]

```

XML:

```
<field_simple_file/>

```

The node array without file field, that succeeds is as below:

```
$new_node = array(
    'body' => array(),
    'type' => 'simple',
    'title' => 'Content created with restws',
    'language' => 'und',
    'status' => 1,
    'promote' => 0,
    'sticky' => 0,
    'author' => 1
);

```

And content-type:

```
'Content-Type: application/json'

```

But I think, I am not 100% sure on how to include a file in it (have tried few different things), which might be leading to failure. Can anyone provide me with guidance for attaching/uploading a file with restws please?

# Answer
> 1 votes
Here is the URL to access a node with file already attached to it

`{domain_name}/[end-point]/node/219.json`

Here 219 is the nid of the node.

Here is the sample JSON format to attach a file to node (node create).

```
{
    "title": "title_of_node",
    "type": "bundle_name",
    "field_samplefile": {
        "und": [{
            "fid": "17",
            "filename": "changes.txt",
            "uri": "public://changes.txt",
            "filemime": "text/plain"
        }]
    }
}

```

# Answer
> 1 votes
I created (and I am maintaining) the RESTful web services support for files and images module, which I believe does exactly what you were asking for.

> This module provides support for creating and updating fields of type file and image. It accepts (multiple) image/file data as base64\_encoded strings in the JSON payload.

It requires the RESTful Web Services module.

---
Tags: services, files, 8
---


# Question
Title: How do I get a date selector field in a content entity?
I have a content entity in Drupal 8 that generates form for datetime. I just want to show only the date selector in the form, but it shows date and time selectors.

```
     $fields['start_date'] = BaseFieldDefinition::create('datetime')
            ->setLabel(t('Start date'))
            ->setDescription(t('The date that the survey is started.'))
            ->setRequired(true)
            ->setDisplayOptions('view', array(
                'label' => 'above',
                'type' => 'string',
                'weight' => -4,
            ))
            ->setDisplayOptions('form', array(
                'type' => 'date',
                'weight' => -4,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);

```

>

How do I show only the date selector?

# Answer
Your problem is that you are setting the option on the form and not the field. The datatime field has an option, `datetime_type` which can be two strings 'date' or 'datetime' (see `DateTimeItem`), and it defaults to 'datetime'.

So, when you are creating your field, you need to update this setting. The following should work for you:

```
$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('The date that the survey is started.'))
  ->setSetting('datetime_type', 'date')
  ->setRequired(true)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

As a side note, when you are having problems like this, the first place to look is at the class implementing the field that you are using, and then look at the tests that cover that field. Often, you will find the example code that you need. In this case, you would look at `DateTimeFieldTest` and see what that integration test is doing.
> 11 votes

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


# Question
Title: Render Array for hook_field_formatter_view not displaying
I'm updating this question on the suggestion of the initial provided answer.

When trying to render out the content of my custom field, outputting the data into a custom theming function to render on to the page when using the suggested method is resulting in the theming function being ignored, even when attempting to output just static strings of text or using the devel module to test it, nothing happens, the code is updated as below

```
/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
  foreach ($items as $delta => $item) {
    if ($file = file_load($item['image'])) {
      list($hours, $mins, $secs) = explode(':', $item['time']);
      $time = ((3600 * $hours) + (60 * $mins) + $secs);
      $element[$delta] = array(
        '#theme' => 'mymodule_formatter',
        '#image' => (array) $file,
        '#time' => $time,
        '#comment' => $item['comment'],
      );
    }
  }
return $element;
}

```

Hook and Theming function

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array('variables' => array()),
      'file' => 'theme_mymodule.inc',
    ),
  );
}

```

In the theme\_mymodule.inc file

```
/**
 * Returns HTML for a MyModule.
 */
function theme_mymodule_formatter($variables) {
  $output = t('test');

  return $output;
}

```

I think I'm a little confused about the naming of the theme hook, when I was copying the image module, the `#theme` variable was just declared as 'image\_formatter' but the function named was 'theme\_image\_formatter', I'm wondering if I've declared my theme hook wrong.

**--Previous question--**

Im trying to write my own custom field in my own module, I've written the field setup, and it's accepting and evaluating data fine, that's all good. I'm struggling to grasp what I need to do when trying to write my own theming output function. As an example to the parts of code I'm working on:

```
/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
  foreach ($items as $delta => $item) {
    if ($file = file_load($item['image'])) {
      list($hours, $mins, $secs) = explode(':', $item['time']);
      $time = ((3600 * $hours) + (60 * $mins) + $secs);
      $variables = array(
        'image' => (array) $file,
        'time' => $time,
        'comment' => $item['comment'],
      );
      $element[$delta] = theme('mymodule_formatter', $variables);
    }
  }
return $element;
}

```

And my theming function

```
/**
 * Returns HTML for a MyModule.
 */
function theme_mymodule_formatter($variables) {
  $item = $variables['image'];
  $image = array(
    'path' => $item['uri'],
  );

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($variables['image_style'])) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image);
  }
  else {
    $output = theme('image', $image);
  }

  return $output;
}

```

Now this returns the correct HTML for my image, so it actually returns a string like

```
<img typeof="foaf:Image" src="[img_path]" width="120" height="90" alt="" />

```

However this doesn't actually render on my page, it doesn't come back with an error, it just doesn't show anything.

When I change my `$element[$delta]` line in my `hook_field_formatter_view()` function to say

```
$element[$delta] = array('#markup' => theme('mymodule_formatter', $variables));

```

By putting the element into a `'#markup'` array, it does actually render the image, however I don't want to just throw everything into a `'#markup'` array if that's not the proper way of doing it.

# Answer
> 2 votes
To add markup that's already been prepared to a render array, you would indeed use `#markup`. There's nothing wrong with using it where appropriate.

However, since you're preparing the markup in the same function anyway, you may as well use the render array version of the call to `theme()`, e.g.

```
$element[$delta] = array(
  '#theme' => 'mymodule_formatter',
  '#image' => $image,
  '#another_var' => 'foo',
);

```

It provides better structure, makes it easier for other modules to alter if necessary, and is better for caching.

# Answer
> 0 votes
Right I've managed to work it out, I've done some additional reading on the render array information Clive posted in his answer, and followed the examples module slightly to realise what I'd done wrong. I'll mark the other answer as correct because what I actually wanted to know was what the correct method was for outputting the data

My problem was with this data

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array('variables' => array()),
      'file' => 'theme_mymodule.inc',
    ),
  );
}

```

Declaring the array in this way means the function is expecting an array called 'variables' as it's only parameter, so you need to declare any parameter it will receive first, so that they can then be passed properly.

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array(
        'image' => NULL,
        'comment' => NULL,
        'time' => NULL,
      ),
    ),
  );
}

```

Anyone having similar troubles I would suggest reading the 'render arrays' link in the other answer, and following the information in that.

# Answer
> 0 votes
Having never read properly about render arrays one issue related to this was driving crazy.

My theme function was receiving null values in the $variable arguments. This was my formatter view:

```
function my_videotype_field_formatter_view ($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = [];
  $settings = $display['settings'];
  foreach ($items as $delta => $item) {
    $element[$delta] = [
      '#theme' => 'my_video_player',
      '#item' => $item,
      '#settings' => $settings,
      '#entity_type' => $entity_type,
      '#entity' => $entity,
    ];
  }
  return $element;
}

```

And my theme declaration:

```
function my_videotype_theme ($existing, $type, $theme, $path) {
  $theme = [];
  $theme['my_video_player'] = [
    'variables' => [
      '#item' => NULL,
      '#settings' => [],
      '#entity_type' => NULL,
      '#entity' => NULL,
    ],
    'file' => 'includes/my_video.theme.inc',
  ];
  return $theme;
}

```

As it turns out (after reading this thread) the hash is actually important... so vars are passed with hash to signal they are data in render arrays, but are actually stripped of the hash to evaluate... (hard to explain). So the theme declaration expects variables=\>\[item=\>value\] not variables=\>\[item=\>#value\] as declared in the render array. Thus the correct theme declaration would be:

```
function my_videotype_theme ($existing, $type, $theme, $path) {
      $theme = [];
      $theme['my_video_player'] = [
        'variables' => [
          'item' => NULL,
          'settings' => [],
          'entity_type' => NULL,
          'entity' => NULL,
        ],
        'file' => 'includes/my_video.theme.inc',
      ];
      return $theme;
    }

```

The other strange thing is that when calling theme through function, not render array:

```
$u=theme('my_video_player',['#item'=>$item,'#settings' => $settings]);

```

It would work even with the hash on the theme declaration... confusing.

---
Tags: 7, theming, entities
---


# Question
Title: How do I change the dependencies of a library from another module
I have a Drupal 8 module with the following section in the file flot\_d8.libraries.yml

```
flot:
  version: 1.x
  css:
    component:
      css/flot.css: {}
  js:
    lib/jquery.flot.js: {}
    js/flot_d8.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

I have another module which is an optional dependency of flot. It does not need to be present, but if it is, it needs to be included in the dependencies section. So I need to add the line `- timezone_js/timezone_js` at the end...or, more likely, add the equivalent entry to the array that this yml file gets converted into.

Is there a way that one module can alter the assets of another module when it is installed?

I seems like I ~could~ just hard-code the line in myself, but I would like other people to be able to extend the flot module, without me having to add new dependency lines for every add-in.

Similarly, the Flot module has an element with a #pre\_render function. Is there a way that a module can add an entry to the pre\_render array of another module?

# Answer
> 2 votes
My flot plugin is called timezone\_js. I created a file, timezone\_js.module and added a call to hook\_library\_info\_alter.

```
function timezone_js_library_info_alter(&$libraries,$extension){
  //We need to add this module as a dependency of the flot module.
  if ($extension == "flot_d8") {
    $libraries['flot']['dependencies'][] = 'timezone_js/timezone_js';
  }
}

```

---
Tags: 8
---


# Question
Title: Error during "composer drupal-update" for Drupal 8.0.5
I've been running a Drupal 8 site since 8.0.0, using the Address module. As this required some CommerceGuys dependencies in the /vendor folder, I've been using the following commands to load dependencies (and update to newer versions of other components):

```
php sites/all/modules/composer_manager/scripts/init.php
composer drupal-update

```

However when I run this for 8.0.5, I'm getting the following error (not all output included):

> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
>
> * Removing guzzlehttp/promises (1.0.2)
> * Installing guzzlehttp/promises (1.0.3)
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
>
> * Removing guzzlehttp/guzzle (6.1.0)
> * Installing guzzlehttp/guzzle (6.1.1)
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
>
> * Removing symfony/browser-kit (v2.7.6)
> * Installing symfony/browser-kit (v3.0.3)
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
>
> * Removing fabpot/goutte (v3.1.1)
> * Installing fabpot/goutte (v3.1.2)
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
>
> * Removing behat/mink (v1.7.0)
> * Installing behat/mink (v1.7.1)
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Script Drupal\Core\Composer\Composer::vendorTestCodeCleanup handling the post-package-update event terminated with an exception
>
> \[RuntimeException\]
> The directory 'tests' in package 'behat/mink' does not exist.

The CommerceGuys modules components are not getting loaded. I'm not sure if this is because of the above exception.

This has worked for every previous Drupal 8 update, so I'm not sure what's different this time.

# Answer
> 3 votes
There is a patch available here - https://www.drupal.org/node/2664274#comment-10954323, which is RTBC.

I can confirm it's working :)

---
Tags: 8, composer
---


# Question
Title: Allowed memory size exhausted after importing PO file
I have a problem after importing the PO of the Drupal core 7.28 (I tried with French and Arabic), whenever I try to create a new feature or open the modules page, I will get an error:

> Allowed memory size of 268435456 bytes exhausted (tried to allocate 5126472 bytes) in .../includes/form.inc on line 3906

After the import, it is consuming a lot of memory and time I tried debugging, this is the path I could trace:

```
menu_execute_active_handler -> drupal_get_form -> drupal_build_form -> features_export_form -> _features_export_form_components -> _features_export_build

```

This is as far as I could get while debugging. The last function `_features_export_build` takes a lot of time but I couldn’t know what is wrong inside.

# Answer
Generating/exporting Feature modules takes a lot of memory, depending on amount of components which you're trying to export. The Features module is constantly improving, so please check the recent stable version if that makes the difference.

Otherwise you've to increase your PHP memory limit either in your `php.ini` or before the import, temporary add this line into your `settings.php` file:

```
ini_set('memory_limit','1G');

```

If you would like to debug what takes so much memory, then you need to use PHP profiler such as XDebug (`xdebug.profiler_enable=1`) or use XHProf.
> 0 votes

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


# Question
Title: Truncate tables before uninstalling a module in Drupal 8
I'm developing a module in Drupal 8, and because it handles quite a few relations between entities, I always need to add a bit of test data before being able to test the forms for the actual entity I'm working on after a uninstall/reinstall of the module. During install I can add this data in the module.install-\>xx\_install hook. But during uninstall I get the error

```
"The following reasons prevent the modules from being uninstalled: There is content for the entity type..."

```

I tried implementing the uninstall hook and truncate the table there, but it seems the check for existing content is done before this hook runs. How can I truncate the necessary tables without having to do it manually? Having to do it manually slows down development quite a bit. Alternatively, is there a way to speed up development of the entity forms and relations so that I don't always have to install/uninstall the module to see changes?

# Answer
That's a known issue right now.

There's no way right now to hook into that automatically. And it came up a few times already here too. See this question for example: Module uninstall dependencies

Beside a form or a drush command to do the cleanup, there really isn't much that you do right now, other than improving core. What I'd like to see is a message on the uninstall confirmation form that tells you that it will delete all records of entity type N and then does so in a batch before actually uninstalling. See the referenced flag issue in the other question and my repeated suggestions to open an issue, but so far, nobody could be bothered with doing that. And I didn't find time myself either.

**Update**

Drupal 8.2 now offers a link on the uninstall form to delete all entities of the given type.
> 8 votes

---
Tags: 8, installation
---


# Question
Title: How to conditionally update and import nodes using Migrate?
I need to migrate new nodes and update others in the same time. 2 installations of the same project are out of sync, which means, that the same `nid` may not indicate the same node on both sides. But I'm sure they're the same if their titles are equal. So I think, that I need a conditional field mapping, as illustrated in the following pseudocode:

```
if source_nid = destination_nid
  if source_title = destination_title
    addFieldMapping('nid', 'nid')
else
  continue

```

I have only one idea, how can I do this - split migrations into two different parts with filters managed by `prepareRow()` method (one of the for node updating, the other for import of new nodes). Is this the only way? I would appreciate something more elegant.

# Answer
OK, at least now I know, that splitting migration into two with filtered rows works just fine. `prepareRow` function looks like this:

```
public function prepareRow($row) {
  // If node exists on destination
  if ($node = node_load($row->nid)) {
    // Use the metatdata wrapper to pull values
    $node_wrapper = entity_metadata_wrapper('node', $node);
    // If destination title is the same as source title
    if ($node_wrapper->label() == $row->title) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  else {
    return FALSE;
  }
}

```
> 0 votes

---
Tags: migrations
---


title: Source of Zen theme variables

text:
# Question
Title: Source of Zen theme variables
This relates perhaps more to Sass then Drupal per se. But, it does come from a Drupal contrib theme; so- I'm hoping someone has encountered this or simply knows the answer.

Question is: where are some of the Sass variable set. For example $nav-height

In the sass file \_responsive.scss the following code

```
/* Navigation bar */
@media all and (min-width: 480px) {
  #main {
    /* Move all the children of #main down to make room. */
    padding-top: $nav-height;
    position: relative;
  }
  #navigation {
    /* Move the navbar up inside #main's padding. */
    position: absolute;
    top: 0;
    height: $nav-height;
    width: $zen-grid-width;
  }
}

```

No where can I fine where $nav-height was initialized or set. Yet, when sass is compiled, magically - somehow, the value is there.

Same question holds for the next variable "zen-grid-width".

# Answer
`$nav-height` is specified in the file \_init.scss (in the sass directory of your sub-theme) and the `$zen-grid-width` is set by the Zen Grids extension in the \_grids.scss file (and if you're developing a non-responsive theme it is set in the \_fixed.scss in the layouts directory of your sub-theme).
> 2 votes

---
Tags: theming
---


# Question
Title: Deploy block and block configuration to production instance
My clients create content and blocks in a staging environment (this is mandated by client) and then we use Deploy with Auto Deployment Plans to send the content over to the production server. They create a lot of blocks for different purposes and on the fly.

With Deploy (and UUID), while we are able to get the block copied over from staging-\>prod, the configuration of the block does not get transferred over. The client must login to the production environment and configure the block settings as an extra step. Is there a known way to copy over block configuration using Deploy (that is reasonable for a client with minimal Drupal knowledge)?

# Answer
> 0 votes
You should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

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

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

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

This module only started as of D7 (because of the "entities" of course that were only introduced in D7). Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

> **This module has been included with Drupal 8 core**. Refer to this issue for more information.

---
Tags: 7, entities
---


# Question
Title: Services Module Authentication with Username and Password in URL
I have to match the following format when implementing Services to maintain some legacy APIs that were poorly written. I understand this is horrible practice and we're going to provide a new better OAUTH2 option going forward but that doesn't change my issue.

https://www.example.com/service/ServiceController.svc?username=YOUR\_USERNAME&password=YOUR\_PASSWORD&travelCode=TRAVEL\_CODE

Short of writing my own authorization module that works with Services can anyone think of a method for getting this done using existing modules and Services.

I have tried Services Basic Authentication and Secure Services and either I am missing something or they don't do what I need.

Any help would be appreciated, I really don't want to customize something if I don't have to.

# Answer
By adding the following argument entries to my retrieve operation for my custom service I was able to achieve the desired effect.

```
                'args' => array(
                    array(
                        'name' => 'none',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'path' => '0'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'version',
                        'type' => 'int',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'version'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'username'
                        ),
                        'optional' => FALSE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'password'
                        ),
                        'optional' => FALSE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'id',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'id'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),

```
> 0 votes

---
Tags: services, tokens, users
---


# Question
Title: How do I modify a core field to use Ajax and add markup?
I am still getting the hang of D8... I have some entity types with various reference fields. I need to ajax in other values from another node type when changing the value of the entity reference select field I have.

Node type form 1:

```
#####################################
#  _____                            #
# |Title|                           #
#  ___________                      #
# |Description|                     #
#  _______________________________  #
# |Node type 2 select reference |v| #
#                                   #
#####################################

```

Whenever I select a node from the *Node type 2 select reference* field I would like to Ajax in a specific view mode of the node as `#suffix` markup. After selecting a node the resulting form should look like this:

```
#####################################
#  _____                            #
# |Title|                           #
#  ___________                      #
# |Description|                     #
#  _________________________        #
# |Some node (node id: 2) |v|       #
#                                   #
#  * Node 2 value from field 'a'    #
#  * Node 2 value from field 'b'    #
#                                   #
#####################################

```

I have attempted using `#ajax` property in a `hook_form_alter` on the select field but am not getting it to work due to errors. **What is the best approach here?**

# Answer
After much testing and finding a missing character in one line even I was able to come up with some working code:

```
<?php
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

function fsed_entry_form_eform_submission_fsed_entry_submit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_faculty_member']['widget']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'fsed_entry_faculty_member_ajax_callback',
    'wrapper' => 'faculty-member-details-wrapper',
  );
  $form['field_faculty_member']['widget']['#prefix'] = '<div id="faculty-member-details-wrapper">';
  $form['field_faculty_member']['widget']['#suffix'] = '</div>';
}

function fsed_entry_faculty_member_ajax_callback($form, &$form_state) {
  $nid = $form_state->getValue(array('field_faculty_member', 0, 'target_id'));
  if ($nid) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $storage->load($nid);
    $build = $view_builder->view($node, 'eform_preview');
    $output = render($build);
  }
  else {
    $output = '';
  }

  $form['field_faculty_member']['widget']['#suffix'] = $output . '</div>';

  return $form['field_faculty_member']['widget'];
}

```
> 3 votes

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


# Question
Title: Are Drush configuration files compatible across all Drush versions?
I've been using the same drushrc.php and aliases.drushrc.php files with Drush 6 and 7 and haven't noticed any problems; however, I also haven't used very complicated Drush configurations in the past.

I'm now using different versions of Drush (6-8) for different sites and am trying to confirm whether there are any significant compatibility issues with configuration files in different versions of Drush. I can't find a conclusive answer anywhere in the Drush documentation; anyone know?

# Answer
Drush configuration files, generally speaking, anyway, only set options for use in various Drush commands. If an unknown option is used directly on the commandline, this will result in an error; however, Drush ignores unknown options that are set in a configuration file. This makes it fairly safe to use the same configuration file for multiple versions of Drush. I have been using the same config file from Drush 5 to present without an issue.

If you do end up with some configuration tricks that only work with specific versions of Drush, you can always make a drush8rc.php file; this will only be loaded by Drush version 8, and will be ignored by all other versions of Drush.
> 4 votes

---
Tags: drush
---


# Question
Title: Feeds XPath parser - how to map to complex content types (eg to field collection field)
I've managed to import nodes of content using the XPath imporer, but where there are deeper levels of data structures, there seems to be no way to map data to a node.

I would have liked to have created these content types using the Field Collection module, but there's no support for that.

# Answer
You can use Field collection feeds module which provides feeds integration for field collection module.

You can read here how to import field collection using feeds.
> 0 votes

---
Tags: 7, entities, feeds
---


# Question
Title: How to programmatically save a value in a long text with summary field?
I have a content type which has a field of type "long text with summary".

When I to try programmatically save a node with the code below, the value is not being saved.

How can I save the data into the field and set the format to "full\_html"?

what does not work (assume the rest of the fields are set):

```
$node = new stdClass();
$node->type ='some_type';
$node->language = 'en';
node_object_prepare($node);
$node->field_custom_description_value = 'some_value';
$node->field_custom_description_format = 'full_html';

/* I also tried this */
$node->field_custom_description[$node->language][0]['value']-> 'some_value';
$node->field_custom_description[$node->language][0][format]-> 'full_html';

```

# Answer
You forget the `#` in the `#format`, use this:

```
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'filtered_html';

```

Read this: How to set the default format per content type at Drupal 7?
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: Some fields are not sorting properly in view
I'm trying to create a directory list in view. But some of the fields are not properly sorting.

**See the below image for my view configuration.**

**And the output of the view.**

**Update:** Style setting

**Update:** Field Settings

**Grouping**

Please anyone help me to get the correct output.

# Answer
> 0 votes
It's probably not a configuration problem. Examine the nodes that aren't sorting correctly. They likely have spaces at the beginning of their titles.

---
Tags: 7, views
---


# Question
Title: Error: Use drupal_write_record() to update only field
I created a custom module for Drupal 7. I have a custom form:

```
$query = db_select( 'taxonomy_term_data', 't' )
    ->condition( 't.vid', '5')
    ->fields('t', array('tid'))
    ->fields('t', array('name'));
$result = $query->execute();
foreach($result as $row){
  $phong_ban[$row->tid] = $row->name;
}

$default_phong_ban[] = '';
if(isset($node->field_phong_ban['und'][0]['taxonomy_term']->tid)){
  $default_phong_ban = $node->field_phong_ban['und'][0]['taxonomy_term']->tid;
  $form['phong_ban_is_new'] = array(
    '#type' =>'hidden',
    '#value' => 1,
  );
}
$form['phong_ban'] = array(
    '#type' => 'select',
    '#title' => t('Lựa chọn phòng ban'),
    '#title_display' => 'invisible',
    '#options' => $phong_ban,
    '#default_value' => $default_phong_ban,
    '#states' => array(
        'visible' => array(
            'select[name="state"]' => array('value' => 'chuyen_xuong_phong_xu_ly'),
        ),
    ),
    '#required' => true,
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Thực hiện'),
  '#attributes' => array(
      'id' => 'edit-submit-form-moderation',
  ),
);

```

And a form submission handler.

```
    $values = array(
      'entity_type' => 'node',
      'bundle' => 'danh_gia_tac_dong_moi_truong',
      'entity_id' => $node->nid,
      'revision_id' => $node->vid,
      'language' => 'und',
      'delta' => 0,
      'field_phong_ban_tid' => $form_state['values']['phong_ban'],
  );
    drupal_write_record('field_data_field_phong_ban', $values, 'entity_type');
    drupal_write_record('field_revision_field_phong_ban', $values, 'entity_type');

```

The code causes the following error.

# Answer
> 2 votes
You should not update the fields directly with sql queries. You can use following function (as Shubham said in the comment) :

field\_attach\_update

> Save field data for an existing entity.
>
> When calling this function outside an entity save operation be sure to clear caches for the entity:
>
> entity\_get\_controller($entity\_type)-\>resetCache(array($entity\_id))

What you simply need to do is :

```
$node = node_load($nid); // Load the node
$node->field_name[LANGUAGE_NONE][0]['value'] = 'Update value'; // Update value
field_attach_update('node', $node); // Update field vlaue
entity_get_controller('node')->resetCache(array($node->nid)); // clear entity cache

```

---
Tags: 7, database
---


# Question
Title: How to upload image or video from mobile device to content
Creating node via mobile browser goes ok, but when adding image or video i can only record and upload which also works fine, but i can not access gallery and choose an image to upload.

Options available after clicking Choose file are:
\- Camera
\- Camcorder
\- Voice Recorder
\- Documents

# Answer
> 1 votes
That's a mobile OS issue. But in general, documents will open a list and show file managers at the bottom.

---
Tags: 7, files, media
---


# Question
Title: How to set a value on a field collection using entity metadata wrapper
I'm trying to programmatically set a value on a field collection item attached to the user entity.

The field collection field in question is titled, `field_user_location`.

I initially had this ($usr\_wrapper being an entity metadata wrapper of the user entity)

```
$usr_wrapper->field_user_location->field_land_phone->set($object['Phone Number']);

```

However that doesn't appear to work.

How do you get data onto a field collection via `entity_metadata_wrapper()`? There isn't much documentation about how to do this that I am seeing.

# Answer
I found the documentation for field collections confusing as well.

Field collections need their own entity metadata wrapper. So, the following code would work for your example:

```
$collection = entity_create('field_collection_item', array('field_name' => 'field_user_location'));
$collection->setHostEntity('user', $user);
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $collection);
$fc_wrapper->field_land_phone->set($object['Phone Number']);

```

I hope that helps for anyone else banging their heads over this.
> 4 votes

# Answer
Based on your example, the could should be:

```
global $user;
$usr_wrapper = entity_metadata_wrapper('user', $user);

// Create the collection entity and set its "host".
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_user_location')); // Name of collection field.
$field_collection_item->setHostEntity('node', $usr_wrapper->value());

// Now define the collection parameters.
$collection = entity_metadata_wrapper('field_collection_item', $field_collection_item);
$collection->field_land_phone = "0123"; // array("0123") in case of multi-valued field.
// $collection->field_land_phone->set("0123"); // Version using set(), use: set(array("0123")) for multi-valued field.

// Save.
$collection->save(); // Or: $usr_wrapper->save();

```

Also check Entity metadata wrappers documentation page (check for *Example using field collections*).

---

Here is another example which adds an entry to a node with a field collection named `field_activity_log`:

```
  // Load the controller class file.
  module_load_include('inc', 'entity', 'includes/entity.controller');

  // Use the currently logged in user if a $uid argument is not defined.
  global $user;
  if (empty($uid)) {
    $uid = $user->uid;
  }

  $now = gmdate('Y-m-d H:i:s'); // Grab the current time.

  // Setup the values in the structure expected by the field_collection entity.
  $values = array(
    'field_name' => 'field_activity_log',
    'field_activity_log_date' => array(
      LANGUAGE_NONE => array(array('value' => $now)),
    ),
    'field_activity_log_message' => array(
      LANGUAGE_NONE => array(array('value' => $message)),
    ),
    'field_activity_log_user' => array(
      LANGUAGE_NONE => array(array('uid' => $uid)),
    ),
  );
  $entity = entity_create('field_collection_item', $values);

  // Attach the field_collection entity to the application node. This has to
  // happen separately so that it actually works -- you can't just specify
  // this via the $values array.
  $entity->setHostEntity('node', $node);

  // Save the entity. Since it's attached to the right application node, this
  // will both create the field_collection entity and update the application
  // node to point to the new field_activity_log record.
  $entity->save();
?>

```

Source: Example: Programmatically adding field collection entries to a node

And this example shows updating (loading/editing/saving) an existing field collection in an Entity Wrapper:

```
<?php
// Load the node by NID
$raw_node = node_load($nid);
// Wrap it with Entity API
$node = entity_metadata_wrapper('node', $raw_node);
// Get the first item from the muli-value field collection
$raw_collection = $node->field_collection->value();
// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
//dsm the old value
dsm($collection->field_example->value());
// Set a new value on the field_example textfield.
$collection->field_example = 'New value';
// Save the changes to the entity
$collection->save();
?>

```

Source: Example: Programmatically create and update field collection with Entity API

---

### Troubleshooting

In case of error when setting the data value with `set()`, be be sure it matches the required data type and format. If your entity won't get saved, check for the logs for any wrapper exceptions (`drush ws --tail`).

See also: Modifying a field collection programmatically missing hostEntity fields at SO
> 0 votes

---
Tags: 7, entities
---


title: multiple views on same page

text:
# Question
Title: multiple views on same page
Say I am writing a page template to show the daily special menu of a restaurant. Each menu item is a content and has a field to store which day of a week it goes on special. The page will have 7 tabs(Mon, Tue, Wed etc) to display the query of that day.

I wonder how to achieve this in drupal 8?

# Answer
A simply solution is to use 7 regions for each day and put a view block in each of them.

More flexible is a solution in page preprocess putting the view block in variables:

```
foreach ( $days as $day ) {
  $variables['view_block_' . $day] = views_embed_view('menu_view', 'block_' . $day);
}

```

And use the variables in a similar twig loop.

Think about holidays or other special cases, in code you can realize all these things. If it gets more complicated, use contextual filters and arguments as third parameter of `views_embed_view()`.
> 1 votes

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


# Question
Title: Get all fields defined in a bundle for a view mode
Is it possible to get all the fields and field groups structures defined in a bundle for a view mode, in Drupal 8?

# Answer
If I understood your question correctly, you need to use the `entity_get_display()` function.

It will return the entity view display, associated with the bundle and view mode you wanted. Simplest example:

```
$display = entity_get_display($entity_type, $bundle, $view_mode);

```
> 1 votes

---
Tags: entities
---


# Question
Title: settings.php not in expected location(s)
We are trying to change the database settings for a long-standing drupal 6 site, but are having trouble finding the correct settings.php file:

```
$ cd /var/www/vhosts/mysite
$ find sites/ -name "settings.php*"
sites/default/settings.php.save
sites/default/settings.php.mod2
sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php
sites/mysite.com/settings.php.pre_handoff_unedited
sites/mysite.com/settings.php~
sites/mysite.com/settings.php.20131022

```

We renamed the two most likely suspects, but the sites continues to run smoothly:

```
sites/mobile.mysite.com/settings.php_hold
sites/mysite.com/settings.php_hold

```

I also looked for a sites.php that might be overriding settings.php, but we don't seem to have one of those either:

```
$ find sites/ -name "*sites.php*"
$

```

Which means I can't find a sites.php or settings.php anywhere in the web directory that seems to control drupal.

We have nginx set up to receive http requests and mysite.com requests are forwarded to apache. Could that be relevant? Where else I might look for the drupal config settings?

# Answer
You should search for setting file as:

```
find sites/ -name settings.php

```

as the file won't have any other name than `settings.php` (unless included from `settings.php`).

So you're down with these 2 valid entries:

```
sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php

```

Normally when you have `settings.php` in `sites/default` it applies to all sites, unless overridden by the site specific file (which is the case).

So:

* `sites/mobile.mysite.com` will work on sites like `mobile.mysite.com`
* `sites/mysite.com/settings.php` works on sites like `mysite.com`

---

Here is example from `default.settings.php` documentation page:

For example, for a fictitious site installed at `http://www.drupal.org/mysite/test/`, the `settings.php` file is searched in the following directories:

1. `sites/www.drupal.org.mysite.test`
2. `sites/drupal.org.mysite.test`
3. `sites/org.mysite.test`
4. `sites/www.drupal.org.mysite`
5. `sites/drupal.org.mysite`
6. `sites/org.mysite`
7. `sites/www.drupal.org`
8. `sites/drupal.org`
9. `sites/org`
10. `sites/default`

> The configuration directory will be discovered by stripping the website's hostname from left to right and pathname from right to left. The first configuration file found will be used and any others will be ignored. If no other configuration file is found then the default configuration file at `sites/default` will be used.

---

If you're still confused, please run `drush status` command to find the right settings file, e.g.

```
$ drush status | grep settings
 Drupal Settings File            :  sites/default/settings.php

```

or for specific site:

```
$ drush -l http://mobile.mysite.com status | grep settings

```

---
> 1 votes

# Answer
**Domain Wise settings.php file**

1) `sites/mobile.mysite.com/settings.php` --\> This is the original file for

2) `mobile.mysite.com domain`

3) `sites/mysite.com/settings.php` --\> This is the original file for mysite.com Domain

4) `sites/mysite.com/settings.php~` --\> This file is last edited and it has the recent changes. But due to unexpected closing of editing application(like vi or emac editor) the file changes are saved in this file

Also you can use below commands to check the last file modification time for all above three files.

e.g.

```
file sites/mobile.mysite.com/settings.php
stat sites/mobile.mysite.com/settings.php

```
> 0 votes

---
Tags: 6, multi-sites, configuration
---


# Question
Title: Simplenews newsletter unsubscribe page- Access denied
I am using Simplenews newsletter module on my Drupal-7 website to send newsletters, but when you click on the unsuscribe link, the user gets an access denied page-you need an account to view this page etc.
Where can I make this page visible to all users or/and change what this page says?
For example, instead of Access denied to show an image or say "Error" or something else.

# Answer
The access arguments for that page are `subscribe to newsletters`, meaning that you need to grant that permission to anonymous users, in order to allow them to unsubscribe without logging in.

Here's how to do that:

1. Navigate to `/admin/people/permissions`.
2. Find "subscribe to newsletters" item.
3. Grant the permission to anonymous users.

Note: I just told you how to allow to do it for everyone. You need to evaluate if this fits your website and workflows.
> 0 votes

---
Tags: 7, users, emails
---


title: How db_set_active works with other db?

text:
# Question
Title: How db_set_active works with other db?
Is db\_set\_active() need to work with a Drupal database or can I use it with a database that doesn't contain any drupal tables ?

# Answer
> 2 votes
`db_set_active()` is used for connecting to another database. The other database does not need to be Drupal at all.

Just don't forget to switch back to default DB when you are done. If you don't, Drupal will try to perform all subsequent queries in the other database, which will result in a lot of errors and potentially mess up the data in the other database.

Here's example code:

```
// Connect to your other database.
db_set_active('your_other_db');
// Run any queries you want.
db_query("...");
// Switch back to the default database of your installation.
db_set_active();

```

You can read more about `db_set_active()` here.

Another note, per Neograph734's reminder: the argument you would pass to the `db_set_active()` needs to be the same key you used for adding another DB access info in `settings.php` file.

Here's an example:

```
$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'your_default_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_other_db' => array (
    'default' => array (
      'database' => 'your_other_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

---
Tags: 7, database
---


title: Revisions revert unexpectedly

text:
# Question
Title: Revisions revert unexpectedly
I have a really horrible intermittent bug where a collection of nodes will reset to a previous revision.

Here is an image of the revisions tab on the node:

There are three unusual aspects:

* The 'current revision' is at the bottom of the list and has lower vid than the rest.
* The date of the 'current revision' is yesterday but the low vid implies it was created a while ago.
* The revision log says "Updated by FeedsNodeProcessor" yesterday but the Feeds log tells me "Last run 1 week ago".

I'm hoping someone can point me in the right direction on where to look for a cause since I can't replicate the behaviour.

It feels like the vid in the {node} table has been changed. Along with the created date and revision timestamp. I'm really not sure how that could happen, though...

**EDIT: Current Hypothesis**

I have a custom module that updates a field. It uses a cron queue, so I'm wondering if the queue contains stale node data:

```
/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();

  $queue = DrupalQueue::get('ih_video_transcripts');
  foreach($videos as $video) {
    $queue->createItem($video);
  }
}

```

In my queue's `'worker callback'`, I should probably reload the node in case the object has been left in the queue for some time? And ensure I set `$node->revision = TRUE` before `node_save`?

# Answer
> 0 votes
I tested my hypothesis above and it was correct. The queue isn't fully processed during a cron run, so there are stale node objects sitting in the `queue` table in the database. The solution was to reload the node in the worker callback.

**Original Code**

```
/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();

  $queue = DrupalQueue::get('ih_video_transcripts');
  foreach($videos as $video) {
    $queue->createItem($video);
  }
}

/**
 * Implements hook_cron_queue_info().
 */
function ih_transcript_import_cron_queue_info() {
  $queues['ih_video_transcripts'] = array(
    'worker callback' => 'ih_transcript_import_import_transcript',
    'time' => '60',
  );
  return $queues;
}

/**
 * Implements callback_queue_worker().
 */
function ih_transcript_import_import_transcript($video_node) {
  // THIS IS THE PROBLEMATIC PART, $video_node is stale since it is
  // pulled from the queue table of the database and there may have been
  // multiple cron runs since it was created (2 days in my case).
  $video_node->field_transcript_text[$video_node->language][0]['value'] = "My value";
  node_save($video_node);
}

```

**The Fix**

```
/**
 * Implements callback_queue_worker().
 */
function ih_transcript_import_import_transcript($video_node) {
  // THIS IS THE IMPORTANT FIX, reload the video node to ensure
  // we are saving the most up to date data.
  $video_node = node_load($video_node->nid);

  $video_node->field_transcript_text[$video_node->language][0]['value'] = $transcript_text->data;
  node_save($video_node);
}

```

**Better Fix**

Save ONLY the node Id in the queue rather than the entire node. Also, I added some code to ensure that there are no duplicates in the queue. My queue table had 64000 records!!

```
/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();
  $currentQueueItems = array();
  $claimedItems = array();

  $queue = DrupalQueue::get('ih_video_transcripts');

  // We only want to add an item to a queue if it doesn't already exist in the
  // queue to avoid the queue table becoming massive.  Retrieve a list of
  // node ids that already exist in the queue.
  while($item = $queue->claimItem()) {
    $currentQueueItems[] = $item->data;

    // Store a copy of the claimed items, so we can release them again. We
    // only claim them in order to grab the node Id, so need to release again
    // to allow processing.
    $claimedItems[] = $item;
  }

  // Release claimed queue items to allow them to be processed by other workers.
  foreach($claimedItems as $claimedItem) {
    $queue->releaseItem($claimedItem);
  }

  foreach($videos as $video) {
    // Don't add videos that already exist in the queue.
    if(!in_array($video->nid, $currentQueueItems)) {
      $queue->createItem($video->nid);
    }
  }
}

/**
 * Implements hook_cron_queue_info().
 */
function ih_transcript_import_cron_queue_info() {
  $queues['ih_video_transcripts'] = array(
    'worker callback' => 'ih_transcript_import_import_transcript',
    'time' => '60',
  );
  return $queues;
}

/**
 * Implements callback_queue_worker().  Can also be called independently of cron
 * to import a single transcript.
 */
function ih_transcript_import_import_transcript($video_nid) {

  $video_node = node_load($video_nid);

  $video_node->field_transcript_text[$video_node->language][0]['value'] = $transcript_text->data;
  node_save($video_node);
}

```

---
Tags: 7, feeds, cron, nodes, queue
---


title: Views - Rewrite Results doesn't work

text:
# Question
Title: Views - Rewrite Results doesn't work
i have three field to show in views: title,body,desc. in desc I choose rewrite results and then put those \[title\] \[body\] but nothing shows up. i used inspect element by chrome, desc is here but empty.

# Answer
Add a field `Global: Custom text` at the end of your field list, add the replacement patterns in the \`Text' box.

The is from the comment by Dom Day which worked for me. Still wondering why the method in the question produced no output at all.
> 1 votes

---
Tags: views
---


# Question
Title: Is there a way to "hard-reset" a module?
I'm not sure why, but I am having extreme problems with several modules, but most noticeably, the signup module. The problems that I am having are sudden, and were not there yesterday, so I know it isn't a problem with the design of the module. I have tried patches, but those have caused other problems. Then it occurred to me: why should I have to do anything like that? Shouldn't there be a way to "hard-reset" a module? (ie remove the module and any remnance of it from the drupal database, and start from scratch as if the module was never installed in the first place, and then go and reinstall it) I have tried uninstalling it, deleting the module files, and the re downloading it and enabling it, but I get the same errors when I enable it again. How can I be delete it as if it was never there to begin with so I can start with a clean slate?

# Answer
> 7 votes
This answer reflects my understanding of how Drupal is working. Anyone with more or different understanding, please speak up, I'd love to know more.

Removing all remnants of a module by uninstalling it works only as well as the code included by the module for cleaning up after itself. For instance, if it has made a change such as adding tables or otherwise changing the database and does not properly delete the tables, they will remain there. Removing the module, should remove much of its potential to cause a problem provided that Drupal core knows it is gone and does not hang up looking for hooks that the module provided. Have you run 'update.php' in the URL? This will cause Drupal to update all the connections to the module. If the module is gone, then it won't make calls to it that cannot be responded to.

The only way to really reset Drupal is to maintain backups. Make backups before installing any module and at least every day or so during site development. The module Backup and Migrate is a simple way to simplify site database backups. In addition, it is also a good idea to look into using Git to keep track of your code when developing a site. Git is basically a unix tool, but there are windows UI versions such as GitGui that are not difficult to learn and put to work keeping track opf your code.

# Answer
> 4 votes
Based on your comment referencing the error below, I don't think a hard reset will help:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'masada\_drupal.field\_data\_field\_date' doesn't exist: SELECT COUNT(\*) AS expression FROM (SELECT n.nid AS nid, n.title AS title, n.type AS type, s.status AS signup\_status, s.close\_signup\_limit AS signup\_close\_signup\_limit, 1 AS expression FROM {node} n INNER JOIN {signup} s ON s.nid = n.nid LEFT OUTER JOIN {signup\_log} s\_l ON s.nid = s\_l.nid LEFT OUTER JOIN {field\_data\_field\_date} d ON d.entity\_id = n.nid GROUP BY nid, title, type, signup\_status, signup\_close\_signup\_limit) subquery; Array ( ) in PagerDefault-\>execute() (line 74 of /var/www/masadatactical.com/htdocs/includes/pager.inc)

This seems to be a known bug for the D7 port of the signup module. There is a patch in the first comment that may help.

---

To answer your question regarding how to 'hard reset' a module:

In a perfect world, I believe disabling the module and then uninstalling (not deleting) it will be equivalent to a 'hard-reset'.

Once 'un-installed' simply re-enable the module and you're done.

Given that it's not a perfect world, you may need to look in your DB for tables that were not properly 'uninstalled' and remove them manually.

I would recommend making a DB backup before you start deleting modules or tables.

You may want to search for known uninstall bugs for the signup module first.

# Answer
> 1 votes
The easiest way is to use drush and re-install the module, either by using Devel command:

```
drush -y dre foo

```

or using the standard way:

```
drush -y dis foo && drush -y pm-uninstall foo && drush -y en foo

```

You don't have you remove any files.

# Answer
> 0 votes
Did you actually uninstall the module or just disable it?

There is a tab on the Modules page called "uninstall." after you disable a module, you have to visit this tab to run the actual uninstall script for the module. If the module is build properly, this uninstall script will remove any trace of the module from the database.

# Answer
> 0 votes
I had similar problem with another module. Problem lied in some of the data that was stored in one of the Database tables of the module itself.

Hard resetting a module generally implies installing it afresh with default data in its tables. In Drupal-7, many modules provide methods to completely uninstall them by removing their database tables. This can be done by going to `admin/modules/uninstall`. After uninstalling it from here, you can re-install it and it will all new.

However, most modules don't provide this functionality. In that case, you will have to take slight risk by deleting the appropriate tables from the database. Just take a backup before going for the kill. Deleting the tables has worked just fine for me, in many instances. But let me warn you again. It is risky. After doing the deletion, check your site thoroughly if it's broken somewhere.

A better for doing manual deletion is to go look into the code of the module, and see which tables it has created. And then, delete the corresponding tables.

---
Tags: 7, installation
---


# Question
Title: Importing data using Feeds into dropdowns/select lists/taxonomy terms
I'm importing a set of users into my website using the Feeds module. The users have various details including company name. I wanted to make the company name field on the website a dropdown list rather than a free text field. I was thinking to make the company field a taxonomy vocabulary, and then add a taxonomy term reference field to the user profile. If I did this how would I import the company data for the user profiles using feeds?

For example if Mark Twain works at Penguin how do I import correctly his company into his record?

Would it be possible to create a new field in my CSV file for the company term ID and then import this into the term reference field in the user profile?

I'm using D7 with the custom user fields and not the old D6 user profile module.

# Answer
> 2 votes
Import the same way you would if it was a textfield. The taxonomy terms will be created for you and reused for terms with the same name.

# Answer
> 0 votes
Feeds module supports importing taxonomy terms, so you're free to use it as a select list. To create a new values, all you need to do is to set *Auto create* option in your Node processor mapping settings next to your field.

---
Tags: 7, taxonomy-terms, feeds, importing-exporting
---


title: Feeds auto create is not working

text:
# Question
Title: Feeds auto create is not working
Am using Drupal 7 Feeds module and I have "Autocomplete term widget (tagging)" field in content type.

As well as I have configured as "Auto create". But, when I import nodes that auto creation does not working, its shows the blank field.

Any other way to do?

# Answer
If Feeds creates empty values on *Auto create*, you need to verify your mapping. Make sure your *Context Value* in *XML Xpath parser* is fetching the right data by enabling *Debug* option, so you can see exact value being imported. If it's not, please validate your XPath on your sample data (for example, on XPath Tester).

If your XPath is correct, then use `hook_feeds_after_parse()` to debug your feed items.

```
/**
 * Implements hook_feeds_after_parse().
 * Invoked after a feed source has been parsed, before it will be processed.
 */
function MYMODULE_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  foreach ($result->items as &$item) {
    drupal_set_message(print_r($item, TRUE));
  }
}

```
> 0 votes

---
Tags: 7, taxonomy-terms, feeds, importing-exporting
---


# Question
Title: Multilanguage in IE does not allow to switch languages
My drupal site is built with 2 languages English/Portuguese, and the default language is English.

But in IE the default language (English) is overwritten and it only displays the Portuguese version, and if i click the English icon it does not change to English.

However if i browse with an English computer the English is displayed, but i can't still switch from Portuguese to English.

Some advice is appreciated.

# Answer
This answer is as simple as ticking a checkBox for the browser language, that for some reason in IE and Edge override the manual language switcher. The reason that i didn't find this before was that it was in a tab far from view.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: What is the purpose of entity_keys in ContentEntityBase?
I'm trying to figure out what is the purpose of `entity_keys` in `ContentEntityBase` entities and what fields should be set as `entity_keys`.

For example in \Drupal\node\Entity\Node we have such entity\_keys:

```
entity_keys = {
 "id" = "nid",
 "revision" = "vid",
 "bundle" = "type",
 "label" = "title",
 "langcode" = "langcode",
 "uuid" = "uuid",
 "status" = "status",
 "uid" = "uid",
}

```

Why exactly these fields are selected to be `entity_keys`? And, for example, why in \Drupal\comment\Entity\Comment `status` isn't in `entity_keys`?

# Answer
entity\_keys are basically an alias for fields. It allows generic code, like the storage backends, to access common fields that have different names, for example the ID. They need write the saved value, so the can't just use id() as most places.

Internally, those keys are also used by generic methods like id(), label(), getRevisionId() and so on, so they work out of the box.

There isn't really a reason that comment doesn't define status. Nothing really uses status, if you search for getKey('status'), there are no matches, while getKey('id') finds a lot.

Node only uses it internally for the isPublished().
> 14 votes

---
Tags: entities, 8
---


# Question
Title: Drupal-7 Where can I change the text from Simplenews unsubscription confirm page?
I want to edit the message of the simplenews confirmation message when you unsubscribe from a newsletter.
It is the simplenews\_confirm\_removal\_form but I can't track the code, to edit the message and the buttons' text.
Do you know where I can find it?

# Answer
> 0 votes
The button is present in the same function "simplenews\_confirm\_removal\_form".

See t('Unsubscribe') & t('Cancel') in line below:

```
return confirm_form($form, t('Confirm remove subscription'), '', t('This action will unsubscribe you from the newsletter mailing list.'), t('Unsubscribe'), t('Cancel')

```

);

And the message is present under "simplenews\_confirm\_removal\_form\_submit" function.

```
drupal_set_message(t('%user was unsubscribed from the %newsletter mailing list.', array('%user' => $form_state['values']['mail'], '%newsletter' => _simplenews_newsletter_name($form_state['values']['newsletter']))));

```

But if you want to change anything, editing it directly to the module is not advisable. The right way to do it is by using String overrides module or for hard coded way by using hooks, etc. by creating your own custom module.

# Answer
> 0 votes
Sounds as if you need the String Overrides module. From the project page:

> Provides a quick and easy way to replace any text on the site.

This includes messages as well. Here's what you would need to do:

1. Extract to your `sites/all/modules` directory.
2. Enable the module in `admin/build/modules`.
3. Configure the access permission in `admin/user/permissions`.
4. Visit `admin/config/regional/stringoverrides` and fill in the strings you'd like to replace. This is the string coming from Simplenews: `%user was unsubscribed from the %newsletter mailing list.`. Just change it to whatever you would like. You have the `%user` and `%newsletter` replacements available.

---
Tags: 7, emails
---


title: Libraries in custom module

text:
# Question
Title: Libraries in custom module
I have the following 2 files in 2 different directoties in a custom module directory.

modules/custom/calculator

This is my info.yml file (calculator.info.yml)

```
name: calculator
type: module
description: Calculator
core: 8.x
package: Custom

```

My css is in the directory modules/custom/calculator/css and js in the modules/custom/calculator/js directory

My libaries file is this: (calculator.libraries.yml)

```
base-style:
  version: VERSION
  css:
    component:
      css/wunderpage.css: {}
  js:
    js/wunderpage.js: {}
    js/jquery.matchHeight-min.js: {}

```

I also have a calculator.module file :

```
<?php

/**
 * @file
 * Contains calculator.module..
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function calculator_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the calculator module.
    case 'help.page.calculator':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Calculator') . '</p>';
      return $output;

    default:
  }

  function calculator_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'calculator/base-style';
  }
}

```

Still my css and js etc is not being loaded.

Somebody knows why my libraries are not being loaded?

# Answer
Either you made a mistake when copying and pasting that PHP code, or you defined `calculator_preprocess_page()` as being inside `calculator_help()`. Also, as Ivan Jaros also pointed out, Drupal 8 requires you to use `hook_page_attachments()` to attach page-level assets.

I do recommend you add these assets elsewhere in the code, preferably in the render array you build that actually needs the library.
> 1 votes

---
Tags: 8
---


# Question
Title: How can I switch to an external db with Views API?
In Drupal 7 I have a module with a `hook_form()`. This form is saving data into an external postgresql database.

I want to create a views to display data recorded. So I `used hook_views_data()` to create a mapping between the view and my custom tables. I created a view with admin but in this view I have the following error :

```
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cars' doesn't exist

```

I have tried something like this but it doesn't run :

```
function carshop_views_pre_render(&$view) {
  if ($view->name == 'cars_overview') {
    db_set_active('carsdb');
  }
db_set_active();
}

```

# Answer
Sounds as if you need the Views Database Connector module.

From the project page:

> Views Database Connector is a powerful module that gives Views full access to external database tables found in the settings for your Drupal installation. With this module, you can setup a view around any table in any database configuration. This can be extremely useful to pull external data from a database to show to your users in a view.
> 2 votes

---
Tags: 7, views, database
---


title: Display in node custom field profile

text:
# Question
Title: Display in node custom field profile
I created a custom field in the users profiles.

I need to display in node.tpl.php, this field for the author of the node.

I tried :

```
<?php
print $node_author = user_load($node->uid);
print ($node_author->field_custom);
?>

```

But i have an error :

```
Recoverable fatal error : Object of class stdClass could not be converted to string

```

Do you know where I'm wrong? And, is it the best way of proceeding?

# Answer
> 0 votes
Try with `print render($node_author->field_custom);`

Or you can try as well:

insert at the top of you node.tpl.php

```
<?php
global $user;
$node_author = user_load($user->uid);
$yourvariable = $node_author->field_custom;
?>

```

Where you want print the field insert:

```
<?php print $yourvariable['und'][0]['value'];?>

```

# Answer
> 0 votes
Replace the above code with below one:

```
<?php
  $node_author = user_load($node->uid);
  print ($node_author->field_custom);
?>

```

# Answer
> 0 votes
You are using print when assigning into a variable, that's you are getting error.

remove print from line 2 and the code should be as below

```
<?php
$node_author = user_load($node->uid);
print render($node_author->field_custom);
?>

```

# Answer
> 0 votes
Issue is in the way you are printing the value. actually `print` is just used for printing string, while `print_r` is used for printing array or Object. so in your case when you use `$node_author->field_custom`, then as it is an array, therefore it is not printing and giving you error. You can print it as below.

```
print_r($node_author->field_custom);

```

It will print the array, and will not give you error, however if you just want to print the value, then you can print somewhat like:

```
print $node_author->field_custom[LANGUAGE_NONE][0]['value'];

```

If above code doesnot work, then paste output of

```
print_r($node_author->field_custom);

```

It will give better approach.

//Edited

```
$image_url = file_create_url($node_author->field_custom[und][0]['uri']);
print render(theme_image($image_url));

```

Or

```
print render($node_author->field_custom);

```

---
Tags: 7, theming
---


title: How to Make Sitcky Item in Select List?

text:
# Question
Title: How to Make Sitcky Item in Select List?
I've got a Select List, let's say Apple, Orange, Raspberry. TBD.

I need TBD to be sticky at top of the list, while the other items are sorted alphabetically.

Recommendations on how to approach this?

# Answer
If it is an option you want to consider, you could use a convention for your select list values like so:

* 01-Apple.
* 02-Orange.
* 03-Raspberry.
* 00-TBD.

The sorted version of this list would look like so:

* 00-TBD.
* 01-Apple.
* 02-Orange.
* 03-Raspberry.

It's what I often do for any software where I somehow want to overrule the whatever sorting (eg to ensure my most often used folder names are always at the top) ... And it works in pretty much every OS I ever used (including mainframes ...)
> 0 votes

---
Tags: entities
---


# Question
Title: Can blocks being exist and displayed without being stored in blocks table?
I'm wondering what could be the problem.

When I queried the homebox\_default table , it showed bids with 1950 1387 1382 953 958 1916

but when queried in the blocks table for these blocks with these bids are not existant there was no blocks with those ids. But when I see the homebox/1 page it shows page with blocks. How is that possible?

# Answer
> 0 votes
Homeblock is actually not storing the data in block, it is actually inserting the data in its own custom table, like homeblock\_users.

```
  $data = new stdClass();
  $data->uid = $user->uid;
  $data->name = $page->name;
  $data->settings = $blocks;
  drupal_write_record('homebox_users', $data);

```

It is saving block data in hoemblock\_users table. It is creating only one Block i.e. Homebox custom block.

```
homebox_prepare_block

```

Above is the function through which dynamic block is created for a page, and all the variables are assigned to it.

---
Tags: blocks, dashboard
---


title: Using a field value as Twig attribute

text:
# Question
Title: Using a field value as Twig attribute
I need to set a field value as CSS class in a page template. How can I do it the Twig way?

`{{attributes.addClass('class-name')}}` is the way to set the class manually.

I have a list field to let the user set a background color for a part of the site. In Drupal 7 I used this code.

```
<div class="<?php print render($content['field_background']); ?>">

```

In Drupal 8, I can print the field with `{{ content.field_background }}`, but `<div class="{{ content.field_background }}">` doesn't work.

# Answer
This can be done in a few ways, you can do it all in the node template with Twig or you can create a preprocess function and create a variable for use in the node template. The key to learning what is in the array is to use Devel Kint. Without that, you won't know what is in the array.

First install Kint which comes with the Devel module for Drupal 8. Next, pick your node template (but this can be done in any kind of template) and examine the content variable like so (ideally at the bottom of the template).

```
{{ kint (content) }}

```

From this, we get debugging info printed on the page and if you expand the array, you'll see a whole slew of information. Right away, I see my background value and I can construct a path to print this out as

```
{{ content.field_background[0]['#markup'] }}

```

Now you can print this as a background style or class in a div

```
<div style="background-color: {{ '#' }}{{ content.field_background[0]['#markup'] }};" class="color-{{ content.field_background[0]['#markup'] }}">
<h2>Hello</h2>
</div>

```

I've tested this ands it works great, the div rendered the background color I had selected in my field list on node edit.

Now this is not ideal so we probably want to create a variable for this in a preprocess\_node in our theme's .theme file.

```
function MYTHEME_preprocess_node(&$vars) {
  $vars['bgcolor'] = '#' . $vars['content']['field_background'][0]['#markup'];
}

```

Now that I have a var created, it's much cleaner to print this out:

```
 <div style="background-color: {{ bgcolor }};" >
      <h2>Hello</h2>
    </div>

```

One note for above, you should probably wrap this with an if statement to check if it's empty or not.

This would work or structure the if statement where you like it

```
   {% if bgcolor %}
    <div style="background-color: {{ bgcolor }};" >
      <h2>Hello</h2>
    </div>
    {% endif %}

```
> 6 votes

# Answer
In a node template the fields are in `{{ content }}`. In a page template there is no content variable, instead there is a page variable which contains regions `{{ page.region }}`.

Since you asked about the page template, we can't use `content`.

But you can use {{ node }} in both templates. The node object is always in a node template and in the page template, when the page is displaying a node.

So this should work in both templates:

```
<div class="{{ node.field_background.value|clean_class }}">

```
> 3 votes

---
Tags: theming, 8
---