title: Rendering contact_form

text:
# Question
Title: Rendering contact_form
I have call my current contactform with this function in mytheme.theme.

```
$form = Drupal::routeMatch()->getParameter('contact_form');

```

I have this

```
object(Drupal\contact\Entity\ContactForm)#412 (23) {
  ["id":protected]=>
  string(8) "feedback"
  ["label":protected]=>
  string(14) "Nous contacter"
  ["recipients":protected]=>
  array(1) {
    [0]=>
    string(21) "mymail@gmail.com"
  }
  ["reply":protected]=>
  string(0) ""
  ["weight":protected]=>
  int(0)
  ["originalId":protected]=>
  string(8) "feedback"
  ["pluginConfigKey":protected]=>
  NULL
  ["status":protected]=>
  bool(true)
  ["uuid":protected]=>
  string(36) "6e997e8b-9d85-4e59-9e43-67004270fe13"
  ["isSyncing":"Drupal\Core\Config\Entity\ConfigEntityBase":private]=>
  bool(false)
  ["isUninstalling":"Drupal\Core\Config\Entity\ConfigEntityBase":private]=>
  bool(false)
  ["langcode":protected]=>
  string(2) "fr"
  ["third_party_settings":protected]=>
  array(0) {
  }
  ["_core":protected]=>
  array(0) {
  }
  ["trustedData":protected]=>
  bool(false)
  ["entityTypeId":protected]=>
  string(12) "contact_form"
  ["enforceIsNew":protected]=>
  NULL
  ["typedData":protected]=>
  NULL
  ["cacheContexts":protected]=>
  array(1) {
    [0]=>
    string(28) "languages:language_interface"
  }
  ["cacheTags":protected]=>
  array(0) {
  }
  ["cacheMaxAge":protected]=>
  int(-1)
  ["_serviceIds":protected]=>
  array(0) {
  }
  ["dependencies":protected]=>
  array(0) {
  }
}

```

But how can I rendering this ? My goal is to render the current contact form.

Edit1: I have tried this How to programmatically render a contact form in a theme in D8

But when I try this

```
    $form = Drupal::routeMatch()->getParameter('contact_form');//get the current form called
    $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $form->id(),
      ));
//$form->id() = 'feedback'
        $form = Drupal::service('entity.form_builder')->getForm($message);

```

I have a very big array (Firefox and Chrome crash when in print them )

When I try this

```
$form = Drupal::routeMatch()->getParameter('contact_form');//get the current form called
ContactController::contactSitePage($form);

```

I have this error

```
PHP Fatal error: Call to a member function getStorage() on null in /var/www/drupal8/core/modules/contact/src/Controller/ContactController.php on line 83

```

**Why I would like to do this in my .theme file ?**

Because I have begin to migrate a website in drupal 6 to drupal 8 .(I have try Drupal Upgrate and they works very good ) The page of this website has been built with a little home framework. It call many others not Drupal script. With this, not Drupal Script (Ex:tagada.com/horoscope.php ) and drupal page ( tagada.com/drupalpart/node/10) works with same css and html structure file in a external folder. In Drupal6 the theme worked correctly with a global variable object with node content `$node`

# Answer
Finnaly I have find the answer to my problem's .

**It was a drupal permission problem's .**

User Anonymous users do not have permission to use the general contact form. I gave permission and everything worked .

Thank you alot for the advice .
> 0 votes

---
Tags: forms, 8, emails
---


# Question
Title: Change entity reference field widget type based on role?
EDIT: See the original post below for context. I think I've figured out how to target the field's widget, and to do this based on the admin role, but the module doesn't seem to be recognizing the widget type for some reason. The reason I say this is that when the module is enabled, the targeted field disappears in the node edit form. I figure this means it's getting targeted correctly, but can't define how to display itself. I think this might be because the autocomplete widget is defined by the Entity Reference module itself, and not by Core. Do I have to tell the module where to find this widget type? Or is there another reason that this might be happening?

```
<?php

//Assign role that will be affected by the module
if(user_access('administer')) {
  function entityreference_widget_field_widget_properties_alter(&$widget, $context) {
    // Change entityreference widget
    $field = $context['field'];
    if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_review_band') {
      $widget['type'] = 'entityreference_autocomplete';
    }
  }
}

```

ORIGINAL POST: I have an entity reference field that I'm using in a "Review" content type. When users create a "Review", they are given options for this field in a select list based on Bands (another content type) that they have created. If a submitted review needs to be moderated, then an admin must go in and edit the "Review". When the review is edited by an admin, I need the band field to stay the same as it was when originally submitted. However, because of the nature of the how the options for the field are populated, the only options that appear when editing as an admin are "Bands" created by the admin user.

There is a second widget type that can be chosen for the entity reference field, which is autocomplete. Is there a way that I can change the widget type from "select list" to "autocomplete" only when the content is being edited by an administrator? This way, users still have the select list for their bands, and administrators are not limited to only their bands. Otherwise, is there a way to that I can leave this specific field unaltered when editing the content?

# Answer
> 2 votes
I ended up getting this to work after finding hook\_field\_widget\_properties\_alter. This allows you to, as the hook implies, target the various properties of the widget directly. `Global $user` seems to provide the `$user` variable, which allows you to select the role that you want to apply the module to. You can change it from 'administrator' to 'authenticated user', 'anonymous user', or any other needed role to fit your needs.

```
<?php
function entityreference_widget_field_widget_properties_alter(&$widget, $context) {
  //Assign role that will be affected by the module
  global $user;

  if (in_array('administrator', $user->roles)) {
    // Change entityreference widget
    $field = $context['field'];
    if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_review_band') {
      $widget['type'] = 'entityreference_autocomplete';
      $widget['module'] = 'entityreference';
      $widget['settings']['match_operator'] = 'CONTAINS';
      $widget['settings']['size'] = '60';
    }
  }
}

```

To find out exactly which pieces of the widget needed to be altered, and what to, I created another test field of the type that I wanted to alter my current field to. I then inserted `dsm($widget)` within the hooks curly brackets of the hook, and then inspected the page with the field on it.

Explanation of dsm() and dpm() for anybody who needs it:

There's so little help anywhere on how to use `dsm()` or `dpm()`, and working through this module finally made me understand it. Basically, modules target different elements, and in order to figure out what to target, or what you will be altering, you need to inspect the elements. What dsm() lets you do is view the properties of any given variable (e.g. $form\_id most commonly it seems, or in this case $widget or $context) in each of the elements on the page that include it. If anybody stumbles on this and still needs clarification, feel free to ask. It took me forever to figure out how the heck to use dsm().

# Answer
> 0 votes
Create

```
function MODULE_form_CONTENT_TYPE_node_form_alter(&$form, &$form_state, $form_id) {
  /*code goes here */
}

```

And change widget type in $form\['field\_name'\] depending of current user roles.

# Answer
> 0 votes
Here is another example I was able to implement thanks to Mrweiner's post.

I wanted to change the widget from a normal autocomplete, to an autocomplete with node creation, depending upon a special user permission.

I am using the references module and the node reference create module. The site it is from is from an early Drupal 7 install before entity reference was available.

```
function YOURMODULENAME_field_widget_properties_alter(&$widget, $context) {

 if (user_access('EXAMPLE PERMISSION NAME')) {

    $field = $context['field'];

     if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_example_ref') {

      $widget['type'] = 'noderefcreate_autocomplete';
      $widget['module'] = 'noderefcreate';
      $widget['settings']['autocomplete_match'] = 'starts_with';
      $widget['settings']['size'] = '60';
      $widget['settings']['autocomplete_path'] = 'node_reference/autocomplete';
    }
  }
}

```

---
Tags: entities
---


title: Views 7.3.1.3 ajax error

text:
# Question
Title: Views 7.3.1.3 ajax error
I am running a 7.41 with views 7.3.1.3 version and editing views causes ajax error?

here is the current error code :

```
an ajax http error code.
http status :500
[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"seven","theme_token":"L0_2m6Pw1Y-YlW1YH8Xlfc_C0oFxmC1n0tPxBJZyDLA","jquery_version":"1.10"},
"artPortfolio":{"art_portfolio-block_1":{"columns":"3"}},"better_exposed_filters":{"views":{"art_portfolio":{"displays":{"block_1":{"filters":[]}}}}},
"viewsImplicitFormSubmission":{"views-ui-preview-form":{"defaultButton":"preview-submit"}},
"ajax":{"preview-submit":{"wrapper":"views-preview-wrapper",
"event":"click","progress":{"type":"throbber"},
 "method":"replaceWith","url":"\/admin\/structure\/views\/view\/art_portfolio\/preview\/block_1\/ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Update preview"}}},
"urlIsAjaxTrusted":{"\/admin\/structure\/views\/view\/art_portfolio\/preview\/block_1\/ajax":true,"\/admin\/structure\/views\/view\/art_portfolio\/preview\/block_1":true}},
"merge":true},

```

Why is this happening in this version? Do I need to downgrade, or is it due to the jquery\_update module? I tested on the following jquery versions :

* 1.5
* 1.7.2
* 1.8
* 1.9
* 1.10 but all are not working.

Any help would be appreciated.

# Answer
Rooby is right, this views happen because of the server not providing enough memory limit to run it and that happens, so I solve it when I asked the server guy to add more memory limit to the site and all good, thank you!
> 0 votes

---
Tags: views, ajax
---


# Question
Title: Display a key from unserialized data field
I really don't understand how the "User: Data" field works. Couldn't find any documentation of this.

I want to set the Display format to "A certain key" to output the identifier value from this serialized data (relevant snippet):

```
a:1:{s:10:"hybridauth";a:26:{s:10:"identifier";s:17:"76561198181833179";

```

When I enter identifier as key, I only get this notice and no output.

> Notice: Undefined index: identifier in views\_handler\_field\_serialized-\>render() (line 60 of www/htdocs/\****/sites/all/modules/views/handlers/views\_handler\_field\_serialized.inc).

What do I have to enter in the "Which key should be displayed" field exactly, to display the identifier value?

# Answer
> 0 votes
You need to add an Global PHP field and put the following code in output value to get the **identifier** field value.

```
<?php
 $result = unserialize($row->data);
 print $result['identifier'];
?>

```

**Note : You should exclude Data field from display.**

Since you very cautious in not using PHP, did you try the following option, change the **ckeditor\_skin to identifier**. But it will produce the output as **76561198181833179\['identifier'\].**

# Answer
> -1 votes
Try %ckeditor\_skin in the field 'Which key should be displayed'.

If the error message

> Notice: Undefined index: identifier in views\_handler\_field\_serialized-render() (line 60 of /www/htdocs/*drupalsite*/sites/all/modules/views/handlers/views\_handler\_field\_serialized.inc).

still exists but the number of the error messages is less than before, try to change the code

```
return check_plain($value[$this->options['key']])

```

to:

```
if (!empty($value[$this->options['key']])) {
  return check_plain($value[$this->options['key']]);
}

```

in line 60 of the module file to avoid the error message.

---
Tags: 7, views
---


# Question
Title: Users who just registered can login & change profile information, but cannot create certain contents until admin lets them
Users who just registered can login & change profile information, but cannot create certain contents until an admin says they can. I know this can't be achieved using the Drupal Approved/Not arppoved scheme. Are there alternatives? Maybe with permissions?

If possible, I would also like to use a block(or other means) to let the logged in user of their status/permissions e.g. they can only change profile info, cannot create certain contents, etc.

# Answer
As Sandesh suggested, give registered users permission to change their profile information, and remove the permission to create content. When an admin sees that a user is qualified to post content, they will give the user the permission. The permissions will be on an individual basis, so we use the User Permissions module.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to get a list of entities available in your Drupal?
Sometimes I need to create a new entity but I don't know the exact machine name of the entity to put in the `entity_create()` method.

Is there an easy way to check which entity types are available to create in your Drupal 7 site?

# Answer
You can just invoke `hook_entity_info()` and check the keys:

```
$info = module_invoke_all('entity_info');
$all_entity_machine_names = array_keys($info);

```
> 3 votes

---
Tags: 7, entities
---


# Question
Title: I have issue with commerce_order_load_multiple function
The way i am using this function is

```
foreach ($mms as $mm) {
  $orders_of_user += commerce_order_load_multiple(array(), array('uid' => $mm->uid, 'status' => 'cart'));
}

```

But i am not getting anything output from this and when i use static value of integer in place of uid i am getting result..

```
$orders_of_user += commerce_order_load_multiple(array(), array('uid' => 421, 'status' => 'cart'));

```

I don't understand what causing the problem in foreach

# Answer
> when i use static value of integer in place of uid i am getting result

Logically speaking, that can only mean that `$mm->uid` doesn't contain what you think it does.

Install the `devel` module and use the `dpm` function to inspect the var:

```
foreach ($mms as $mm) {
  dpm($mm);
}

```

That should tell you what's going wrong.
> 0 votes

---
Tags: commerce
---


# Question
Title: Does a new site installation run through hook_updates of every module?
I have an existing D7 website for which i write hook\_updates whenever i have to make any changes to the schema. Now, i have altered the taxonomy\_term\_data table using one such update. My question is if I install this website in another Schema(Database) will it automatically make those changes to taxonomy\_term\_data? Or, do i need to make those changes again explicitly?

# Answer
> 4 votes
When you install a module, the largest number found in `hook_update_N` hook will be stored in the `system` table's `schema_version` field. It will not run the function. Just stored in the table.

When you copy a module to a new site, any of the `hook_update_N` hooks will **not** be executed for you. However, if you would like to make any change, you can implement `hook_install` to make the necessary database or any other changes.

---
Tags: 7, updating
---


title: Why do I keep getting this error?

text:
# Question
Title: Why do I keep getting this error?
I am getting this error message in the logs after installing RNG module for Drupal 8 and trying to submit a completed a event form. The error log contains this error.

> Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Value is not a valid entity." at /home/vhosts/\***********/public\_html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php line 757, referer: http://\**********/node/add/event\_1

Any idea on how I can resolve this please?

# Answer
I eventually traced back the issue as being caused by the rules module not RNG. Removing the rules enabled me to save the event.
> 0 votes

---
Tags: entities, rng
---


# Question
Title: Generate a cookie when user closes a webform block
I have been tasked with having to setup a cookie that records when an anonymous user closes a newsletter signup webform block so that it no longer appears when reloading the current page or navigating to another page on a website.

Can anyone please advise if there is module that performs this function?

Or can someone please point me in the right direction in terms of the correct code snippet I can use to make this work?

Many thanks!

# Answer
> 0 votes
First you need to create a custom module and add javascript user identificator on your page with web form(to find out user anonymous or not) Here is example

Next use jquery library and do the next thing:

```
// its just an example you need to put your #id or .class
$("#subform_close").on('click', function() {
      if(Drupal.settings.user_js_uid == 0)
           {
              // set cookie for whatever you want
              $.cookie("dont_show_web_form", 1, { expires : 1 });
          }
})

```

and in your php code check for that cookie

```
$_COOKIE["dont_show_web_form"]

```

and hide your webform.

---
Tags: blocks, webforms, cookies
---


# Question
Title: How do I programatically create and display a one-off view?
I am programmatically generating views based on an entity with varying fields and saving them with `$view->save()`. Just to be clear, I have to do this because my entities have x-amount of fields, and the view needs to display all the fields.

I am thinking that creating all these views in the database might not be a good long term plan, especially when I go into the Views UI, and see a billion views there.

Can I create a one-off view (e.g. typical Views export code producing a block), and print its block to a page without saving it?

# Answer
I figured it out myself in the end - by looking at how Views does it itself in `views_block_view()`.

```
function page_callback($my_entity) {
  //create view
  $view = new view();

   ... //Do all the views creation stuff e.g. code in export view

  $display_id = 'block_1';
  $view->new_display('block', 'Block', $display_id);

  if ($view->access($display_id)) {
    $output = $view->execute_display($display_id);
    views_add_block_contextual_links($output, $view, $display_id);
    $view->destroy();
    return $output;
  }
$view->destroy();
}

```

The above code renders a view that is created from scratch and never saved to a database. If you wanted to do a page you could look at the code in `views_page()`.
> 0 votes

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


# Question
Title: Hook to track commerce product category view
I am creating a drupal commerce module for tracking users. I want to access a hook in drupal commerce on product category page. Went through most of the documentation but was not able to find the hook to listen to for product category page view.

# Answer
> 2 votes
Well, since you're dealing with Drupal, there's no "product category page"s ... per say ... but there are taxonomy terms that are often used for catalogs and attributes. So, you could, in theory, use hook\_entity\_view() to tap into when a taxonomy term is being viewed.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_entity\_view/7

If you're building a module, I could see you building an interface that lets people assign urls and taxonomy terms that would potentially "make" the catalog pages trigger whatever it is you want to trigger.

Ultimately, though, there's no hard and fast rule on how to build a commerce store, so there's nothing for you to hook into.

---
Tags: commerce, hooks
---


title: Turn Drupal into a USER API

text:
# Question
Title: Turn Drupal into a USER API
I'm developing the main website (A) for an organisation in D7 but for other reasons there are microsites (B) related to this website using CMSs.

I need to give this other users an endpoint in which they can check if the user and password given to them are correct in my drupal instance and of course be able to verify the request only comes from a trusted source (in another physical server without a fixed IP)

So this would be something like:

1. User enters credentials in website B
2. Website B's server sends those credentials to my endpoint (A)
3. Website A check if they are correct and return either ok and the role that user has or error is there's no user matching them

I looked into Open ID and OAuth approaches but those require user interaction and rely on the users authorizing, etc. What we need is to make it all transparent to the end user so they don't have to know in which of the CMS he/she is in and make an authorization for each one.

# Answer
Install and configure services module in site A, and on site B you will have to write a custom php post method,

```
POST http://example.com/rest/user/login

Content-Type: application/json
{
"username":"user_1",
"password":"password"
}

```

If the response you get from this post method is `status 200` then you can verify that the `username` and `password` are matching.

**Some useful resources:**

Services installation doc: https://drupal.stackexchange.com/a/15718

Also found php-curl example here: https://www.drupal.org/node/1334758
> 0 votes

---
Tags: users, 8
---


# Question
Title: Context in Drupal.attachBehaviors is object or string
What do we really pass to Drupal.attachBehaviors in context, is it object or string ?

# Answer
`Drupal.attachBehaviors` has 2 arguments:

> * **context** \- An element to attach behaviors to. If none is given, the document element is used.
> * **settings** \- An object containing settings for the current context. If none given, the global Drupal.settings object is used.

So both arguments are objects, but can be `undefined` (or simply not provided) if required.
> 1 votes

# Answer
You can pass strings, variable or array depending on your requirements.

Here I will show you really basic implementation:

You can call `drupal_add_js` function to include javascript in your module or theme:

```
// $your_variable contains the values you want to pass it to JS file.
drupal_add_js(array('exampleModule' => $your_variable), 'setting');

```

Below code goes to your javascript file:

```
    Drupal.behaviors.exampleModule = {
      attach: function (context, settings) {
                // values passed from custom module can retrieved here as an object. check browser log for the values.
               console.log(settings.exampleModule);
               // check length of the data object.
               console.log(Object.keys(settings.exampleModule.Data).length);
      }
    };

```

You can read more about it here: https://goo.gl/HgzZoI
> 0 votes

---
Tags: 7, javascript
---


title: Why Search APi detect wrong SOLR host?

text:
# Question
Title: Why Search APi detect wrong SOLR host?
Configuration view:

As you can see Search API uses site base url as SOLR host which is obviously wrong...

# Answer
Ok, localhost replaced by $\_SERVER\['name'\] value is only for presentation purposes. More info here: https://www.drupal.org/node/2512986

I had other issue with SOLR, so that's why it didn't work
> 1 votes

---
Tags: 7, search
---


# Question
Title: Getting a custom block image field URL in the block Twig template
I have a custom block containing a text field and an image field. I would like to render the block so that the image's URL can be defined as a data attribute of the block's wrapper div so that it can be used by a javascript function to create a parallax background effect behind the text field.

If I make a template file block.parallax.html.twig, I am able to render the image HTML.

```
{{ content.field_parallax_image.0 }}

```

However If I try to get the actual image URL, nothing is returned

```
{{ content.field_parallax_image.0['#url'] }}

```

If I dump the #item keys

```
{{ dump(content.field_parallax_image.0['#item']|keys) }}

```

I am able to get target\_id, alt, title, width and height values, but I can't find the URL defined anywhere.

I have also tried to see if I could find anything useful in the block preprocess function but the field\_parallax\_image #url field in the variables is also empty

```
function mytheme_preprocess_block(&$variables) {
    if( isset($variables['content']['body']['#bundle']) && $variables['content']['body']['#bundle'] == 'parallax'){
        $variables['img_url'] = $variables['elements']['content']['field_parallax_image'][0]['#url'];
    }
}

```

Is there a way I can get this URL?

# Answer
> 11 votes
`#url` at this stage is not processed yet. This happens later in the image templates.

To get the url in the block template you can access the uri field in the image file entity instead:

```
{{ file_url(content.field_parallax_image.0['#item'].entity.uri.value) }}

```

BTW you didn't find this property in the dump output, because it is a computed value to make it easier to handle entity references.

---
Tags: theming, 8, media
---


# Question
Title: why are Twig template variables with markup not being rendered?
In my template preprocess function I have a variable:

```
$test = "<p>this is a paragraph</p>";

```

and I pass it to my template:

```
$variables['test'] = $test;

```

and output it in twig:

```
{{test}}

```

but instead of getting a formatted paragraph, I'm getting the original output in plain text:

```
<p>this is a paragraph</p>

```

How do I get Drupal to render this as normal HTML?

# Answer
Because twig auto-escapes unsafe content and your content isn't marked as safe.

You can explicitly tell it that it is with `$test = Markup::create($test)`; but you should be *very* careful with that. If it contains any sort of user input, you might open yourself for XSS issues.

Better approaches are using a render array like \['#markup' =\> 'your text'\] which by default will allow a certain amount of html tags but not all of them. You can also use an inline template as documented here: https://www.drupal.org/node/2311123.

Twig natively understands render arrays, so it doesn't matter for your template if you provide a render array or a string.
> 18 votes

# Answer
These are two possibilities to wrap $test in a paragraph and pass it to the twig template:

```
$variables['test'] = [
  '#markup' => $test,
  '#prefix' => '<p>',
  '#suffix' => '</p>',
];

$variables['test'] = [
  '#type' => 'inline_template',
  '#template' => '<p>{{ text }}</p>',
  '#context' => [
    'text' => $test,
  ],
];

```
> 15 votes

---
Tags: 8, theming
---


# Question
Title: How to bring custom block theme suggestions into the right hierachy?
I have to create theme suggestions for my content block types (custom blocks - configured via admin/structure/block/block-content/types), because i didn't find them as default suggestions.

The default was:

```
FILE NAME SUGGESTIONS:
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
x block--block-content.html.twig
x block--block-content.html.twig
* block.html.twig

```

block--block-content.html.twig is not enough, because i need different custom block type templates. (Btw. 2 times block--block-content.html.twig?)

I need:

```
FILE NAME SUGGESTIONS:
x block--block-content--header-content-block.html.twig
* ...
* block.html.twig

```

So i tried in the theme file:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */

function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables)
{
    $block = $variables['elements'];
    $blockType = $block['#configuration']['provider'];
    if ($blockType == "block_content") {
        $bundle = $block['content']['#block_content']->bundle();
        $suggestions[] = 'block__' . $blockType . '__' . $bundle;
    }
}

```

This brings up:

```
FILE NAME SUGGESTIONS:
x block--block-content--header-content-block.html.twig
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
* block--block-content.html.twig
* block--block-content.html.twig
* block.html.twig

```

Nice - but my suggestion is higher then the id based ones for single blocks - not good ... so i added

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function oeb_theme_suggestions_block_alter(array &$suggestions, array $variables)
{
    $block = $variables['elements'];
    $blockType = $block['#configuration']['provider'];
    if ($blockType == "block_content") {
        $bundle = $block['content']['#block_content']->bundle();
        $blockUuid = $block['content']['#block_content']->uuid();
        $blockId = $block['#id'];
        $suggestions[] = 'block__' . $blockType . '__' . $bundle;
        $suggestions[] = 'block__' . $blockType . '__' . $bundle . '__' . $blockId;
        $suggestions[] = 'block__' . $blockType . '__' . $bundle . '__' . $blockUuid;
    }
}

```

Result

```
FILE NAME SUGGESTIONS:
* block--block-content--header-content-block--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
* block--block-content--header-content-block--registernowheaderblock.html.twig
x block--block-content--header-content-block.html.twig
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
* block--block-content.html.twig
* block--block-content.html.twig
* block.html.twig

```

This is not nice, because of the doubled id stuff - is it possible to get something like:

```
FILE NAME SUGGESTIONS:
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
x block--block-content--header-content-block.html.twig
* block--block-content.html.twig
* block.html.twig

```

Means: Single blocks are the highest - but unique? Or should i live with this to keep the stuff simple?

# Answer
What you need is simple array manipulation. Basically split of the original suggestions add the the suggestions and merge the suggestions again.

Some like this should work (untested).

```
function oeb_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  ...
  $first_sugestions = array_slice($suggestions, 0, 2);
  $last_sugestions = array_slice($suggestions, 0, 2);
  $first_sugestions[] = 'block__' . $blockType . '__' . $bundle;
  $suggestion = array_merge($first_suggestions, $last_suggestions);
}

```
> 6 votes

# Answer
I add this hook in MYTHEME.theme:

```
function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $block = $variables['elements'];
  $blockType = $block['#configuration']['provider'];
  if ($blockType == "block_content") {
    $bundle = $block['content']['#block_content']->bundle();
    array_splice($suggestions, 2, 0, 'block__' . $bundle);
  }
}

```
> 7 votes

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


# Question
Title: Statistics module doesn't show the "Enable access log" checkbox
Drupal 8 Statistics Configuration http://curiosidad-racional.tk/drupal8statistics.png

I dont know what to do to show "Enable access log" option.

I activated logging all messages and checked all statistics permissions.

Thanks.

# Answer
> 3 votes
I'm not sure what you are looking for exactly. That's the only thing that statistics.module is doing in 8.x.

Anything else was removed. Maybe there will be or already are contrib modules providing what statistics module did in 7.x. But tools like Google analytics or Piwik provide a lot better data anyway.

---
Tags: 8, nodes
---


# Question
Title: How to change search index for a view in the Views
We made a lot views using Views module type of Search API index#1. Now, we realize that we need to go with another index#2. Is there any way to change indexes in existing Views? Can anyone point me in right direction?

Thank in advance!

# Answer
> 2 votes
I also had this problem after realizing switching indexes also requires changing the view's index. So to accomplish that quickest way I could think of was to change these values from the ‘export’ of the original index being used.

Main lines of original view:

```
    $view = new view();
    $view->name = 'es_connector';
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_index';
    $view->human_name = 'ES Connector';

```

New search view:

```
    $view = new view();
    $view->name = 'es_connector_rebuild’; // changed arbitrarily to my new view name
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_rebuild’; // changed to work - see below as to how determined
    $view->human_name = 'ES Connector Rebuild’; // changed arbitrarily

```

To find the name of base table click name of your new index (admin/config/search/search\_api/index/) and append search\_api\_index\_ with the machine name. Find and replace any occurance of your new view name.

Then paste all of the export into an import script. This will leave you with a new view based on the new index (with the original search view still available). Then just swap out the new search block for the old one. You also probably need to change the path under page settings of the view.

---
Tags: views, search
---


title: Hide content type labels by default

text:
# Question
Title: Hide content type labels by default
Field labels can be hidden for a content type by going to "Manage display" and changing the labels to hidden.

However, I rarely need to show labels.

Is there a way to have the labels hidden by default, site-wide?

# Answer
> 0 votes
I think preprocess\_node should do the trick

use that in your template.php

```
function template_preprocess_node(&$vars){
  //Supposing that your content type name is "group"
  if($vars['type'] == 'your type'){
    $vars['content']['your_field']['#title'] = '';
  }
}

```

# Answer
> 0 votes
Use hook\_field\_create\_instance() to hide content type labels by default.

```
<?php
// implementation of hook_field_create_instance()
// sets all labels to Hidden for new fields
function MODULENAME_field_create_instance($instance){
  // fetch the instance info
  $instance_info = field_info_instance(
    $instance['entity_type'],
    $instance['field_name'],
    $instance['bundle']
  );

  // set label in each display to hidden
  foreach( $instance_info['display'] as &$display ){
    $display['label'] = 'hidden';
  }

  // save back to disk
  field_update_instance($instance_info);
}
?>

```

---
Tags: 7, entities
---


title: Aegir content types extra fields

text:
# Question
Title: Aegir content types extra fields
Is there an official way to add extra fields on a content type on Aegir.
To be more accurate, I want to a comment (text) field for the 'sites'.

# Answer
It's Drupal, so yes you can add an extra field to the site content type on `/admin/structure/types/manage/site/fields`.

Warning: you must enable first the `field_ui` module, as it's disabled by default in Aegir installation profile.

I started a documentation page about this: http://docs.aegirproject.org/en/3.x/extend/frontend/
> 1 votes

---
Tags: aegir
---


# Question
Title: How do I check if a block region is empty?
I'm wanting to apply some specific CSS on the condition that a block region is empty. How do I make this check?

# Answer
> 0 votes
If you're in you're in a page template you can check your `$page` region variable for an empty an array of block objects.

```
if (empty($page['my_region']) { /*DO STUFF*/ }

```

If you're in another context you can use the block\_list function to determine this.

```
$blocks = block_list('my_region');
if (empty($blocks)) { /*DO STUFF*/ }

```

# Answer
> 1 votes
An update on this. I used the solution at https://drupal.stackexchange.com/a/73685/56728 as follows

```
  module_load_include('inc', 'block', 'block.admin');
  global $theme_key;
  $blocks = block_admin_display_prepare_blocks($theme_key);
  //test for a named block's (here the help block) visibility
  foreach($blocks as $block){
    if($block['delta'] == 'help' && $block['region'] != -1){
      sdpm($block['delta']. " is visible!");
    }
  }

```

This detects whether the block is visible or not, but does not quite do what I'm after which is to test for the visibility of a given block on the current "page" for the current user. That to me sounds like what block\_list() does, but I'm stumped by block\_list() as I mentioned above. My "solution" also very likely not the most elegant way of doing things so any help from experts out there would be greatly appreciated. Nat

---
Tags: blocks, theming
---


title: Function to list all the blocks

text:
# Question
Title: Function to list all the blocks
I am searching for a function that list all the blocks that are enabled in a theme. Is there any function for this purpose?

# Answer
> 10 votes
The function `block_admin_display_prepare_blocks()` is the function used in the block module admin page for this purpose, but it's not part of the documented API, so you cannot absolutely rely on it. You would need code along the following lines:

```
module_load_include('inc', 'block', 'block.admin');
global $theme_key;
$blocks = block_admin_display_prepare_blocks($theme_key);
...

```

This will return all blocks, unlike block\_list() which only returns those for the current user and for the current page.

# Answer
> 1 votes
You try with the following code.

```
global $theme;
$all_regions = system_region_list($theme);
$blocks = array();

foreach (array_keys($all_regions) as $region) {
   $blocks += block_list($region);
}

```

# Answer
> 0 votes
I used Alfred Armstrong's code to write a quick and dirty test function:

```
  function is_block_visible($block_name) {
    module_load_include('inc', 'block', 'block.admin');
    global $theme_key;
    $blocks = block_admin_display_prepare_blocks($theme_key);
    foreach ($blocks as $block) {
      if ($block['delta'] == $block_name && $block['region'] != -1) {
        sdpm("The block '" . $block['delta'] . "' is visible in the '" . $block['region'] . "' region.");
      }
    }
  }

```

What I would like to do, but can't get to give me anything but WSOD or a zero length array is to use the block\_list() function which I understand returns a list of visible blocks on the current page for the current user. Any help to get that to work would be greatly appreciated. Nat

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


# Question
Title: Custom Block Form Not redirecting to New Page
I have created a form to take a node ID and then you select either edit or delete and then I would like it to go to 'node/\[nid\]/edit' or 'node/\[nid\]/delete' depending on the selection of the radio button.
Here is my code:

```
function edit_node_block_info(){
    $blocks['edit_node'] = array(
        'info' => t('Custom Block to allow edit/delete/copy'),
        'status' => 1,
        'region' => 'Primary',
        'weight' => 0,
        'visibility' => BLOCK_VISIBILITY_LISTED,
    );

    return $blocks;
}
/*
 * Implements hook_block_view: sets how the block is displayed
 */
function edit_node_block_view($delta = ''){
    switch ($delta) {
        case 'edit_node' :
            $block['subject'] = t('Edit Nodes');
            $block['content'] = drupal_get_form('edit_node_form');
            break;
    }
    return $block;
}
/*
 * implements custom form/creating custom form for drupal_get_form named above.
 */

function edit_node_form($form, &$form_state) {
    $form['node-id'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter the Node ID'),
        '#max-length' => 8,
        '#required' => 1,
    );
    $form['edit-node'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array(t('edit'), t('delete')),
        '#required' => 1,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function edit_node_form_validate($form, &$form_state){
    $query = db_query('SELECT nid FROM {node}');
    foreach ($query as $result) {
        if (!($form_state['values']['node-id'] != $result)) {
            form_set_error('node-id', 'Node-id must match a current nid.');
        }
    }
}

function edit_node_submit($form, &$form_state){
    if (form_state['values']['edit-node'] == 'edit'){
        $form_state['redirect'] = 'node/' . (form_state['values']['node-id']) . '/edit';
    }
    if (form_state['values']['edit-node'] == 'delete'){
        $form_state['redirect'] = 'node/' . (form_state['values']['node-id']) . '/delete';
    }
}

```

In the $form array do I need some sort of redirect handler to make it work? Or a print\_r or render?

I also tried `$link = (form_state['values']['node-id']);`

# Answer
Looks like the issue I was having was twofold. First I need to add some settings:

```
$form['node-action'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array (
            edit => t('edit'),
            delete => t('delete'),
            add => t('add'),
            ),
        '#required' => 1,
    );

```

Then added:

```
$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('edit_node_submit'),
    );

```

And lastly my submit function:

```
function edit_node_submit($form, &$form_state){
    $node_id = $form_state['values']['node-id'];
    $node_action = ($form_state['values']['node-action']);
    $form_state['redirect'] = TRUE;
    if ($node_action == 'edit') {
        $form_state['redirect'] = ('node/' . $node_id . '/edit');
        }
    if ($node_action == 'delete'){
        $form_state['redirect'] = 'node/' . $node_id . '/delete';
    }
    if ($node_action == 'add'){
        $form_state['redirect'] = 'node/add/hospitalist-schedule';
    }
}

```

Everything is working for the most part.
> 0 votes

---
Tags: 7, webforms, redirection
---


title: How do I use Bootstrap scrollspy?

text:
# Question
Title: How do I use Bootstrap scrollspy?
I would like to use Bootstrap's scrollspy plugin in Drupal 8. So I edited the `html.html.twig` file replacing

```
<body{{ attributes.addClass(body_classes) }}>

```

With

```
<body{{ attributes.addClass(body_classes) }} data-spy="scroll" data-target=".nav-scrollspy" data-offset="50" >

```

Where `.nav-scrollspy` is the class of my navigation block. Additionally I added the following JavaScript to my theme:

```
$('body').scrollspy({ target: '.nav-scrollspy' });

```

But as this does not work I were wandering whether or not this plugin is already integrated in Drupals Bootstrap theme. Apparently not, as I could not locate such a file in `themes/bootstrap/js/`.

Unfortunately I did not find such a file in the web neither, so I am asking my self, where to get it and how to add it to Drupal?

# Answer
AFAIK your bootstrap theme will be having `bootstrap.js` or `bootstrap.min.js` included. Generally, scrollspy plugin related code will be inside these files.

So try to recheck whether you have added `nav-scrollspy` to your div element. I think you might need to have 'id' for your div element and a proper link to it.

```
<!-- The navbar - The <a> elements are used to jump to a section in the scrollable area -->
<nav class="navbar navbar-inverse navbar-fixed-top">
  <ul class="nav navbar-nav">
    <li><a href="#section1">Section 1</a></li>
</nav>

<!-- Section 1 -->
<div id="section1">
  <h1>Section 1</h1>
  <p>Try to scroll this page and look at the navigation bar while scrolling!</p>
</div>
</body>

```

Also in Drupal 8, caching is a bit aggressive so try to rebuild your cache and check again. For better understanding refer http://www.sitepoint.com/understanding-bootstraps-affix-scrollspy-plugins/
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Creating REST service to get complex node type
I'd like some advice as I don't know if I'm doing this the correct way...

I'd like to create a web service to get a specific node type. I don't need create/update/delete functionality, just being able to retreive the data is enough. It also shouldn't contain any authentication (the data is public).

This node type contains several field collections. Each field collection could occur multiple times in the node. (for example, there's the node type "Car" which contains the field collections "Audi", "BMW", "Skoda". Each of these can occur multiple times in the node).

The JSON I'd like to return should look like this:

```
{"cars": {
    "title": "newest cars",
    "image": "http://www.example.com/image.jpg",
    "audi": [
       {
        "title": "A1",
        "price": "expensive"
       },
       { "title": "A6",
         "price": "very expensive"
       }
    ],
   "BMW": [
       // multiple BMW's
    ],
}}

```

It's possible that zero cars of a specific brand are returned.

I've been looking how to do this in Drupal. I don't have much Drupal experience, so I'm sorry if this is a very easy thing.

I'm currently using the services module. I've had a look at this tutorial:
http://pingv.com/blog/an-introduction-drupal-7-restful-services

It looks pretty easy, however, the field collection module adds all fields in a different database table. With all fields I have, I'd have to join more than 20 tables in the query and the Drupal database can get pretty confusing this way.

I'm wondering if there's a much easier way to do this. I've already looked at other modules like "Services Views", but these don't seem to do the things I want:

* Return specific node (and specific node id) which contains field collections
* Return image url
* Return only the fields I want
* Return easy, readable names
* Accept certain parameters in the URL (which I'd like to define myself) to filter

Is there an easy way to do this or is the only way creating the very complex query?

Thanks!

# Answer
> 2 votes
You can use any of the following modules:

1. Views Datasource

**Pros**

* Very easy to export using views.
* Does not need require a lot knowl

**Cons**

* This implementation is only to export data, meaning that is not bidirectional.

### Description

> Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.

2. Services

**Pros**

* Very flexible.
* Bidirectional.
* A lot support and documentation by the Drupal community on how to use it.
* Its the module with most install comparing the another two modules.

**Cons**

* Very complex compare to the rest modules.

> A standardized solution for building API's so that external clients can communicate with Drupal. Out of the box it aims to support anything Drupal Core supports and provides a code level API for other modules to expose their features and functionality. It provide Drupal plugins that allow others to create their own authentication mechanisms, request formats, and response formats.

3. RESTful Web Services

**Pros**

* The Drupal 8 version of this module is in core.
* Bidirectional
* In theory migrating to Drupal 8 from this module will be a lot easier to compare to the rest of them. Since this in core now.

**Cons**

* Does not have as many install as the rest of the modules.
* Level difficulty is in between views dataresource and services.
* This project is not as flexible as services.

> Exposes Drupal resources (e.g. entities) as RESTful web services.
>
> The module makes use of the Entity API and the information about entity properties (provided via hook\_entity\_property\_info()) to provide resource representations for all entity types (nodes, comments, users, taxonomy terms, ..). It aims to be fully compliant to the REST principles.

In the end is comes down to your need you should check this presentation - Producing REST Web Services in Drupal 7 - Baltimore Drupal Camp 2014. In the presentation is going to create a webservice and show a more details explanation on the best use case of each.

# Answer
> 3 votes
Views Datasource is very popular module to return json, xml or any other type of data.

> > Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML.

Install the module. Create the view that return your node. then under format select data source as json. You can only select the field you want to render in field settings.

---
Tags: 7, views, services
---


# Question
Title: Select an Image style depending on external/dynamic factors (theme region or other field content)
I have a Bean (bundle that generates blocks) which I display in one of 2 different theme regions. Either in the header, or the footer. This Bean contains an Imagefield, which is rendered through an Image Style.

I would like to be able to display the Image using a different Image Style, depending on which region the Bean is being displayed in. For example, if the Bean is being displayed in the header region, then I want the image to be rendered in style A. If it's being displayed in the footer then the image should use style B.

So - how can I select the Image Style that is used for an Image Field depending on which region the content is being displayed in?

One option would be to add another field to the Bean which would be a 'Style selector', however this introduces another step for the site owner as then then have to manually specify which style they want to use. It would be better if this were done automatically based on where the content is being displayed. However, if this can't be done, then how would I adjust the Image Style based on the value of another field?

# Answer
> 0 votes
You could use Viewmodes (Layout Plugin / Display suite) in order to use different image styles.

E.g. Use a view with rendered viewmode "Teaser-Big" in Header and "Teaser small" in footer and pass an context argument to the view.

---
Tags: 7, theming, media, blocks
---


# Question
Title: Generate new password for users periodically and notify user of new password
I am running a private Drupal 7 site where all user accounts are created by admins and managers. I need to ensure that all users have access to the email account that their accounts were created with.

**What is the best way to do the following:**

* Create a user account with an automatically generated password, and notify the new user of their password via email.
* After a 4 week period, a new password must be generated for the user and set as their active password automatically. The user needs to be notified of their newly updated password via email, and the newly generated password must be used to access the site until it is reset again.

Are there any Drupal 7 modules that can help achieve this?

Any suggestions on building a custom module that can help resolve this?

# Answer
This issue was talked about during the great Drupalgeddon. Because no such bulk reset tool existed for a site.

Here is a recently created tool to perform this task. Other such tools have existed since Drupalgeddon.

Mass Password Reset Module

> This module allows users with "Administer users" permission to reset all user accounts and notify all users
>
> **Details**
>
> The module will reset the passwords of all users except the administrative superuser id 1. You can optionally reset the administrative superuser id 1. Once passwords have been reset, users will optionally receive emails using the Drupal password recovery email. The password recovery email content can be edited at the account settings configuration page.
>
> **Use Cases**
>
> You have a large number of user accounts pre-created and want to send password recovery emails to all users during a site launch. You need to quickly change all passwords on a site for security reasons.
> 4 votes

# Answer
You can use the Force Password Change module too. Read the description:

> This module allows administrators to force users, by role, individual user, or newly created user, to change their password on their next page load or login, and/or expire their passwords after a period of time.
> 2 votes

---
Tags: 7, users
---


title: Rewrite link field in views

text:
# Question
Title: Rewrite link field in views
I'm trying to rewrite the output of a link field in a view in Drupal 8, to include a font-awesome icon, I have tried overriding my view field template in twig, but all i'm getting in the twig template is `{{ output }}`, which contains a rendered link already.

Desired output

```
<a href="http://www.facebook.com/profile"><i class="fa fa-facebook"></i></a>

```

Current output

```
<a href="http://www.facebook.com/profile">http://www.facebook.com/profile</a>

```

# Answer
> 5 votes
Have you tried doing this through the Views UI? You can use the Rewrite results as per the image below. In the rewrite output you should be able to add your font-awesome div. You might need to use the output this field as a link option to make it clickable (you can use the replacement token of your link field) but that dependends on the field, so I am not sure if it is required.

Source: https://www.drupal.org/node/1578524

---
Tags: views, 8
---


# Question
Title: Where is the location of developer/globals.php
It's documented on the drupal website here but this path does not exist in the drupal installation.

# Answer
> 0 votes
That is because there is no such file in the codebase. It is documented separately. When the API site is built, it combines documentation from code comments in Drupal core and the documentation project.

---
Tags: 7
---


title: MIgrate to drupal 7 join related tables

text:
# Question
Title: MIgrate to drupal 7 join related tables
I am migrating from a another non Drupal CMS. I have 4 tables:

* stories (story1, story2, story3)
* story\_tags (story\_id, tag\_id)
* tags (ABC, NBC, WTOP, CBS, clinton)
* tag\_types (radio, tv, person)

How can I link tags to stories by `tag_type`. So that when I open a story I can see all it's related tags, knowing that a story can have several tags.
Any good detailed tutorial of migrate module link will be appreciated also.

**update**
How can i translate this in a migrate query

```
SELECT t.name FROM tags t
    join tag_types tt on (tt.id = 3)
    join story_tags stg on (stg.tag_id = t.id) WHERE story_id = $row_id'

```

Tried but it is not working:

```
->select('story_tags', 'tags')
->fields('tags', array('tag_id'))
->leftJoin('tag_types', 'tt', '(tt.id = tag.tag_type_id)')
->condition('tag_type_id', '3', '=' )
->condition('story_id', $row->id, '=')
->execute()
->fetchCol();

```

What am i missing?

# Answer
My approach to this would be to have a content type called `Story` that had 2 taxonomy term references. One tag field could just be called `tags` and then other could be called `tag_types`. These 2 fields would be 2 distinct Taxonomy Vocabularies in Drupal.

Drupal 7 actually installs with a `tags` vocabulary out-of-the-box which is assumed to be free-tagging terms as your legacy site appears to be already using. So you just need to make 1 vocabulary for the `tag_types`.

Anyways then in your migration class for Stories. Your source SQL statement would figure out the necessary terms for these 2 fields, probably using a sub-select, and the migrate module can set the terms for the content type as Stories are inserted into the system.

So, some psuedocode is:

```
<?php

class StoryMigration extends Migration
{
  public function __construct($arguments)
  {
    parent::__construct($arguments);
    $query = Database::getConnection('default', 'legacy')
      ->select('stories')
      ->fields('stories', array('pgid', 'page_title', 'page_body'));
    // Create subqueries to get the tags for the story we are on. We will call
    // a fake field in our SQL query as legacy_tags or legacy_tags_type to be
    // passed using Migrate field mappings.
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_terms WHERE page_id = pgid' ,'legacy_tags');
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_term_types WHERE page_id = pgid' ,'legacy_tags_type');
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('page');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'pgid' => array('type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => t('Source ID'),
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('title', 'page_title');
    $this->addFieldMapping('body', 'page_body');

    // Import a story's tag(s). Make the term in the vocabulary if it's not
    // there already, ignore the CaSe of the term so sloppy legacy terms
    // come across as 1 term.
    // By specifying this could have a SEPERATOR VALUE this can create any N
    // terms provided by our SQL statement above.
    $this->addFieldMapping('field_tags', 'legacy_tags');
    $this->addFieldMapping('field_tags:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags:ignore_case')
      ->defaultValue(TRUE);

    // Similar steps as for the above term, but for the tags_type reference field.
    $this->addFieldMapping('field_tags_type', 'legacy_tags_type');
    $this->addFieldMapping('field_tags_type:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags_type:ignore_case')
      ->defaultValue(TRUE);
  }
}

```

Term Reference Fields and the Migrate module are described in the documentation. Adding SQL Expressions to an SQL query is covered in the sql documentation.

My above code is an example and not guarenteed to work. It's simply 1 method of doing this and is to be referenced as an outline. Your SQL schema and php may look different in the end.
> 1 votes

---
Tags: 7, migrations
---


title: Entity Average Rating

text:
# Question
Title: Entity Average Rating
I have **Player** (Entity) which is referenced on a **Match** (Content Type).

Now I'd like to **Rate** (from 0 to 10) the player for every match and get the **average rating**, can someone point me to the right solution.

# Answer
You can make a View and use the Views Aggregator Plus or Views Calc.

From Views Calc module page:

> This module adds simple calculations to a views table.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

You can found some screenshots here: How can I show average votes of fivestar nodes?
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Correct usage of hook_user_login and hook_user_presave for saving data to user
I have a custom module that syncs LDAP-data to custom user fields (every 24 hours, depending on when the user logs in). Everything seems to be working, but I'm not an expert on PHP and Drupal hooks so I want to be sure I'm not doing anything silly.

My understanding is that when user account is saved in hook\_user\_login, hook\_user\_presave is run and the values are saved (values are located in the $edit variable). Am I saving the values correctly? Have I missed a critical check that could lead to errors?

Here's my code:

```
// runs everytime a user logs in, checks if ldap attributes need to be updated
function company_ldap_user_login(&$edit, $account) {

      // If the user is user 1 or guest, then do nothing
      if ($account->uid <= 1) {
        return;
      }

      // don't update data if it's less than 24 hours ago
      if (isset($account->data->ldap_sync) && $account->data->ldap_sync < time() - 3600 * 24) {
        return;
      } else {

        // load custom LDAP configuration
        require_once('custom_ldap.inc');

        $ldap = new ldap();

        // get LDAP data
        $data = $ldap->get_info();

        // do nothing, since user does not exist in LDAP
        if($data["count"] == 0)
        {
          return;
        }

        $data = $data[0];

        $first_name = trim($data["givenname"][0]);
        $last_name = trim($data["sn"][0]);
        $fullname = "$first_name $last_name";
        unset($data['mailaddresses']['count']);

        // load the user that has logged in
        $account = user_load($account->uid);

        // save LDAP data to an array
        $edits = array(
          'first_name' => $first_name,
          'last_name' => $last_name,
          'fullname' => $fullname,
          'emails' => $data['mailaddresses'],
          'ldap_sync' => time(),
        );

        // save the user with the data provided above
        user_save($account, $edits, 'company_ldap');

      }
}

// when user account is being saved or updated
function company_ldap_user_presave(&$edit, $account, $category) {

  // make sure to only update ldap-attributes when needed
  if ($category == 'company_ldap') {

    // if there is no data to save, don't save
    if (isset($edit['fullname'])) {

      // save ldap-data to custom user fields
      $edit['field_company_fullname'][LANGUAGE_NONE][0]['value'] = $edit['fullname'];
      $edit['field_company_first_name'][LANGUAGE_NONE][0]['value'] = $edit['first_name'];
      $edit['field_company_last_name'][LANGUAGE_NONE][0]['value'] = $edit['last_name'];

      // loop through all mail addresses and add them to the custom user field
      foreach ($edit['emails'] as $i => $email ) {
        $edit['field_company_emails'][LANGUAGE_NONE][$i]['value'] = $email;
      }

      // save serialized data of last ldap sync to users.data table
      $edit['data']['ldap_sync'] = $edit['ldap_sync'];
    }

  }

}

```

# Answer
IMO you don't need the implementation of the `hook_user_presave()`, I see that in the implementation of `hook_user_login()` you have all the values that you need to create the user.
> 2 votes

---
Tags: 7, hooks, authentication-authorization, users
---


# Question
Title: How do I remind users to pick an avatar?
I use the Avatar Selection Module to provide a list avatars my users can choose from. I don't want to make choosing an avatar required, but I'd like to have a persistent reminder for users who have not picked an avatar for themselves.

How can I identify users who have NOT chosen an avatar and use Context (or something else) to conditionally display a message in a block like, "Hey you haven't chosen an avatar yet. GO HERE (User Form) to choose one."?

# Answer
> 1 votes
Profile Complete Percent helps to guilt users into filling their profile details. This isn't avatar specific, but you can configure the PCP block to only use a single field for its percentage calculation.

# Answer
> 1 votes
## The following only works if you created your own image field. Ex: I added an image field called avatar to my users fields and disabled the default picture field over at `/admin/config/people/accounts`

Going off memory here.

You can do this using Rules

Add a new rule:

React on event \>\> After user has logged in

Add Condition \>\> Data is Empty \>\> account:field-avatar

Action \>\> \[under system\] Show message \>\> Hello \[account:name\] you have not selected an avatar yet, please go `<a href="/user/[account:nid]/edit">here</a>` to add an avatar. \>\>

Repeat message: True.

---

## If you're using the Drupal default picture, take a look at the answer to this:

## How to check with Rules if users have a custom picture

---
Tags: 7, media
---


# Question
Title: How to make a stacked flexslider slideshow carousel
I would like two ad blocks showing the same randomized content, but without duplicates.

I could just use two different blocks, with different flexslider options, (both starting on different images and moves by two), but that only works with even number images and can not be randomized.

Right now, I'm trying to make a carousel showing two images, and trying to restrict the container to a size that they form two layers. The problem: flexslider still moves on to white space, as if it was still one long layer.

Thank you for your time.

# Answer
Got it to work, but using views slideshow. I just clicked "View Action Advanced Options" in the action setting, setting it to two slides. I also renamed the flexslider library and made sure that I downloaded the full version of cycle. And that's it!
> 1 votes

---
Tags: javascript
---


title: Add custom text to certain pages

text:
# Question
Title: Add custom text to certain pages
To add custom text to a node I have a code like this:

```
function mymodule_node_view($node, $view_mode, $langcode) {
  $var=....;
  if (.....) ){
      $node->content['new'] = array(
       '#markup' => $var,
     );
  }
}

```

It works perfectly, but now I need to add this text to pages that don't load any node. So I can't use this hook.

I mean something like the drupal\_set\_message function, showing custom text at the top of certain pages.

# Answer
maybe you can add this to your if condition:

```
if($view_mode == 'full' && node_is_page($node)){
   //your code here
 }

```
> 0 votes

# Answer
Have you tried adding your text inside a block, then assigning it to a region? Context is useful for assigning blocks to regions based on a variety of conditions.
> 0 votes

# Answer
I would use panels and panels everywhere for that. You can actually just create custom text panes and add to any page.

To get started with these two modules I can recommend the videos by cojanti

Block and Context as mentioned above is also possible but we never use that since blocks are not deployable so easy.
> 0 votes

---
Tags: 7
---


title: How to attach node to user profile?

text:
# Question
Title: How to attach node to user profile?
How can I attach a node to a user profile with profile 2 (or some other way)? It says here that it is possible but it does not say how.

# Answer
You could add an entity\_reference field to the profile and reference the node in that field.
> 2 votes

# Answer
Please read documentation of this module. Another doc googled. Screencast.

About Profile2 module: As described in the documentation Drupal 7 allows adding fields to user account pages - what serves as simple way for building user profiles. The main differences between that and profile2 are:

* With profile2 user account settings and user profiles are conceptually different things, e.g. with the "Profile pages" module enabled users get two separate menu links "My account" and "My profile".
* Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
* Profile2 supports private profile fields, which are only shown to the user owning the profile and to administrators.
> 0 votes

---
Tags: 7, nodes, users
---


# Question
Title: Can I strip my form of some classes and DIVs?
Can I strip my form of these classes and DIVs as shown in the code below?

```
<form action="/example/unsubscribe" method="post" id="exampleform-unsubscribe" accept-charset="UTF-8">
  <div>/** this div **/
    <div class="form-item form-type-textfield form-item-email">/** strip these class and add my own class? **/
      <label for="edit-email">E-mail address <span class="form-required" title="This field is required.">*</span></label>/** strip classes form-required from span **/
      <input type="text" id="edit-email" name="email" value="" size="60" maxlength="128" class="form-text required" />/** strip form-text and required class **/
    </div>
    <input type="submit" id="edit-submit" name="op" value="Remove me!" class="form-submit" />/** remove form-submit class **/ <input type="hidden" name="form_build_id" value="formjKkl1KLWJLnv0hM4DSVd8-40boTgBQAzWWhUn44c15Q" />
    <input type="hidden" name="form_token" value="LB07DqsDXK9idWdOHLxUen7jKxm52JqTyHiR7-pNumA" />
    <input type="hidden" name="form_id" value="exampleform_unsubscribe" />
  </div>/** this div **/
</form>

```

Would it affect any form or ajax form functions of the form?

# Answer
There are 2 Drupal theme functions which you need to override in your theme's template.php

You can paste this code in your theme's template.php and change "themename" to the name of your theme (Drupal 7 code):

It shouldn't affect any ajax form functions if you have a custom theme, however if you are using a contributed theme you should check the javascript files to see if there are any functions using the classes / selectors you have stripped out.

1. Override theme\_form() to remove the div

```

function themename_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
}
element_set_attributes($element, array('method', 'id'));
if (empty($element['#attributes']['accept-charset'])) {
 $element['#attributes']['accept-charset'] = "UTF-8";
}
return '' . $element['#children'] . '';
}
```
2. Override theme\_form\_element() function to strip out the classes

function themename_form_element($variables) {
  $element = &$variables['element'];
  $element += array(
    '#title_display' => 'before',
  );
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  // Remove line below if you don't want a custom class
  $attributes['class'] = array('your-custom-class');

// Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '' . "\n";
  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }

$prefix = isset($element['#field_prefix']) ? '' .   $element['#field_prefix'] . ' ' : '';

$suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';

switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

```
case 'after':
  $output .= ' ' . $prefix . $element['#children'] . $suffix;
  $output .= ' ' . theme('form_element_label', $variables) . "\n";
  break;

case 'none':
case 'attribute':
  // Output no label and no required marker, only the children.
  $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  break;

```

}

if (!empty($element['#description'])) {
    $output .= '' . $element['#description'] . "\n";
  }

$output .= "\n";

return $output;
}

> 1 votes

---
Tags: forms, theming
---


# Question
Title: How to compare 2 row fields in a view and don't display them if some conditions are verified?
I have a view table with 12 Fields & 10 Rows and I wish to compare two known fields with defined field names and check if both fields are:

1. If data partially matches (Field 1 with Field 2 or vice versa) then display rows, e.g.:

* Field 1: Apples, Oranges.
    * Field 2: Oranges, Grapes.
2. If none matches then don't display either of the two rows.
3. If row data is blank for one of the fields then don't display them.

# Answer
## Views Conditional

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty
> * Not Empty
>
> Views conditional allows you to output text based on the result of the condition.
> 4 votes

# Answer
Yo can use the Views PHP module. To filter your rows in your view, in the filter criteria add a `Global: PHP` field, in the *Filter code* edit you can have access to all the rows of the view (`$handler->view->result`) and to the values of the current row (`$row`) then you check your condition and if the code returns `TRUE` the current row is removed from the results.
> 2 votes

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


# Question
Title: How to output custom field of Content type in page.tpl.php?
I want to display a custom field which I created in my custom Drupal theme.

The field I created called "Startnummer" so the machine name of the field (I didn't change it) was created as "field\_startnummer".

Furthermore, I found an article of that topic an the answer is to put the following line into my page.tpl.php:

```
<?php print render($content['field_startnummer']); ?>

```

Unfortunately, that doesn't work!

The next problem is, I do not know how other people would call that problem, so I can't find any solutions.

Any help?

# Answer
> 0 votes
To output content types fields within a template you'll need to create a specific node.tpl.php for that content type for example node--article.tpl.php and then using the code you already have above should work.

# Answer
> 0 votes
To print your field in **page.tpl.php** do this:

Add this to your **template.php** file

```
function YOURTHEMENAME_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    $node = node_load($node->nid);
    node_build_content($node);
    $vars['field_YOURFIELD'] = render($node->content['field_YOURFIELD']);
  }
}

```

Then add this to your **page.tpl.php** file (or page--customname.tpl.php whatever file you are using to render page). We are using if statement here to avoid errors when/if field is empty.

```
<?php
if (isset($field_YOURFIELD)){
   print $field_YOURFIELD;
}
?>

```

After this you might notice that you are getting field output as double. That is because you have field active in Manage display of your content type (admin/structure/types/manage/YOURCONTENTTYPE/display).

So you need to add one more function to **template.php**.

```
function YOURTHEMENAME_preprocess_node( &$variables, $hook )
{
    if( $variables['page'] )
    {
      hide($variables['content']['field_YOURFIELD']);
    }
}

```

This one hides field from node content array. So your field is only printed when you are calling it on **page.tpl.php** file.

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


# Question
Title: How to add CSS class to password-strength and password-confirm on /user/register page?
I want to add a class to password-strength and password-confirm on /user/register page? I tried to alter the form but as these are made with js I could not change or add anything to them. How can I alter these?

# Answer
> -1 votes
Trying to explain, first you need to implement hook\_theme(), in this case, you have to implement the function in your template.php file, that is located in the folder that contains the theme you are using (sites/all/themes/your\_theme\_folder).

```
function yourThemeName_theme()
{
$items = array();
$items['user_register_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'yourTheme') . '/templates',
        'template' => 'user-register',
);
return $items;
}

```

After implementing the function, you have to create the template file, in the example, the template file is called user-register.tpl.php and it's located inside the "yourThemeFolder/template" folder.

In the user-register.tpl.php file you define your custom html, for the form, the code that will be rendered inside the `<form></form>`. I can't test this now, but if I'm not wrong you can use the debug function to output the form array and check the fields names of your form.

```
debug($form);

```

Your template file would look like this:

```
<fieldset class="form-wrapper" id="edit-account">
        <legend><span class="fieldset-legend"><?php print t('User Account'); ?></span></legend>
        <div class="row">
            <div class="col-md-6">
                <?php
                // print render($form['account']);
                print render($form['account']['name']);
                print render($form['account']['mail']);

                ?>
            </div>
            <div class="col-md-6">
                <?php
                print render($form['account']['pass']);
                print render($form['account']['pass2']);
                ?>
            </div>
        </div>
    </fieldset>

```

For a more detailed example, check the following link: https://www.drupal.org/node/350634

---
Tags: users, forms
---


# Question
Title: How to make an custom content entity can be refered like user in Drupal 8?
Follow project examples, I have created a content entity, but how can make it can be attached into another entity as a reference field like user in drupal 8?

# Answer
Eyal's comment is just the answer, Choose content as the reference type.
> 0 votes

---
Tags: entities
---


title: SQLite Backup-Restore

text:
# Question
Title: SQLite Backup-Restore
*Backup and Migrate* is great as a backup system and thus allows some sort of versioning. This enables me to roll back easily when developing and testing small sites which I tend to develop in a live environment.Migrating a dev version to a live site is also quite easy this way.

Backup and Migrate does not work for SQLLite, however. I assume the best would be to put the site in maintenance mode, and copy the .ht.sqlite as a backup ... restoring should then be the same in reverse.

Am I on the right track?

# Answer
> 3 votes
I suggest the use of the Read only mode module, it places your site in the maintenance mode, but your visitors can still view the site without enter or change content.

Then make a copy of your database and get out of the maintenance mode.

# Answer
> 1 votes
In general that sounds ok. You should also establish a shared lock on the database file using the SQLite API though.

There is also a backup api. So if you do this more often, maybe you could write a module for that.

More info: https://www.sqlite.org/backup.html

---
Tags: backups, database
---


# Question
Title: How can I add extra information for each term reference?
I'm trying to create a content type that matches a product. The product can be made of several thing in different percentages:

Eg.

```
material 1:
    material 1.1: 5%
    material 1.2: 0%
    material 1.3: 20%
material 2: 75%
material 3: 0%
material 4:
    material 4.1 0%
    material 4.2 0%

```

I've built the materials hierarchy using taxonomies. How can I add a parameter to a taxonomy so I can do this?

I've tried using Field Collection, but the problem I encountered was the inability to work with Solr

# Answer
> 3 votes
You can use the Multifield module, it is a "lightweight" version of field collection, instead of creating an entity structure with relationships, it covers the simple use cases without creating the entity. It works with Solr.

I think that you must read this: Field Collection vs Entity Reference

# Answer
> 3 votes
There are two options:

1. Create own module based on taxonomy. Most flexible, but also most complicated. That's what I would do, if I had time and motivation to play.
2. Use Field collection \- create a collection of term and percentage fields, and make this collection (not individual fields in it) multivalue. *Warning:* I know of no easy way to make sure your percentages adds up to 100%. I know how to do it easily in custom module.... see point 1.

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


# Question
Title: Where is the code for added user registration fields?
I've added a few extra fields relevant to my interests to the user registration form. The problem being, I'd like to insert a db\_insert function to make use of those fields, but I don't know where the code for the extra fields are. That being said, I'm not entirely sure if altering that code is even necessary.

I'm very new to all this. I'd really appreciate some help, have a good day.

# Answer
In the field settings, tick "display on user registration form".

All of the database stuff is taken care of automatically in drupal so you'll rarely have to worry about that stuff unless you are adding your own custom modules that require tables.

What are you trying to accomplish with these tables? Views etc. will have access to them.
> 2 votes

---
Tags: 7, hooks
---


title: Sending private messages between users

text:
# Question
Title: Sending private messages between users
## EDITED

The excellent Privatemsg module provides a wealth of functionality but some sites might not need/want this degree of complexity. Rather than starting with something complex and disabling/removing features, I would like to think about ways to build something relatively simple from basics.

Using the basic infrastructure of D7 what are the ways one could create a simple messaging system that allows user A to message user B, and both of these corresponding users to delete this message individually (i.e. user A deletes message 1, but user B does not; therefore user B can still see message 1)?

How might message threads (i.e. successive related messages) be managed and displayed?

How well would the solution scale (e.g. 1,000,000 messages, 100,000 threads, etc.).

Thank you.

# Answer
By default, giving a role the permission to delete messages will not delete the message for the other user. I just tested this and it works as you require.

As for only allowing messages between certain users, you can prepopulate the "To" field with /messages/new/\[nid\]. So on the user page or in views or whatever, you can create this link using tokens or replacements. Then disable the field with a custom module. Savvy users could change the \[nid\] in the url or even the html in the page so this depends on how secure it needs to be. They'd need to know another user's nid to be able to do this but they can only know that if they can already view the user.

```
function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_new') {
    $form['recipient']['#disabled'] = '1';
 }
}

```
> 3 votes

---
Tags: 7, privatemsg
---


title: Views Taxonomy selection and display

text:
# Question
Title: Views Taxonomy selection and display
I am displaying a list of taxonomy terms for registered users on a Node and the user is asked to make multiple selections depending on what appeals to them. e.g what are their Top Ten song choices for 2016

I would like them to put that same list of taxonomy terms with their 2016 choices (Selected) within a View and I would like to email them that View list in 2017 and ask them to check if its still correct and or to make amendments to their choice to reflect their choice for 2017.

I can get the Views list to display the list of taxonomy terms, but how do I get check boxes to display with ticks with past choices for 2016 in Views and then store the changes for 2017?

Perhaps I'm overlooking something and this should be very simple.

Anyway, thanks in advance.

# Answer
> 0 votes
This can be achieved using following approach.

1. Create a content type for example "Favorite song" and add a field of "Term reference" type into this content type where widget will be "Check boxes/radio buttons" and select the vocabulary of songs for options.
2. Give permission to users to add/edit content "Favorite song",then while adding user will select their favorite songs from the list of songs.
3. Again to view/edit favorite song list of a user you can find the correct node by author of the node.

Hope it will help.

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


# Question
Title: Can I include nodes in a view's results only at URLs specified in the nodes?
Is it possible to conditionally include nodes in a view based on the paths specified in a field on that node? The idea is to essentially mimic the default property of blocks, making their display allowed or disallowed at specified paths. My view (technically a view block) is being used to show sponsor images as a slideshow, and I'd like to be able to define which pages each specific sponsors' graphics should display.

I'd imagine it would include the use of a contextual filter on the field containing the paths, but I can't figure out how it would work. Possibly via some implementation of Views Argument Substitutions, although that seems to base its results off of specified path arguments and not the whole path. In the meantime, I'm implementing Nodeblock as a partial substitute, but I'd prefer to leverage views if possible.

EDIT: Thanks to mchar's answer below, I was able to get a working snippet for this functionality. It could probably be optimized, but that's for another thread.

```
function MYMODULE_views_pre_render(&$view) {
    if($view->name=='sponsors') {
        $current_path = drupal_lookup_path('alias',current_path());
        foreach($view->result as $row_num => $row) {
            foreach($row->field_field_urls_to_show_up_on as $urlNum => $url) {
                $this_path = $url['rendered']['#markup'];

                // If the path contains an asterisk
                // Asterisks should only appear at the end of a path at the time of writing
                if (strpos($haystack = $this_path, $needle = '*') !== false) {
                    $this_path = str_replace('/*', '', $this_path);
                    if (strpos($haystack = $current_path, $needle = $this_path) === false) {
                        unset($view->result[$row_num]);
                    }
                }

                // if current_path is not the same as the provided path (no *)
                elseif ($current_path != $this_path) {
                    unset($view->result[$row_num]);
                }
            }
        }
    }
}

```

# Answer
> 1 votes
Hook views\_pre\_render should meet your needs.

Here is a sample code of what you are describing:

```
$string_pos = strpos($haystack = current_path(), $needle = 'chickens'); // or you may use drupal_get_path_alias()
  if ($view->name == 'view_name' && $view->current_display == 'view_display') {
    foreach($view->result as $row_num => $row) {
      if ($string_pos && strpos($haystack = $row->node_path, $needle = 'chickens')) {
        unset($view->result[$row_num]);
      }
    }
  }

```

It can be optimized but I guess you got the idea.

Hope that helps!

# Answer
> 0 votes
1. Add an Entity reference field in the sponsor image content type.
2. On every sponsor image node, refer the master content to which you need this sponsor to be displayed with.
3. In your view, add a contextual filter on the above entity reference field, and `Provide the default value -> Content ID from url`.

This will filter the sponsor images those only refer the current node in the entity reference field.

# Answer
> 0 votes
A\> For non-node pages, set up a taxonomy with terms like the below and add it as a field to your sponsored posts content type.

```
User Pages
Search Pages
Login Page
Homepage
About Page
etc.

```

Then create multiple view blocks with each one only displaying on those pages using block settings. In each view, filter by that taxonomy term.

B\> For node pages without panels, use Kevin Siji's answer.

C\> For node pages that use panels, use Kevin Siji's answer but create a content pane. In Pane Settings, click Argument Input and select "From Context\>Content ID" or maybe "From Panel Argument" but I think it's the first one.

That way, your sponsor can choose either nodes, page types, or both.

Bonus\> For choosing nodes when creating a sponsored post, you can go one step further and have your entity reference field use an "entity reference view" to decide which nodes can be selected.

This allows you to add things like tiers where the user can choose "premium posts" for example. It also allows you to decide if sponsored posts should show on a regular node when you're creating it. Taxonomy or Booleans can achieve this because your "entity reference view" can filter them.

---
Tags: blocks, views
---


# Question
Title: How to add a new permission in "node_list_permissions"?
Is there a way to add a new item in `node_list_permissions` function in node module from a custom module. Let me explain my problem.

I have a module say "audit" which will track node history, I have a new tab say history and user whoever have access to see the node history should be allowed to see the history of that node. Is that possible?

# Answer
> 0 votes
Yes it is possible. To achieve this, you need to create permission.

Following code will create list of permission for all content type.

```
/**
 * Implements hook_permission().
 */
function HOOK_permission(){
  $permission = array();
  foreach (node_permissions_get_configured_types() as $type) {
    $info = node_type_get_type($type);
    $permission["View history $type content"] =  array(
        'title' => t('%type_name: View content history', array('%type_name' => $info->name)),
    );
  }
  return $permission;
}

```

You need to replace HOOK with your custom module name, and then clear at least "registry" cache.

Then, on permission page you can easily grant permission for each of content type per role.

Hope it will help you.

**Updated answer as per comment**

If I've understand your problem correctly then you want to grant permission to user(s) who have access to see the node revision.

With the above code,I hope you have list of permissions per node for each role.

Now you need to implement hook menu alter .

```
/**
 * Implements hook_permission().
 */
function HOOK_menu_alter(&$items) {
  $items['node/%node/revisions']['access callback'] = 'your_custom_access';
  $items['node/%node/revisions']['access arguments'] = array(1);
}

```

Here you will alter the 'access callback' argument to check if user has access to see node revision(Don't forget to clear menu cache to see it in action and also make sure that "Create new revision" is checked for the content type).

```
function your_custom_access($node){
  if(user_access("View history $node->type content")){
    return TRUE;
  }
  return FALSE;
}

```

I hope this will help you to solve your problem.

# Answer
> 0 votes
A more experienced user should check the below.. I've only added permissions to contrib modules.

From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_permission/7 This will add the permission to the people page.

```
function YOURMODULENAME_permission() {
  return array(
    'see history' => array(
      'title' => t('See History'),
      'description' => t('Blah Blah.'),
    ),
  );
}

```

From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7 This should check for the permission when viewing that url. I might have gotten the % wrong.

```
function YOURMODULENAME_menu() {
  $items = array();

  $items['user/%/history'] = array(
    blah
    'access arguments' => array('see history'),
    blah
  );

```

---
Tags: nodes
---


# Question
Title: Find matching fields between content types and create new nodes
I'm working on a project that collects information about a corporate client and then based on the information provided, connects that client with other companies that can help them with a specific need.

I have worked through the first half of the project to collect data conditionally based on the type of industry/operations the company is involved with using rules. Now i need to use the information collected and filter a view to find matching companies.

Essentially once a client submits their finalized application (a collection of different fields within a handful of content types), behind the scenes I need to figure out a way to filter a view of other companies with matching characteristics, then for each company that matches the filtered view, add a new node within a separate content type and then entity reference that node back to the finalized application for further input/editing. Here is a simplified visual:

Most of the fields being filtered are taxonomy references; however, some would be numeric inputs filtered by a less than, greater than, or equal to filter.

---

Financials Taxonomy: good financials; so so financials; challenged financials

Industry Taxonomy: technology, manufacturing, real estate, etc...

"Client A" node field answers in Clients content type:

* good financials (financials taxonomy reference)
* focused on technology (industry taxonomy reference)
* 50 employees (numerical field)

Companies content type contains the following nodes:

* Company A: likes only challenged financials; focused on manufacturing; works with companies \<100 employees
* Company B: likes only good financials; focused on technology; works with companies \<500 employees
* Company C: likes only challenged financials; focused on manufacturing; works with companies \<25 employees
* Company D: likes only good or challenged financials; focused on manufacturing; works with companies \<100 employees

Once client A selects a field indicating the answers are finalized and the content type Clients is saved, I need to find a way to have the matching companies filtered based on client A's answers, and a new node for a different content type (content type called Partner Details) should be created for each matching company.

That content type would be called Partner Details and would consist of the following fields for each matching company:

* entity references the client content type
* entity references the matching company to the client
* custom blah blah blah entered by rules that indicates why the match makes sense
* contact information from the company content type
* etc., etc...

So to sum up, client A answers the questions noted above within the client content type, then based on that information, the data within the Companies content type would be filtered - and for this example - two new nodes of Partner Detail content type would be created because nodes in the Companies content type matched the fields that Client A answered in Clients content type. Company B and Company D matched the criteria so they would be entity referenced by the two new Partner Details nodes created. This way, Client A could log in and see their matches and edit the matching partner details and view information about Company B or D based on their entity referenced nodes.

---

I have an intermediate understanding of views, panels and rules, but can't seem to figure out how i would do this behind the scenes once a user indicates the application is finalized. I also have an understanding of how to use rules to create new nodes and entity reference them. Hoping for a step by step example as detailed as you can provide. Any help is greatly appreciated. Thanks for bearing with my long winded explanation, hopefully that makes some sense.

(Finally, I had no idea what to title this question so if anyone has a better suggestion, let me know and I'll change it.)

# Answer
> 1 votes
You need the below rule to fire when the client's content type is saved.. And all relevant fields must exist in BOTH content types. It will talk your clients answers, feed them through a VBO, get the company NIDs that match and then loop through them to create Partner Details nodes.

1. First, you need to have Views Bulk Operations (VBO) which will give a new rule action.. "Load a list of entity IDs from a VBO View". In this action, you can specify a VBO view and a list of arguments (taxonomy tids etc.) to send to the view using replacement patterns. The list of returned IDs is what you will use to create your "partner details".
2. You need to create the VBO view by adding "Bulk operations: Content (Content)" as a field in a new view. The arguments sent from the rules action can be picked up by contextual filters using the "Provide Default: Raw Value from URL" setting. If I remember correctly, the first argument starts with path component 2.
3. The results of the VBO should be limited to those nodes that match the arguments. Now we have a list in rules that we can use Loop to go over.
4. Depending on needs, you can just create the new entities and reference the client and company nodes or do a two way reference so that the client and company nodes also reference each partner detail node.

The above is will do the taxonomy fine but for the integers, it's a bit more complicated since the contextual filter must match perfectly. For this, you can use the contextual filter: Global Null (which won't limit the results) and use Views Argument Substitutions to take the value from the contextual filter and use it in your views filters (the regular ones on the left). * * \*!2 * * * (no spaces) if your global: null is the second contextual filter.

This is pretty limited but it could work. If you need it to only be 50-100 employees for example, on the company content type, have minimum and maximum integer fields and use "greater than" and "less than" filters in VBO view.

You should do quite a lot of testing on the VBO preview to make sure things work as expected. I really believe this is the only way to do this without writing a nasty amount of custom code. Good luck!

---
Tags: views, rules
---


# Question
Title: How to create dynamic panel column content?
Hello i am new to drupal and trying to make a dynamic column content using panels, so i had created a two columns the right side one is a menu and left side one is about to be dynamic, so when we click a link in the right side menu the content will be rendered in the left side one and we keep the right side menu visible.

# Answer
By "dynamic", do you mean "only that panel pane changes and the page doesn't reload"?

If so, check https://www.drupal.org/project/jquery\_ajax\_load and this tutorial http://www.stevepolitodesign.com/blog/load-content-drupal-ajax-without-coding .

If you don't need that functionality, then enable the panel page that overrides /node/%node and put your fields in the left side and your menu in the right.
> 0 votes

---
Tags: routes, panels
---


# Question
Title: Can you allow user to add another item without editing the administrator post?
I have a field which allows multiple inputs. What I want to achieve is to allow user to add another item only and not edit the content of the post of the admin. Thank you.

# Answer
My suggestion is to use hook\_form\_alter for your node edit page and set '#disabled' =\> TRUE for your content field (assuming here as body field) by checking the current user role or something.
> 0 votes

# Answer
Ok, what I think you need to do right here is allow the user to edit nodes of that type, but then limit his ability to change any other field.

Take a look at https://www.drupal.org/project/field\_permissions and tell me if it suits your use case.
> 0 votes

---
Tags: nodes
---