# Question
Title: add CSS programmatically for a specific page in .theme file
I have a question about adding a CSS file programmatically depending on which site I visit. In Drupal 7 I could achieve this by calling the following line in the preprocess\_html method in the template.php file:

```
function template_preprocess_html(&$vars) {

    $css_file_name = 'specific-page';
    drupal_add_css(path_to_theme() . '/css/pages/'.drupal_clean_css_identifier($css_file_name).'.css', array('group' => CSS_THEME));

}

```

But I can't achieve the same with Drupal 8. I tried the same like in 7 just with the new Drupal 8 way. So here are my tries in the template.theme file

```
use Drupal\Component\Utility\Html;

```

1.)

```
function template_page_alter(&$page) {

  $css_file_name = 'specific-page';
  $clean_alias = Html::cleanCssIdentifier($css_file_name);
  $path_to_css = drupal_get_path('theme', 'template') . '/css/pages/' . $clean_alias  . '.css';

  $page['#attached']['css'][] = $path_to_css;

}

```

2.)

```
    function template_preprocess_page(&$vars, $hook) {

      $css_file_name = 'specific-page';
      $clean_alias = Html::cleanCssIdentifier($css_file_name);
      $path_to_css = drupal_get_path('theme', 'template') . '/css/pages/' . $clean_alias  . '.css';

      $local_css = array(
        '#attached' => array(
          'css' => array(
            $path_to_css => array(
              'group' => CSS_THEME,
              'weight' => 9999),
          ),
        ),
      );

      drupal_render($local_css);

    }

```

Here I get the error: You are not allowed to use css in #attached

3.)

```
function template_page_alter(&$page) {

          $css_file_name = 'specific-page';
          $clean_alias = Html::cleanCssIdentifier($css_file_name);
          $path_to_css = drupal_get_path('theme', 'template') . '/css/pages/' . $clean_alias  . '.css';

          $vars['attached_css'] = array(
            '#attached' => array(
            'data' => $path_to_css,
            'options' => array(
             'group' => CSS_THEME
            ),
           ),
          );

}

```

In my template file:

```
{{  attached_css }}

```

None of my tries worked so far. I collect the information for the code from serveral tutorials and stackoverflow questions, but it looks like that many of them are very old comparing to the stable release date of Drupal 8. So maybe there are some changes which I forget.

# Answer
I could solve the problem (thanks to @Eyal).

template.theme :

```
function template_preprocess_html(&$variables) {

    $css_file_name = 'specific-page';
    $clean_alias = Html::cleanCssIdentifier($css_file_name);

    $activeThemeName = \Drupal::theme()->getActiveTheme()->getName();

    //OR

    $activeThemeName = 'template';

    $variables['#attached']['library'][] = $activeThemeName . '/' . $clean_alias;

}

```

template.libraries.yml:

```
specific-page:
  css:
    base:
      css/pages/specific-page.css: {}

```
> 0 votes

---
Tags: hooks, 8, theming
---


# Question
Title: How to get user data by providing user name or user profile field
I am using postman. I want to provide the username or a user profile field say roll no and fetch the user's information. What should be the URL.

I am able to fetch the user information when I provide the `uid` using the following URL :

```
http://[yourdomain]/[endpoint]/user/[uid]

```

# Answer
If you want to get the user data by providing username, you can use pass `name` (username) as a parameter to the service URL like follows

```
http://example.com/<endpoint path>/user?parameters[name]=krishna

```

If you want to pass either username or other user profile fields you can achieve that using Services Views module. After installing this module make sure to enable it under service resources list.

Create a **view** with contextual filter(s)

**Executing view via views resource**

After enabling "views" resource in your services endpoint you can do GET request to:

```
http://example.com/<endpoint path>/views/<view name>

```

This will execute a view and pass results.

**Possible arguments:** \- display\_id: views display

* args: array of view arguments
* filters: array of view filter values
* offset: views offset
* limit: limit views number of results
* format\_output: boolean whether we would like to get themed view or data
> 2 votes

# Answer
Please get the user token with below URL:

http://\[yourdomain\]/\[endpoint\]/user/token (you might need to login first)

Use the token as x-csrf-token with headers with your URL with GET method:

http://\[yourdomain\]/\[endpoint\]/user/\[uid\]

if above is working then you can choose query parameter as below.

http://\[yourdomain\]/\[endpoint\]/user?name=kalpan
> 0 votes

---
Tags: 7, services
---


# Question
Title: Add images from external URL in WYSIWYG Editor
I am new to Drupal 8, and having some trouble with inline images.

## Need

I store my images on Flickr, and want add them as inline images (in editor) in articles on my Drupal 8 site. I also need to **set captions**, and **alignment** for those images.

I **don't** need Drupal to manage the image files for me.

## Problem

* Drupal 8 uses a customized CKEditor Image Upload dialog, which does not support inserting images from a URL and only supports uploading images to the web server.
* When I double clicked on a Flickr image added via HTML code, the image dialog won't show up.

## My current workaround

* In `Configuration -> Text formats and editors`:

+ Disable image uploads;
    + Turn off the filters `Track images uploaded via a Text Editor`, `Caption images` and `Align images`;
    + Allow `align` attributes for `<img>`, allow `<figure>` and `<caption>` tag. (Or just use Full HTML and don't filter tags)
* Hard-core the image (`<img src="....">`) via Source in CKEditor;
* Switch to WYSIWYG, double click on the image. Now **the origin CKEditor image dialog** (not the Drupal one) will show up which allows me to add captions or set alignment.

## Further Observations

Images added this way will have code like `<figure><img align="left"></img><caption>Caption</caption></figure>` even in editing mode.

Images managed by Drupal (if `Caption images` and `Align images` are on) will have alignment and caption added as `data-caption` and `data-align` attributes on `<img>` (no `<figure>` in editing, but will expand into that structure when viewing).

---

## My Questions

* How to disable the `DrupalImage` and `DrupalImageCaption` plugins (at `core/modules/ckeditor/src/Plugin/CKEditorPlugin`)? (I guess disabling them will solve this problem once for all.)
* Are there any better ways to achieve my needs, for example a media library module that can support a range of image storing services. (But that will also need some hack into the CKEditor, right?)

# Answer
> 1 votes
This question was answer in the Drupal issue queue - https://www.drupal.org/node/2119379

> Reusing existing images will be possible in Drupal 8 contrib by overriding the `managed_file` element, which is the element that renders the image upload button. E.g. https://drupal.org/project/filefield\_sources does that: it provides a "Reference existing" option.
>
> When you disable image uploads, you can insert image URLs. It's either of the two, not both. If you want both, then again something like https://drupal.org/project/filefield\_sources provides the solution.

---
Tags: media, 8, wysiwyg
---


title: Custom block from module

text:
# Question
Title: Custom block from module
I am trying to create a custom block using a module.

I have followed the instructions on the Drupal site but my block does not appear in the list of custom blocks, or at the bottom of the Block Layout page.

So I installed the Examples for Developers module. It seemed to install and enable correctly but again, there didn't seem to be any example blocks in the Structure, Blocks Layout screen.

Thinking that there must be something wrong with my installation, I used the demon site to test the example modules: https://simplytest.me/project/examples/8.x-1.x

Again, when I enable the Block Example module I don't see any block modules in the list of custom blocks, or at the bottom of the Block Layout page.

Am I doing something wrong, or is this broken in Drupal 8.0?

# Answer
In order to add a new block you need to click on the button place block then click again on the place block button base on what block you want to added it.
> 0 votes

---
Tags: blocks, 8
---


# Question
Title: Make a custom block to render a published content
Is there way to make a custom block displays a list of published contents?

I tried...

1. Create a new block type with just one field of type Reference-\>content.
2. Create a new block with recently created type.
3. Configure visibility -\> type of content to a particular type of content on this recently created block.
4. Place block in block layout.
5. Publish a new content.

But at the end nothing is rendered on my page.

Drupal 8 question.

# Answer
The easier way to achieve this problem is by creating a view block. That only show the content that is been published. Then you going to add that view block on any region that you wish.

Here is the code for a export view block that only show content that have been published.

```
uuid: 36b6dd0f-8a30-4d08-a718-24afe8b4cfc0
langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_published
label: 'Content Published'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: some
        options:
          items_per_page: 5
          offset: 0
      style:
        type: default
      row:
        type: fields
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          settings:
            link_to_entity: true
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          order: DESC
          entity_type: node
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: 'Content Published'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }

```
> 0 votes

---
Tags: blocks, 8
---


title: Favicon not loading from https

text:
# Question
Title: Favicon not loading from https
I have enabled `https` for my site. All images and files are served with `https` url, but favicon it is serving from `http://example.com/sites/default/files/favicon.ico` instead it should show as `https://example.com/sites/default.files/favicon.ico`. When I open the site in **Firefox** it is displaying below error message in console

> Loading mixed (insecure) display content on a secure page "http://example.com/sites/default/files/favicon.ico"\[Learn More\]

Suggest me a way to resolve this.

# Answer
I have also faced same situation where favicon is serving from `http` whereas all images including logo are serving from `https`. I am using Metatag module, in the module configuration default favicon path is given as `http://example.com/sites.default/files/`, so favicon is serving from `http`. I have changed the path to `https://example.com/sites/default/files/favicon.ico`. This fixes the problem, this may also the reason in your case.

If this is the case you can change the favicon default path, go to `https://example.com/admin/config/search/metatags/config/global` Under `favicon and touch icon tab` change the path.
> 5 votes

# Answer
May be some security reasons you can't upload by https:// but you can update favicon by below Process.

Please add below line into your **/yourproject\_folder/sites/all/themes/your\_theme\_name/your\_theme\_name.info**

**features\[\] = favicon**

and place favicon.ico named files into **/yourproject\_folder/sites/all/themes/your\_theme\_name/**
> 0 votes

# Answer
Check this blog may be it is helpful to solve your problem.

**What is Mixed Content?**

> When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.
>
> However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.
>
> What do I mean by “certain HTTP requests”? Why wouldn’t the Mixed Content Blocker just block all HTTP requests? To answer this question, I will first explain how the browser security community divides mixed content into two categories; Mixed Active Content and Mixed Passive Content.
> 0 votes

---
Tags: 7
---


# Question
Title: How to use Drupal as static website generator?
When I want to convert my Drupal 7 site to html files I have used Static module, which converts Drupal 7 site to html files. However, I will like to know how I can convert a Drupal 8 into static html pages.

Any ideas on how I can make a Drupal 8 website into static html pages ?

# Answer
I do not think there are any plans for the static project to be ported to Drupal 8.

However, a workaround to turn your Drupal 8 into a static site is by using the `wget --mirror` command. This will take an exact copy your site.
> 2 votes

---
Tags: 8
---


# Question
Title: Page title tag translated based on view title
I've been working on a multilingual site using i18n modules, with the 'translate view' ('Internationalization Views') module, provided by i18n, active too.

I can translate the view's title and the content, but what I need to translate now it's the content of the tag `<title>`. I've searched the web, but didn't found any answers to this problem, can anyone help me?

EDIT:

I didn't see that the problem actually apply on just one view. The text in italian is "cinematismi" and it should be translated into "Wiper mechanisms".

In the "translate interface" section I see the following strings: (the first one doesn't matter because it was an old view)

The problem is that all strings are actually translated. Can someone tell me what string should it be?

# Answer
I Actually managed to do it. I'm still not really sure on what did the work, but I tried to handle the taxonomy translation too using entity translation. The view's name was based on a taxonomy name, so it's probable that translating the name of that taxonomy added the title tag translation some way (I hadn't done anything else, so...)
> 3 votes

# Answer
You need the Internationalization Views module. After install it you can translate the strings of the view.
> 2 votes

# Answer
I think this can be solved with the Metatag module. That is capable of rewriting Page titles and supports i18n. Additionally you might need the Metatag Views sub-module that comes bundled. That way you can override the default page title in Views.
> 2 votes

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


# Question
Title: fonts/glyphicons-halflings-regular.woff2 404 error
Our drupal site uses `fonts/glyphicons-halflings-regular.woff2` through bootstrap v3.3.2. But I am getting `404` for the `file fonts/glyphicons-halflings-regular.woff2`. Is it some issue with the bootstrap? What is proper way to fix this?

# Answer
wget https://github.com/metaskills/less-rails-bootstrap/raw/master/app/assets/fonts/twitter/bootstrap/glyphicons-halflings-regular.woff2 and move it to the openatrium/themes/oa\_radix/assets/font directory. Here: https://www.drupal.org/node/2625784
> 1 votes

---
Tags: theming
---


title: Limit access and editing menu by user

text:
# Question
Title: Limit access and editing menu by user
I have created a new menu and I'm trying to limit the access to a particular user to edit instead of role with the following code but it's not working, I still can't see the menu and edit the menus items by logging in with the relevant user login (user id 3 in this case). Wondering what's the proper way of doing.

```
/**
 * Implements hook_menu().
 */

function menu_access_by_uid_menu(){
  $items = array();
  $items['admin/structure/menu/manage/new-menu'] = array(
    'title' => 'New Menu',
    'access callback' => 'menu_access_by_uid_validate',
  );

  return $items;
}

function menu_access_by_uid_validate() {

 global $user;

 if (user_is_logged_in() && ($user->uid == 1 || $user->uid == 3)){
   return TRUE;
 }

 return FALSE;
}

```

# Answer
> 0 votes
There is a nice module to handle visibility of menu items. You can use the module or see code in side the module.

May be It will help you. I am not sure :P

https://www.drupal.org/project/menu\_item\_visibility

# Answer
> 0 votes
If all you want to do is limit access to the admin pages for a specific menu then something like this should work:

```
function mymodule_menu_alter(&$items) {
  $items['admin/structure/menu/manage/menu-new-menu']['access callback'] = 'mymodule_access_by_uid';
  $items['admin/structure/menu/manage/menu-new-menu/%']['access callback'] = 'mymodule_access_by_uid';
}

function mymodule_access_by_uid() {
  global $user;

  if ($user->uid == 1 || $user->uid == 3) {
    return TRUE;
  }

  return FALSE;
}

```

You need to use hook\_menu\_alter() to add your own access callback for an **existing** page because hook\_menu() is for defining your own menu items and page callbacks.

Also, I don't think you need user\_is\_logged\_in() since that's already implied if the uid is something other than 0.

---
Tags: routes
---


# Question
Title: Search snippet does not appear in Search API search page
I am using

* Drupal 7.28
* Apache Solr 4.4.0
* Search API Solr 7.x-1.5
* Search API attachment 7.x-1.3 and
* Search API Page 7.x-1.1.

I have created 2 content types with \- Title \- ID \- Document date (not the default node creation date) \- Attachment

My index and preprocessing settings are the following: **Index Fields:** **Processor settings:**

In the search page I am searching all the fields and have set View mode: Themed as search results

The searches work correctly only that when I search for a keyword appearing in the attachment text, the results return without the search snippet, whereas when I search in the title, the returned result is correctly highlighted

The funny thing is that when I submit the query directly to solr with e.g. `q=tm_title:Spain?hl=on` the `<lst name="highlighting">` is empty.

Any ideas?

# Answer
It appears that **Create Excerpt** was the option that was not allowing the search snippet to appear. After I disabled it, everything worked as expected. Should have done my homework better :-/
> 1 votes

# Answer
Posting this for anyone stumbling upon this problem when using Display Suite: if you use the standard "search result highlighting input" view mode with the "search snippet" field, make sure to apply the patch in this issue to get results.

Also, under Advanced options in your solr server settings, make sure to enable "Return an excerpt for all results", "Retrieve result data from Solr" and "Highlight retrieved data".
> 1 votes

---
Tags: 7, search
---


title: Return a variable from field template

text:
# Question
Title: Return a variable from field template
I want to return a "global" variable from a field template file

Assume I have a content type called "basic\_page". Basic Page has a field called "my\_field". In the template for basic page (`node--basic-page.tpl.php`), I render "my\_field" by calling:

```
$fieldMarkup = drupal_render($content['field_my_field']);

```

In `field--field-my-field.tpl.php` I do whatever I need to do to return the field HTML / markup - no problems here. But I want to return a variable to node--basic-page.tpl.php as well. Is there a way to insert this variable into the node render array, or something of the sort?

I do not want to do this in a hook\_preprocess function. If there is no other option I will, but was hoping I can avoid this.

# Answer
> 2 votes
Use template\_preprocess\_field in your template.php and add your variable there.

Then in your tpl.php you can easily access that variable and render that variable along with your markup.

---
Tags: nodes, entities, theming
---


# Question
Title: How to disable/enable all products in commerce?
The Commerce Backoffice module allows to delete all selected products from the list. But how about to change the status for all products or for the selected ones?

# Answer
> 3 votes
It will take just a few steps to create a view for your commerce product
fields values manipulation:

* add a new View:
    + "show group" set to Commerce Product "of type" - type of
    you commerce product, you want to change fields values;
    + "display format" set to "Table";
    + press "Continue & Edit";
* In "fields" group add "Bulk operations:Commerce Product" field:
    + set checked "Modify entity values " in "Bulk operations" group;
    + press "Apply" button;

That are the main settings for your operation view. Just add fields and filters whatever you want. Save your view and use it for change field values using bulk operations.

---
Tags: commerce
---


# Question
Title: How to aggregate field results to a chart?
I installed the Chart module and I'm using it in my Views display.

I have a field: **Score**

I added a chart but it shows two different charts (see image) instead of **just one** with all the results from that field.

How can I put them together? If it's with aggregation, can you give me some guides?

Here is how another attempt looks like:

And this is how my View currently looks like:

The tabular format of its data to be charted looks like so:

**Notes**:

* I'm using the Chart module because I need the "radar" type which only exists in that module.
* I want to create a chart with all the scores displayed in the table, and not one chart per score.
* I don't want all the fields to appear as data, as in the last pictures in my question. I want the text to be the legend and the number to be the data.

# Answer
This kind of questions show up quite often. And each time I try to get them resolved with this very first attempt (if it is related to a Views display):

> You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In my experience, 90% of the issues turn out to be related to errors in the creation of the table that contains the data to be charted.

If this question is about creating a chart using the Views integration, then refer to the appropriate Community documentation resources with more details about how to do so:

**Disclosure**: I'm a (co-)maintainer of both Chart and Charts, and co-author of the documentation resources mentioned.
> 4 votes

---
Tags: 7, views, charts
---


# Question
Title: Is it possible to have an entity with fields, which doesn't use bundles?
I have an entity (using entity API) for which I would like a fixed number of fields (and would prefer to use fields and the API rather than just creating properties) - it makes no sense to make a bundle - but do I need to create a bundle nonetheless to allow fields to be attached?

I'm thinking this is the case since field\_attach\_instance takes a 'bundle' value in the array to pass in (and field\_config\_instance contains the bundle column).

# Answer
> 0 votes
Technically, yes! For each **entity type** you must have a **bundle**. Since bundle is the implementation of entity type. If you define your entity type without a bundle the bundle will be of the same name with entity types. For example user entity doesn't have a separate bundle so it uses the default one with the same name of entity type.

Please go through this and this for details.

---
Tags: 7, entities
---


# Question
Title: Using same pictures twice in one node (media module)
I've been using the EPSA crop module for a while now without any complaints. But I've run into a small problem, which I can't fix. I use the media module in combination with the EPSA crop module. When I add a picture twice in one node then only one cutout will be saved and all the same pictures will be cut the same way. So a cutout isn't unique. Does someone have an idea?

Using Media 7.x-2.0-beta1 and EPSA crop 7.x-2.3.

# Answer
> 1 votes
No solution right now, because all the cropping modules stores their information using fid, without entity id or something else which can give information where it will be used. As a workaround on this problem, I altered some crop forms and created a new image per each crop.

---
Tags: nodes, media
---


# Question
Title: Do I need a cron task for processing a queue?
I've got a task that takes about 45 minutes to complete and needs to happen every day (synching users to several external database, etc).

To handle the work, I've set up a cron queue with `hook_cron_queue_info()` as follows:

```
function mymodule_cron_queue_info() {
  $queues = array();
  $queues['update_users_queue'] = array(
    'worker callback' => '_mymodule_process_user_queue_item',
    'time' => 120,
  );
  return $queues;
}

```

I fill the queue using this function:

```
function mymodule_queue_all_users_for_synching() {
  //...query for users...

  $queue = DrupalQueue::get('update_users_queue');
  foreach($users as $user) {
    $queue->createItem($user);
  }
}

```

The queue-filling function gets called as a cron task. I use Elysia Cron, so my implementation of `hook_cronapi()` is:

```
function mymodule_cronapi($op, $job = NULL) {
  $items = array();
  $items['queue_users_for_synch'] = array(
    'description' => 'Queue all user accounts for synching.',
    'rule' => '0 3 * * *', // Run this job every day at 3am.
    'callback' => 'mymodule_queue_all_users_for_synching',
  );
  return $items;
}

```

The worker function for each queue item, defined in `mymodule_cron_queue_info` is like:

```
function _mymodule_process_user_queue_item($item) {
  //...synchronize user ($item)...
}

```

My question is, *when is cron actually going to start processing the queue?*

Say I fill the queue every day at 3am, and want to process it 120 seconds out of every 30 minutes until it's done--*do I need to create another cron task?*

# Answer
When Drupal runs cron tasks, it automatically handles any cron queue defined from modules, in `drupal_cron_run()`; first `hook_cron()` implementations are invoked, and then the cron queues are emptied.

Inmplementing `hook_cronapi()`, you can add an entry for another function handling the cron queue of your module.

```
function mymodule_cronapi($op, $job = NULL) {
  $items = array();

  $items['queue_users_for_synch'] = array(
    'description' => 'Queue all user accounts for synching.',
    'rule' => '0 3 * * *', // Run this job every day at 3am.
    'callback' => 'mymodule_queue_all_users_for_synching',
  );

  $items['clean_queue'] = array(
    'description' => 'Clean the queue for the user synching.',
    'rule' => '0 4 * * *', // Run this job every day at 4 AM.
    'callback' => 'mymodule_clean_queue',
  );

  return $items;
}

function mymodule_clean_queue() {
  $queues = module_invoke('mymodule', 'cron_queue_info');
  drupal_alter('cron_queue_info', $queues);

  // Make sure every queue exists. There is no harm in trying to recreate an
  // existing queue.
  foreach ($queues as $queue_name => $info) {
    DrupalQueue::get($queue_name)->createQueue();
  }

  foreach ($queues as $queue_name => $info) {
    $function = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      $function($item->data);
      $queue->deleteItem($item);
    }
  }
}

```

The alternative is letting Drupal handle the cron queue for you, but that happens when Drupal cron tasks are executed. If you want to empty the cron queue of your module more frequently, you can only add a new cron task handled by the Elysia Cron module.

The Elysia Cron module handles the cron queues in `elysia_cron_run()`; this function is being invoked from `elysia_cron_cron()` (an implementation of `hook_cron()`), `drush_elysia_cron_run_wrapper()` (a Drush command callback), and from its own cron.php. If you followed the instructions in the INSTALL.txt file (in particular in "STEP B: CHANGE SYSTEM CRONTAB (OPTIONAL)"), and replaced any invocation of http://example.com/cron.php with http://example.com/sites/all/modules/elysia\_cron/cron.php, the Elysia Cron module should be already handling the cron queues. The code I suggested could be used to speed up handling the cron queues used from your module, if there is effectively the need of doing so.

```
// This code is part of the code executed from modules/elysia_cron/cron.php.
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_override_server_variables(array(
  'SCRIPT_NAME' => '/cron.php',
));
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  if (function_exists('elysia_cron_run')) {
    elysia_cron_run();
  }
  else {
    drupal_cron_run();
  }
}

```
> 20 votes

# Answer
The queue will be populated via the Elysia cronapi hook at the set time.

However, the queue will be processed whenever the standard Drupal cron run occurs.

See this worker callback processing snippet at the end of core: drupal\_cron\_run

```
 foreach ($queues as $queue_name => $info) {
    $function = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      $function($item->data);
      $queue->deleteItem($item);
    }
  }

```
> 2 votes

# Answer
as stated above when using Elysia Cron your queues do not get processed.

you (and drupal) have no access to queues that would otherwise run on drupal\_run\_cron

the workaround is to create a custom cron task - (this will be visible to elysia cron) to either process all queues or one you want and invoke queue processing there. i.e:

```
function mymodule_cron() {
// below is copied from drupal_cron_run() in common.inc

// Grab the defined cron queues.
$queues = module_invoke_all('cron_queue_info');
drupal_alter('cron_queue_info', $queues);

//if you want to target only one queue you can remove 'foreach'
and your $info = $queues['your_queue'];

  foreach ($queues as $queue_name => $info) {
    if (!empty($info['skip on cron'])) {
      // Do not run if queue wants to skip.
      continue;
    }
    $callback = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
     while (time() < $end && ($item = $queue->claimItem())) {
      try {
        call_user_func($callback, $item->data);
        $queue->deleteItem($item);
      }
      catch (Exception $e) {
        // In case of exception log it and leave the item in the queue
        // to be processed again later.
        watchdog_exception('cron', $e);
      }
    }
  }
}

```

now queues processing can be controlled by ElysiaCron
> 1 votes

# Answer
I don't use Elysia, but my solution have always been something like this:

```
function mymodule_cron() {
  $queue = DrupalQueue::get('mymoudule_queue');
  $queue->createQueue();
  $item = $queue->claimItem(300);

  if (!empty($item->data)) {

    // Do the work.

    if ($sucess) {
      $queue->deleteItem($item);
      watchdog('mymodule', 'It worked.');
    }
    else {
      watchdog('mymodule', 'It did not work!', array(), WATCHDOG_ALERT);
    }
  }
}

```

It only handles one item, for each cron run. Maybe you want to change that.
> 0 votes

# Answer
I've also been trying to wrap my head around this, as I'm using the Queue API for the first time along with Elysia cron. Upon closer inspection you can see that Elysia cron executes queue items when the function **elysia\_cron\_run** is called. See this snippet from **line 1044** within the file **elysia\_cron.module**:

```
if (EC_DRUPAL_VERSION >= 7) {
  // D7 Queue processing
  foreach ($queues as $queue_name => $info) {
    $function = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      $function($item->data);
      $queue->deleteItem($item);
    }
  }
}

```

This helped demystify queue processing for me when using Elysia cron.
> 0 votes

---
Tags: 7, hooks, cron, queue
---


# Question
Title: Problems creating a custom blank page with my custom module
I'm trying to upgrade old Drupal 7 modules to 8 and I am struggling to figure out how to create a blank page (by this I mean, a page with zero HTML from enabled themes) for my module. I added routing to my custom controller, my controller method takes care of all the logic and returns the following array:

```
[
        'showVideo' => [
            '#theme' => 'videoPage',
            '#content' => $content
        ]
]

```

I already defined "videoPage" in mymodule.module using hook\_theme:

```
Function mymodule_theme($existing, $type, $theme, $path){
  return array(
    'videoPage' => array(
      'variables' => array('content' => NULL),
      'file' => 'mymodule.html.twig'
    )
  );
}

```

"mymodule.html.twig" is a full stand-alone HTML file from the opening HTML tag to the closing tag. I don't want any other content to show up there but instead I'm getting the content in that Twig file, then followed by the HTML for the currently selected Drupal theme. ~~Also, my {{ content.value }} calls in Twig seem to be getting ignored. And by this I mean, I can literally see {{ content.xyz }} in the markup being printed. The $content being returned by the controller is an array and I'm sure all the values are set. It almost feels like the Twig file is being called while the Controller's logic is being ignored.~~ (this last bit has been solved by Clive's response)

Any help? Am I totally off in this approach?

# Answer
You can output the html of one twig only in a symfony response:

```
use Symfony\Component\HttpFoundation\Response;

public function my_page_controller() {

  $build = array(
    'page' => array(
      '#theme' => 'videoPage',
      '#content' => $content,
    ),
  );
  $html = \Drupal::service('renderer')->renderRoot($build);
  $response = new Response();
  $response->setContent($html);

  return $response;
}

```
> 7 votes

# Answer
The **file** parameter is:

> The file the implementation resides in.

That should be used if you're creating a theme *function*, rather than template, and it will contain the path to the file that function is in.

What you're looking for is the **template** parameter:

> If specified, the theme implementation is a template file, and this is the template name. **Do not add 'html.twig' on the end of the template name**. The extension will be added automatically by the default rendering engine (which is Twig.)

(emphasis mine)

So your implementation might look something like this:

```
function mymodule_theme($existing, $type, $theme, $path){
  return array(
    'videoPage' => array(
      'variables' => array('content' => NULL),
      'template' => 'mymodule'
    )
  );
}

```

Assuming "mymodule.html.twig" is in the root of your module's folder.

In case you're interested in why your current implementation is doing what it's doing: as you've provided a **file**, Drupal performs an `include` on it, and anything not within `<?php` tags gets written straight out to the buffer.

Source
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Hook for csv export view - flag exported items
I am using Views data export to export view with exposed filter, is there any hook or another way to run an action over these filtered items?

My goal: set "flag" (boolean field) for these exported items so I will know, they have been exported.

# Answer
Views Data Export isn't transactional and so if you're looking for something, you'd likely need to wrap up Views Data export with your own code that loops over the results and sets the flag then.
> 0 votes

---
Tags: hooks, importing-exporting
---


# Question
Title: Multiple values in creating a new field instance
This is the code I actually have:

```
$instance = array(
    'field_name' => FIELD_PROJECT_TAGS,
    'entity_type' => 'node',
    'label' => $vocabulary->name,
    'bundle' => 'portfolio_project',
    'required' => true,
    'widget' => array(
        'type' => 'taxonomy_autocomplete',
        'behaviors' => array(
            'multiple values' => FIELD_CARDINALITY_UNLIMITED,
        ),
    ),
    'display' => array(
        'default' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
        ),
        'teaser' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
        ),
    )
);
field_create_instance($instance);

```

What's wrong with this? Why does the portfolio module allways install this field with allowing only one value?

Hope somebody can help. I'm bit frustrated.

# Answer
> 2 votes
Hopefully this will prove useful: To create a field that allows multiple values, you set the `cardinality` to `-1` when using `field_create_field`. Then all instances will allow multiple values (provided the widget supports that).

Example:

```
field_create_field([
  'cardinality' => -1,
  'field_name' => 'field_unlimited',
  'type' => 'special_content',
  'entity_types' => ['node'],
]);

```

# Answer
> 1 votes
As reported in Field API, the array indexes used for the `widget` array are the following ones:

* type (string) The type of the widget, such as text\_textfield. Widget types are defined by modules that implement hook\_field\_widget\_info().
* settings (array) A sub-array of key/value pairs of widget-type-specific settings. Each field widget type module defines and documents its own widget settings.
* weight (float) The weight of the widget relative to the other elements in entity edit forms.
* module (string, read-only) The name of the module that implements the widget type.

It is `hook_field_widget_info()` that defines the behaviors of the field widgets.

```
function hook_field_widget_info() {
  return array(
    'text_textfield' => array(
      'label' => t('Text field'),
      'field types' => array('text'),
      'settings' => array('size' => 60),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'text_textarea' => array(
      'label' => t('Text area (multiple rows)'),
      'field types' => array('text_long'),
      'settings' => array('rows' => 5),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'text_textarea_with_summary' => array(
      'label' => t('Text area with a summary'),
      'field types' => array('text_with_summary'),
      'settings' => array(
        'rows' => 20,
        'summary_rows' => 5,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

```

The module you are writing should implement that hook, in order to allow the field to use multiple values.

The taxonomy widget allows to enter multiple values by entering them separated with a comma; if you are expecting the widget to appear more than one time on the page, then it is not how that widget works. Other widgets can probably use more form fields to contain multiple values.

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


# Question
Title: What path to images to use with CKEditor to insert images in content?
When putting images in content items, I have to put the full URL, otherwise images don't show up.

It works for this full path:

```
http://localhost/IT/sites/default/files/mypictures/apache_pb.png

<p><img alt="" src="http://localhost/IT/sites/default/files/mypictures/apache_pb.png"/></p>

```

But doesn't work for this path:

```
sites/default/files/mypictures/apache_pb.png

<p><img alt="" src="sites/default/files/mypictures/apache_pb.png" /></p>

```

I know I must be missing something? A token? Variable to path?

# Answer
> 1 votes
You are missing the forward slash: /sites/default/files/mypictures/apache\_pb.png

Incidentally, IMCE will make this easier for you.

---
Tags: wysiwyg
---


title: Is there any alternative to OpCache?

text:
# Question
Title: Is there any alternative to OpCache?
I have a hosting with suPHP handler which doesn't support opcache. I want to start working on Drupal 8 sites which highly recommend opcache.

Is there any alternative to opcache? Should I change my hosting?

# Answer
> 4 votes
Any properly configured opcode cache should work. Notice that Drupal only currently checks for PHP Opcache in its requirements. Some people have got Drupal 8 working with XCache, for example.

APC is really not the way to go. It exists in a backwards-compatible way in PHP 5.5 and as a token-based data cache (still useful, but it isn't an opcode cache in that configuration).

# Answer
> 0 votes
You might consider using APC "http://php.net/manual/en/book.apc.php" as alternative to op-cache, op-cache is bundled with PHP by default in PHP 5.5.0 or later. so you should check with the hosting company if they support version 5.5.0 or later version of PHP.

---
Tags: 8, caching, installation
---


# Question
Title: Preventing a field from rendering on a page
How would I prevent `field_home_slider` from rendering when `$page['content']` is loaded? I only want it to load when I call it separately. I also still want the page content to be displayed just do not include the `field_home_slider`

Display image by itself

```
  if(isset($node->field_home_slider)){
     $field = field_get_items('node', $node, 'field_home_slider');
     $bannerImage = field_view_value('node', $node, 'field_home_slider', $field[0]);
     print render($bannerImage);
  }

```

and below to display content on the page

```
print render($page['content']);

```

# Answer
> 3 votes
Go to Display management of your content type in `admin/structure/types/manage/{yourcontenttypename}/display` and set `Formatter` as `Hidden`.

Also you can hide it with hide function before render it in `node template`.

```
  hide($content['field_home_slider']);
  print render($content);

```

---
Tags: theming, entities
---


# Question
Title: How do I check if a single on/off checkbox is checked?
There does not appear to be any way to check the value of a single on/off (boolean) checkbox in the data selector for the Rules module. If "field-MyField" = checked or "field-MyField" = 1, then do 'blah'. Can Rules do this? I must be missing something

# Answer
After many hours of trial and error, I ended up solving the problem. Do not ask me to explain this because it makes no sense to me. If anyone can explain, then that would be greatly appreciated!

I set a new condition using DATA COMPARISON. I then select the "node:field-MyField:0" (there are actually up to 4 of these - node:field-MyField:1,node:field-MyField:2, etc..). I then set the COMPARISON to EQUALS. Then at the 2nd data selector part, it no longer is a text input box data selector, but now appears as a checkbox dataselector. When I click that checkbox data selector, and hit save, now the rules module is working correctly.

*bangs head on wall*
> 2 votes

# Answer
There's a mix of correct and incorrect details here, so I will try to sort them out. This is for Rules on Drupal 7, and applies to working with a Boolean field.

To make a condition that checks a field's Boolean state (true/false, yes/no, checked/unchecked), first make sure that you can access the field in the data selector. As Bojan mentioned above, and as it mentioned on the admin page itself,

> To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

The operator you want to choose is "equals".

For the "Data Value" field, you can input values in two modes, make sure you are using "direct input mode". You should then be able to check the checkbox that represents TRUE for that field.

Translated, what you are saying is, "Is this field equal to TRUE?" You can also negate it by leaving it unchecked or using the "negate" option below.
> 6 votes

# Answer
You just add a "Data comparison" condition, specify the field name, and enter "1" as the value. If the field doesn't appear in the list of fields, first add an "Entity has field" condition, and select the field there. Then add the "Data comparison" next.
> 3 votes

# Answer
In the updated (fixed?) version of Rules, to do this, add a Data Comparison condition, select the appropriate field in the data selector `node:field-to-check`, then on the next step leave the comparison operator as `equals`. In the Data value group, there will be a checkbox helpfully named "Data Value" Rules will compare against the value of the checkbox as submitted on this page.
> 0 votes

# Answer
Most likely you have to use Rules Forms Support.

Once you activate the form rules for specific form, you can use the condition like: *Form element has value*. This condition can be used either when form is being *built* or *validated*.

Other module to consider is Entity Rules.
> 0 votes

---
Tags: 7, rules
---


title: theme variables in array

text:
# Question
Title: theme variables in array
I try to rewrite

```
return theme('table', array('header' => $header, 'rows' => $rows, array('variables' =>$my_vars));

```

into:

```
$build = array();

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

 $build['variables'] = array(
'variables' =>$my_vars);

 return $build;

```

But it does't work:

```
$build['variables'] = array('variables' =>$my_vars);

```

How can I do this?

# Answer
> 1 votes
Since the second argument of `theme()` is an array, you are writing code for Drupal 7. In that case, `theme('table')` doesn't use any array item whose index is an integer. The only array indexes you should pass as second argument to `theme('table')` are the following:

* header
* rows
* attributes
* caption
* colgroups
* stricky
* empty

Since you are using `array('variables' =>$my_vars)` it could be you are trying to set *attributes*, but in that case the array should be an array of HTML attributes, or *colgroups*, and in that case the array should be similar to the following one.

```
$colgroup = array(
  // COLGROUP with one COL element.
  array(
    array(
      'class' => array('funky'), // Attribute for the COL element.
    ),
  ),
  // COLGROUP with attributes and inner COL elements.
  array(
    'data' => array(
      array(
        'class' => array('funky'), // Attribute for the COL element.
      ),
    ),
    'class' => array('jazzy'), // Attribute for the COLGROUP element.
  ),
);

```

If you are trying to set *attributes*, your code should set the `$build` variable as following.

```
$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => $my_vars,
);

```

Replace `'#attributes'` with `'#colgroups'` to set *colgroups*.

In the case `theme('table')` accepted *variables* (which could be the case if a module overrodr the default implementation of the theme function), then the code should be similar to the following one.

```
$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#variables' => $my_vars,
);

```

---
Tags: 7, theming
---


title: Odd $_SESSION contents

text:
# Question
Title: Odd $_SESSION contents
I have a page in Drupal from which I want to be able to read the $\_SESSION data to determine the userid and their assigned role. As an exploration I attempted to print to the page the contents of $\_SESSION so that I could see what was being stored and what the keys were to retrieve these values.

When I attempt to print to the page using `echo print_r($_SESSION);`, instead of a set of reasonable session data, I instead get only this:

`Array ( [batches] => Array ( [1] => 1 ) )`

I had a bit of a Google around to see if I was doing something wrong, and I came across the documentation for session.inc, which says:

> These functions should not be called directly. Session data should instead be accessed via the $\_SESSION superglobal.

So it seems that, while Drupal wants me to use $\_SESSION to retrieve the session data, I can't do this because my $\_SESSION data has only this odd pair of nested one-element arrays that store only the number 1.

I also came across some reports that not having the uid 0 in your users table can cause similar issues, so I have checked the users table and I do indeed have user 0.

Any ideas what is going wrong here?

Thanks.

# Answer
> 0 votes
The `$_SESSION` variable contains values set by Drupal; in your case, `$_SESSION['batches']` is the value set by the Batch API. Drupal, although, doesn't use the session to store the user ID; that value is stored in the `$user` global variable, as cilefen correctly said in his comment.

```
global $user;
$uid = $user->uid;
$roles = $user->roles;

```

Keep in mind that the `$user` global variable doesn't contain a fully-loaded user object; to get that, you need to use the following code.

```
$account = user_uid_optional_load();

```

`$account` will contain every field associated with the user entity, and any property attached to the user object from third-party modules.

---
Tags: sessions
---


# Question
Title: who is responsible for printing [safe_value]
I would like to know who's responsible for printing \['safe\_value'\]

```
$node->body['und'][0]['safe_value']

```

because for some reasons, it is missing when I checked it using `dpm($node)`, I only see `['value']`, `['summary']`, and `['format']`.

All my modules are up to date and I'm using i18n(multilingual).

# Answer
To augment MZ's answer, while a node\_load() will load the node, a node\_build\_content() is required to get all these extra types of fields. In this case, that would be the Field Module's Text Module that creates this sanitized field based upon the filter in use on that field.
> 2 votes

# Answer
Quick grep on standard D7 installation reveals the following:

```
./modules/field/modules/text/text.module:159:        $items[$id][$delta]['safe_value'] = isset($item['value']) ? _text_sanitize($instances[$id], $langcode, $item, 'value') : '';
./modules/field/field.api.php:321:        $items[$id][$delta]['safe_value'] = isset($item['value']) ? _text_sanitize($instances[$id], $langcode, $item, 'value') : '';

```
> 0 votes

# Answer
The value key "save\_value" of "Long Text" fields is set given either of these two is true:

Note that this applies to fields being attached to the node when the node is loaded via `node_load() / entity_load()`, regardless of whether it's going to be displayed or not.

For display purposes, such as printing the values from the node template, see the `field_attach_prepare_view()` function which will actually prepare a renderable array, that will apply the proper text format, for the fields attached to the entity.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Purpose of "rows" when adding Long Text field
When adding a Long Text field to a content type, I am asked to supply the number of *rows* for the field. What is the purpose of this?

This seems like it has something to do with how the data is stored in the database. At first I thought it was required because I was using a SQLite database that stores everything in a flat file, so I switched to a MySQL backend. However, the field is still required.

# Answer
Rows control the height of your text area for editors. It does not change how the data is stored in the database.
> 5 votes

# Answer
Number of row will be display to end user at a time.
> 0 votes

---
Tags: entities
---


title: Need Nodes to Appear Only Once

text:
# Question
Title: Need Nodes to Appear Only Once
I've created a view to display items with a certain content type. I'd like to display the terms in an associated taxonomy along with them. Many of these nodes have more than one term selected.

The output currently displays nodes one time for each taxonomy term assigned. How can I adjust this so that it displays each node once with every term associated with it?

Thank you!

# Answer
> 4 votes
You can apply **GROUP BY** or **DISTINCT** by enabling views aggregation settings to remove duplicate records.

1. Go and edit your view
2. In Advanced » OTHER section by enabling Use aggregation: Yes
3. In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

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


# Question
Title: Can the speed of my cron job be improved?
Can I improve my cron job speed?

Ex: it takes me 30 seconds to complete a certain cron job. Can I make it do this faster?

Does cron speed depend on the server machine?

# Answer
You've to check which modules implement hook\_cron and see what's happening during your cron run. It is also useful to run cron from the command like, e.g.

```
drush -v cron

```

and check for any screen messages or Drupal logs (`drush ws`). You may prefix your command with `strace -f`/`dtruss` to debug the command processing.

Check also if manually calling `cron.php` via `curl` would help, e.g.:

```
time curl -v "http://example.com/cron.php?cron_key=XYZ"

```

especially on your local server, then eventually check via `tcpdump` if you've any outgoing connections or it's CPU/resource thing.

Here are few common reasons which can give you some ideas:

* you've some network timeouts (try disabling Update module, check firewall/proxies),
* you're executing cron in the wrong way, see: Setting up cron,
* you've too many modules enabled which overusing hook\_cron,
* you've some migration going in the background (e.g. Migrate module), so you may decrease number of items to process in the settings,
* you don't have any caching implemented (check your OPCache/XCache configuration), enable memcached, see: How do you improve Drupal performance?
* you've unnecessary PHP/Apache modules enabled (e.g. XDebug),
* your cron task needs more time than 30 seconds, so you may increase your `max_execution_time` either in `php.ini` or during your cron run.
> 2 votes

# Answer
> Does cron speed depend on the server machine?

Yes, to an extent. Maybe even a large extent, it depends on a lot of different factors.

> Can I make it do this faster?

Probably, but that's as much as anyone can tell you from here. Profile the code, see where the bottlenecks are, and fix them. There's no magic formula
> 3 votes

---
Tags: 7, cron
---


title: Dynamic Content in a Block

text:
# Question
Title: Dynamic Content in a Block
I'm new to drupal. I'm trying to do something very simple, but feel I'm going the wrong way about it.

I have html content that is in a block on my homepage. There is a button in this block that is a link to a content page.

I simply want to change this button to a different button, if the user is logged in.

I've read that using php filtering is the wrong way to go about this. What would be the best practice for doing this?

# Answer
You can do this by simple css rule, no php, no logic

Inspect your element and check the body classes you will see class "logged-in" for logged in users and class "not-logged-in" for anonymous users. Just apply your changes like so:

```
.logged-in <block-class> <button> { // your style }

```
> 2 votes

# Answer
You can create two blocks and set the Roles Visibility settings to *anonymous user* or *authenticated user* depending on which one you want to display to that group. That way you don't have to enable php filter.
> 2 votes

---
Tags: 7, blocks, hooks
---


# Question
Title: How to show views calendar by node field_date
I have a date field with **start,end** dates.

But i can't understood how to show it in a views block by contextial filter **date** -\> **content from node**

Thanks for any help!)

# Answer
Just configured your Contextual filters like below snapshot.
> 2 votes

---
Tags: views, datetime
---


# Question
Title: Different vat rate per commerce shipping service
I have a complex shipping price grid, with :

* Different modes : tracked or not
* Different zones : France, EU, World
* Different prices per weight steps (\<250g, \<400g, etc.)

I started to implement that using Commerce shipping, Commerce flat rate and Commerce physical products, and a lot of rules, but now I need to apply a fixed VAT rate (20%) on shipping ONLY for tracked shipping in France.

Any idea of how I can do that? The VAT rate rule calculation seems to apply everytime, I don't know how to say "only for tracked shipping service".

Maybe it's time to make my own shipping module?

# Answer
As the author answered in a comment, this can be achieved by adding a rule condition to the rule that applies the VAT rate. Often pricing tables requires custom PHP code. Though, it's better to create a custom module and define your own rule condition in code.

You just have to implement one of the following hooks:

**Custom Rules Action** (not what you need, but good to know)

```
/**
 * Implements hook_rules_action_info()
 */
function MODULE_rules_action_info() {
  return array(
    'machine_name' => array(
      'label' => 'Custom Action',
    ),
  );
}

/**
 * machine_name custom action
 */
function machine_name() {
  // do action
}

```

**Custom Rules Condition** (definitely what you need)

```
/**
 * Implements hook_rules_condition_info()
 */
function MODULE_rules_condition_info() {
  return array(
    'machine_name_condition' => array(
      'label' => 'Custom Condition',
      'arguments' => array(
        'type' => 'user', // there are lots of types
        'label' => 'Fancy user',
      ),
    ),
  );
}

/**
 * machine_name_condition custom rules condition
 */
function machine_name_condition($user) {
  if ($user->uid == 1) return true;
  return false;
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: No images, content, or theme after site migration from dev server to nginx on ubuntu
I have recently worked on a site for a client and worked on an acquia devdesktop to make changes on a Windows machine. The production site is on a linux server and I am trying to deploy the site on a digital ocean ubuntu server running nginx. For some reason my file and folder permission are completely messed up. I have gotten the site to the point where some images show up, but my themes and content are still behaving strangely. I followed what I thought was the procedure:

1. Set up a clean installation.
2. Migrate the database
3. copy the sites folder
4. run the update script

I ran though a series of issues with folder permissions, and was able to squash most of the bugs. I don't get any meaningful to me warnings in the admin/status/reports, and near as I can tell I've tried to follow the correct permissions for files and folders.

```
site --> 775
site/default -->775
site/default/files --> 775

```

UPDATE: So, I guess part of the issue had to do with an .htaccess file htaccess file issues, but I still had a mess of warnings regarding the folder and ownership permissions. I guess the environments are really unfriendly to one another. This a big site with 85+ modules enabled. The annoying part is that I could only piece together the diagnoses from the php warnings. I finally hit a wall a WSOD.

# Answer
> 2 votes
Try to give more information about the files/directories. What user/group owns the files? You should also make sure you know what user nginx is running on. Try these commands for debugging:

`ls -l` for printing details about file permissions and ownership

`ps -ef` to check running processes to see if any user stands out (like www-data or www, figure out which user nginx uses)

Files in sites/default/files should be rw- permissions, and directories in sites/default/files should be rwx permissions. rw- is 6 and rwx is 7.

The file: `-rw-r--r-- 1 ubuntu www-data 468 Dec 10 15:59 test.php` is owned by the `ubuntu` user and the `www-data` group. The ubuntu user can access the file with read/write, and the www-data can only read the file. If this file were in sites/default/files it would be a problem, because the webserver wouldn't have rights to remove it.

# Answer
> 0 votes
Rebuild the registry and also change ownership of file folder to www-data:www-data. To rebuild the registry you can use below drush command.

**drush rr**

After rebuilding registry clear the cache.

---
Tags: migrations
---


# Question
Title: Why the core migrate modules won't be enough?
I've seen that Drupal 8 comes with 2 core migration modules; These are "Migrate", and "Migrate Drupal".

My question: if we want to migrate SQL from a Drupal 7 site to our brand new Drupal 8 site, why aren't these two enough, and why do we also need to download the module Drupal Upgrade? Wasn't there a plan to make the process free of any contrib modules whatsoever?

# Answer
Have a look at the Drupal Upgrade page, which includes this:

> UI and drush command for core upgrades from D6 or D7 to D8 - **the plan is for this to live in contrib for now and ultimately bring the UI into core** (a decision will be made shortly before RC whether it will make it into 8.0.0) and the drush command into Drush itself

So since it is still in active development, it has **not yet been added to core**. In other words: consider this as a "didn't make it to D8 CORE **yet**".

Refer to the issue about "Plan for Drupal Upgrade 8.x-1.0 release" for what, IMHO, is probably the best place to see how this is going to evolve in the (near?) future ... Like will it make it into Drupal 8.1 "core"?

**Note**: The module's Project page ***title*** is "Drupal Upgrade", while de module's project page URL ends with "migrate\_upgrade" (and not with something like "drupal\_upgrade").
> 1 votes

# Answer
This is asking two questions. 1) What do I need beside core for migrating to D8 from D7. 2) What is Drupal Upgrade.

1. If all your fields and data in D7 are core fields, then you do not need anything from contrib. If you have non-core fields i.e. userpoints, then you'll need source and destination migrate plugins for those non-core field types. Same applies to any non-core Drupal data.
2. Core does not currently have a UI. It is in the works, but until then if you want a UI, use Drupal Upgrade. Or you can use drush and migrate\_tools. Mike Ryans's blog post provides a break-down of the current module landscape for D8 migrations.

Lastly, if you are trying to suck in strait SQL data, the above mentioned blog post provides some suggestions.

> In migrate\_plus, open up migrate\_example/README.txt and it will guide you through the basics of implementing SQL-based migrations. It's simpler than you think!
> 6 votes

---
Tags: 8, migrations
---


# Question
Title: How to integrate the link embedded in custome HTML(using ) to breadcrums?
`Home >>`

On the Home page I have created a div and inserted some text there and one of word I have added in Text area using CKeditor is ***Link to page-1***, so if i click that link it leads to me to page-1, so breadcrumb shows,

`Home >> page-1`

Now in the text area(body) of page 1 I have added another word ***Link to Page-2***, page-2 is a page created using the **views**. so after clicking this second link breadcrumbs shows,

`Home >> page-2`

But I want `Home >> page-1 >> page-2` which is the sequence in which I arrived on that page

although I have added this all links in the Body of text area using `<a></a>`, what I can do so breadcrumbs read this and make in the sequence as I want, In short how can we customize the breadcrumbs.

# Answer
> 1 votes
you can either extend the breadcrumb array with your link in your theme with theme\_breadcrumb (further information here) or drupal\_set\_breadcrumb in your module, or use one of the many modules around breadcrumb. maybe custom breadcrumbs fits your needs.

you can extend the breadcrumb array with html, like:

```
$breadcrumb[] = l(t('My first page'), 'node/x');

```

or push it to the second postion with array\_splice, like:

```
array_splice($breadcrumb, 2, 0, l(t('My first page'), 'node/x'));

```

# Answer
> 1 votes
Perhaps you should consider using a module for your breadcrumbs, such as:

### Path Breadcrumbs

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path Breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

Here is a nice video tutorial

**or my personal favourite:**

### Crumbs, the Breadcrumbs suite

> Crumbs calculates breadcrumbs for your site. It does so by finding the parent of the current page, then the parent of the parent, etc, until it arrives at the home page.
>
> Crumbs comes with a bunch of built-in plugins, that can be individually enabled, disabled and prioritized, and some of which provide further configuration options.

**FYI: To access the config you need to go to** www.yourdomain.com/admin/structure/crumbs

---
Tags: breadcrumbs
---


title: Running drush site-install on Windows

text:
# Question
Title: Running drush site-install on Windows
I ran the following commands:

```
drush dl drupal-8 --drupal-project-rename=drupal_8
cd drupal_8
drush site-install standard --account-name=****** --account-pass=******** --db-url=mysql://*****:******@localhost/drupal_8 --site-name=Drupal_8

```

in windows 7 but I get following error: Drush 6.7.0 does not support Drupal . See drush for more information.

Command site-install needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this

command. The drush command 'site-install standard' could not be executed.

Am I doing something wrong or drupal 8 standard installation is not supported by drush yet?

# Answer
Didn't realize that I need to upgrade my drush to 8.0.1 as drush 6.7 won't work with drupal 8.
> 0 votes

---
Tags: drush, 8, installation
---


# Question
Title: Deleting Aliases unchecks 'generate automatic alias'
I'm sure this is a bug.

I have a bunch of alias paths set where page URLs are generated based on menu location. I'm testing to see if I restructure the site and move a lot of content around, can I use path-auto, bulk update to change all the URLs.

Obviously I can't update without deleting the existing ones first (tested).

So I went in and delete all the aliases via Admin \> Config \> Search \> URL aliases \> Delete aliases. All aliases deleted, great.

But Bulk update won't give me new aliases. After a bit of poking around it turns out that running Delete Aliases has caused the 'Generate Automatic Alias" checkbox to be turned OFF on all my content.

so...

1. Why did running Delete Aliases cause all my content to change to using custom aliases?
2. Can I (somehow) revert all pages to automatic aliases?

Note - I'm using the govCMS distribution, so adding modules like VBO is not an option. I have almost zero understanding of drush, but I'm willing to dive in with instructions.

Note again - I had pathauto persistant state enabled when this happened.

# Answer
Okay, never mind. I spent over an hour with this repeatedly happening, dug through pages full of people having the same issue and the opposite issue, flicked persistant state on and off, and it suddenly started working in the time it took me to write this. Caching I guess
> 1 votes

---
Tags: path-aliases
---


title: Show content type field on front page

text:
# Question
Title: Show content type field on front page
I created a content type, I need to place several fields on *front page* (text field, dropdown list and button). How can this be done? Do I need to use the *Form API*?

Please let me know what's the best way to go about this.

P.S. I m fairly new to Drupal. Coming from Joomla.

# Answer
> 0 votes
I think the best option for You is the module "Webform",

but you can solve your problem also by **Form api**, though in that case you must create custom module and write enough code...

# Answer
> 0 votes
To display the node form on the front page you can use Form block module. This module fulfill your requirement.

**Form Block:**

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

# Answer
> 0 votes
You can use "webform"

Using webform you can create all kind of fields, Also you can display that form fields as a block using webforms settings, And you can display that block anywhere on your site.

Here is description, How you can create a block for your webform "webform in a block"

---
Tags: nodes
---


# Question
Title: A better way to show a node-based field in a region outside of the node itself
I'm using the 'AddThis' sharing module with Facebook and Twitter so that when a user is on a page of the site they will be able to share it with others. This would include the front page.

The problem I'm discovering is that to use this module you have to add it as a field for a content type...so I can basically add it to all pages EXCEPT the home page.

Putting aside the issue with the front page for a moment, I'd like the sharing buttons to actually appear in the footer, not in the node body itself. The footer is a totally different region. Would this entail me using my .tpl files to change where this specific field appears (ie. hiding it and then showing it again but in the footer for the node)?

Or is there a better way to handle this?

# Answer
> 1 votes
If you aim to keep your footer region's wrappers in page.tpl.php your only option is to:

1. hide field in node.tpl (tpl file or field display settings)
2. render the field in page.tpl.php where you want it.

a) use hook\_preprocess\_page in tepmlate.php to set page=variable = field value (if exists); then print/render that variable in page.tpl.php b) less elegant and more error prone: render field from page's $node variable

The above is assuming you're using standard drupal's theming system.

3. THE QUICKEST: Alternatively you can use something like: https://www.drupal.org/project/fieldblock to expose your value as a block a,d them place it in whatever region. this one is compatible with whatever you use; panels DS; stabdrad block stystem; Context....

---
Tags: theming
---


# Question
Title: Is there a way to use $front_page in node.tpl?
I'm aware that `$front_page` is a variable used in page.tpl, but is there a way to use it (or something similar other than a direct link) to print the index url in a node.tpl?

# Answer
> 4 votes
Absolutely:

```
function MYTHEME_preprocess_node(&$vars) {
  $vars['front_page'] = url();
}

```

---
Tags: uri
---


# Question
Title: How can I randomize search results in Views?
It seems like the simple answer to this issue would be to select **Global:Random** from the Sort Criteria, but choosing this results in a selection of **Global: Random (asc)** -- the asc being ascending.

And indeed the results are displayed as ascending instead of random.

How can this be corrected?

# Answer
Results are displaying in ascending order because you may have another sort criteria present above **Global: Random (asc)** like say **Content: Post date (desc)**.

**Solution:** Move **Global: Random (asc)** sort criteria to top. Surely it will work.

> Note: If you have more than one sort criteria lets say 3, then results first get sorted with first criteria then with second and then with third.
> 3 votes

---
Tags: views
---


# Question
Title: How to get $form_id based on $form_state for custom form rule?
I'm building custom form rule which is having `$form_state` as rule input parameter, however I would like to use `drupal_form_submit()` which requires `$form_id`.

Is it possible to fetch/compute automatically `$form_id` based on its `$form_state` to make my rule generic?

Or maybe there is some documentation that explains what `$form_state` should consist exactly?

My rule is like:

```
/**
 * Implements hook_rules_action_info().
 */
function rules_forms_rules_action_info() {
  $actions['rules_forms_submit'] = array(
    'label' => t('Submit the form'),
    'group' => 'Rules Forms',
    'parameter' => array(
      'form_state' => array('type' => 'form_state', 'label' => t('Form state')),
    ),
    'base' => 'rules_forms_action_submit',
    'access callback' => 'rules_forms_integration_access',
  );
  return $actions;
}

/**
 * Action: Submit the form.
 */
function rules_forms_action_submit($form_state) {
  // $form_id = ?
  drupal_form_submit($form_id, $form_state);
}

```

I've checked `$form_state` and it's a huge (~0,5MB size-like) ArrayObject with the following main keys/properties:

```
build_info, temporary, programmed, programmed_bypass_access_check, cache, entityform, entityform_form_mode, field, storage, rebuild, rebuild_info, redirect, submitted, executed, method, groups, buttons, input, values, complete form, process_input, invalid_token, triggering_element, submit_handlers, clicked_button

```

# Answer
> 2 votes
I think the easiest way was to pass `$form` ArrayObject which has `$form_id` present. So:

```
'form' => array('type' => 'form', 'label' => t('Form')),

```

needed to be added next to `$form_state` parameter in `hook_rules_action_info` and the final function looks like:

```
/**
 * Action: Submit the form.
 *
 * @param ArrayObject $form
 *   A reference to the form array of the form for which the event
 *   was triggered.
 * @param ArrayObject $form_state
 *   A reference to the form state array of the form for which the
 *   event was triggered.
 */
function rules_forms_action_submit($form, $form_state) {
  $form_id = $form['form_id']['#value'];
  $form_state = (array)$form_state;
  drupal_form_submit($form_id, $form_state);
}

```

For submitting entity form, check: How to programatically submit an entityform?

# Answer
> 0 votes
Given `$form_state` of an array or ArrayObject, the Form ID can be found in:

```
$form_state['build_info']['form_id']

```

or:

```
$form_state['build_info']['base_form_id']

```

as this location is used in Drupal core functions (e.g. `drupal_prepare_form()`) so it should be pretty reliable.

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


# Question
Title: How to programatically submit an entityform?
My use case:

1. Anonymous user submits information via an entityform.
2. The form data ($\_POST) is cached and a modal dialog box displays with a login form.
3. The user authenticates, and the cached form data is retrieved and then submitted.

I've been able to do this with webforms, but I haven't been able to accomplish the same task for entityforms. I can get the form using the following code...

```
<?php
$entityform = entityform_empty_load('my_eform_type');
$form = entityform_form_wrapper($entityform);
?>

```

**What I've had trouble with is creating a $form\_state array with the correct structure and values** from the cached $\_POST that I can then pass to drupal\_form\_submit(). My entityform has image, date, and checkbox fields, so that adds to the complexity.

I've been able to manually create and save an entityform submission using the following code...

```
<?php
$values = array(
  'type' => 'my_eform_type',
  'uid' => $user->uid,
  'created' => time(),
  'changed' => time(),
  'language' => LANGUAGE_NONE,
);

// For brevity's sake, I don't show adding all the fields
// from the cached $_POST to the $values array.

$entityform = entityform_create($values);
$entityform->save();
?>

```

...**but that doesn't provide the form validation and reload on error functionality**. Errors such as the wrong size image being uploaded, which is caught during form submission.

When my entityform is submitted, there is also an entityform notification email sent and the user is redirected to the confirm page. I don't want those things to happen prior to the user authenticating.

There's some code in the d.o. handbook, but it doesn't talk about drupal\_form\_submit().

I'm using Entityform 1.1.

# Answer
I don't think you can submit entityform using `drupal_form_submit()` as it's entity, not a standard form.

The best way is to save the entity as you did, but you are missing `field_attach_submit` which is necessary to perform operations on field data submitted by a form.

The syntax is:

```
field_attach_submit($entity_type, $entity, $form, &$form_state, $options = array())

```

Example based on given `$form_state`:

```
$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

// Copy top-level form values that are not for fields to entity properties,
// without changing existing entity properties that are not being edited by
// this form. Copying field values must be done using field_attach_submit().
$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);

```

Alternatively you can submit entity form by using `entityform_save()`, e.g.:

```
$form = new Entityform(array('type' = 'my_entitty_form', 'language' => LANGUAGE_NONE));
$form->field_entityform_1 = array(LANGUAGE_NONE => array(array('value' => 'field_1')));
$form->field_entityform_2 = array(LANGUAGE_NONE => array(array('value' => 'field_2' )));
$form->uid = 1; // this is the form id
entityform_save($form);

```

Source: sushantpaste's gist
> 1 votes

---
Tags: 7, forms, entities
---


# Question
Title: Apache solr filter based on array values
Has anyone succeeded in filtering array values using Apache solr? I have nids as an array, programmatically I want to use the array to filter the solr based on the 'entity\_id'.

I tried something like

```
  $solr = apachesolr_get_solr();
  $query = apachesolr_drupal_query("custom", array('q' => ''),'sort_label asc', 'search/site');
  $query->addFilter('entity_id', '[10915 11013]');
  $response = $query->search();

```

But I don't get the desired results, somewhere the apachesolr\_search or apachesolr module seems to be adding quotes to the filter values something like

```
webapp=/solr path=/select params={sort=sort_label+asc&start=0&q=&json.nl=map&wt=json&fq=entity_id:"[10915+11013]"&rows=10} status=500

```

# Answer
> 4 votes
I finally figured it out. Just a small change to what Clive suggested will solve the issue.

```
$query->addParam('fq', "entity_id:(10915 OR 11013)");

```

The above code gives me the expected response, i.e., result of node 10915 and 11013.

Hope this helps :)

# Answer
> 1 votes
`addFilter` can't guess what your intentions are, so it assumes you're passing a string value for the filter - which is then properly escaped so Solr doesn't misinterpret special chars as part of it.

If you want a more complex condition, you need to go a bit more manual:

```
$query->addParam('fq', "entity_id:[10915 11013]");

```

(that's assuming `field:[x,y]` is valid Solr query syntax for an `IN` operation, I don't know that it is; you might have to use a basic `OR` instead).

---
Tags: 7, search
---


title: Local moved to Server all nodes 404

text:
# Question
Title: Local moved to Server all nodes 404
My homepage works perfectly fine on the live server but when I use any of the links they give me a 404 Page not Found.

I tried a couple things which was:

* Made sure .htaccess was there
* Tried a copy/paste of an .htaccess that someone provided
* Tried setting $base\_url
* Tried setting Rewritebase /

Tried making sure this was in .htaccess

```
 Options +FollowSymLinks
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

```

I did go from an xampp local testing environment on Windows to a nginx setup on Ubuntu 14.04 so I figure it has something to do with that. I'm just not sure what to try next I've done most everything that googling brings me to.

# Answer
> 1 votes
Ok so it was a bit weird how it all came together, I restarted the nginx and that didn't do anythig.

I opened the default config file for nginx and just saved it without making changes and restarted the service.

After than I went from a 404 error to a 500 error.

To fix the 500 error I changed a line in my default from this:

```
 try_files $uri $uri/ /index.html;

```

To this:

```
 try_files $uri/ $uri /index.php?$query_string;

```

I saved the config file and restarted nginx and it worked!

---
Tags: .htaccess, 8
---


title: Saving form fields on custom entity

text:
# Question
Title: Saving form fields on custom entity
I'm having problems saving my custom entity to the db. I created a custom entity called 'review' using `hook_entity_info()` with a custom controller. I have specified some parameters in the controller using:

```
      public function create(array $values = array()) {
      global $user;
      $values = array(
      'rid' => '',
      'uid' => $user->uid,
      'nid' => $_GET['nid'],
      'created' => REQUEST_TIME,
      'changed' => REQUEST_TIME,
      'published' => 1,
      'quality' => '',
      'design' => '',
      'versatility' => '',
      'design' => '',
   );
   return parent::create($values);
 }

```

Everything seems to be working just fine but when I try to submit my form to create a new entity not all fields are saved in the db.

I attached the value of the fields in the form using `field_attach_form('review', $review, $form, $form_state);` and in my submit function I have this:

```
$review_submission = (object) $form_state['values'];
field_attach_submit('review', $review_submission, $form, $form_state);
$review = entity_create('review', array('type' => 'review'));
$entity = entity_metadata_wrapper('review',  $review);
$entity->save($review_submission); //This saves info but not fields

```

This creates a new entity but the fields `'quality', 'design', 'versatility', 'relevance'` are not saved. However if I use this instead in my submit function:

```
review_submission = (object) $form_state['values'];
field_attach_submit('review', $review_submission, $form, $form_state);
$review = entity_create('review', array('type' => 'review'));
$entity = entity_metadata_wrapper('review',  $review);
entity_get_controller('review')->save($review_submission); //This saves fields but not info

```

those fields are correctly saved BUT then `'rid', 'uid', 'nid', 'created', 'changed', 'published'` are not saved.

What am I missing? How can I saved the entity info and the values from the form fields?

# Answer
As far as I understand, you need to provide these values manually before the save, for example:

```
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
$entity->uid = $user->uid;

```

or copy them directly from `$form_state['values']`.

I've found `entityFormSubmit` method from Inline Entity Form module which is manually copying all fields which are not fields to entity properties, so gave me the idea for this code:

```
$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);

```
> 0 votes

---
Tags: forms, entities
---


# Question
Title: How to make the module Node Embed work for any content type?
I have installed Node Embed and created a content type called Text Page, and it works very well to embed nodes of all kind.

But I also have a content type called Article and there, no kind of node will be embedded.....I only get the \[\[(nid:number)\]\]. Both content types have the text field called: body; which is the long text and summary.

# Answer
SOLVED!!! The body text was rendered through a view, and therefore it did not show the node embed content! So I changed it to "Node being viewed" Body....and there it was :)
> 1 votes

---
Tags: nodes
---


# Question
Title: How do print term image field as background style attribute in views-view.tpl.php?
How do print term image field as background style attribute in views-view.tpl.php or in views-view-unformatted.tpl.php file? I have view which lists terms of taxonomy vocabulary. All terms have title and image fields. I need to lists terms like:

```
<div style="background-image:url(http://example.com/term1_field_image.jpg);">
<h2>Title</h2>
<div>
<div style="background-image:url(http://example.com/term2_field_image.jpg);">
<h2>Title</h2>
<div>

```

# Answer
You can achieve this with row style instead. Go to your views advance settings then click on theming information and look for appropriate name for row styling and write something like this.

```
$uriImagefromView = $row->field_field_image[0]['rendered']['#item']['uri'];
$urlImagefromView = file_create_url($uriImagefromView);

```

This will give you the url to the path of that image. Now you can easily render it as background.

If you want to render your background image in particular size you created in image style you can do like this

```
$resized_url = image_style_url('<style_name>', $uriImagefromView);

```
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: How can I create a Simple page that display the latest node of a content type?
I write a little module for loading the content via ajax(one of the used tutorials) and now I need a page for the first visiting(front page). I don't want to do this with Views and looked around, but didn\`t found a simple solution for this.

So, I extend the hook\_menu () function with:

**EDITED**

```
$items['first-node'] = array(
  'page callback' => 'first_node_callback',
  'access callback' => TRUE, //EDIT -> 'user_access' creates Menu error
  'type' => MENU_CALLBACK,
);

```

and the callback:

```
function first_node_callback() {
  $query = db_select("node", "n");
  $query->fields('n', array('nid'))
    ->condition("type", "mytype", "=")
    ->orderBy("created", "DESC")
    ->range(0, 1);
  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);
  return node_view_multiple($nodes, 'full');
}

```

**EDITED END**

Should i load this in the #markup or use a normal return or need i an extra theme output? I'm little bit confused with the possibilities!

# Answer
Just do the following with node object in your page callback function. No need of returning separate `#markup`.

```
return drupal_render(node_view($node));

```
> 2 votes

---
Tags: nodes
---


# Question
Title: In Ubercart, can I make a "View Cart" link appear only when an item is in the user's cart?
Ubercart is only a small part of our site and we only want the default cart block to appear when a user is in that shopping section. Simple enough to do with "Show block on specific pages" rules.

However, when a user navigates away from the ubercart section, the cart block disappears, but I would still want to denote that the active cart exists. I don't want users to think their cart has completely vanished.

Preferably it would be a simple, tiny "View my cart" link to the default Ubercart cart page in the Header Block region. Or even added to the end of the main site navigation menu.

So, to reiterate, how can I make a Block (or menu link) render only when an item is placed in a user's cart?

# Answer
Create a block with your "View Cart" html code then set block visisbility to "Pages on which this PHP code returns TRUE (experts only)" with the following:

```
<?php
$items = uc_cart_get_contents();
if (count($items) > 0) {
  return true;
}
return false;
?>

```
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Add two items with different shipping methods to basket / checkout in drupal commerce
I am currently using drupal commerce to build a website for my partner who sells jewellery. I consider myself a fairly confident drupal user and have built various websites using the platform. This is the first time i have used commerce though.

So my issue is with shipping. I have three shipping package types defined in a taxonomy, and a nice way to select which of these 3 package types the product should be shipped by using a term reference field in product creation. I have successfully got commerce to reference to this term reference using Commerce Taxonomy Conditions. So far I have 3 shipping package types set up and 3 world zones and can get the correct shipping cost associated to each of these options to come up fine in the checkout pane.

So i have 9 shipping services (3 package types x 3 world zones)

BUT

The problem comes when there are two different package types (taxonomy terms) added to the basket and therefore there should be two prices added together and in checkout it comes up with "No valid shipping rates found for your order, and we require shipping service selection to complete checkout."

How can I get this to work please? What am I missing?

I have tried OR and adding to that the taxonomy term which is true and the two taxonomy terms which are false and now i can get two package types displayed in shipping in the check out pane but not getting them adding together?

This is currently doing my head in, any help would be gratefully received. Thanks,

# Answer
Currently, shipping is set on an order-basis. If you want to have per line-item shipping that would be something you'd have to build custom. Line items *are entities* so you can add new fields to them (including shipping profiles) and then create a shipping module or ruleset that properly configures shipping.
> 0 votes

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


# Question
Title: How to access the value of a referenced node's field to use it as a Rules action?
I have a content type A that has a node reference to type B. Type B has an email address field that I would like to use in a Rules Action. How do I get the value of a referenced node's fields?

**Note**: After much searching, I tried the steps Link suggested in Rules: Do action on the field of referenced node, but after adding the Entity has Field condition on my node reference field, there are not any replacement patterns like `node:node_reference:field_email`, just the normal `node:field_email`.

# Answer
Try adding a Rules Action (as the very first action) like "*Fetch entity by id*", which in your case is probably something like `node:node_reference:nid`.

This should make the data available from the node that is referenced via your node reference field.
> 0 votes

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


# Question
Title: theme() parameters sent to output.tpl.php
What I am trying to do, is to set some variables in my function and to send this to my output.tpl.php.

My steps are the following.

1. Declare my theme template

```
function mymodule_theme() {
  return array(
    'my_file' => array('template' => 'output')
  );
};

```
2. Define the following function

```
function mymodule_myfunction() {
  $build['variables'] = array(
    '#theme' => 'my_file',
    '#variables' => $my_vars
  );
  return $build;
}

```
3. I use the following code for my output file (output.tpl.php)

```
<?php echo $my_vars[0]; ?>

```

I get an error saying *`$my_vars` is unknown*.

What am I doing wrong?

# Answer
As described in Override template files based on template filename as well as hook name, if you theme function is *my\_file*, your template file needs to be *my-file.tpl.php*; you cannot use *output.tpl.php* because Drupal would not recognize it as template file, at least until Drupal code is not changed as per the issue I linked.
The variables that you pass to the template file needs to be defined in your implementation of `hook_theme()`.

Your code should be similar to the following one.

```
function mymodule_theme() {
  return array(
    'mymodule_output' => array('template' => 'mymodule-output', variables => array('my_vars' => NULL))
  );
};

function mymodule_myfunction() {
  // Add here the code that initializes $my_vars.
  // …

  $build['variables'] = array(
    '#theme' => 'mymodule_output',
    '#my_vars' => $my_vars
  );
  return $build;
}

```

```
// mymodule-output.tpl.php
<?php echo $my_vars[0]; ?>

```

I used mymodule\_output as name of the theme function and mymodule-output.tpl.php as name of the template because the coding standards used from Drupal suggests to use the module name as prefix; it would not change if you used *output* where I used *mymodule-output* or *mymodule\_output*.

If all you are doing is printing a variable, then you don't need a theme. Theme functions (and template files) are used when you plan to allow themes or other modules to alter the output of your module. That is why Drupal uses *node* as theme function: to allow themes to alter how a node is rendered. The Node module defines its own node.tpl.php file, and the Bartik theme uses its own node.tpl.php.
> 0 votes

# Answer
To simplify the task use the following code.

```
function mymodule_myfunction() {
  $my_vars = array()
  $my_vars[0] = 'bla bla bla';
  $my_vars[1] = 'some other value';
  return theme('my_file', $my_vars);
}

```

And your theme function will look like

```
function mymodule_theme() {
    return array(
        'my_file' => array(
            'template' => 'output',
            'variables' => array(),
         )
    );

}

```

Now in output.tpl.php you simply print

```
<?php print $variables[0]; ?>

```
> -1 votes

---
Tags: theming
---