# Question
Title: Displaying content from an entity reference in a view
I have a node type, Medical Group, that has an entity reference field (field\_accreditation) to another node type, Accreditation.

I would like to create a block to display on each Medical Group page that displays the Accreditation for that particular Medical Group.

I also need to provide a default value when the block is placed on a page that does not have an Accreditation field.

I've tried adding a relationship and then using that as a contextual filter, but that doesn't seem to work. Any advice or steps to go about this?

# Answer
> 0 votes
* Remove current contextual filter and relationship
* In contextual filter add nid.
* In its configuration select raw value from URL, then select argument number which is your nid form url
* Now you can also set default value in this configuration
* In block display setting show your block on your content type.

---
Tags: blocks, views
---


# Question
Title: htmlLawed in text format corrupts Scald insert in CKEditor module
I have htmlawed text format filter. When I enable it for any filter that it is used by any CKEditor profile, it causes corruption for inserted Scald atoms in the CKEditor.

In other words, the following is a correct code for an image atom as shown in CKEDITOR source view:

```
<div class="dnd-atom-wrapper" data-scald-align="none" data-scald-context="sdl_editor_representation" data-scald-options="" data-scald-sid="8" data-scald-type="image">
    <!-- scald embed --></div>

```

After changing the text format to a format that it uses htmlawed and saving the node and then edit it again and switching to Rich Text Editor, I got the following code in CKEDITOR source:

```
<div class="dnd-atom-wrapper" data-scald-align="undefined" data-scald-context="undefined" data-scald-options="" data-scald-sid="undefined" data-scald-type="undefined">
    <!-- scald embed --></div>

```

This cause alerting an error message:

Just removing htmlawed filter makes ecerything works fine, but this is not an option for me.

I tried the following settings - in the screen shoe - for htmlawed:

However, it does not work as expected to preserve the scald attributes.

I alse tried to change the order of the filter by making it before or after `Embedded atoms` filter

Where is the mistake?

# Answer
The solution, simply, is to change a Security setting of the CKEditor profile meant by this issue as follows:

1 - go to \`admin/config/content/ckeditor/edit/(TheProfileName)

2 - In Security tab, goto Security Settings and choose `Run security filters only when CKEditor is set to start automatically.`

Of course, you have to notice that CKEditor in this profile is not started automatically.
> 0 votes

---
Tags: 7, wysiwyg, input-formats, scald
---


title: Rewrite HTML title tag in Drupal 7

text:
# Question
Title: Rewrite HTML title tag in Drupal 7
I want to change the title and title head html element. I have tried with `drupal_set_title()` but Drupal insists on adding the site name to the title output. How can I override it so the title reads exactly as I want?

# Answer
You can change the page header title in template.php by adding the below code in `template_preprocess_html()`.

```
 function my_theme_preprocess_html(&$vars) {
   if (current_path() == 'you_path') {
     $vars['head_title'] = t('header title');
   }
 }

```
> 5 votes

# Answer
The title in `drupal_set_title()` only refers to the page title, not the HTML `title` element in `head`. To change that you need to change the `$head_title` variable in **html.tpl.php**
> 4 votes

---
Tags: 7
---


# Question
Title: On drupal main page menu, number after /node/7/1
i am starting to learn drupal right now. I downloaded a template and I am trying to figure out where are all the components are stored.

I encountered a problem where on the menu for website, there are different submenu items under that menu. and one of the items has URL like this: www.example.com/node/7/1, another item URL like this: www.example.com/node/7/2, the list goes on, like www.example.com/node/7/3. When I click on any of those link, it brings me to the same page, however the representation is different.

I am able to find node 7 in the content, however i am not able to find how to configure the number after /node/7. Can somebody tell me what does that number means? Thank you very much and have a great day.

# Answer
Not sure I fully understand the question, but my 2 cents.

First, default Drupal URLs take the format of `/{entity}/{id}/{action}`, eg. `/node/7/edit` and `/node/7/view`. In both cases you are looking at the `7`th `node` to be created, the first is the `edit` (admin) display, the second is the default display that visitors will see (`view` is dropped so you only see `/node/7`.

The second argument in your example is a little tricky as numbers don't give much away, so without knowing every module you have installed I would assume this is related to your template.

You can tell if this is the case by changing template to the default.

If these are the result of the custom template, the have a look in `template.php` as this is where theme level custom logic is done. On the off chance it hasn't been done well, have a look in the `page.tpl.php` and `node.tpl.php` files too.
> 0 votes

# Answer
> When I click on any of those link, it brings me to the same page

That is Drupal's default behaviour. If it can't find a page, it displays you the parent.

Example, try going to: `/node/7/asdfkl` and it will show you `/node/7` since it can't find `asdfkl` which doesn't exist.

Not sure why your submenu links are like that... did you install a module that added those links?
> 0 votes

---
Tags: nodes, 7, blocks
---


title: hook_cron_queue_info 'time' value

text:
# Question
Title: hook_cron_queue_info 'time' value
I've been searching around, but I can not find a good explanation (or understanding) what the 'time' value in hook\_cron\_queue\_info actually does, or how to set it to work properly.

From: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_cron\_queue\_info/7

it is said that: 'time': (optional) How much time Drupal should spend on calling this worker in seconds. Defaults to 15.

I don't quite understand that. Does calling the worker mean time allowed to execute the cron queue job? And does the next cron queue job starts after this time? Or when the previous job is completed?

# Answer
It's literally what the description says it is - during a cron run, Drupal will spend a maximum of the seconds you provide in that value processing that particular queue, regardless of the number of jobs in it.

If you're looking for the relevant code it's in `drupal_cron_run()`

```
foreach ($queues as $queue_name => $info) {
  if (!empty($info['skip on cron'])) {
    // Do not run if queue wants to skip.
    continue;
  }
  $function = $info['worker callback'];
  $end = time() + (isset($info['time']) ? $info['time'] : 15);
  $queue = DrupalQueue::get($queue_name);
  while (time() < $end && ($item = $queue->claimItem())) {
    $function($item->data);
    $queue->deleteItem($item);
  }
}

```
> 6 votes

# Answer
Queue items will be processed until the "time" value has expired. The processing may take longer than this, but no new items will be processed after this time has passed.

So, for example, if "time" is 15 and each queue item takes 14 seconds to process, the processing will deal with two items, taking 28 seconds in total. The second item is processed because the first item has finished before the time has expired.
> 2 votes

# Answer
The answer is obvious if you look at the following two items in combination:

* '**worker callback**': The name of the function to call. It will be called with one argument, the item created via DrupalQueue::createItem().
* '**time**': (optional) How much time Drupal should spend on calling *this worker* in seconds. Defaults to 15. (my emphasis)

So the optional `time` value is the maximum time that will spent, during a cron run, to execute the callback `worker callback` function that *you* supply in your implementation of this hook.
> 0 votes

---
Tags: cron, queue
---


# Question
Title: Permission denied when configuring my module though admin page
I am following drupal's module development tutorials. I am using drupal 7.41 and my operating system is ubuntu.

I am creating a module that list links in the footer section of the page. I am making an admin configuration for my module. I have done everything what the tutorial said and I went to my configuration page, I couldn't see my configuration button of my module in `admin/config/content`. Here is my `hook_menu()` implementation:

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

$items['admin/config/content/footer_links'] = array(
    'title' => 'Footer Links',
    'description' => 'Configuration for Footer links posts module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('footer_links_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
);

return $items;
}

```

I have manually tried to access to `admin/config/content/footer_links`, I got a permission denied error. However, I was already logged in as the admin. I have changed the value of `access arguments` to `array('access content')`. And it worked. What was the problem? If I leave my code like this, can others also edit my module through the form? Thanks in advance.

# Answer
Try to change

`'access arguments' => array('access administration pages'),`

into

`'access arguments' => array('administer site configuration'),`
> 0 votes

---
Tags: routes
---


# Question
Title: Is it possible to style the new node page?
Is it possible (with Drupal 7) to style the new node page?

I can add content by going to `node/add/article`, but I want this to be on its own URL and styled like my site's theme.

Is this the correct way to go about this? Or is it better to create a new module with validation to submit data back to the database?

# Answer
You can style your node edit or add form by adding `page--node--edit.tpl.php`

or check here and here for more Suggestions.
> 0 votes

# Answer
Go to appearance/theme settings, here you have your theme on, but most probably also an admin theme, in the bottom of the page, your admin theme is selected. Here you will also find a checkbox, make sure this is not selected. This makes new node page use the admin-theme.
> 0 votes

---
Tags: 7, nodes, theming
---


# Question
Title: Cardinality Violation during Views contextual filter setup, how to fix this?
I'm currently getting this error in my views setup:

**SQLSTATE\[21000\]: Cardinality violation: 1241 Operand should contain 1 column**

I'm not sure why its giving this error as it seems like it should work. I have a contextual filter that matches taxonomy term id's. I have it configured to pass in an array() of tid's, but it throws the error if its more than one. What could be wrong?

Below are screenshots of my setup and sql statement generated by views:

http://img14.imageshack.us/img14/8079/f4bw.jpg

# Answer
Reading the instructions for multiple views contextual filter arguments you get the solution:

> **Allow multiple values**: If selected, users can enter multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).

So if you need an **OR operator** you should return a **string** of "1+2+3" and if you need an **AND operator** you should **return** a string of "1,2,3".

So don't return an array() but a string.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Losing custom #theme settings set in hook_field_widget_form after an error
I have defined a custom field in a custom module. The new field applies a custom font to the options, and I have run into an issue with the widget form after an error. I have implemented hook\_field\_widget\_form in a manner similar to the following:

```
mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch ($instance['widget']['type']) {
    case 'mymodule_custom_widget':
      $element += array(
        '#theme' => 'mymodule_checkboxes',
      );
      break;
  }
  return $element;
}

```

mymodule\_checkboxes and mymodule\_checkbox have been defined in hook\_theme as follows

```
function mymodule_theme() {
  return array(
    'mymodule_checkboxes' => array('render element' => 'element'),

    'mymodule_checkbox' => array(
      'template' => 'mymodule_checkbox',
      'pattern' => 'mymodule_checkbox__',
      'arguments' => array('element' => NULL),
    ),
  );
}

```

To put it shortly, `theme_mymodule_checkboxes` calls `theme(array('mymodule_checkbox'), array('element' => $current_element));` on every element in the `#options` array.

Everything is working great on the initial load of the form, the `theme_mymodule_checkboxes` function is called and the options are output using my custom template (the template isnt really necessary, I plan on replacing it with a theme function but havent gotten around to it. I don't think that particular oversite has any bearing on this issue but I may be wrong). After I submit the form with an error - say I don't input a title or some such - the field is rendered using the default checkboxes theme.

Is there some hook I am missing in which I can define the default theme for the form widget before hook\_field\_widget\_form? One that hopefully fires even after a form fails validation? I think I might be able to require a form rebuild in my custom field validation, but that forces extra work, and I would like to avoid that.

# Answer
> 1 votes
This one turned out to be a fairly simple fix. I had `theme_mymodule_checkboxes` living in `mymodule.admin.inc` which was not being included on every page. Moving the function to the `mymodule.field.inc` which is specifically included in the module file caused the theme function to be included and fixed the error.

Many thanks to the drupal user Ayalon who found this fix.

---
Tags: 7, entities
---


# Question
Title: Make Commerce Kickstart home page show up at a different URL
By default, the store is the front page in Commerce Kickstart. I want to have a different page as the front page, but be able to switch to Commerce Kickstart by clicking on a menu link. However, when I change the front page to be my welcome page in Site Information, the store is no longer accessible. How do I link the front store page to a link in a menu? Essentially, I want the commerce kickstart store to be accessible from http://homepage/store.

# Answer
The `front` page on Commerce Kickstart is `node`. The content is defined via blocks. So if you want to change the front page to another page, you could create a page and set it as the `front` page in the admin. None of the blocks should show up. If you want to make the contents of the current `node` page visible on a new or custom page, then you'll need to change the block configuration of all of the blocks that are currently visible on `node` and configure them to show up on another page.
> 0 votes

---
Tags: commerce, path-aliases
---


# Question
Title: Format 'Table Of Files' Field Display For Commerce Product Display?
We have a Commerce Product Display for a Product Variation. If you're not familiar with Commerce Kickstart, it's basically just a form to add an item to a shopping cart. Each Product Display includes links to various PDF documents. The display format for the PDF field is 'table of files'. It works, however it looks clunky.

I'm having trouble locating the tpl or inc file that controls formatting for this type of field ('Table Of Files'). We don't want to globally change table display, we just want to alter it on this one Display.

Where is the php located to theme this? Or is there a function I need to add to my theme to hook into that display?

Specifically, we want to:

1. Get rid of the header.
2. Get rid of the file size column.

# Answer
I am not sure which `tpl.php` file you will need to override, but you can try to "inspect" for it using Devel Themer and then override it with your own `tpl.php`.

This doc page has some common overrides and you can kind of get the override pattern. I am guessing you will need to something like `field--field-name--content-type.tpl.php`.
> 0 votes

# Answer
If you're using core's `file.module`, then there is no .tpl.php, you want to override this function in your theme:

```
/**
 * Returns HTML for a file attachments table.
 *
 *     @param $variables
 *   An associative array containing:
 *   - items: An array of file attachments.
 *
 * @ingroup themeable
 */
function theme_file_formatter_table($variables) {
  $header = array(t('Attachment'), t('Size'));
  $rows = array();
  foreach ($variables['items'] as $delta => $item) {
    $rows[] = array(
      theme('file_link', array('file' => (object) $item)),
      format_size($item['filesize']),
    );
  }

  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}

```
> 0 votes

---
Tags: entities, theming, commerce
---


title: How do I set default product attribute?

text:
# Question
Title: How do I set default product attribute?
Simple Question here I hope.

I've got a Format taxonomy field on my product type Record that's defining an attribute (cd, vinyl, download etc.).

I'd like to have the same order and default value on the attribute dropdown on product displays. I've set the terms in the vocabulary in the order I want on product displays but it still seems the order is random when browsing the site...

any ideas?

# Answer
> 1 votes
According to Ryan, it's based on the weight of the terms you reference.

As far as the default product that is selected, it should be the first product referenced in the field. If you're wanting to set that dynamically, you can look at Commerce Product URLs which provides that functionality.

---
Tags: commerce
---


# Question
Title: How to theme views fields template to display a gallery?
My question is generic because the solution will allow me to use various jquery gallery as bxslider, galleria or flexslider. My need is about creating a gallery with thumbnail nav, for that I need to create a views display that provide this kind of code (ex from bxlsider):

```
<ul class="bxslider">
  <li><img src="/images/730_200/tree_root.jpg" /></li>
  <li><img src="/images/730_200/houses.jpg" /></li>
  <li><img src="/images/730_200/hill_fence.jpg" /></li>
</ul>

<div id="bx-pager">
  <a data-slide-index="0" href=""><img src="/images/thumbs/tree_root.jpg" /></a>
  <a data-slide-index="1" href=""><img src="/images/thumbs/houses.jpg" /></a>
  <a data-slide-index="2" href=""><img src="/images/thumbs/hill_fence.jpg" /></a>
</div>

```

The list creation is easy for mu but I don't find a way to produce the thumbnail part..the views PHP module seem to be the path (to add data attributes and create the thumbnail "list") but I don't find the right way.

If someone can help me.All of this come from that actually using Drupal 6. :/

Thanks

EDIT: use case with data from $row views object.I don't know how to print field data settings in my view as in the template to override the output. Here I would to add the "data-thumb" attribute dynamically, provided by views data.

```
<ul class="slides">
    <li data-thumb="slide1-thumb.jpg">
      <img src="slide1.jpg" />
    </li>
    <li data-thumb="slide2-thumb.jpg">
      <img src="slide2.jpg" />
    </li>
    <li data-thumb="slide3-thumb.jpg">
      <img src="slide3.jpg" />
    </li>
    <li data-thumb="slide4-thumb.jpg">
      <img src="slide4.jpg" />
    </li>

```

No difficulty to build the list in views.

EDIT2: back on my second example, I improve my code and I'm near the goal.In a views field tpl I put actually:

```
<?php

    $imgurl = file_create_url($field->uri);
    $img_filepath = $fields['filepath']->content;
    $img_slide_size = $fields['field_galerie_image_vdl_fid']->content;
    $img_caption = $fields['field_galerie_image_vdl_data']->content;
    print '<li data-thumb='.$img_filepath.'><img src="'.$img_slide_size.'" />'
            . '<p>'.$img_caption.'</p>'
            . '</li>';

?>

```

Naturally when it'll be ok, a foreach loop will needed.But I need to clean the provided views code, because actually I put off all HTML things via the Views UI but I think it's possible to that by PHP code.

EDIT 3: my new base code to continue looking for theming my views output from unformatted content.

```
<ul class="bxslider">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
<!-- TEMPLATE DE VIEWS FIELDS CUSTOM BX SLIDER -->
<?php
//création des variables utiles pour la mise en forme de la sortie de la vue
  $imgurl = file_create_url($field->uri);

    $img_thumb_filepath = strip_tags($fields['field_galerie_image_vdl_fid_1_value']->content);
    $img_slide_size = strip_tags($fields['field_galerie_image_vdl_fid_value']->content);
    $img_caption = strip_tags($fields['field_galerie_image_vdl_data_value']->content);
    $img_delta = strip_tags($fields['delta']->content);
    ?>

 <?php
               foreach ($fields as $key => $lien) {

                    print '<li>'.$img_slide_size.'</li>';
               }
      ?>

  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</ul>

```

actually my variables doesn't return the right content, but I don't know how to find the right syntax.

# Answer
Yeah, ok you are using the views-view-list.tpl.php, then maybe try it like this if your list is exactly as you shown above:

```
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>
    <h3><?php print $title; ?></h3>
  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes[$id]; ?>"><?php print $row; ?></li>
    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
  <div id="bx-pager">
  <?php for ($i=0;$i<count($rows);$i++): ?>
  <a data-slide-index="<?php print $i; ?>" href=""><?php print str_replace('/730_200/', '/thumbs/', $row[$i]); ?></a>
  <?php endfor; ?>
  </div>
<?php print $wrapper_suffix; ?>

```

Sure there might be a more elegant solution possible, but maybe as a starting point or for a simple case this could work.
> 2 votes

# Answer
I would recommend going via Views Templates, take a look at views-view-fields.tpl.php template. From there you should be able to duplicate and modify the views content for the thumbnail part.
> 1 votes

---
Tags: views, theming, 6
---


# Question
Title: Why I've got Fatal error of undefined validation function in my form?
I get the error in below code, it is strange, why it occurred?

In `hook_menu`

```
$items['share/%'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ym_alter_sharing_content'),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

```

and:

```
function ym_alter_sharing_content($form, $form_state) {
  module_load_include('inc', 'node', 'node.pages');
  $nid=arg(1);
  $form = node_add('share');

  //$form['field_nid']['und'][0]['value']['#value']=$nid;
  //$form['#submit'][]='ym_alter_sharing_submit';
  //form_load_include($form_state, 'inc', 'node', 'node.pages');
  return $form;
}

```

but it return me:

> Fatal error: Call to undefined function node\_form\_validate()

Where is the problem?

# Answer
Change page callback form drupal\_get\_form to function, because if you use `drupal_get_form` in call back it return form and in your function you create another form, it means form in form and make conflict.

```
$items['share/%'] = array(
    'page callback' => 'ym_alter_sharing_content',
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

```
> 1 votes

# Answer
You got the error, because of missing `&`.

When you're using `form_load_include()` in hook\_form\_alter(), make sure you're following the right API syntax which is:

```
hook_form_alter(&$form, &$form_state, $form_id)

```

otherwise `form_load_include()` can't perform alterations of your current state of the form (`$form_state`).
> 0 votes

---
Tags: 7, forms
---


title: Modal form file upload is not working

text:
# Question
Title: Modal form file upload is not working
I am trying to use ctools modal form to edit node form. This form is containing a file field. The Form is rendering properly. When I try to upload a file on clicking upload button, file field has been deleted from the page. I tried to debug via firebug to see the response, it was correct as we get without modal form.

I added the following code in modal callback.

```
ctools_include('node.pages', 'node', '');
ctools_include('modal');
ctools_include('ajax');

$form_state['build_info']['args'] = isset($form_state['build_info']['args']) ? $form_state['build_info']['args'] : array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');

```

I took the reference from Ajax upload in Ctools Modal Window but it still having problem.

# Answer
Make sure you're implementing the right Drupal API syntax which requires `$form_state` to be the reference to the original array, so it can be properly modified through certain hooks.

For example if you're using `form_load_include()` in hook\_form\_alter(), make sure you're following the right API syntax which is:

```
hook_form_alter(&$form, &$form_state, $form_id)

```

(note the `&`) otherwise `form_load_include()` can't perform alterations of your current state of the form (`$form_state`).
> 0 votes

---
Tags: 7, chaos-tool-suite, modal-dialogs
---


# Question
Title: How to add 3 text boxes for a phone number field?
I want to add 3 text boxes for a phone number field. The phone number format should be xxx xxx xxxx.

I need to show 3 text boxes and stored values into single field.

How can I do this?

# Answer
You can use Masked Input to format a field. It won't give you three text boxes. But it can solve your problem by formatting the text box like below,
> 4 votes

# Answer
Instead of creating the three different fields, create only one field of type phone by installing any of the below module.

1. Phone
2. Phone Number (CCK)
3. Telephone
> 1 votes

# Answer
Have a look at the Field Group module, to create a group of 3 'fields' (1 for each of your 3 textboxes).

Excerpt from its project page:

> Fieldgroup will group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
> 1 votes

---
Tags: 7
---


title: menu is not showing for non admin

text:
# Question
Title: menu is not showing for non admin
I have facing this issue like I have given menu link say http://localhost/mcs/admin/config/b\_creation but that menu only admin can able to access not any other users, all most all the menu which comes under http://localhost/mcs/admin/config/ will not show to authenticated user I have tried many times by setting the permission in people-\>permission but no use of it it shows

> Access denied You are not authorized to access this page

. can any one tell me why is it happening?

# Answer
> 1 votes
You probably need to manage permissions in the following area,

* Goto Structure-\>Menus-\>Management
* Under Administration-\>Configuration-\>b\_creation
* Click Edit link
* At the bottom check the roles you need to grant access and Save

But make sure this has security issues, give the permissions to trusted users only.

---
Tags: routes
---


# Question
Title: How to show organic groups users that their subscription is pending?
I'm using the Organic groups (=OG) module. When a user subscribes to an OG they just see "Unsubscribe from group", even if they are not yet members, but their membership is pending. What is the best way to display a message such as "Thanks for your subscription request, it is currently being considered." or something like that?

Note: I have quite a number of questions related to Organic Groups but this is the best place I have found or support. If you can suggest other sources of OG support I would be very grateful!

# Answer
> 0 votes
A possible solution for this is to use a combination of the Flag and Rules modules, which integrate very well with the Organic groups module.

Here are the highlights of how you could make it work:

1. Create a 'global' flag (using Flag) that will be used to identify (flag) users with their membership is pending
2. Create a 1st rule (using Rules) like so:
    * Rules Event = User has become a group member
    * Rules Condition = `og-membership:state` EQUAL TO `pending`
    * Rules Action = set the flag (defined as in "1.") the user (using Flag)
3. Create a 2nd rule (using Rules) like so:
    * Rules Event = User has become a group member
    * Rules Condition = `og-membership:state` EQUAL TO `active`
    * Rules Action = unset the flag (defined as in "1.") the user (using Flag)
4. Create a 3rd rule (using Rules) like so:
    * Rules Event = Content is viewed
    * Rules Condition = *"Path matches some path on which you want to show such message"*
    * Rules Action = Show a message on the site

In case you have multiple organic groups for which you want to implement something similar, you have these options:

* Create a similar flag and a similar set of 3 rules for each of these groups.
* Use the Rules Conditional module so that you can combine the above logic for all groups in an enhanced version of rule2, -3 and -4.
* It would probably also be a good idea to move part of the logic in the above rules in a 'rules component'.

Using the Rules Conditional module you could also combine rule 2 and rule 3 above in a single rule.

In case the above may seem like overkill (2 extra modules, and 3 rules to be created ...), keep in mind that with these very same 2 modules you can implement lots (dozens?) of other functions/features. Probably also to address "*... quite a number of questions related to Organic Groups*..." you mentioned in your question.

# Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module. For Organic Groups there is another set of amazing videos to Learn Organic Groups.

# Possible alternative

For anybody who considers the Organic Groups module as rather complex (like me ...), have a look at the Group module as a possible alternative. For (way) more details about this module, refer to my answer to "How to create basic Organic Groups functionality with flags and references?".

---
Tags: organic-groups
---


# Question
Title: Upload zip & unzip to multiple image field
I am using drupal 7 and I want to upload a zip file and automatically extract it into multiple image fields on a node. The zip file contains images. Is there a easy way to do this? cause I'm not a programmer

# Answer
> 1 votes
Take a look at imagefield zip module. It suits only for drupal 6, but related issues has two forks for drupal 7.

If none of that doesnt suits your needs, you can do it with little trick:

* Create second file field for handle zip file upload;
* Take a look at unzip function in imagefield zip module;
* Implements something similar in `hook_node_save()`.

If you have module creation skill you can give your solition back to comunity ;)

# Answer
> 2 votes
I think your main goal is upload multiple image on a single upload and this goal you can achive via a module name 'Multiupload Imagefield Widget' https://drupal.org/project/multiupload\_imagefield\_widget.

This module provide a widget to select multiple images . For more info go through the module instructions.

# Answer
> 0 votes
Drupal 7 solution for this issue Pack & Upload.

Got to this post while searching for a solution.

---
Tags: media, files
---


title: hook_theme() to twig template of eform

text:
# Question
Title: hook_theme() to twig template of eform
I have an eform printing out some fields. I want to create a module to change layout of the eform using hook\_theme(). So, I have hook\_theme() in my mymodule.module file and mymodule-form.html.twig file in template folder. Since I'm testing it, I only want to print out one field. But it prints out all of the field which seems like hook\_theme() or twig is not working. Here's my code.

mymodule.module

```
<?php

/**
  * Implements hook_theme()
  */
function gq_theme($existing, $type, $theme, $path) {
 return array(
    'gq_form' => array(
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

/**
 * Prepares variables for the gq form template.
 *
 * Default template: gq-form.html.twig.
 */
function template_preprocess_gq_form(&$variables) {
  $variables['first_name_field'] = $form['field_first_name'];
}

```

mymodule.html.twig

```
{{ first_name_field }}

```

Also, I only have two files, mymodule.module, mymodule.info,yml, templates/mymodule-form.html.twig in module directory. Are there some necessary files?

# Answer
> -1 votes
Assuming that your template file is in a subfolder of your module folder (it looks like it's in templates), then your `hook_theme` needs to define the path. So it should look some thing like:

```
function gq_theme($existing, $type, $theme, $path) {
  return array(
    'gq_form' => array(
      'path' => $module_path . '/templates',
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

```

where `$module_path` is the path to your module.

---
Tags: 8, entities, theming
---


# Question
Title: Hide empty results in views caused by entity translation?
I have a view generated by Views module and Entity Translation module enabled with the option "**Enable language fallback**" disabled. This should mean that if the language is not available the post should not be shown.

So if I'm showing the site in *English* and a post is only available in *Italian* it should not be considered.

In fact, in the view the post are shown as they have all fields empty.

I tried to check, inside, every field of the view

* "**Hide if empty**"
* "**Hide rewriting if empty**"
* "**Count the number 0 as empty**" and even
* "**Remove whitespace**" in **rewrite result**.

In the "**Format**" part of the view I choose "**Grid**" and "**Fields**" and in fields setting checked "**Hide empty fields**"

I tried to apply path 35 and 40, no fortune.

```
  https://www.drupal.org/node/1452820

```

Any ideas?

# Answer
> 0 votes
THE SOLUTION: after three days, i got that if you use entity translation in the 'entity' mode, you get some option in Views filters. In my case, only the field "body" in nodes was translatable and there was an option, among filter

```
Body's language

```

Setting this to "Current user's language" does the trick.

I heard about an option Node Translation to be set this way, but you don't have that option if you check as translatable only some field and not the whole node.

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


# Question
Title: Drupal 6 to Drupal 7 migration redirect not working
I am migrating a D6 site to D7 and for some odd reason the redirect module is not creating the redirections. Any ideas? I am not getting any errors, warnings or notices

This is what I have:

```
class MyNewsMigration extends MyNodeMigration {
  public function __construct(array $arguments) {

    parent::__construct($arguments);

    $this->addFieldMapping('field_tag', '8')
         ->sourceMigration('Tag');
    $this->addFieldMapping('field_tag:source_type')->defaultValue('tid');
    $this->addFieldMapping('field_tag:create_term')->defaultValue(FALSE);
    $this->addFieldMapping('field_tag:ignore_case')->defaultValue(TRUE);

    // Redirect module to issue a 301 for each changing path
    $this->addFieldMapping('pathauto')->defaultValue(1);
    $this->addFieldMapping('migrate_redirects', 'path');

  }
}

```

**Note:** I added the migrate.redirect.inc using patch from here https://www.drupal.org/node/1116408

# Answer
> 2 votes
To use the Migrate D2D with the redirect feature listed here so that you only need to only have to do something like this:

```
$this->addFieldMapping('migrate_redirects', 'my_old_path');

```

**Do the following:**

> 1. In you class add something like this:

```
class MyNewsMigration extends MyNodeMigration {
  public function __construct(array $arguments) {

    parent::__construct($arguments);

    $this->addFieldMapping('migrate_redirects', 'my_old_path');

  }
}

```

> 2. Then what I was missing was the definition of the "my\_old\_path" in the prepareRow method.

```
public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  /*
    You can query the DB to get the alias or
    built it when you finish doing all the
    processing assign it.
  */

  $row->{'my_old_path'}  = 'PUT RESULT HERE';

}

```

> 3. Now you are ready to run your migration and rollbacks as need it.

**Note:** depending on your needs you can do at lot in the prepareRow to get the path of the old now or taxonomy term or any other entity.

# Answer
> 2 votes
I had a slightly different use case - changing aliases for users from /source/user-name to /author/user-name and creating redirects from the old alias the new one - but the steps are still the same.

First, I implemented a complete() method in my migrate class. This is called after the new entity (node, user, etc) has been created:

```
  /**
   * Implementation of MigrateDestinationEntity::complete() method.
   *
   * @param $entity
   * @param $row
   */
  function complete($account, $row) {
    // Create redirect from old Source alias that uses /source/
    // to new user profile alias.

    if (!redirect_load_by_source($row->dst)) {
      // First, get the alias for the user profile. We have to generate it separately
      // here because pathauto_create_alias() has already been run by the time the code
      // gets here, and we don't have access to that path.
      $new_alias = pathauto_create_alias('user', 'return', 'user/' . $account->uid, array('user' => $account));

      // Next, create the $redirect object and save it.
      $redirect = new stdClass();

      redirect_object_prepare(
        $redirect,
        array(
          'source' => $row->dst,
          'source_options' => array(),
          'redirect' => $new_alias,
          'redirect_options' => array(),
          'language' => LANGUAGE_NONE,
        )
      );
      redirect_save($redirect);
    }
  }

```

And then, to handle rollbacks (during development), I created a new class that overrides DrupalDestinationUser and implements a custom prepareRollback method:

```
class CNSUserDestination extends DrupalDestinationUser {
  // Add prepareRollback() method to this class.
  public function prepareRollback($uids) {
    parent::prepareRollback($uids);
    // Load all of the entities, since we need them for pathauto_create_alias().
    $users = entity_load('user', $uids);

    // Load pathauto.inc file.
    module_load_include('inc', 'pathauto', 'pathauto');

    foreach ($users as $uid => $user) {
      $redirects[] = pathauto_create_alias('user', 'return', 'user/' . $user->uid, array('user' => $user));
    }

    // Delete redirects for user profiles.
    db_delete('redirect')
      ->condition('redirect', $redirects)
      ->execute();
  }
}

```

It worked like a charm.

---
Tags: 7, migrations
---


# Question
Title: Modifying the properties and output of a select list when adding content with the admin Drupal 7
I have a type of content. Depending on the domain (I use Domain Access), I want to show a different content in a field which is a select list with reference to term. By several reasons, I do need to do this programmaticaly, to have full control. Also need to change the property: "required" of the field on-the-fly. What hook should I use, is there some example where I can look at? Thanks.

# Answer
> 0 votes
You need hook\_form\_FORM\_ID\_alter() or hook\_form\_alter() to modify the select list. Something like this should work:

```
// form_alter hook for "mycontent" content type.
function mymodule_form_mycontent_node_form_alter(&$form, &$form_state, $form_id) {
  switch ($_SERVER['SERVER_NAME']) {
    case 'domain1.example.com':
      // Remove term 2 from select list.
      unset($form['field_myfield']['und']['#options'][2]);
      break;
    case 'domain2.example.com':
      // Make term reference field required.
      $form['field_myfield']['und']['#required'] = TRUE;
      break;
  }
}

```

Bear in mind that you can't just add new terms to the select list since they will fail validation when the form is submitted. You can only choose which existing terms to include in the list.

What you could also do is create different fields for different groups of terms and unset whole fields depending on the domain so that only the relevant field is displayed.

---
Tags: 7, forms
---


# Question
Title: Views Calendar Pager Skips a Month Forward
In our calendar constructed by Views, the pager (also constructed by Views) skips a month when you hit next. *However,* the "previous" pager button only goes back one month. So it goes forward two months and back one...

Has anyone else experienced this? I've tried messing with the pager settings, but to no avail. This calendar was added to the site before my time, so I don't really know what to look for, but if you need more info, let me know and I'll try to find it!

# Answer
This is a bug in the Date module, fixed by this simple RTBC patch in comment #35

https://www.drupal.org/node/2375235#comment-10205617
> 2 votes

---
Tags: 7, views, paging, datetime
---


# Question
Title: Unable to save variable(s) from a custom form
I want to create a custom form with a few textfields and then use `variable_set` to save those textfields as variables.

I am not able to save the variable with the code below.

Question: I do not see the drupal message on hitting submit and when I go to the 'variables' table, I do not see the variable 'id\_event'. I have tried clearing all caches several times.

Code below is from \*.module file of my custom module "mymodule"

```
    function mymodule_menu() {

     $items['example_form'] = array(
         'title'        =>  'Progress Numbers',
         'description'  =>  'Form to enter variables that will be shown on Progress Update Block on Front Page',
         'page callback'    => 'drupal_get_form',
         'page arguments'   => array('example_form_form1'),
         'access arguments' => array('access administration menu'),

     );

     return $items;
 }

```

The callback function:

```
 function example_form_form1($form, &$form_state) {
  $form['id_event'] = array(
    '#type' => 'textfield',
    '#title' => t('Id Event'),
    '#required' => TRUE,
    '#default_value' => variable_get('id_event', 7),
  );

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

```

Submit Function

```
function example_form_form1_submit(&$form, &$form_state) {
  variable_set('id_event', $form_state['values']['id_event']);
  drupal_set_message($id_event);
}

```

# Answer
I have tried the solution and my result was excelent!

```
function felicitacion_mensaje_form($form, &$form_state) {
$form = array();
$form['felicitacion'] = array(
'#type' => 'textfield',
'#title' => t('Mensaje de felicitacion'),
'#default_value' => variable_get('congrat','Feliz cumpleaños !nombre te deseamos!.'),
'#description'   => t("Some description"),
);
return $form;
//   return system_settings_form($form);
}
function felicitacion_mensaje_form_submit(&$form, &$form_state) {
variable_set('congrat', $form_state['values']['felicitacion']);
$id_event = variable_get('congrat', '');
drupal_set_message($id_event);
}

```
> 0 votes

# Answer
Modify your example\_form\_form1\_submit function as follows

```
function example_form_form1_submit(&$form, &$form_state) {
  variable_set('id_event', $form_state['values']['id_event']);
  $id_event = variable_get('id_event', '');
  drupal_set_message($id_event);
}

```
> 4 votes

# Answer
Drupal's variable API allows for storage of persistent variables across separate requests.

If you want to set a Drupal variable, you need to use variable\_set().

Example:

```
$my_variable = 'very_important_value';          // Here we set a php variable

variable_set('my_variable_name', $my_variable); // Here we store the php variable
                                                // into a Drupal variable

```

If you want to retrieve the Drupal variable's value, you need to use variable\_get().

```
$saved_value = variable_get('my_variable_name', 'default_value'); // Get the value of the
                                                                  // Drupal variable. If
                                                                  // it does not exist, then
                                                                  // use the second argument

```

You are seeing the value stored correctly in the database because you are making use of **variable\_set()** correctly. However, when you are trying to retrieve the value, you need to be sure to call **variable\_get()** to retrieve the value and store it into a php variable for further usage.

Suggestion:

```
function example_form_form1_submit(&$form, &$form_state) {

  variable_set('id_event', $form_state['values']['id_event']); // Stores the value

  $saved_value = variable_get('id_event', 'Default');          // Retrieve the stored value.
                                                               // If it is not saved,
                                                               // $saved_value will be set
                                                               // to 'Default'.
  drupal_set_message($saved_value);
}

```
> 0 votes

# Answer
I resolved my problem using "system\_settings\_form($form);" since the solutions above did not work for me. (Will try later and if it works, will post any learnings here).

Following is what worked for me for reference:

My .module file:

```
function neil_menu() {

$items['admin/settings/neil'] = array(
    'title' => 'Node images',
    'description' => 'Control how to upload node images.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('neil_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'neil.admin.inc',
);
 return $items;

```

}

neil.admin.inc file:

```
function neil_admin_settings() {
   $form['progress_so_far'] = array(
'#type' => 'textfield',
'#title' => t('Progress So Far'),
'#default_value' => variable_get('progress_so_far', '0'),
'#maxlength' => 255,
);

return system_settings_form($form);
}

```
> 0 votes

---
Tags: 6, forms, configuration
---


# Question
Title: How to create a view using the References module?
I currently have **Two content types**:

Content Type 1: Videos

Content Type 2: Politicians

The main **Videos** content type references the **Politicians** content type as a way of "*tagging*" **Politicians** that can be seen in the videos. What I'd like to do on each Video node is create a view that shows all other **video nodes** that have the same Politicians referenced within them. For some reason I cant seem to get it to work. This is what I have so far.

* Create a view block with title field from the **Video id** like to see
* Create a relation to the **Politicians field** with a reverse
* Create a filter based on Content **NID**

For some reason when i go to a Video node I don't see any results at all. In fact I don't even see the video of the node I'm currently on.

If I change the relation to **Politicians** field *without the reverse* I only see the same node that I'm currently on. I should be seeing all videos with the same politician. What am I doing wrong here?

Keep in mind **I and not using and wont be switching to the Entity Reference module** since this is a large legacy project (I'm using the References module).

# Answer
You could achieve your goal by building two views

**The first** is the view you have build with relationship to politicians content type, **Add** new field gets the politician id tagged in that video

**The second** is a view that gets videos for politicians ids sent as a contextual filter

> that accepts multiple values by checking that checkbox as in the picture

**Install** that module views field view that enables you to embed a view inside another view as a field

**Add** new field in the first view that embed the second view and send the politicians ids as tokens to that view

Now you could achieve your goal
> 2 votes

# Answer
I think @Mhmdgomma is right, Views Field View module is useful here. Furthermore, it can be done with one view, albeit containing more than one display.

We will create one view with two displays. One serves as the video overview page, the other display is used to pull in the related videos.

Start with installing the Views Field View module to achieve your one-view goal.

**Create the view with the displays**

* Create a view "Videos" with a page display to display your video nodes. I named the page display "Overview Page".
* Create a block display for that view. I named the block display "Related Videos Block".

**Configure the Related Videos Block**

* Create a *Relationship* to field\_politicians in video nodes. Do not pick the reverse reference.
* Create a *Contextual Filter* with Content: NID, which uses the relationship field\_politicians and allow multiple values.
* Create another *Contextual Filter* with Content: NID, without a relationship, set it to exclude.

Test the block display by entering a NID from a politician node into the "Preview with contextual filters" field. You should see a list of videos tagged with this politicians NID.

**Configure your Overview Page**

* Create everything you like to display for your video nodes
* Create another field from *field\_politicians*, exclude it from display, use the Node ID Formatter, and display all values on one row with a comma separator and no additional space.
* Create a field from Content: NID and exclude it from display. This is the current video nodes node id.
* Create a field Global: View (from the Views Field View module), embed the current "Videos" view. As display, pick the "Related Videos Block".
* Configure the Contextual Filter by using the provided Replacement Patterns. My configuration ended up being "\[%field\_politicians\_1\]/\[!nid\]".

The first parameter is the rendered output from the politicians field, a comma separated list of politician node ids. The second parameter is the video nodes NID, used to remove the current video from the list of related videos.

Optionally add a Contextual Filter with Content: NID to display a single video with its related videos, or create another display for this detail view. If you enter a video node NID, you should see that single video with its related videos.
> 1 votes

# Answer
!\[Entity reference field clearly check the description A bridge to the Content entity that is referenced via field\_politicians \]

\[!\[enter image description here\]\[5\]\]\[5\]
> 0 votes

---
Tags: nodes, views
---


# Question
Title: AJAX append content via link on existing page
I am trying to recreate the functionality of the ajax\_link example in the Examples for Developers module. Here is the code I have so far:

In animal\_licence.module:

```
function animal_licence_menu() {
  $items['buy-animal-licence/animal'] = array(
    'page callback' => 'ajax_link_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'animal_licence.inc',
  );
  return $items;
}

```

In animal\_licence.inc

```
function ajax_link_response($type = 'ajax') {
      if ($type == 'ajax') {
        $output = t("This is some content delivered via AJAX");
        $commands = array();
        $commands[] = ajax_command_append('#content', $output);
        $page = array('#type' => 'ajax', '#commands' => $commands);
        ajax_deliver($page);
      }
      else {
        $output = t("This is some content delivered via a page load.");
        return $output;
      }
    }

```

The ajax link on-page is:

```
<a href="/buy-animal-licence/animal/nojs/" class="use-ajax ajax-processed">Click here</a>

```

When I visit /buy-animal-licence/animal/ and click the link I get the ajax spinner and it eventually times out with the following:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /buy-animal-licence/animal/ajax/
StatusText: OK
ResponseText:...

```

I'm not sure where to go from here, any suggestions would be much appreciated.

# Answer
> 0 votes
you need to add the nojs uri part in your menu item like:

```
$items['buy-animal-licence/animal/%ctools_js']

```

also, to make all more clear - your *type* argument in the callback should default to NULL

```
function ajax_link_response($type = NULL) {

```

---
Tags: ajax
---


title: Can I make a node reservable?

text:
# Question
Title: Can I make a node reservable?
Is it possible to make a node reservable (for users that do not have rights to edit/add content, or even anonymous users)? The node in this case is a "timeslot" for a service.

So there would be lots of nodes and each node could only be reserved once. At reservation time the person making the reservation should give his/her contact details. No payment or anything like that is made at this point.

I found the tutorial about Using webfom 3.x to reserve items/nodes in Drupal 7 (using the Webform module to "reserve a node"), but not sure if it is the best way (I am looking into it).

Or if anyone can just point me into the right direction, would be appreciated.

# Answer
> 0 votes
you can try the reservation API

---
Tags: nodes
---


# Question
Title: How can I hide Delete option from Operations in Admin - Drupal 7
I have a user with a **role** with restricted **permissions**. The content type is restricted to "Edit" only. However, the Operations Select box still displays `Delete`.

Well, as I can check several checkboxes of different kind of content, that is correct. But the problem is that the user can continue to the **next screen**, where she is asked if she wants to delete the item. IMHO, this message should never display, because the user has no deletion permissions, so it is quite confusing.

Can I override this screen in a simple way, so it will not listed those nodes which have no deletion permission?

# Answer
> 1 votes
There is always more than one way to skin a drupal, but they are rarely of equal merit.

It sounds like you have a page that is using Views Bulk Operations? If that is the case, find the view that generates the page and remove Delete from the operations selected.

If that is not the case, but you would like it to be, then see if the page in question is covered by Admin Views. Enable the module, find the related view, and modify it to suit you.

If that also is not the case, then fortunately for you this interaction is a form of some type. You can use a hook\_form\_ID\_alter() function to change the `$form['field']['#options']` array and remove Delete from it. If php is not your language, I am sure there is a javascript method of doing the same thing ... but I don't like that, feels like too weak of a solution. You can also have this same alter function check the `global $user; $user->roles` array so you retain the delete function for yourself.

If you want to let the user in question retain the Delete option, and just fail when they select that for a nodetype that is out of their permission range, then use drupal form validation. This lets the form stay as it is, but if your check of the node types selected does not match up with the current user's roles then you can just fail their action before it reaches the **next screen**.

There is always more than one way, they may not all work for you but one of them should. If none of these match your need then please update the question.

---
Tags: 7, users
---


title: How do I change XML tag names?

text:
# Question
Title: How do I change XML tag names?
I've created views as XML data document using Views Datasource which looks like:

```
<?xml version="1.0" encoding="utf-8"?>
<node><node>
<title>My title</title>
<field_feed_description>My description</field_feed_description>
</node></node>

```

How do I now change generated XML name tags?

For example I want to rename `field_feed_description` name into something else.

# Answer
> 2 votes
On the Views UI tick the **Create a label** checkbox and enter in your element name in the **Label** textfield. The value of **Label** will be used for the element name.

---
Tags: 7, views
---


# Question
Title: How to translate Global:PHP in the view?
I need translate view's global:php in the no results behaviour,Can i do that?

# Answer
Try by using your text inside **t()**.

`t('your text to display');` or `t($string);`
> 1 votes

---
Tags: views
---


# Question
Title: How can I add or delete the front page's blocks?
I am using Drupal 7, with the Stability theme. I'm trying to add featured products block to my home page but couldn't. I am able to add them to other pages, though.

How can I add or delete the front page's blocks?

# Answer
1)First of all create a tpl file "page--front.tpl.php".

2)Suppose you want to place block in sidebar second region use devel module to see the content of your page.

```
<?php dpm($page);
dpm($page['sidebar_second']);?>

```

3) Write following code after executing above code:

```
<?php print render($page['sidebar_second']['id_of_your_block']) ?>

```

**for deleting/hide the front page block**

1)Go to edit page at block/region setting/none
> 2 votes

# Answer
You can assign condition `<front>` on each block which you want to display in home page.
> 0 votes

---
Tags: blocks
---


title: How to add breadcrumbs for view page?

text:
# Question
Title: How to add breadcrumbs for view page?
I have added content type breadcrumbs, but I don't know how to add view's breadcrumbs

# Answer
You can achieve your requirement by installing any of the below modules:

1. Custom Breadcrumbs

> Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.

2. Path Breadcrumbs

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

You can also follow this link.
> 2 votes

# Answer
You can also make your custom breadcrumbs in `template.php` file as your requirement.
> 0 votes

---
Tags: breadcrumbs
---


title: Sort contents in content list

text:
# Question
Title: Sort contents in content list
I need to sort contents in the same manner as blocks are sorting in the block list. In the block list we can drag an drop blocks to place the them up and down, same functionality I needed for content list for contents.

# Answer
> 1 votes
To add *Sort* functionality using *Drag and Drop* into `admin/content` section, you need to play with administration views using Admin Views module. Note that Weight module is also necessary for this. After installing and enabling these module you can *edit* administrative views under `admin/views` section.

But if you simply want to add your new views of specific contents then there is already *Weight* view available under `admin/views` section. You can check this view to see the working and functionality using *Drag and Drop*.

Note: Weight module must be enabled for contents to be sorted.

---
Tags: nodes
---


# Question
Title: How to change core search result snippet?
I want to change core search result snippet. I tried with preprocessor `theme_preprocess_search_result(&$vars)` but in `$vars['result']['node']` there coming basic fields values and rendered content array. In my node, content is with paragraph bundles and field collections. I want to display one of my bundle value in search snippet.

`$vars['result']['node']` values coming in array key 'rendered'

```
stdClass Object
(
    [vid] => 1039
    [uid] => 1
    [title] => What are the cut off times for funds transfers to an external bank?
    [log] =>
    [status] => 1
    [comment] => 0
    [promote] => 1
    [sticky] => 0
    [nid] => 235
    [type] => support
    [language] => und
    [created] => 1444988988
    [changed] => 1446531922
    [tnid] => 0
    [translate] => 0
    [revision_timestamp] => 1446531922
    [revision_uid] => 1
    [field_support_type_ref] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [tid] => 16
                            [taxonomy_term] => stdClass Object
                                (
                                    [tid] => 16
                                    [vid] => 4
                                    [name] => Internet Banking
                                    [description] =>
                                    [format] => filtered_html
                                    [weight] => 0
                                    [vocabulary_machine_name] => support_type
                                )

                        )

                )

        )

    [field_paragraph] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1102
                            [revision_id] => 7916
                        )

                )

        )

    [name] => orangedigital
    [picture] => 0
    [data] => b:0;
    [workbench_access] => Array
        (
            [28] => 28
        )

    [entity_view_prepared] => 1
    [rendered] =>
Type:
Internet Banking
Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

)

```

# Answer
> 0 votes
You could build your own search result .tpl file inside your theme and take control over what displayed and the markup by creating a file named like **search-results--\[searchType\].tpl.php** After that you have to clear the cache in order to be recognized in theme registry

In your case you could limit the number of words displayed or divide based on empty line which mean a pragraph.

Take a look at D7 theme suggestions

---
Tags: nodes, search, entities
---


# Question
Title: Entity reference form in views below node
I have a machine content type (clients have machines) and i would like to display all their machines in a view (done) and have a webform/entity form display below the node so that the client can submit issues to the machine. Therefore my end result should look something like this;

Johnny's machines;

**Machine 1 - Model Number 234567**

Form exposed

Sumbit form button

**Machine 2 - Model Number 876543**

Form exposed

Sumbit form

Etc.

Any ideas how I might be able to pull this off?

Thanks

# Answer
> 1 votes
Ok. After suffering on many different options to get this integrated, I eventually decided to use a workaround. I used the standard node comment form and created a view to display teaser nodes. It works. It's not necessarily the right option but it might help someone looking for something similar.

Thanks for your help guys.

---
Tags: views, forms, entities
---


# Question
Title: Alternatives to creating a large number of one-use, page-specific blocks?
I'm working on a relatively large site using Drupal 7, and find myself creating a large number of one-use, page-specific blocks in order to embed custom content on some of the pages in this site. Is this the best way to go about doing this, or are there other alternatives?

I've used the Views module for a few things, but it is not always able to meet my needs.

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

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

Combined with the options available for granting **Bean permissions**, it should give you a lot of flexibility about how exactly you want to use this (great) module.

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

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

# A rising star ...

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

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

I'm not aware (yet) of any other contributed module that "only" started in D7, and made it right into core in the very next major Drupal release ... If there are other modules with a similar track record, I doubt there would be many of them ...
> 9 votes

# Answer
If the content of that block is related to the content of that page/node, you could add an extra field to your content type(s), then use the CCK Blocks, Field as Block or Region View Modes module to display that field in another region of your theme. I think that Views is too heavy in this case.
> 5 votes

# Answer
You could add a field called "block" to your content types, then use the Views module to display the block field.
> 4 votes

# Answer
Just throwing my 2 cents in there.

I like to use the Ctools Content Panes module for some bits of custom content.

Then if this content is to be shown on certain page(s), use a module such as Ctools Field or Pane Field to create a multiple value field on a node to reference the custom pane(s) as needed on nodes.
> 3 votes

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


# Question
Title: Iterate through all children of an element
I have a Drupal code below:

```
function myid_create_template($form, &$form_state){
    $form['myid_templates_editor']['#access'] = TRUE;
    foreach (element_children($form['myid_templates_editor']) as $child1)   {
        $form['myid_templates_editor'][$child1]['#access'] = TRUE;

    }
    return $form;
}

```

This code iterate to the first child only of an element, but not the child with degree 2 or more. How will I iterate it to all child/grandchild of the element?

# Answer
A simple recursive function will do the trick:

```
function allow_access(&$root_element) {
  $root_element['#access'] = TRUE;
  foreach (element_children($root_element) as $key) {
    allow_access($root_element[$key]);
  }
}
allow_access($form);

```
> 4 votes

# Answer
I believe you will have to manually add support for 2nd/3rd/etc. levels.

Didn't test the code, but this should point you in the right direction:

```
function myid_create_template($form, &$form_state){
  $form['myid_templates_editor']['#access'] = TRUE;
  foreach (element_children($form['myid_templates_editor']) as $child1) {
    // Check if this element is a parent of another element.
    if (count(element_children($form['myid_templates_editor'][$child1]))) {
      foreach (element_children($form['myid_templates_editor']) as $child2) {
        if (count(element_children($form['myid_templates_editor'][$child1][$child2]))) {
          foreach (element_children($form['myid_templates_editor']) as $child3) {
            // You can continue to search for more levels here, if necessary.
          }
        }
        else {
          $form['myid_templates_editor'][$child1][$child2][$child3]['#access'] = TRUE;
        }
      }
    }
    // This is just a regular element.
    else {
      $form['myid_templates_editor'][$child1]['#access'] = TRUE;
    }
  }

  return $form;
}

```
> -1 votes

---
Tags: 7, forms
---


title: HybridAuth registration

text:
# Question
Title: HybridAuth registration
I am using HybridAuth as my login module and I want that user have to register with *email* and *password*. How can I do that ?

In the current process, user gets mail only and then sets the password instead of doing it on the registration form.

Thanks for the help

# Answer
> 1 votes
User Registration Password Module will do the job for you;)

> By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.

---
Tags: users, authentication-authorization
---


# Question
Title: How to make a raw SQL query to get the node/node_votes pairs?
I'm not familiar with drupal. Using raw SQL, I'd like to extract votes given to each node, but I wonder how `vote_rating` is related to `node`?

I see that the votes are stored in `field_vote_rating` of this table:

```
mysql> DESCRIBE `field_data_field_vote`;
+-------------------+------------------+------+-----+---------+-------+
| Field             | Type             | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+-------+
| entity_type       | varchar(128)     | NO   | PRI |         |       |
| bundle            | varchar(128)     | NO   | MUL |         |       |
| deleted           | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id         | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id       | int(10) unsigned | YES  | MUL | NULL    |       |
| language          | varchar(32)      | NO   | PRI |         |       |
| delta             | int(10) unsigned | NO   | PRI | NULL    |       |
| field_vote_rating | int(10) unsigned | YES  |     | NULL    |       |
| field_vote_target | int(10) unsigned | YES  |     | NULL    |       |
+-------------------+------------------+------+-----+---------+-------+

```

I'm aware of Drupal's database structure schema, which looks like so:

But I cannot figure out how to make a query to connect them.

**My question**: How to make a raw SQL query to get the node/node\_votes pairs?

Any suggestions?

# Answer
Try this query:

```
SELECT field_vote_rating from field_data_field_vote
WHERE entity_type = 'node' AND entity_id = $nid;

```

You can use the database api to create SQL Queries
> 1 votes

---
Tags: 7, database
---


# Question
Title: Allow users to manage other users but all content is site-wide not based on group
I am building a website that requires a UserA to be able create UserB, UserC, etc...and have whatever content they create to be managed by UserA (edit, delete, update, etc...)

However I don't think role based permissions are the way to go. I only want UserA to be able to manage those subusers, not assign them a "manager" role where another manager (say, UserX) has created UserZ and if both UserA and UserX are "managers", UserX can change UserB's content.

It looks like the Subuser module is the way to go, however, it is hardly updated and seems to be incomplete. Is there another module or set of modules that can do the same thing?

Organic groups also gives me the access control I need, however, the content that all users should be site-wide and not actually tied to any group. I don't need a container to keep nodes, just the access control for users to manage other users within their own sphere.

Does any one have any other way in which this can be accomplished?

# Answer
> 1 votes
This could be convoluted but this is how I would do it.

To start with, I would use rules and have either entity reference fields or integer fields for the users and content.

With rules, when the new users are created, USER A is referenced (or their UID in the integer field) using rules.

Then, using rules, every node the new users create have this entity reference (or UID integer) applied to it automatically.

For editing, I would give USER A's role editing permissions and then write a custom module that redirects users from the node edit page if the node's field doesn't match the user's field. (And allow certain roles like admin and also allow the node author).

One benefit of this is that you could create a view for USERS A that only shows nodes they can edit and provide a link per node. And I'd use an intreger field as a preference.

Edit: You could do all of this without any extant contrib modules or rules and just custom code. But I always have rules so it's an obvious go to for me.

# Answer
> 0 votes
I have not used it myself. But I attended a DrupalCON where this module was presented for HigherEd usage and the maintainer swore by its usage. This is similar, but different from say the Workbench Suite of modules.

Give Monster Menus a try out in a sandbox or something and see if it meets your needs, or as detailed in the project page try out the demonstration site provided by the institution that created this project.

# Answer
> 0 votes
Have a look at the (fairly new) alternative for the Organic groups module, which is the Group module. Some more details about it (from its project page):

> **Organic Groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
>
> **Groups** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" OG module.

---
Tags: users, organic-groups
---


# Question
Title: Contextual Links not appearing for blocks
I have contextual links enabled. I've added

```
print render($action_links);

```

to both my page template and every block template I have but it's always blank. Out of desperation, I set permissions to allow even anonymous users. Still nothing.

I read that Devel might mess with contextual links but I don't have it enabled.

EDIT:

```
<?php print render($title_suffix); ?>
<?php print render($action_links); ?>
<div style="border: 1px solid #044faa">
   <div style="background: #044faa; color: #fff; padding: 5px 15px; font-size: 16px"><strong><?php echo $block->title; ?></strong></div>

   <div style="padding: 5px 0; text-align: center"><?php
   echo preg_replace("/(<)[\/]?[p](>)/is", "", $content);
   ?></div>
</div>

```

# Answer
> 2 votes
Contextual links are printed with:

```
print render($title_suffix);

```

I Have checked it on `block.tpl.php`

See: Working with contextual links

I would suggest not to put inline css in your template. Here working code:

```
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix" <?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <div <?php print $title_attributes; ?> style="background: #044faa; color: #fff; padding: 5px 15px; font-size: 16px">
     <strong><?php print $title; ?></strong>
   </div>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <div style="border: 1px solid #044faa">
    <div style="padding: 5px 0; text-align: center">
      <?php print preg_replace("/(<)[\/]?[p](>)/is", "", $content); ?>
  </div>
</div>

```

# Answer
> 0 votes
I wish I could add this as a comment but I don't have enough reputation.

In your Chrome or Firefox tools, delete any custom css you've added that could cause them to not show.

I've managed to make this mistake before and also helped someone on /r/drupal who had done the same.

---
Tags: 7, navigation
---


# Question
Title: D7 to D8 users migration processes 0 items
I am working on my first migration from D7 to D8. I am trying to keep it very simple and start with users. I have created a custom module migrate\_custom, created my definition at config/install/migrate.migration.d7cafe\_users.yml:

```
id: d7cafe_users
label: User accounts
migration_tags:
  - Drupal 7
source:
  plugin: d7cafe_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  timezone: timezone
  langcode: language
  init: init

```

Then I have my source plugin at src/plugin/migrate/source/User.php:

```
<?php
/**
 * @file
 * Contains \Drupal\migrate_custom\Plugin\migrate\source\User.
 */

namespace Drupal\migrate_custom\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Extract users from Drupal 7 database.
 *
 * @MigrateSource(
 *   id = "d7cafe_users"
 * )
 */
class User extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('dcf_users', 'dcf_u')
      ->fields('dcf_u', ['uid', 'status', 'created','access', 'login',    'name',
        'pass', 'mail', 'init', 'language']);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'uid' => $this->t('Account ID'),
      'status' => $this->t('Blocked/Allowed'),
      'created' => $this->t('Registered date'),
      'access' => $this->t('Time of last access'),
      'login' => $this->t('Time of last login'),
      'name' => $this->t('Account name (for login)'),
      'pass' => $this->t('Account password (raw)'),
      'mail' => $this->t('Account email'),
      'init' => $this->t('init'),
      'language' => $this->t('language'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'dcf_u',
      ],
    ];
  }

}
?>

```

And finally I have a manifest.yml file containing:

```
- d7cafe_users

```

I run the migration with:

```
drush migrate-manifest manifest.yml --legacy-db-url=mysql://root:root@localhost/d7cafe

```

But all I get on command line is:

```
Running d7cafe_users                                                                                [ok]
Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'd7cafe_users'

```

I don't think I'm far off, as I could see running it and importing the 4 users from the legacy db, but did a bit of fiddling on the definition file and now I can't get it back to importing records. What is wrong with my code?

# Answer
> 1 votes
Ok I tried it on a new site install and the code works and migrates users perfectly. All I can think of is that db got corrupted after running migration and rolling back a number of times.

---
Tags: 8, migrations
---


# Question
Title: Send email after 100 webform submissions
I'd like to be able to send an email to the nth person (or every n people) that submit a specific webform. I've tried utilizing rules for this, but I can't seem to expose webform submission data to rules (using submission id). Any thoughts on how this could work through rules? Any suggestions for alternatives?

# Answer
Have you tried using Webform Rules ?

This should expose webform results to rules, then create a new rule with conditions "if submission ID is 100, 200 etc" then... action: Send email.

You would either need a way to find the nth of 100, or depending on how many submissions you are expecting, just check against a comma separated list, eg "100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200" etc
> 1 votes

# Answer
in hook\_webform\_submission() there is a variable `$submission`. So all you need to do is to implement this hook in your custom module and check for `$submission->sid` accordingly to your wisches.

If condition matches: drupal\_mail()
> 1 votes

# Answer
Use rules to add +1 to an integer field on a solitary node when a web form is submitted. Have another rule that fires when a webform is submitted and that integer field is equal to 100.

Use that rule to send an email and reset the integer to 0.
> 0 votes

---
Tags: rules, webforms
---


# Question
Title: Creation of products completely except the admin
I am using Drupal Commerce and I need to let my users to create products without the product display.

I thus adjusted the permissions, but when a user creates a product, **1/** the url is the one of the admin `admin/commerce/products/add/1` and **2/** once the created product, the user has a access denied.

My question: how to let the users to create products completely except the admin (modification of the url etc.) ?

# Answer
One option is to use a custom node bundle along with Rules. Allow the users to create the new node type. Then, when the node is being saved, use Rules (or a custom module) to take the values that were entered into the node form and carry them over to a product and save it.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How do I change the type of a field attached to a content entity?
So I've been banging my head against this for a few hours, and I'm probably going to give up and just uninstall/reinstall the module (and update the View that relies on the old `entity_reference` field and thus makes that fail).

A bit about my use case: I originally created some `entity_reference` fields pointing at files. I then learned that the File module will only automatically track file usage on `file` fields. I want to convert my fields to `file` fields and preserve the data. This seems impossible, however.

Consider this update code:

```
/**
 * Use file fields instead of entity_reference fields for referring to files.
 */
function fillpdf_update_8103() {
  $edum = \Drupal::entityDefinitionUpdateManager();
  $em = \Drupal::entityManager();

  $form_file_def = BaseFieldDefinition::create('file')
    ->setLabel(t('The associated managed file.'))
    ->setDescription(t('The associated managed file.'))
    ->setName('file')
    ->setProvider('fillpdf_form')
    ->setTargetBundle(NULL)
    ->setTargetEntityTypeId('fillpdf_form');

  $fc_file_def = BaseFieldDefinition::create('file')
    ->setLabel(t('The associated managed file.'))
    ->setDescription(t('The associated managed file.'))
    ->setName('file')
    ->setProvider('fillpdf_file_context')
    ->setTargetBundle(NULL)
    ->setTargetEntityTypeId('fillpdf_file_context');

  // Save existing fillpdf_form data.
  $form_files = [];
  $forms = $em->getStorage('fillpdf_form')->loadMultiple();
  foreach ($forms as $form) {
    $form_files[$form->id()] = $form->file->target_id;
    $form->file = NULL;
    $form->save();
  }

  // Save existing fillpdf_file_context data.
  $fc_files = [];
  $fcs = $em->getStorage('fillpdf_file_context')->loadMultiple();
  foreach ($fcs as $fc) {
    $fc_files[$fc->id()] = $fc->file->target_id;
    $fc->file = NULL;
    $fc->save();
  }

  // Now install the new field definitions.
  $edum->updateFieldStorageDefinition($form_file_def);
  $edum->updateFieldStorageDefinition($fc_file_def);

  foreach ($form_files as $entity_id => $fillpdf_form_file) {
    /** @var ContentEntityInterface $entity */
    $entity = $em->getStorage('fillpdf_form')->load($entity_id);
    $entity->file->target_id = $fillpdf_form_file;
    $entity->save();

    // We want postSave() hooks to run so that file usage gets recorded.
    // @see ContentEntityStorageBase::invokeFieldMethod().
    $result = [];
    // So $update = FALSE gets passed to the handler.
    $args = [FALSE];
    $method = 'postSave';
    foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
      $translation = $entity->getTranslation($langcode);
      // For non translatable fields, there is only one field object instance
      // across all translations and it has as parent entity the entity in the
      // default entity translation. Therefore field methods on non translatable
      // fields should be invoked only on the default entity translation.
      $fields = $translation->isDefaultTranslation() ? $translation->getFields() : $translation->getTranslatableFields();
      foreach ($fields as $name => $items) {
        if ($name === 'file') {
          // call_user_func_array() is way slower than a direct call so we avoid
          // using it if have no parameters.
          $result[$langcode][$name] = $args ? call_user_func_array([
            $items,
            $method,
          ], $args) : $items->{$method}();
        }
      }
    }
  }

  foreach ($fc_files as $entity_id => $ffcf) {
    /** @var ContentEntityInterface $entity */
    $entity = $em->getStorage('fillpdf_file_context')->load($entity_id);
    $entity->file->target_id = $ffcf;
    $entity->save();

    // We want postSave() hooks to run so that file usage gets recorded.
    // @see ContentEntityStorageBase::invokeFieldMethod().
    $result = [];
    // So $update = FALSE gets passed to the handler.
    $args = [FALSE];
    $method = 'postSave';
    foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
      $translation = $entity->getTranslation($langcode);
      // For non translatable fields, there is only one field object instance
      // across all translations and it has as parent entity the entity in the
      // default entity translation. Therefore field methods on non translatable
      // fields should be invoked only on the default entity translation.
      $fields = $translation->isDefaultTranslation() ? $translation->getFields() : $translation->getTranslatableFields();
      foreach ($fields as $name => $items) {
        if ($name === 'file') {
          // call_user_func_array() is way slower than a direct call so we avoid
          // using it if have no parameters.
          $result[$langcode][$name] = $args ? call_user_func_array([
            $items,
            $method,
          ], $args) : $items->{$method}();
        }
      }
    }
  }
}

```

Don't worry too much about the hack to run `$field->postSave()`. That actually works fine.

The main issue is that if I update the `FieldStorageDefinition` for `file` BEFORE I run the update, it fails because then the calls to `loadMultiple()` try to use the new schema.

If I leave the code alone (a.k.a. don't change the schema), it runs alright, but it re-saves the data using the old field type, and thus the `postSave` hooks don't actually run...at least not the one I want, `FileFieldItemList::postSave()`.

I don't find it surprising that the change record uses the database to save the data to be re-inserted; that's probably deliberate, since otherwise you get the aforementioned schema errors. But doing that is in no way portable. I mean, what if they aren't using SQL storage?

The ideal solution in my head would be to be able to get the storage manager to retrieve the entity based on the old definition before I update the schema and the new definition after updating it. However, the logic that retrieves the old schema is tied up in protected functions, e.g. `SqlContentEntityStorage::doLoadMultiple()`.

Supporting information: this is the error I get when I try to run the update after having updated the schemas in-module:

```
fillpdf module

Update #8103

- Failed: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.file__target_id' in 'field list': SELECT base.fid AS fid, base.uuid AS uuid, base.file__target_id AS file__target_id, base.file__display AS file__display, base.file__description AS file__description, base.admin_title AS admin_title, base.title AS title, base.default_entity_type AS default_entity_type, base.default_entity_id AS default_entity_id, base.destination_path AS destination_path, base.scheme AS scheme, base.destination_redirect AS destination_redirect FROM {fillpdf_forms} base; Array ( ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->getFromStorage() (line 429 of /var/www/site/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

```

Is my only option to create a new field, move the data, and just deprecate the old field? I don't want to do that because I don't think I'll *ever* be able to remove it while schema storage keeps working like this, lest a future update fail when trying to load entities.

# Answer
Talking with chx and catch on IRC, I learned that `hook_update_N()` is an SQL-only world, pretty much precisely for the reason I encountered. I couldn't find any issues *clearly* stating this, but `hook_update_N()` itself does say this:

> Be careful about API functions and especially CRUD operations that you use in your update function. If they invoke hooks or use services, they may not behave as expected, and it may actually not be appropriate to use the normal API functions that invoke all the hooks, use the database schema, and/or use services in an update function -- you may need to switch to using a more direct method (database query, etc.).
> In particular, loading, saving, or performing any other CRUD operation on an entity is never safe to do (they always involve hooks and services).

So, with that in mind, my finished update hook became the following.

```
<?php
/**
 * Use file fields instead of entity_reference fields for referring to files.
 */
function fillpdf_update_8103() {
  $edum = \Drupal::entityDefinitionUpdateManager();
  $em = \Drupal::entityManager();
  $db = \Drupal::database();

  $form_file_def = BaseFieldDefinition::create('file')
    ->setLabel(t('The associated managed file.'))
    ->setDescription(t('The associated managed file.'))
    ->setName('file')
    ->setProvider('fillpdf_form')
    ->setTargetBundle(NULL)
    ->setTargetEntityTypeId('fillpdf_form');

  $fc_file_def = BaseFieldDefinition::create('file')
    ->setLabel(t('The associated managed file.'))
    ->setDescription(t('The associated managed file.'))
    ->setName('file')
    ->setProvider('fillpdf_file_context')
    ->setTargetBundle(NULL)
    ->setTargetEntityTypeId('fillpdf_file_context');

  // Save existing data.
  $form_files = $db->select('fillpdf_forms', 'ff')
    ->fields('ff', ['fid', 'file'])
    ->execute()
    ->fetchAllKeyed();

  $fc_files = $db->select('fillpdf_file_context', 'fc')
    ->fields('fc', ['id', 'file'])
    ->execute()
    ->fetchAllKeyed();

  // Remove data from the storage.
  $db->update('fillpdf_forms')
    ->fields(['file' => NULL])
    ->execute();

  $db->update('fillpdf_file_context')
    ->fields(['file' => NULL])
    ->execute();

  // Now install the new field definitions.
  $edum->updateFieldStorageDefinition($form_file_def);
  $edum->updateFieldStorageDefinition($fc_file_def);

  foreach ($form_files as $entity_id => $fillpdf_form_file) {
    /** @var ContentEntityInterface $entity */
    $entity = $em->getStorage('fillpdf_form')->load($entity_id);
    $entity->file->target_id = $fillpdf_form_file;
    $entity->save();
  }

  foreach ($fc_files as $entity_id => $ffcf) {
    /** @var ContentEntityInterface $entity */
    $entity = $em->getStorage('fillpdf_file_context')->load($entity_id);
    $entity->file->target_id = $ffcf;
    $entity->save();
  }
}
?>

```

Note that I'm kind of ignoring the thing about not using CRUD, and I use it *after* the schema has been updated. I didn't want to deal with the kind of `INSERT` query I saw on https://www.drupal.org/node/2554097#change-field-schema, and it worked just fine. Your mileage may vary there if dealing with more complex entities, but it worked great for me.
> 1 votes

---
Tags: entities, 8, database, updating
---


# Question
Title: return message after hook_form_submit without Ajax
This might seem trivial to many of you, but how can you return a form with a customized message (according to the fields) in a hook\_form\_submit ? Like :

```
   <?php
/**
 * @file
 * Pages and display.
 */
/**
 * Constantes
 */

/**
 * *************** Formulaire *******************
 */

/**
 *
 * Implements a standard form.
 */
function MY_MODULE_form($form, $form_state, $arg) {
  $form = array ();
  $form ['#type'] = 'type';
  /**
   * All the form elements
   */

  // soumission du formulaire
  $form ['submit'] = array (
      '#type' => 'submit',
      '#value' => t ( 'Lancer la simulation' ),
      '#weight' => 10000
  );

  $form ['simul_message_retour'] = array (
      '#prefix' => '<div id="result-div">',
      '#suffix' => '</div>',
      '#markup' => isset($form_state ['input']['simul_message_retour']['#markup'])?$form_state ['input']['simul_message_retour']['#markup']:'',
      '#weight' => $form ['submit'] ['#weight'] + 1
  );
  if (!empty($form_state['response_module'])) {
    $form['simul_message_retour']['#markup'] = convert_data_to_markup($form_state['response_module']);
  }
  return $form;
}

/**
 * Validation Works
 */
function MY_MODULE_form_validate($form, &$form_state) {

  $form_numbers = array (
    //Some form fields
  );
  // operations of validation
}

/**
 *
 * @param unknown $form_element
 * @param unknown $form_state
 * @return Ambigous <multitype:, unknown>
 */
function MY_MODULE_format_simul_datenaissance($form_element, &$form_state) {
  //checking some of the form construction
}
/**
 * Function of submit
 *
 * @param unknown $form
 * @param unknown $form_state
 */
function MY_MODULE_form_submit($form, $form_state) {
  $form_state['response_module'] = project_call_WS($form, $form_state);
  $form_state['rebuild'] = TRUE;
}

/**
 * function processing the call to the WS
 * @param unknown $form
 * @param unknown $form_state
 */
 function project_call_WS($form, $form_state){
  // checking if there are no errors
  if (form_get_errors ())
    return '';

  //Operations on the form
  $url = implode ( '/', $url_array );
  $parameters = 'URLTOWEBSERVICE';
  // HERE IS CALLED THE WEBSERVICE(the function call_ws is working well)
  $call = call_ws ($parameters );

  $build = array (
      //ETC
  );
 //Operations on the $builds array
  return $build;
}

```

Thanks a lot

# Answer
> 4 votes
The form API and message system are not the same thing, even though there are helper functions in the FAPI to produce messages - you don't return a form with a message, you set a message when it's appropriate to do so. That might be when the form is being built, when it's being validated, after it's been submitted, and so on.

Generally speaking, if you're setting a validation error, use `form_set_error()` in a validate callback:

```
function MYMODULE_form_validate(&$form, &$form_state) {
  if (something_wrong_with($form_state['values']['foo'])) {
    form_set_error('foo', 'Run away, bad things happening');
  }
}

```

If you want a confirmation message on form submission, use `drupal_set_message()` in a submit callback:

```
function MYMODULE_form_submit($form, &$form_state) {
  if ($form_state['values']['foo'] == 'bar') {
    drupal_set_message(t('You chose: %foo', array('%foo' => $form_state['values']['foo'])));
  }
}

```

There's no point returning anything from a form submit callback - it will be ignored. If you want to rebuild the same form again after submission, use:

```
$form_state['rebuild'] = TRUE;

```

It may or may not be necessary depending on your final goal.

---
Tags: forms
---


title: Re-use fields in a content type

text:
# Question
Title: Re-use fields in a content type
I have a content type with 4 different sections to it. At the bottom of each section, there are 2 "Call to action" links.

These links all point to the same 2 urls. I'd like to be able to set up 2 fields of the type "link" and then re-use those fields 4 times, instead of having to set up 8 links.

Is this possible?

Is there a better way of doing it ?

# Answer
> 2 votes
If these sections are text or similar, you can create field collections that enclose other fields.

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

---
Tags: navigation
---


title: Filtering a table using views

text:
# Question
Title: Filtering a table using views
I am new to drupal and I already created a table using view. I also applied exposed content filtering and I got the following screen

Now I want to **show all the category and author are listed in a drop down** and i want to select one from that. Also how can I display all the content of table before filter?

Thanks in advance.

# Answer
> 0 votes
Any time you need a dynamic dropdown view filter, you need a Taxonomy vocabulary (Drupal core).

In your example, you need first to create a vocabulary named Authors (no need to enter terms).

Secondly, you add a field Author, type Term reference, related to your vocabulary Authors, in the content type displayed in your View.

Choose autocomplete widget to allow term creation when a content is created.

Now, if you create a new content and enter a value in the field Author, it will add each new term or suggest existing ones.

Finally, in your View, you add an exposed filter related to your field Author, and you can select dropdown list. All authors entered during content creation will appear in the list.

If you need to enter manually authors, you just have to get to your Vocabulary Authors and add terms. They will also appear in your dropdown filter.

Hope this helps.

# Answer
> 0 votes
You can change filter view settings. goto admin/structure/views and edit your views and follow the screenshots

# Answer
> 0 votes
You can do it when you select add filter checked dropdown box

For more details dynamically-filter-content-drupal-view

---
Tags: views
---