# Question
Title: How to upload/insert images in content from module?
```
  $article = entity_create('node', array(
    'type' => 'article',
    'title' => generate_demo_content('lorem_ipsum_title'),
    'body' => array(
      'value' => generate_an_article(),
      'format' => 'full_html',
    ),
    // how attach here, a file or an image?
  ));
  $article->save();

```

I create an article from a .module file, and I would like know if I can link an image/file object to my article?

By example if I have an image inside **/modules/my\_module\_name/images/img.jpg**, how I can insert this image inside my article object from my .module file please?

Thanks.

# Answer
> 0 votes
I have tried the below code with node\_save method but not with entity\_create way. Check if it works.

```
$dir = 'public://';
if (file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
  $file = file_save_upload('image', array(), $dir, FILE_EXISTS_RENAME);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $attachment = array(
    'fid' => $file->fid,
    'display' => 1,
    'description' => $file->name,
    'title' => $values->tooltip
  );
}

$article = entity_create('node', array(
  'type' => 'article',
  'title' => generate_demo_content('lorem_ipsum_title'),
  'body' => array(
    'value' => generate_an_article(),
    'format' => 'full_html',
  ),
  'field_attachment' => $attachment, //may need to change here
));

```

---
Tags: 8, media, files
---


# Question
Title: CKEditor not displaying in latest 8.0.x-dev version
After updating Drupal from version `8.0.0-beta7` to version `8.0.x-dev` — to fix `text_format` fields not submitting their value due to a missing `name` attribute —, my field is now displaying as a basic `input` field with the format bar under it.

Here's the code that defines the `content` field of my entity (inside the `baseFieldDefinitions` method):

```
$fields['content'] = BaseFieldDefinition::create('text')
  ->setLabel(t('Content'))
  ->setDescription(t('The content of the block'))
  ->setSettings(array(
    'max_length'  => 1024
  ))
  ->setDisplayOptions('form', array(
    'type'   => 'text_format',
    'weight' => -6
  ))
  ->setRequired(TRUE)
  ->setDisplayConfigurable('form', TRUE);

```

As said above, this code works fine on the latest beta but breaks on the latest version from GitHub.

**Expected result (8.0.0-beta7):**

**Obtained result (8.0.x-dev):**

I had submitted a bug report, thinking this was a bug, but apparently it isn't. I was told I need to use a `textarea` for the editor to show up. The thing is... `text_format` defaults to a `textarea`.

I'm guessing there's something I'm not doing right here, but after hours of searching, I just can't seem to understand what. I've tried changing the type passed to `BaseFieldDefinition::create()` to `string_long`, too, but then I just get a `textarea` with no format.

# Answer
Here is the correct code to create a WYSIWYG field:

```
$fields['title'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Content'))
  ->setDescription(t('The content of the block'))
  ->setDisplayOptions('form', [
      'type' => 'text_textarea',
    ])
  ->setDisplayOptions('view', [
      'type' => 'text_default',
    ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```
> 2 votes

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


title: Twitter Module with Formatted tweet

text:
# Question
Title: Twitter Module with Formatted tweet
I use the Twitter module to create a feed from various accounts for my website.

If I created a block with a field `Twitter: Formatted tweet`, the preview doesn't show anything. A broken image, a blank message etc.

If I add also the field `Twitter: Twitter status message ID`, the preview show most of the tweets, but there are still some of them without content.

If I set the fields custom without the Formatted tweet, I don't have this problem.

Also, I have this error on the page where I show this block:

```
Notice: Trying to get property of non-object in twitter_views_handler_field_formatted_tweet->render() (line 146 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Undefined property: stdClass::$text in twitter_views_handler_field_formatted_tweet->render() (line 157 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 11 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 12 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 35 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 38 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 41 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in twitter_views_handler_field_formatted_tweet->render() (line 146 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Undefined property: stdClass::$text in twitter_views_handler_field_formatted_tweet->render() (line 157 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 11 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 12 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 35 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 38 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 41 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in twitter_views_handler_field_formatted_tweet->render() (line 146 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Undefined property: stdClass::$text in twitter_views_handler_field_formatted_tweet->render() (line 157 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/twitter_views_field_handlers.inc).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 10 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 11 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 12 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 21 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Trying to get property of non-object in include() (line 25 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 35 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 38 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).
Notice: Undefined property: stdClass::$twitter_id in include() (line 41 of /var/lib/openshift/54f9b83bfcf933c2b800009a/app-root/data/sites/all/modules/twitter/tweet.tpl.php).

```

# Answer
I'm gonna give you an answer that will not sound like good news. The rendering of the **Twitter: Formatted tweet** field is a bit buggy at times.

As a quick workaround I'd says don't use **Twitter: Formatted tweet** and use all the other **Twitter: .........** fields available to you. And then style your output which ever way suits you with a template.

The alternative is to debug the module...
> 1 votes

---
Tags: 7, social-network
---


title: Taxonomy term related content

text:
# Question
Title: Taxonomy term related content
When click on any term, content related to that term should be displayed on the right hand side of a page. I have my taxonomy tree on left sidebar using Drupal API function.

What I had done is:

1. Created view with content type, containing all products related to taxonomy terms.
2. Add a field in that content type with field type "term reference" and widget type "simple hierarchical select" module.

Now what should I do in order to filter the term based content? Any Ideas?

# Answer
If I understand your question correctly, sounds like you maybe want to use a contextual filter for the taxonomy term TID, and embed as a block in the sidebar for taxonomy pages.

This may help: http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7

Steps to help:

* create a relationship, Content: Taxonomy terms on node, choose taxonomy, check require this relationship
* add contextual filter, Taxonomy Term: Term ID, select the relationship you just made, check "provide default value- Taxonomy term ID from URL, Load default filter from term page.

Just checked on a vanilla install, and that worked a charm for me...
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: drupal overlay text when you hover over the image views
I have the content type with image, title and text fields. I deduce views. I want to hover over the image appear the title and text field and a button with link. Example http://demo.weebpal.com/#onepage portfolio section

how to do it?

# Answer
> 1 votes
This is only in part a Drupal question. The part that interests you most is the CSS styling.

As a tutorial, this could take several hours to explain, using the classes, wrappers, fields and so forth. I will jump over the styling, but I hope this will help as well.

As for the view itself, managed by Drupal, it is a little tricky. You need 2 containers in a wrapper. The first container should have the link set on the image and the second container should have the rest of the text and buttons.

Create a page or a block view listing all your nodes you need to include, printing fields.

Add the field image and set it to link to the node itself.

Add the text fields you need, one after the other, in the right order (title on top, text in the middle, button - linked to content - at the end and so forth).

Here comes the Drupal tricky part. Set everything as "exclude from display".

Now, as a last field, add a Global Text Area and print the 2 containers. Use tokens generated by Drupal and include them inside the containers.

1. For the first container, write down the wrapper code including the link over the image as a token generated by field no. 1.
2. For the second container, write the code for the wrapper and include inside every token for the hover visible content, in the proper order.

Then you need the right CSS, using position absolute, setting the view wrapper as relative and the second container as absolute.

Good luck.

---
Tags: views
---


title: Menu will not display - D7

text:
# Question
Title: Menu will not display - D7
I have an issue where I have created a menu within Drupal, assigned the block created by that menu to a region and set it to display on certain pages, but it's not displaying.

It's a Drupal 7 site (v 7.31)

Here's how it's set up:

* Menu created
* Block for menu was automatically created when menu was created
* Block is assigned to appear in a region (Sidebar First) in my theme
* Block is assigned to appear *only* on pages with certain path patterns (foo/\*)
* Pages with those patterns exist (e.g. foo/bar)
* Some pages with these URL patterns do have multiple URL aliases assigned to that page, but other pages do not. The issue is the same
* The Context module is installed/enabled on the site but there are no enabled rules/conditions associated with these pages
* The site uses the Omega theme (7.x-3.1), but there are no enabled Delta settings on these pages either.

So far, I have:

* Deleted and recreated the menu
* Cleared the cache, multiple times before and after creating the menu, using the UI and Drush
* Tried creating/deleting the menu on an earlier backup of the site (running 7.26)
* Used the regular block created by the built in Drupal menu module, and tried using MenuBlock
* Created a dummy regular block and assigned it to Sidebar First on the same pages - this did not display either
* Checked the source code to see if the menu was appearing (and maybe not being displayed by the CSS) - it wasn't appearing in the code either
* Tried assigning the block to a different region. Assigning the block to Sidebar Second produced the same issue, but assigning it to the "Content" section display the block below the content.

# Answer
The issue in this case was that the site was set up so that the `sidebar_first` region only displayed if explicitly directed to do so by the *Delta* module used with the Omega theme.

If there was not an explicit Delta rule telling Drupal to display the `sidebar_first` region, then by default it wasn't displayed.
> 0 votes

# Answer
It's definitely your theme that is at fault. I'm not familiar with Omega; I personally *never* use third-party base themes. They make the whole process more complex, IMHO. If you are skilled with HTML/CSS, there's no reason to use a base theme like Omega. You may find more information on what you are trying to achieve here.

Other than that, here are a few suggestions about debugging your theme:

**A) Check you `.info` file.**

In your `.info` file, you should have a few lines defining what regions are available to your theme. **These regions are not inherited from the parent theme !** You must explicitly define them as follows:

```
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar

```

If you needed to add these lines, don't forget to **clear your site cache**.

**B) Check your templates**

This is not necessary if you inherit the `page.tpl.php` template file from the parent theme, **unless you don't use the exact same regions**. Note that, because you don't inherit them in the first place, **this is often source of confusion**. If you use different regions, **you must also have your own `page.tpl.php` file.**

This sucks, but it's just the way it is.

Another, pretty common, mistake is to print these regions in Drupal 6 style. If you use this in your template:

```
print $sidebar_first;

```

you're doing it wrong. The Drupal 7 syntax is:

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

```

It's ugly, but what can you do ? (actually you *can* do something about it, but that's out of this scope).

**C) Clear cache, clear cache, clear cache...**

Drupal 7 is *very* resilient when it comes to clearing caches. *Everything* is in a cache somewhere. Make sure you clear the caches every time you create a new template file, you add a new `hook` (especially `preprocess` hooks) or make any changes to the `.info` file.
> -1 votes

---
Tags: routes, blocks
---


title: Expose roles to views

text:
# Question
Title: Expose roles to views
I am using the role reference module (https://www.drupal.org/project/rolereference) to allow me to add roles to a content type.

For some context, in my case we are managing policies. The policy content type will have fields such as "Owner" and "Sponsor" that will reference roles using the module above.

My issue comes when trying to put together views. I am able to access the role reference field through views without issue, but its sorting is based role id (rid) instead of the role name.

I am attempting to sort by role name, and am unable to create a relationship as Role is not available.

What is the best way to do this? At the moment it appears that writing a custom module that invokes hook\_views\_query\_alter() to alter the query before it runs might be the best solution.

I'm wondering if anyone has had any success exposing roles as a relationship within views?

Thanks in advance.

# Answer
Turns out this can only be done programatically in a module. Here is an example in case its useful for someone else:

```
function HOOK_views_query_alter(&$view, &$query) {
    /***** Owner ****/
  if ($view->name == "policy_listing" && $view->current_display == "policy_by_owner") {
    //alter the query so role reference fields are sorted by the role name rather than role id (rid)
    //replace the rid with the actual owner name
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['field'] = "name";
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['table'] = "role";
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['num'] = 2;

    //add the join to the role table
    $join = new views_join();
    $join->table = "role";
    $join->left_table = "field_data_field_policy_owners";
    $join->left_field = "field_policy_owners_rid";
    $join->field = "rid";
    $join->type = "LEFT";
    $join->extra = array();

    $query->table_queue['role'] = array (
      'alias' => "role",
      'table' => "role",
      'relationship' => "field_data_field_policy_owners",
      'join' => $join,
    );
  }
}

```

In this case I am replacing rid with the actual name of the role in the view so the sorting works. Obviously, replace HOOK with your module name.
> 0 votes

---
Tags: users, views
---


# Question
Title: Access violation with Drupal 7 multisite using shared DB
I'm building a Drupal 7 multisite and I want to have a separate database for each site but with some shared tables. So, I have two sites called siteone and sitetwo. I also have **3 databases** \- **oxone** (for first site), **oxtwo** (for second one) and **oxshared** (where I want to keep shared tables for both sites.

I used the following config for settings.php (for siteone), but it shows me a PDO exception... What I'm doing wrong? Will be very appreciate for any help or advice.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'oxone',
      'username' => 'oxone',
      'password' => '*********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
         'default'   => 'oxone.',
         'users'     => 'oxshared.',
         'users_roles'     => 'oxshared.',
         'sessions'  => 'oxshared.',
         'role'      => 'oxshared.',
         'role_permission'      => 'oxshared.',
         'authmap'   => 'oxshared.',
     ),
    ),
  ),
  'oxshared' =>
  array (
    'default' =>
    array (
      'database' => 'oxshared',
      'username' => 'oxshared',
      'password' => '**********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

The exception is:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1142 SELECT command denied to user 'oxone'@'localhost' for table 'users': SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid; Array ( \[:sid\] =\> \_5UERN3eEWligNxBusEYCq3Lnf48pfvWDu9FDQDZUI8 ) in \_drupal\_session\_read() (line 102 of /home/qsoul/public\_html/siteone.dev.lo/includes/session.inc)

Why doesn't Drupal use the oxshared user when accessing the tables in the oxshared database, as defined in the `prefix` array? It uses the oxone user instead.

# Answer
The question is closed. It seams to be that to have some tables in a separate database:
1) that second db should be placed at the same host as default one.
2) the user who has access to the default db should also has access to the second db.

Adding one more db to settings.php is not needed. It my case the correct settings.php db config has to look like:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'oxone',
      'username' => 'oxone',
      'password' => '*********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
         'default'   => 'oxone.',
         'users'     => 'oxshared.',
         'users_roles'     => 'oxshared.',
         'sessions'  => 'oxshared.',
         'role'      => 'oxshared.',
         'role_permission'      => 'oxshared.',
         'authmap'   => 'oxshared.',
     ),
    ),
  ),
);

```
> 1 votes

---
Tags: multi-sites
---


# Question
Title: Get select options for an entityreference field using another field as a contextual filter?
* I have a *Course Offerings* vocabulary where each taxonomy term is an educational course.
* Users have a multivalued *My Courses* Entity Reference field referring to the terms of the courses they're enrolled in.
* I have a custom content type (Entityform) with two more Entity Reference fields: a *Course* field and a *Student* field. The user must first select a course (a *Course Offerings* taxonomy term), and then select a student (a user).

**Here's the kicker**: I need to filter the *Student* select list options based on what the user selected in the *Course* field.

The *Course* field select options are generated by a view that returns the current user's *My Courses* field courses. After the user selects one of their courses, the *Student* field select options should be generated by a view that uses the course they chose as a contextual filter to return a list of only the users enrolled in that course.

I know how to build the view once I have the contextual filters, but I'm stumped as to how to pass the *Course* term to the view as a contextual filter. Is this possible?

**EDIT FOR CLARIFICATION:**

* Both the *Course* and *Student* fields are Entity Reference fields.
* Both use select-list widgets whose options are populated with views Entity Reference displays.
* The *Course* field comes before the *Student* field on the eform. The intention is that the person filling out the form will first choose the course. Then they'll choose the student from a list of students enrolled in the course they just selected.

# Answer
> 1 votes
I've kept an eye out for a module that does this since the original post, but never came up with anything. I've been using a sort of "one off" solution to do this on a case-by-case basis instead:

1. In a custom module, implement hook\_form\_FORM\_ID\_alter() for the form with your dynamic fields.
2. Add #ajax attributes to the first element to trigger and handle changes to it with AJAX. This will specify the AJAX callback handler and the HTML ID of the element to be replaced with the AJAX response.
3. In the ajax callback for that element, use the AJAX-submitted value to dynamically get the appropriate values for the second value. For me, this is usually a query of some sort with the submitted value as a filter.
4. Update the second field's form element #options attribute with the dynamic values and return the element.

# Answer
> 1 votes
Take a look at the Reference field option limit module, it also does what you want.

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

---
Tags: views, entities
---


# Question
Title: Importing data into specific fields from CSV - into pre-existing nodes?
I've used the Feeds module before to import nodes and users. I need to import data into new fields on pre-existing nodes - is that possible?

# Answer
Feeds requires you to map a unique identifier in order to update existing content; I've not tried this but presumably if your existing content has a unique field/property which you can map to your import then you will be able to update existing content.
> 1 votes

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


# Question
Title: Show contact form in block only, not page?
I'm using the Contact and Contact Form Blocks modules to create a contact form and display it in a block.

The problem is that the Contact module creates a page but I don't want a page, only the block.

Is this possible, perhaps with a different set of modules? If not then I guess I can deny access to the page using .htaccess, but that seems a bit of a hack (although since it's easier to do that than to add custom code, I'm not really interested in a custom code solution).

EDIT: I've tried using a webform instead but have the same issue. There's an option to make the webform available in a block, but the page (node) is also created

# Answer
> 1 votes
You can use the module Webform for contact forms. It comes with the option to make it available as a block. Here's a quick screenshot of the option:

You can also add other function like email notification, AJAX, template for confirmation page, etc. It's a highly customizable module, very recommended.

# Answer
> 0 votes
The Views Contact Form module might help you or else you can create a custom contact us for and display it in the `hook_block`.

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


# Question
Title: Views Search API with Search API database, sort handler
I need to have a views handler for Views Search API that will allows empty (i.e. NULL) values in fields to be sorted last. For the simple views there is a solution: Views Sort Null Field but I'm totally lost, How to implement the same functionality for Views Search API?

More specifically - Views Search API provide only `$query->sort()` method that not allow you to add sort formula like `$this->query->add_orderby(NULL, "ISNULL($this->table_alias.$this->real_field)", $this->options['order'], $alias)`

# Answer
In case you are using Search API Database Search as a backend for the Search API you can solve the problem by using hook\_search\_api\_db\_query\_alter hook:

```
/**
 * Implements hook_search_api_db_query_alter().
 *
 * Preprocesses a search's database query before it is executed.
 *
 * @param SelectQueryInterface $db_query
 *   The database query to be executed for the search. Will have "item_id" and
 *   "score" columns in its result.
 * @param SearchApiQueryInterface $query
 *   The search query that is being executed.
 *
 * @see SearchApiDbService::preQuery()
 */
function custom_module_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  $db_query->orderby('ISNULL(field_field_name)', 'ASC');
}

```

This solved it and moved items with NULL values to bottom of the view. Cheers!
> 1 votes

---
Tags: 7, search, views
---


# Question
Title: How to create charts in Drupal while working offline that integrate with the Quiz module?
I'm now working on a local offline network website, which needs a graphical chart report for their quiz. But since it's offline I cannot use the (interactive) Google Charts API as a charting engine.

I tried FusionCharts already for the Webform Report module, but it has no integration with Quiz.

Any suggestions would be great.

# Answer
You can use Flot since it has views integration as Quiz. Flot can be used offline while Google charts can't because of their TOS.
> 2 votes

# Answer
# Possible options

To create charts in Drupal, have a look at the Comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison includes quite some charting modules ... and related charting libraries (engines).

# Options to be eliminated

Possible alternatives that for sure will **not** solve this specific question (= illustrate the "pain"?), are the Chart module, or the Charts module. Because the D6 version of both modules require an internet connection.

However, for somebody using D7, using the Charts module in combination with the Highcharts library could work, provided you have a valid license for it (which is free for non-commercial use).

# License requirements

The **license** that comes with the related charting library (engine) in each of these charting modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. Some other typical items to consider are:

* Possible privacy concerns.
* Yes or no support for saving charts in PDFs (usually supported by PHP based libraries, and not supported by JS based libraries).
* Flash based libraries should be avoided if charts are to be displayed on mobile devices.
* Some libraries (like the Google flavors ...) require a working internet connection (not always available in local DEV environments ...).

# Recommended charting libraries

In this specific case, I think you should go for a PHP or JS based library (assuming you have a way to get the library downloaded) and consider one of the modules using pChart or SVG Graph (both open source).

# Examples

Here are some online examples created with either of these libraries:

* The SVG Graph demo uses the SVG Graph library. It's created by the Forena module, which you can use to create your own custom charts.
* The Days of week example uses the pChart library. It's created by the Visitors module and can be used as an example of "roll your own cookies" without using a typical charting module (by looking at its source code).

**Be aware**: I'm a (co-)maintainer of all modules mentioned, and the author of the Comparison of charting modules.
> 2 votes

---
Tags: 6, quiz, charts, log-messages
---


# Question
Title: save base64 images alongside entity creation
I need to save and edit entities via services like {user, nodes, products ...etc}

the problem comes with images posted form mobile apps encoded base64.

I saved the file and stored the object in session to be used in hook\_services\_request\_postprocess\_alter to be added to the entity saved by loading it again and assign the value to the field

```
// in preprocess
$_SESSION['file'] = file_save_data(base64_decode($args[0]['image']),'public://test.png');

// in postprocess
$product = entity_load('commerce_product', array($result->product_id));
$wrapper = entity_metadata_wrapper('commerce_product', $product);

//$wrapper->field_field_user_avatar->file->set($_SESSION['file']);
//$wrapper->field_field_user_avatar['und'][0]['value']=(array)$_SESSION['file'];
//$wrapper->save();
entity_save('commerce_product', $product);

```

what missing here I have tried many answers either adding the file object to the field when creating the field nor entity saving

# Answer
> 3 votes
It works after getting file mime type here is the code sample

```
$data = base64_decode($args[1]['avatar']);
$finfo = finfo_open();
        $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
        finfo_close($finfo);
        // get file type png. jpg
        $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
        $file_name = str_replace(' ', '-', $args[1]['name']);

```

then you we save the file using

```
$file = file_save_data($data, 'public://users/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);

    $args[1]['field_field_user_picture'] = array(
        'fid' => $file->fid,
        'width' => 100,
        'height' => 100,
        'alt' => $args[1]['name'],
        'title' => $args[1]['name']
    );

```

---
Tags: services, entities
---


# Question
Title: Create donation product with Commerce Kickstart
I've installed a fresh copy of Commerce Kickstart 2 and then installed Commerce Donate.

After the installation, step 1 of the Commerce Donate readme says:

* Create a donation product at Administration » Store » Products

I go `/node/add/add-product` and choose the type Donation. When creating the product there is a select field called product with no options.

It seems like I'm creating the display node not the actual product.

How do I create the actual product?

EDIT: Just found the same question on the Commerce Donate issue queue: Problem Creating Donation Product.

# Answer
Someone replied on the Commerce Donate issue thread with a solution.

The solution is to manually go to: `/admin/commerce/products/add/donation` where you can then make your product.
> 0 votes

---
Tags: commerce
---


title: Different image styles for each result?

text:
# Question
Title: Different image styles for each result?
I am trying to achieve a masonry-style blog post display using Views, which will look similar to this: http://blog.iamcreative.me/wp-content/uploads/2012/10/MASONRY.jpg

I have an image in each result, but I want the Image Style to vary (e.g. 400x300, 400x400, 400x600) between the results. I would then use the Masonry Views module to achieve the masonry functionality.

Does anyone know how I can vary the image styles between the results so the post pictures will be of varying sizes?

Thanks in advance :)

# Answer
It's quite a broad question – so my answer will also appear to be rather broad: there are various ways to achieve this. From fields, that would let an editor select an image style to views in combination with display suite – and you yould even achieve a similar effect using css-only. I'll skip the views+display\_suite and instead just add some thoughts about the other two options, that might appear to be a bit more quick-n-dirty, but could still very well let you achieve what you're looking for – hope it helps:

* style selection by additional field: for example have a select list offering different picture styles e.g. "portratit", "square" and "landscape" and then preprocess your images according to the selector choice, using a picture style – inside your template.php. This might sound a bit complicated at first, but at least for me this works perfectly well. And it's quite editor-friendly in my opinion.
* css: if you ***just*** want to fit entries always in the same grid the easiest way could be to use css3 selectors like "first-of-type" and "nth-of-type(n)" (find out more e.g. here on w3schools.com: http://www.w3schools.com/cssref/css\_selectors.asp)
> 0 votes

# Answer
If you enable Display Suite, you will get a format setting to choose a different view mode for each item.

You'd just need to set up each different view mode in display suite, then create your view and set each row to the needed style.
> 0 votes

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


title: Migrate deregister

text:
# Question
Title: Migrate deregister
For the following question, note that the site is currently running Migrate 2.5, with a plan to upgrade to 2.7.

I have the following migration, as represented by running migrate-status:

`$ drush ms`

```
Group: default         Total  Imported  Unimported  Status  Last imported
 TiWpAuthor             70     64        0           Idle    2015-02-17 21:17:20
 TiWpImage              15525  14643     882         Idle    2015-02-18 17:11:32
 TiWpPost               13417  12638     608         Idle    2015-02-18 16:57:22

```

I would like to deregister the TiWpPost node. So I run the following commands:

`$ drush migrate-deregister TiWpPost`

`Deregistered 'TiWpPost' migration`

`$ drush cc all`

`'all' cache was cleared`

However, when running migrate-status again, the output is unchanged, with the same Total, Imported and Unimported counts for TiWpPost. (I am expecting to see zero in all of these columns.)

Am I missing something in my understanding of how migrate-deregister is meant to work?

# Answer
> 1 votes
Try this instead:

```
drush migrate-deregister --orphans
drush migrate-reset-status
drush ms --refresh

```

---
Tags: migrations
---


# Question
Title: What is the recommended way for handling a multilingual service?
I'm using the Services module together with a multilingual backend (field translation). My endpoint is v1. What I would like to have is `<domain>/v1/fr/...`.

Is this possible without having a redirect? What is the recommended way for handling multilingual services?

# Answer
If you are using the language code as a URL prefix, then you should be able to access your endpoint as usual with the language code prefixed to it:

```
?q=fr/v1/...

```

For example, to get a node in *French* you could make a **GET** call on:

```
?q=fr/v1/node/123.json

```
> 0 votes

---
Tags: services, i18n-l10n
---


title: Give ID to View?

text:
# Question
Title: Give ID to View?
How can I give my View an ID? I can give it a class under Advanced pane, but how can I add an ID to a particular View?

Anyone ever bumped into anything like this before

# Answer
You can override the default template and wrap the view with a div tag and supply an id.
> 1 votes

---
Tags: 7, views
---


title: Variation on Views exposed filter

text:
# Question
Title: Variation on Views exposed filter
I am working on a Drupal 7 site. One View on the site that lists hundreds of publications around a scientific theme has this great set of exposed filters in a bar at the top that allows researchers to search the publications. Unfortunately, the site owner and graphic artist went a little wild with another section, and designed this great set of filters that should bring up results in a View, but the filters aren't on a View page. Can the "exposed filters" for a View Page be placed on a different page altogether?

Thanks for your help!

# Answer
> 1 votes
Yes, make it a block. Assign it to a region on a particular page. When the user clicks the Apply button the view will be displayed.

---
Tags: views
---


title: Passing variables to custom templates

text:
# Question
Title: Passing variables to custom templates
In Drupal 7 I have a web site with dozens of custom templates. I used `theme()` to pass variables to my templates defined in `hook_theme()` in a page callback defined in hook\_menu. How do you do this in Drupal 8? The `theme()` function is no longer available.

# Answer
> 3 votes
Drupal 8 uses render arrays for the structure, and `drupal_render()` to render them (as can Drupal 7 for themeing, incidentally).

The examples from the change record are as good as any:

Drupal 7

```
// Theme a table with header and row data.
$markup = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));

// Render a pager.
$markup = theme('pager');

```

Drupal 8

```
// Theme is available as an element type (may have additional processing in rendering).
$table = array(
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => array(
    'id' => 'my-module-table',
  ),
);
$markup = drupal_render($table);

// Pager is not an element type, use #theme directly.
$pager = array('#theme' => 'pager');
$markup .= drupal_render($pager);

```

There's a useful warning too:

> Also note that when preparing output for Twig templates (in preprocess functions) it is preferable to avoid calling drupal\_render() whenever possible. The Twig environment in Drupal 8 will automatically render any render arrays printed in the template, allowing for manipulation by later preprocess functions and preventing unnecessary rendering if the variable is never printed in the template.

---
Tags: theming, 8
---


# Question
Title: field output dependend on mime type of another field
I have a node type with 2 fields: preview\_image and file (multivalue).

I can upload image and video files.

For the output I need the following:

The preview\_image should only be displayed when the first file of the file field (multivalue) has a specific mime type (in my case any video mime type).

Is there a solution for that?

UPDATE:

Now we have a change in field structure. We use 2 mime types, images and videos. But for the images we need a cropping function. And we need an easy possibility to arrange the files within node editor.

Now we would like to create 2 new node types - for example 'image' and 'video'. In both node types we create the file fields - in 'image' with the cropping function.

In the main node type we now create 2 fields as entity references to get the files.

Now we need a solution to display the preview image only when the referenced node is of type 'video'.

**Show preview image:**

media element (referencing field)

* entity of type 'video' (referenced entity)
* entity of type 'image' (referenced entity)
* entity of type 'image' (referenced entity)
* entity of type 'video' (referenced entity)

**Don't show preview image**

* entity of type 'image' (referenced entity)
* entity of type 'image' (referenced entity)
* entity of type 'video' (referenced entity)
* entity of type 'image' (referenced entity)

# Answer
This can be done with a template preprocess added to the template.php file in your theme. You would need to test for the video mime type on the correct node and then use Drupal's hide function, to tell Drupal to skip the field on render.

```
    /**
     * Override or insert variables into the node templates.
     *
     * @param $variables
     *   An array of variables to pass to the theme template.
     * @param $hook
     *   The name of the template being rendered ("node" in this case.)
     */
    function THEMENAME_preprocess_node(&$variables, $hook) {
      $type = $variables['type'];

      switch ($type) {

          case 'NODE_TYPE_MACHINE_NAME':

            if (isset($variables['FILE_FIELD_MACHINE_NAME'][0])) {
              $mime_type = $variables['FILE_FIELD_MACHINE_NAME'][0]['filemime'];
              $mime_regex = '/^video/';
              // We have to check the string for the presence of "video", because it could be any of 18 video mime types.
              $is_video = preg_match($mime_regex, $mime_type);

              if ($is_video) {
                hide($variables['content']['IMAGE_FIELD_MACHINE_NAME']);
              }

            }
          break;
      }
    }

```
> 1 votes

# Answer
Per the update, your code inside your main nodes preprocess would need to change to check the type of the referenced node and hide dependent upon that.

```
 if (!empty($variables['REFERENCE_FIELD_MACHINE_NAME'])) {
     $referenced_nid = $variables['REFERENCE_FIELD_MACHINE_NAME'][LANGUAGE_NONE][0]['target_id'];

     // Load the referenced node to get the type
     $node = node_load($referenced_nid);
     $type = $node->type;

     if ($type == 'video') {
       hide($variables['content']['IMAGE_FIELD_MACHINE_NAME']);
     }
 }

```

You may need to use Devel and output `$variables` to get your tailor this to your field.
> 0 votes

---
Tags: theming, files
---


# Question
Title: How to not show a comments field if user logged in
I have a field called 'email' I added to my node comments form. However I don't want this to display to users who are logged in. What's the best way to hide this field for logged in users?

I created a module 'hideemail.module' (and info file) with the following code, and flushed caches multiple times...but it's still not working. Note: I double-checked the form name with Firebug and the field name in the resource content type \> comments fields.

From hideemail.module (and yes its enabled):

```
 <?php
 /**
 * Implements hook_form_alter().
 */
function hideemail_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'comment-form' && $user->uid != 0) {
    $form['field_email']['#access'] = FALSE;
  }
}
?>

```

# Answer
Use hook\_form\_alter():

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'comment_form' && $user->uid != 0) {
    $form['field_email']['#access'] = FALSE;
  }
}

```
> 2 votes

---
Tags: comments
---


# Question
Title: (Nearly) single page website - any clever ways to manage menu anchor links?
So,

I am creating a (nearly) single page website. It has a one-page homepage, plus a contact page and a ToS page which are standalone pages. The menu links on the homepage are like '#intro', '#whatwedo', etc, but on the standalone pages I need the links to be 'site.com/#intro' so that it links them to the anchor on the homepage.

How is the best way to achieve this **without** having two menu blocks?

Cheers

# Answer
> 1 votes
Use the single page site module, this has all the functionality you need to get this working. https://www.drupal.org/project/single\_page\_site

# Answer
> 0 votes
Wow, I can't read.

Alright, well you can use a hook\_MENU\_ALTER and just edit the links if the current path is not the front page.

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


title: changing the process of registration

text:
# Question
Title: changing the process of registration
I need to make a different process for user registration in drupal. 1\] set username, email and password. 2\] send a verification email to user's email address. 3\] by clicking on the link in the email direct to the site as a logged in user.

I mean I need to set password in the first step, not after clicking on the link in the email. although It's a bit illogical but users would be less confused in this way.

if there is a module for this please let me know otherwise I need to change it programmatically.

# Answer
User registration password.
This is the first result when searching "drupal user registration password" on google.
> 1 votes

---
Tags: users, emails
---


# Question
Title: How to get values which changed during node edit in node api?
I have a node with user entity reference field. Now I want to get newly added users id's to this node via this field in hook\_node\_update

What is the best way?

# Answer
> 1 votes
The `$node` argument to `hook_node_update` contains a `$node->original` object. With that you can identify the newly added user IDs by comparing `$node->your_user_ref_field` to `$node->original->your_user_ref_field`.

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


# Question
Title: Editing the template for Comments editing page
I've got my comments for my nodes looking good ON the node. However, as an admin, or using the permalink, if you go to the actual comment page (/comment/comment#) it looks funky. I'd like to format it so the sharebar doesn't appear, the whole node doesn't appear, all the rest of the comments don't appear, and the ability to add yet another comment doesn't appear. I JUST want the comment to appear on that page. Sort of like when you go to comments \> edit (as an admin).

Does anyone know how to edit this page or what the template file is at least so I can edit that?

Thanks!

# Answer
You can achieve the same by adding `template_preprocess_node` in `template.php` of your theme as shown below:

```
function <THEME_NAME>_preprocess_node(&$vars) {
    $path = explode('/', request_path());
    if ($path[0] == 'comment' && is_numeric($path[1])) {
        $node = $vars['node'];
        unset($vars['content']);
        $comment = comment_load($path[1]);
        $vars['content'] = comment_view($comment, $node);
        unset($vars['content']['links']);

        //If you want to set separate tpl for comments section
        $vars['theme_hook_suggestion'] = 'node__comment'; //Need to create node--comment.tpl.php
    }
}

```

**Update #1**

To add page--comment.tpl.php add following function to `template.php` file:

```
function <THEME_NAME>_preprocess_page(&$vars) {
    $path = explode('/', request_path());
    if ($path[0] == 'comment' && is_numeric($path[1])) {
        //If you want to set separate tpl for comments section
        $vars['theme_hook_suggestion'] = 'page__comment'; //Need to create page--comment.tpl.php
    }
}

```

Remember to clear cache after adding this function to `template.php`
> 1 votes

# Answer
As the comment page does not use it's own theme so you probably have to do it as outlined in this question.

But, If you just want to redirect the comment page back to the original post, the latest **dev version** of the Global Redirect module has a setting for this. I recently did this on a site as the comment pages were causing SEO problems.
> 1 votes

---
Tags: comments
---


title: Fatal error wheen running update.php

text:
# Question
Title: Fatal error wheen running update.php
Kindly assist me in solving this error. It appears once I try to run update.php

> Fatal error: Class CToolsCssCache contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

This is how my css-cache.inc file looks like;

```
<?php

/**
 * @file
 * Custom cache implementation for the CTools CSS cache.
 */

class CToolsCssCache implements DrupalCacheInterface {

  /**
   * {@inheritdoc}
   */

  public function clear($cid = NULL, $wildcard = FALSE) {
    // Only clear the caches if the wildcard is set, this ensures that the cache
    // is only cleared when the full caches are cleared manually (eg by invoking
    // drupal_flush_all_caches()), and not on a cron run.
    // @see drupal_flush_all_caches()
    // @see system_cron()
    if ($wildcard) {
      ctools_include('css');
      ctools_css_flush_caches();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function get($cid) {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getMultiple(&$cids) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function set($cid, $data, $expire = CACHE_PERMANENT) {
  }

}

```

I think it is affecting the site such that any updates done cannot display on the live site. I will really appreciate your help.

# Answer
there are a few steps you need to do:

1. Please upgrade you Drupal Core
2. Apply this patch: Patch to your Ctools Module, you can be found the file here **/includes/css-cache.inc**
> 1 votes

---
Tags: chaos-tool-suite
---


# Question
Title: Videos Stored in D7-s private file system do not play on Android devices
I have .mp4 video files that I store on my D7 site's Private File system. I am using Video JS module for videos. I am having issues on playing them on devices (Phone, Tablet) running Android OS. Does anyone have a solution for this?

I had the same issue on iOS platform, the fix was using Resumable Downloads module for iOS. For Android the problem still exists.

# Answer
To make it work on android device you need to pass .webm format along with .mp4 of the same video. Please check sample shown below:

```
<video id="my_vid_id" class="video-js vjs-default-skin" controls preload="auto" width="640" height="264" poster="poster.png" data-setup='{}'>
   <source src="movie.mp4" type='video/mp4' />
   <source src="movie.webm" type='video/webm' />
</video>

```
> 1 votes

---
Tags: files
---


title: Enable field formatter settings

text:
# Question
Title: Enable field formatter settings
I have a field that I created using hook\_field\_extra\_fields, and I want it to have a cogwheel like in the image below, so that I can customize it. Right now the only format setting for the field is "Visible". Any ideas on how to enable the formatter settings for that field?

Note that I am also using display suite.

# Answer
You can use `hook_field_formatter_settings_form` to add formatting of the field as shown in example below:

```
function example_field_formatter_info() {
  $info = array();
  $info['default_formatter'] = array(
    'label' => t('Show as link'),
    'field types' => array('example_field_type'),
     'settings' => array('target' => '_blank'), // <--- THIS
  );
  return $info;
}

function example_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $element['target'] = array(
      '#type' => 'select',
      '#title' => t('HREF target'),
      '#options' => array('_blank' => 'New window', '_self' => 'Same window'),
      '#default_value' => $settings['target'],
      '#description' => t('Control where the link opens (i.e. set the TARGET attribute of the A element).'),
    );
  }
  return $element;
}

function example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $target = $settings['target'];
    foreach ($items as $delta => $item) {
      $element[$delta]['#markup'] = "<a href=\"{$item['href']}\" target=\"{$target}\">{$item['label']}</div>";
    }
  }
  return $element;
}

```

Update #1:

```
/**
 * Implements hook_field_formatter_settings_summary().
 */
function example_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Show as link'); // we use t() for translation and placeholders to guard against attacks
  return $summary;
}

```
> 1 votes

---
Tags: entities, display-suite
---


# Question
Title: What is wrong in my XML structure to add nodes using a RESTFul web service POST?
I'm using RESTFul Web Services module with Drupal 7. I can log in with basic authentication, get CSRF-token, get nodes, and so on.

The problem is with POST/PUT: I cannot get **adding nodes** to work. I get a node of type "page" and I use the same structure to do the post. But it doesn't work.

I'm using Delphi RAD Studio 2010 and Indy components to connect with RESTFul service. It works good with all restful request. When I do a POST, I get a 200 OK result, but the page is NOT added.

Here is the XML structure I use:

```
<node>
<body>
  <value>This is a simple test page</value>
  <summary/>
  <format>full_html</format>
</body>
<type>page</type>
<title>Test Page</title>
<language>es</language>
<status>1</status>
<promote>0</promote>
<sticky>0</sticky>
<views>0</views>
<day_views>0</day_views></node>

```

I send csrf-token with post, and server gives me 200 OK.

**My question**: Where could be the problem, perhaps the XML structure is incorrect?

# Answer
After a lot of research about my question I've changed to format, which works fine.

I still think I have an error in my XML structure, but since it works with JSON now, I switched to using that instead.

UPDATE: With this data it works fine.

```
{ "title":"Test page",
  "type":"page",
  "status":0,
  "language":"es",
  "author":1,
  "body":{  "value": "Aptent bene capto euismod ...",
            "summary":"",
            "format":"filtered_html"
         }
}

```
> 0 votes

---
Tags: services
---


# Question
Title: how to limit view to just show each type one time?
I have a content type what is **news**, the news has a field type that is **List (text)** *to keep different types of news*. for example I have Health, Sport, Economic and etc.

So now I am going to create a block and have each of these type in that as a hyperlink.

I can do it and I created a new view block but each **news\_type** may showing more than one time according to published content.

How to set the view (for block) to just show **news\_types** and show them just one time?

# Answer
You can achieve this by following the steps given below:

1. Enable aggregation under Advanced Accordion of the view
2. Add Nid field & set aggregation type as Count Distinct
3. Exclude Nid field from display
4. Add news type field & set Aggregation type as Group results together, in Group Column select Value option from dropdown
5. Remove Publishing Date from sort criteria

Please check attached screenshot for reference

and for more information you can check this question
> 4 votes

# Answer
You can set Distinct in the advanced settings of your view. A distinct will only show unique records. So if you have a list of all Lists then it will show all unique values of List
> 3 votes

---
Tags: 7, views, nodes
---


# Question
Title: Multiple content types in views in order one by one
I have 3 content types (A, B, C).

I need to output all of them in views in order:

A1 B1 C1 A2 B2 C2 ...

I need to get the last node with content type A, then the last node of content type B, then the last node with content type C, then the node of content type A created earlier etc.

So, is it possible to alternate content types in views?

Thanks a lot!

# Answer
Yes that is possible. If A is the name of the content type and 1 is the ID of the content. Then you first sort on ID and then on Content Type.
> 3 votes

---
Tags: views
---


# Question
Title: How can I add a skip button above the webform (with multistep)
I use webform with multistep for a quiz. I want to add a "skip" button (equivalent to the submit/next button in the bottom of the form) above the form so that people can go directly to the next question without having to scroll down the page like that :

" Skip this question

My form

\< Previous | Next \>"

I succeeded to add an another submit button (check code below). But when I click on this button it returns to the previous step instead of going to the next step ... I don't understand why .. And I can not put it above the form.

```
function mytemplate_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'webform_client_form_13':
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('skip'),
    );
    break;
  }
}

```

Have you got an idea for help me ?

Thanks you for advance

PS : sorry for my bad english

# Answer
It seems that basically, you want a copy of "next", but with different title and placed on top. To achieve it:

1. Examine structure of form you are alerting. Find where original "next" is defined.
2. Create a copy of it. Use code like:

```
$form['my_skip_button'] = $form['path']['to']['next']['button'];

```

You Don't really need to know or care what it is, you need a copy, so you go and make a copy, simple as that.
3. Set weight to something low to get it to top:

```
$form['my_skip_button']['#weight'] = -10;

```
4. You can alter the title in the same way you altered weight.
> 2 votes

# Answer
Please also think about ability to hide/show field depending on user's selection. It's called 'Conditionals'. For example, user selects his role ('speaker') and some fields could be hidden and some new shown.

If all fields in this step are hidden (even required fields) this step will be skipped.

More details:
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: How to configure EU cookie compliance module for only Google Analytics
I have installed and configured the EU cookie compliance module, but it only displays the message when I log into admin section. I use Google Analytics and I must show the message for all the site.

I think that the issue is that Drupal doesn't set any cookie and that's why it doesn't display the message (the GA cookie is external to Drupal).

How can show the message when I use only the GA cookie?

# Answer
In the permission page (admin/people/permissions), check "Display EU Cookie Compliance popup" for the anonymous user.
> 1 votes

---
Tags: cookies
---


# Question
Title: How to close comments with just 1 click?
My site editors want a quick way to close comments on a particular node, i.e. they just want to click a button on an item, rather than having to click edit, then select the comment settings tab, then click the "closed" box. (This is for Advanced forum, but I guess it could apply anywhere).

I have a feeling this should be fairly easy to do but I can't work out how to do it. Any pointers you can give would be appreciated. (I am using the Flag module and thought flag actions would be a simple way to do this, but closing comments doesn't seem to be an available action).

# Answer
> 3 votes
You can achieve this by following steps given below:

1. Create a flag on nodes for administrator only
2. Add new rule using Rules module
3. Set React on in Event "A node has been flagged, under
4. Add action "Set a data value"
5. Select Data "flagged-node:comment"
6. Click Continue and set value as 0

Please check Rule given below(exported):

```
{ "rules_disable_comments" : {
    "LABEL" : "Disable comments",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_disable_comments" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:comment" ], "value" : "0" } },
      { "drupal_message" : { "message" : "Comments closed" } }
    ]
  }
}

```

& Flag given below(exported):

```
$flags = array();
// Exported flag: "Disable comments".
$flags['disable_comments'] = array (
  'entity_type' => 'node',
  'title' => 'Disable comments',
  'global' => '0',
  'types' =>
  array (
    0 => 'article',
  ),
  'flag_short' => 'Disable comments',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Enable comments',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => 'Disabled comments',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

```

---
Tags: comments, nodes
---


# Question
Title: Using theme_get_setting getting empty value
I am using theme settings in my Drupal 7 theme to provide a theme option as follows.

```
$form['mythemename_settings']['loaderImage'] = array(
  '#type' => 'fieldset',
  '#title' => t('Loader Icon'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

$form['mythemename_settings']['loaderImage']['loader_img'] = array(
  '#type' => 'file',
  '#title' => t('Upload Loader Icon Image'),
  '#default_value' => theme_get_setting('loader_img','mythemename'),
  '#description' => t("Upload your desired loader icon."),
);

```

I then use `theme_get_setting('loader_img')` to call the value of the setting, but it returns an empty value. I have also added `settings[loader_img] = "loading.gif"` in my theme.info file, but I am still getting only the empty value.

My intention is to add a Image browse button which can be accessed in the admin end and can be changed time to time. I have uploaded the image but I couldn't find my image inside my projects. Do I need to set a path for the image to get uploaded?

Where are the values of the settings page get stored in the database? I checked my whole database but I couldn't find the value I saved.

# Answer
> 1 votes
Change the type of image input to `managed_file`. Check updated code below:

```
$form['mythemename_settings']['loaderImage'] = array(
  '#type' => 'fieldset',
  '#title' => t('Loader Icon'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

$form['mythemename_settings']['loaderImage']['loader_img'] = array(
  '#type' => 'managed_file',
  '#title' => t('Upload Loader Icon Image'),
  '#default_value' => theme_get_setting('loader_img','mythemename'),
  '#description' => t("Upload your desired loader icon."),
  '#upload_location' => 'public://images/',
);

```

Values of theme settings are stored in `variable` table. Check `theme_<THEME_NAME>_settings` under name column & value is stored as serialized array in value column.

# Update 1

To get file object use following sample:

```
$file = theme_get_setting('loader_img','tmhgs');
$file = file_load($file);

```

---
Tags: 7, forms
---


# Question
Title: Replace node add/edit form with a custom form
I have this custom form I made in my module which is responsible for adding/editing a specific node type. I was not able to alter the built-in add/edit form to meet my requirements so I decided to make my own forms using the form API.

The forms are doing good but I need drupal to use my custom forms whenever a user tries to add/edit a node from that specific node type instead of the original drupal's standard forms.

It should be a matter of routing/path. I already tried menu hook but it did not work. So how can I make drupal to replace the content add/edit form for that specific node type with the one I want?

# Answer
Try the pathauto module. You can use the Url Aliases page to add an alias for all of your custom node edit links.
> 1 votes

---
Tags: forms, uri
---


# Question
Title: Show last, last two or last three nodes depending on role
I'm working on a site where members can have three different roles. Gold, Silver and Bronze.

Now I'm trying to set up a view that will display the: last three nodes of all Gold members and last two nodes of all Silver members and the last node of all Bronze members,

I want all these nodes displayed together on the homepage, randomly ordered. And I just can't figure out how to do this.

I can make a view that shows all last nodes of all users. And I tried working this out with "views field view" making different views showing nodes per user and combining these views in one view but then I am not able to randomly order them.

Well I hope someone can help me out here. Thanks in advance

# Answer
> 0 votes
Okay, I finally solved it. What I basically wanted but wasn't able to find the right words for is to merge content of two views. Basically it's not necessary to have two views. It's possible to use one filter with AND/OR logic use of the filter option. All is explained in this wonderfull post:

http://www.webomelette.com/drupal-views-filters-and-or-logic

Thanks for thinking with me.

# Answer
> 1 votes
Create a fresh (block) view that displays all nodes. Then you can add a relationship to `Content: Author`.

After adding the relationship, you will be able to add a new filter for `User: Roles` that uses the Author relationship. Set this filter to your Gold member role. Set the view to display 3 items.

Add a new Attachment display:

Under attachment settings, attach it to your first views display (the gold member display). Attachment position should be "After". Set the User: Roles filter to show Silver members and set the "Items to display" to 2 items.

Add another Attachment view and repeat the last steps, setting the User: Role to Bronze and changing the Items to display to 1.

Now when you view the block, it will show 3 gold, 2 silver and 1 bronze node.

---
Tags: views
---


# Question
Title: Notices: Undefined index and trying to get property of non-object include()
I have a "page--front.tpl.php" and get these notices:

> Notice: Undefined index: nodes include() (line 47 in file /home/dunmicro/public\_html/sites/all/themes/dunartis/page--front.tpl.php).
>
> Notice: Trying to get property of non-object include()(line 47 in file /home/dunmicro/public\_html/sites/all/themes/dunartis/page--front.tpl.php).

Here is my code:

```
<?php if ($site_name): ?>
    <?php if ($title): ?>
      <div id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <strong>
          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">
                      <span><?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?></span></a>
        </strong>
      </div>
    <?php else: /* Use h1 when the content title is empty */ ?>
      <h1 id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">
                    <span><?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?></span></a>
      </h1>
    <?php endif; ?>
  <?php endif; ?>

```

How do I fix these notices?

# Answer
> 2 votes
You need to check if `$page['content']['system_main']['nodes']` is set or not:

Please check updated code:

```
<?php if ($site_name): ?>
    <?php if ($title): ?>
      <div id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <strong>
          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">
                      <span>
<?php if(isset($page['content']['system_main']['nodes'])):?>
<?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>
<?php endif;?>
</span></a>
        </strong>
      </div>
    <?php else: /* Use h1 when the content title is empty */ ?>
      <h1 id="site-name"<?php if ($disable_site_name) { print ' class="hidden"'; } ?>>
        <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home">
                    <span>
<?php if(isset($page['content']['system_main']['nodes'])):?>
<?php print $page['content']['system_main']['nodes']['63']['#node']->title; ?>
<?php endif;?>
</span></a>
      </h1>
    <?php endif; ?>
  <?php endif; ?>

```

---
Tags: 7, theming
---


title: How to attach css to bean preprocess?

text:
# Question
Title: How to attach css to bean preprocess?
So we define the function with this hook...

```
/**
 * Implements hook_preprocess_bean().
 */
function MODULE_preprocess_bean(&$variables) {

  // Attach css...

  return $variables;
}

```

What can this be attached to please?

```
$variables['SOMETHING']['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';

```

# Answer
> 1 votes
It can be attached to whatever you like - the important thing is that you render it.

So you could quite simply use:

```
$foo['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';
drupal_render($foo);

```

Or stick it in a var like you're already doing:

```
$variables['SOMETHING']['#attached']['css'][] = drupal_get_path('module', 'MODULE') . '/MODULE.css';

```

And in the template:

```
drupal_render($SOMETHING);

```

It works because `drupal_render()` unconditionally calls `drupal_process_attached()` on any element it finds with an `#attached` property, regardless of what you're doing with the result of the render (or if there's even anything *to* render).

# Answer
> 0 votes
You can attach CSS files using the dedicated function `drupal_add_css` :

```
 drupal_add_css(drupal_get_path('module', 'MODULE') . '/MODULE.css');

```

By the way, you don't have to return your `$variables` since it's passed by reference.

I hope that help :)

---
Tags: 7, blocks
---


# Question
Title: Enable CSS files in Omega 3 sub theme with Drush?
Is it possible to enable CSS files in an Omega 3 sub theme with Drush?

Im working locally and regularly importing the latest database from live. I have a build script that I run to clear cache, enable modules im using etc. However im manually enabling the CSS files in my theme each time. Can this be added to the build script?

# Answer
I'm only a bit familiar with Omega 4. In order for your css files to be "enabled" by default, you need to transfer the theme settings from the database into the theme's .info file and make sure this is enabled also in the live site. So if you have css/style.css and its declared in the .info file, Omega 4 will just follow the .info file.

Hope this helped. :)
> 0 votes

---
Tags: drush, theming
---


# Question
Title: Any way to customize default nomask used in file_scan_directory() to allow Node.js modules?
I would like to use Node.js modules (such as `grunt-contrib-imagemin`) in my Drupal theme, but that adds `*.info` files which confuses Drupal. If there were some way to change the default value of `nomask` used in `file_scan_directory()` to include 'node\_modules' or some way to tell Node.js to use a local folder other than `node_modules` then the problem would be solved.

There is a post here that suggests patching Drupal core, but I'm hoping there's a more elegant solution.

# Answer
As far as Drupal/PHP are concerned, no, there's no option other than either changing the default arguments to the function, or finding all calls to that function that don't include the 2nd arg, and updating things there. Either way you're likely to have to patch a core method or two.

NPM's convention is to use a folder called `node_modules`. They don't want to change that (https://github.com/npm/npm/issues/2734, https://github.com/npm/npm/issues/775), but there *is* a prefix config option which may be suitable for your needs.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to allow user of certain role to create user only of selected roles?
I have few profiles. One profile per role. I've created few registration paths by Profile2 Registration Path module.

I have an issue with permissions, for example I want allow user of role A, to create users of roles A or B, but because Profile2 Registration Path uses 'administer users' permission on it's registration paths, certain role can create users of all roles or none at all. Maybe I missed something, but I'm stuck.

# Answer
> 3 votes
Try Role Delegation

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.

---
Tags: 7, users
---


# Question
Title: After creating a node in activity module I am getting an error "undefined index"
After installing the Activity module, there is a default view activity/all.

After creating an activity template I am able to see the view result as I required. But why am I getting this error?

```
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).

```

# Answer
> 0 votes
Have a look at the issue queue for Activity.

In particular: Causes undefined index \_node\_query\_node\_access\_alter

> Not sure why activity would be a culprit of this, but non admin users see this error when viewing default activity view or any other acitivity views created. This error will also occur on a page when the view is a block.
>
> Notice: Undefined index: table in \_node\_query\_node\_access\_alter() (line 3197 of /var/sites/my/modules/node/node.module).

---
Tags: views
---


# Question
Title: How can I use webform to upload assets and create a project that can be assigned to different users
I am trying to put together a creative request form that a client would fill out. A studio manager would then follow up and assign to a project manager. I am using webform and rules as a starting point with the possibility of using Open Atrium.

# Answer
if you want client submissions to become content I recommend EntityForm Then you could use for example the Workbench module to assure the content is moderated by a *manager* into approval.

You likely want your content type to show limited items to the client and then more options to the manager. I would try to do this with the Field Permissions module.

Lastly you could automate sending emails and stuff on some events if you want using Rules.
> 0 votes

---
Tags: rules, webforms, distributions
---


# Question
Title: How to display a view within a template only if there is something to display
I'm looking to embed a view within a template file BUT only if there is something being returned within the view.

I'm using this solution that I saw within the Drupal forum:

```
<?php
 $view = views_get_view_result($name, $display, $args);
 $result = count($view);
?>

<div class="row">
    <div class="col-xs-12 related-articles">
      <?php if ($result) : ?>
        <h3>Related Articles</h3>
        <?php print views_embed_view('related_articles', 'related_articles'); ?>
      <?php endif; ?>
    </div>
  </div>

```

So is this the right way to check if that view is returning anything? Or am I missing something there?

# Answer
> 3 votes
Instead of embedding a view in a template, please consider having your view output a block display, which you can place on your site using the Block System, Panels or Context.

---
Tags: 7, views
---


title: Migrating passwords from WordPress

text:
# Question
Title: Migrating passwords from WordPress
I am using the Feed module in Drupal to import the list of my users from WordPress and I have faced a big problem: The password field mapping in the Feed module says "unencrypted password", and there is no way of decrypting phpass WordPress passwords into a CSV file (it is not even safe). What should I do?

# Answer
> 3 votes
Instead of trying to decrypt users passwords, and then re-encrypt them to be stored in drupal. Why dont you:

* import the users all over into drupal
* get all users to reset there own passwords (through the normal email method) when they next try to login

# Answer
> 2 votes
You cannot decrypt the passwords, simply because you don't have encrypted passwords, but values returned from a function that calculates the hash of the given parameter. The hash is a one-way value: You can get it from the input, but you cannot calculate the input given its hash.

What you can do is:

* Setting the password to a random value, using user\_hash\_password()
* Show a message to the users telling them they need to reset their password

The right way to call `user_hash_password()` is the following one.

```
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$hash = user_hash_password($password);

```

# Answer
> 1 votes
The method found at https://www.drupal.org/sandbox/selexin/2384473 works like a charm.

The idea is simple. The module uses the Wordpress hasher and salter to check the entered password against (read the modules readme). If they match, then the password is correct and the users entered password is rehashed with Drupal's hasher and salter, then saved to database. So the idea would be that you would use this for a period of time after initial release then remove the module. Any existing users (that have not logged in) would then have to reset password.

Additionally, to get the wordpress hash I used Feeds to import the users. Which currently does not allow you to import user-\>pass.

After I did this, I added the wordpress database to the settings.php as a second database. Ran a quick Views Bulk Operations PHP operation on all the users.

```
$id = db_query('SELECT guid FROM {feeds_item} WHERE entity_id = :uid AND id = :id', array(':uid' => $entity->uid, ':id' => 'wp_users'))->fetchField();

if($id){
  db_set_active('wordpress');
  $user_hash = db_query('SELECT user_pass FROM {wp_users} WHERE ID = :id', array(':id' => $id))->fetchField();
  db_set_active();
}

if($user_hash){
  $entity->pass = $user_hash;
  entity_save('user', $entity);
}

```

I am sure there are numerous other ways of achieving those last few steps, but that seemed the quickest for me.

---
Tags: users
---


title: Bootstrap subtheme move main navigation

text:
# Question
Title: Bootstrap subtheme move main navigation
I have a sub theme based off Bootstrap and my current nav bar look like this

My goal is to move the menu (Home ... contact) to appear underneath the slogan when the page is larger than 768px as it is the breakpoint when it turns into a burger button and appears on the right. I was trying to play around with the css and the `page.tpl.php`, but no results there. This is the first time I've used Bootstrap with Drupal.

# Answer
> 0 votes
You can add a breakpoint in your LESS/CSS (ideally you're using LESS or SASS with bootstrap, but anyway) and I'd probably make the slogan absolute position and use the `top` property as suggested by @Darvanen like this:

```
    /* Small devices (tablets, 768px and up) */
    @media (min-width: @screen-sm-min) {
        div.slogan {
            position: absolute;
            top: 0;
        }
        div#main-menu {
            margin-top: 30px; // Depends on the size of the slogan div
        }
    }

```

You might need to experiment with the positioning of the menu div, like make it `position: relative;`.

For more see the excellent bootstrap docs: http://getbootstrap.com/css/#grid-media-queries

# Answer
> 0 votes
To move things around like that you will either need to use the CSS `top` property within your CSS or SASS file(s), or move it around with Javascript.

# Answer
> 0 votes
I successfully modified page.tpl.php file and completely replaced the header section with -

```
<div class="container">

  <div class="masthead">
    <h3 class="text-muted">
      <a class="logo" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
      </a>
    </h3>
  </div>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>

      <div class="navbar-collapse collapse">
        <nav role="navigation">
              <?php if (!empty($primary_nav)): ?>
                <?php print render($primary_nav); ?>
              <?php endif; ?>
              <?php if (!empty($secondary_nav)): ?>
                <?php print render($secondary_nav); ?>
              <?php endif; ?>
        </nav>
      </div>
    </div>
  </nav>
</div>

```

---
Tags: navigation, theming
---


# Question
Title: Field Collection vs. Entity View Modes with Field Group
I have been using Entity View Modes to organize my fields, have different display types, and use Field Groups to add bootstrap-style wrappers around my content.

As often as humanly possible, I have views and panels render nodes with these view modes to keep a consistent look throughout the site.

I keep hearing about Drupal Field Collections, and have a basic understanding that it goes further and makes an Entity out of the grouped fields. Seems like a different approach to achieve similar results. It has a lot more uses, but also a lot more open issues, and needs other modules to integrate with Views and Features.

I'd love to hear some thoughts on this.

Thanks,

Ji

# Answer
Jim -

I love Field Collections because it allows me to create "structures" of fields that I can tie to multiple content types. You can still use Field Collections with Field Groups (in order to create field sets and the like). Would definitely recommend for projects with lots of content types / data that needs organization.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How to display the node title in different region 2 using theme method in drupal 7
I want to display the breadcrumb and page title in my main content area.

For breadcrumb I used `theme('breadcrumb', array('breadcrumb' => $breadcrumb));`

What should I use for page title? I have tried `theme('pagetitle', array('title' => $title_text))`, but it is not working.

Also that how can I use the built in theme styles of paragraph tags or heading tags... e.g. I used the following for generating a table in built in theme style

```
theme('table', array('header' => $headers, 'rows' => $rows));

```

# Answer
You're looking for the `$title` variable.

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

```

Here is a list of all of the variables that are available to you in a theme file (for a page).
> 4 votes

---
Tags: theming
---


# Question
Title: CKeditor removes iframes in editor after update to 6.x-1.14
Similar to this issue on the CKeditor project, CKeditor removes embedded iframes after I've updated the module. Though there is a solution in the first comment for Drupal 7, I can't find a solution for this for Drupal 6.

Is there a solution to this?

# Answer
In **ckeditor.config.js**, add `config.allowedContent = true;` to disable the filtering of HTML elements in the editor.

```
CKEDITOR.editorConfig = function(config) {
    config.allowedContent = true;
}

```
> 3 votes

---
Tags: 6, wysiwyg
---


# Question
Title: Is entittyfieldquery result can be loaded into select list?
Trying to populate select list in VBO action form (basically could be anyform) and using enityfieldquery to get list. By this methods $result object contains node arrays.

Can this array can be loaded into select list directly? or we need to apply node\_load\_multiple on $results array.

Reason why I am asking is, there are many field and for the select list, only title and nid is enough right?

Are there any workaround for this?

# Answer
> 1 votes
Can this array can be loaded into select list directly? or we need to apply node\_load\_multiple on $results array.

A FAPI select list expects an Array with `id` and `title`. An entityfieldquery returns only a list of IDs unless you get creative. Typically you perform extra work to `load` fields you want to show as text in your select field. You can do this via SQL, `node_load` a view resultset ... whatever means you're comfortable with.

EDIT

Well I didnt say you have to use node load. There are various extensions to EFQ that let you use community created EFQ classes:

---
Tags: database
---


# Question
Title: Contrib Module JavaScript interfering with Node
If one has a contrib module that works fine in most cases, but on a specific page (say /comment/comment) you wish it NOT to appear, but the options in Config don't give you that ability...what's the best practice for disabling functionality (in this case javascript) coming from the contrib module?

I'm using the sharebar module but it's all messed up in my comment/comment page. I tried hiding it with CSS (visibility:hidden) but can't target it no matter what I try. I even hid the html of the page itself and it still shows up! (although nothing else does)...which leads me to believe it's javascript...so how can I disable that for a particular page?

# Answer
That seems to be a common issue with the sharebar module. The 7.x-2.x-dev version moves the sharebar into a block so that you can place it anywhere with either the block ui or the context ui.

The 7.x-2.x version is still in dev so you may need to do a little testing before enabling it on production, however, the module maintainer is suggesting that people upgrade to this version anyway.
> 1 votes

---
Tags: javascript, theming, comments
---


# Question
Title: What is the best way to alter image style in view for a teaser
I have an image style set for all my nodes for teasers. There is one view that I need it to display differently. Is there a way I can alter in code?

I know that I can just change my setting from **Content** to **Field** and modify the image style that way but I am looking for a way that I can do it in code.

# Answer
> 2 votes
While I would generally just access this from the **field** output type from the View. I would recommend looking into some theme adjustments (and preprocessing Views). Since you are outputting content to the Teaser, you could add some additional verification from the template (https://www.drupal.org/node/53464).

Some helpful links would be:

---
Tags: 7, views, media
---


# Question
Title: Targeting nodes dynamically with breadcrumbs
I'm using a 'resource' content type that can be browsed, searched, or accessed via a custom module. I'm also using the Custom breadcrumbs module.

I'm wondering if anyone knows a way to target \[whichever\] resource profile I user happens to have been viewing (dynamically since I won't know ahead of time which profile they're coming from)...and then target it in the breadcrumbs so that on pages accessed FROM the profiles (ie. a webform to give feedback on the profile for example)...a user can click the resource profile in the breadcrumb to go BACK to the profile they were viewing.

Anyone know a good way to do this?

# Answer
I feel like what you are looking to implement would require you to use hook\_menu\_breadcrumb\_alter and then using `drupal_get_destination()` to give you the necessary URL parameter. The results from `drupal_get_destination()` will be compatible with the `l()` function and can be handled from the `hook_menu_breadcrumb_alter()`.
> 1 votes

---
Tags: nodes, breadcrumbs
---


# Question
Title: Which module can be used to get the number of logged in users per day and supports views?
I need to get number of users logged in a site / per day.

For ex :

May 1 : 123 logins

May 2 : 140 logins

...

May 30 : 400 logins

I've looked into few modules like login\_history and counter. Login history tracks this data, but does not support Views. Is there any module which does this out of the box ?

Thanks

# Answer
Couple of options (haven't tested either one):

1. This sandbox project seems to track login time and provides Views integration: https://drupal.org/sandbox/AshishThakur/1614582
2. Login History also tracks login time, but does not have Views integration yet. A patch was started for this, but looks like it isn't complete: https://drupal.org/node/1402266
> 9 votes

# Answer
Maybe the visitors module might be a valid alternative to consider? Or at least a good starting point? Refer to its community docu for some more details.

**Be aware**: I'm the new maintainer of this module, it was unsupported until recently ...
> 1 votes

# Answer
Another approach that might work, based on the "*Login history tracks this data, but does not support Views*":

* Find the data base table used by 'login history' for the tracking of the data.
* Use the views integration of the Forena module to access those data in the 'login history' table from within your custom view. Refer to the available community documentation of Forena (linked on the project homepage) for more details.

**Be aware**: I'm a co-maintainer of this module.
> 1 votes

---
Tags: users, nodes
---


# Question
Title: Call to undefined function db_affected_rows()
D6 module https://www.drupal.org/project/uc\_dependent\_attributes is converted to D7 here: http://dupgrade.com/ and I found out db\_affected\_rows() was removed from D7.

I tried few codes, basically copy and paste, based on this answer db\_affected\_rows gives fatal error in drupal 7. Now I have a different error: Call to a member function rowCount() on a non-object.

Code which throws Call to undefined function db\_affected\_rows()

```
function uc_dependent_attributes_uc_product_adjustments_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['body'] as $value) {
    if (!$value['enabled']) {
     db_update('uc_dependent_attributes')->fields(array(
        'enabled' => 0,
      ))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
      if (!db_affected_rows()) {
       db_insert('uc_dependent_attributes')->fields(array(
          'nid' => $form_state['values']['nid'],
          'combination' => $value['combo_array'],
          'enabled' => 0,
        ))->execute();
      }
    }
    else {
      db_delete('uc_dependent_attributes')->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
    }
  }
}
```

Changed: This gives 'Fatal error: Call to a member function rowCount() on a non-object' error.

```
function uc_dependent_attributes_uc_product_adjustments_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['body'] as $value) {
    if (!$value['enabled']) {
     $result = db_update('uc_dependent_attributes')->fields(array(
        'enabled' => 0,
      ))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
      $affected_rows = $result->rowCount();
      if ($affected_rows!=0) {
        db_insert('uc_dependent_attributes')->fields(array(
          'nid' => $form_state['values']['nid'],
          'combination' => $value['combo_array'],
          'enabled' => 0,
        ))->execute();
      }
    }
    else {
      db_delete('uc_dependent_attributes')->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
    }
  }
}

```

How can I change db\_affected\_rows() to D7 properly?

# Answer
As it happens `UpdateQuery::execute()` returns

> The number of rows affected by the update.

So instead of:

```
$result = db_update('uc_dependent_attributes')->fields(array(
  'enabled' => 0,
))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
$affected_rows = $result->rowCount();
if ($affected_rows!=0) {

```

use:

```
...
$affected_rows = db_update('uc_dependent_attributes')
  ->fields(array('enabled' => 0))
  ->condition('nid', $form_state['values']['nid'])
  ->condition('combination', $value['combo_array'])
  ->execute();

if ($affected_rows == 0) {
...

```

(there's also a small fix to the conditional logic)
> 0 votes

---
Tags: 7
---


# Question
Title: How to create a hit counter for each published node to find out how often a specific node has been viewed?
I’m trying to create a hit counter for each published node. I’ve been googling this feature for Drupal 6.x and tried a few hits but with no luck.

I’ve enabled the Statistics module for my site and under admin/reports/settings I’ve enabled the counter but can’t seem to figure out how to put a hit counter on each overview page and node page.

I found a post explaining that I could use a customize query as such `SELECT count(*) from accesslog where node = node` but when I navigate to my database, the access log is empty (don’t know if it require to some time to enable the page / hit counter).

I want to count every hit and not only unique hits so each time a person access a node it should “just” increment a visitor number and I want to show it within my node-templates (not block) for some specific node content types.

I might miss something but any help or suggestions would really be appreciated.

# Answer
> 6 votes
There is a settings page at `admin/reports/settings`, try looking there first.

Also, look in the `node_counter` table instead of `accesslog`. The query should actually be as follows ($nid being the node ID of the node which you want records for).:

```
SELECT totalcount FROM {node_counter} WHERE nid = $nid;

```

On another note, I'm pretty sure if you enable the Statistics module, you can simply pull the node's page view count out in Views.

# Answer
> 1 votes
Also, if not doing sql's yourself and instead relying on the module putting in the links in your pages, after turning on the settings mentioned above, be aware of the permission `view post access counter` so users less than admins can see the information as well.

# Answer
> 1 votes
Maybe the visitors module might be a valid alternative to consider? Refer to its community docu for some more details.

**Be aware**: I'm the new maintainer of this module, it was unsupported until recently ...

---
Tags: nodes
---


# Question
Title: How do I avoid the "too many connections" error message is shown?
How do I avoid the following error message is shown to normal users?

> PDOException: SQLSTATE\[HY000\] \[1040\] Too many connections in lock\_may\_be\_available()

# Answer
There are two issues here:

1. Users are seeing site error messages that they shouldn't
2. The error message itself

For 1, go to `admin/config/development/logging` and set **Error messages to display** to None. Don't worry, this won't affect messages like "incorrect login details" or "page not found, we did a search instead" ... things that the user really needs to know.

As for 2, here are a couple of things to try:

* Turn off all your custom modules if you have any, re-enable them one by one to see if you can find the cause
* Do the same with contributed modules
* Read up on the error message, there are too many things that could be causing it that are non-drupal specific to be useful on this site.
> 1 votes

---
Tags: 7, theming
---