# Question
Title: What arguments does a _custom_access callback exactly receive?
The example given in Access checking on routes for using `_custom_access` is the following.

### example.routing.yml

```
example:
  path: '/example'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _custom_access:  '\Drupal\example\Controller\ExampleController::access'

```

### ExampleController.php

```
/**
 * @file
 * Contains \Drupal\example\Controller\ExamleController.
 */

namespace Drupal\example\Controller;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;

    /**
     * Builds an example page.
     */
    class ExampleController {

      /**
       * Checks access for a specific request.
       *
       * @param \Drupal\Core\Session\AccountInterface $account
       *   Run access checks for this account.
       */
      public function access(AccountInterface $account) {
        // Check permissions and combine that with any custom access checking needed. Pass forward
        // parameters from the route and/or request as needed.
        return $account->hasPermission('do example things') && $this->someOtherCustomCondition();
      }
    }

```

From this example, I get the first parameter of such callbacks is `$account` as I would expect, since the access is normally checked against an account.

Looking at code used from Drupal core modules, I find the following.

### toolbar.routing.yml

```
toolbar.subtrees:
  path: '/toolbar/subtrees/{hash}'
  defaults:
    _controller: '\Drupal\toolbar\Controller\ToolbarController::subtreesAjax'
  options:
    _theme: ajax_base_page
  requirements:
    _custom_access: '\Drupal\toolbar\Controller\ToolbarController::checkSubTreeAccess'

```

### ToolbarController.php

```
public function checkSubTreeAccess($hash) {
  $expected_hash = _toolbar_get_subtrees_hash() [0];
  return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && Crypt::hashEquals($expected_hash, $hash))->cachePerPermissions();
}

```

In this case, `$account` is not passed as parameter, but the controller gets it from the dependency injection container, which leaves me puzzled.

I also checked at the class implementing the access service used for `_custom_access`, but I just see the following code, which doesn't make things clearer.

```
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
  $callable = $this->controllerResolver->getControllerFromDefinition($route->getRequirement('_custom_access'));
  $arguments_resolver = $this->argumentsResolverFactory->getArgumentsResolver($route_match, $account);
  $arguments = $arguments_resolver->getArguments($callable);

  return call_user_func_array($callable, $arguments);
}

```

(See `CustomAccessCheck::access()`.)

If then I watch at `ArgumentsResolver::getArguments()` (the method called with `$arguments_resolver->getArguments($callable)` in the previous method), I see the following code.

```
public function getArguments(callable $callable) {
  $arguments = array();
  foreach ($this->getReflector($callable)->getParameters() as $parameter) {
    $arguments[] = $this->getArgument($parameter);
  }
  return $arguments;
}

```

`$account` seems ignored.

What arguments does a \_custom\_access callback exactly receive?

# Answer
See `\Drupal\Core\Access\AccessArgumentsResolverFactory::getArgumentsResolver()` which is called by your snippet above to create the argument resolver. I think that covers it pretty well.

It gets all raw parameters, all possibly upcasted parameters, plus request, route match, and account. The access callback receives the arguments from that list, based on the names and type hints.

So account isn't ignored.

That logic is the same as for any other access check, the whole point of \_custom\_access is to have an easy way to do a one-off access check without having to go through the additional steps of a service that's defined with a special tag.
> 12 votes

---
Tags: routes
---


# Question
Title: show image field twice with different image style
In my content type, I am using an image field.

But in display, I want to show this image twice. Once with large style, and another with medium.

How can I do this?

# Answer
If you're displaying your field programmatically you've to use:
For Large :

```
<?php echo theme('image_style', array(
    'style_name' => 'large',
    'path' => $node->field_image['und'][0]['uri'],
    'alt' => t('Image'),
    'title' => t('Title'))); ?>

```

For Medium :

```
<?php echo theme('image_style', array(
    'style_name' => 'medium',
    'path' => $node->field_image['und'][0]['uri'],
    'alt' => t('Image'),
    'title' => t('Title'))); ?>

```

Your can also call any format you added on back office his name
> 2 votes

---
Tags: media
---


# Question
Title: Can't access default Drupal twig functions
I am unable to get a result back from app.request.attributes.get('\_route'). What could cause this. I have tried similar variable and still get no response.

# Answer
> 2 votes
Because of Drupal's granular caching, it is not possible to make the global request object available in templates (at least by default); if a template was used on multiple pages, it would be cached with the data from one page and have incorrect information on any others.

If you require the request information in a particular template, you will need to add a preprocess hook to add the additional variable, and ensure that you add the correct cache tags.

To see what variables are available within a particular template, use `{{ dump() }}`

---
Tags: 8, theming
---


# Question
Title: How to generate 'tag' field in form config module?
I'm need to create a tag field (the field that you see in this stackexchange.com website for tagging)

I'm wondering is there any api for this or this has to be created from scratch?

If this has to be created from scratch, how to make a 'custom' field in drupal - a very simple sample will be much appreciated.

# Answer
> 1 votes
The standard site install includes a "Tags" taxonomy vocabulary, and includes a "Tags" field on the "Article" content type. You can either reuse these components on your own site, or duplicate them for your particular use case.

---
Tags: entities, 8
---


# Question
Title: How to split up a View up amongst different Panels panes? Context display?
I know there's a way to take a view, and then put different slices into different panes in Panels or Page Manager. I've done it before, but not for a few years now.

I thought it was something that Views and Panels did 'out of the box', and I'm sure the Context module stopped being necessary a few years ago, but it's possible that's changed. I'm sure it involved a special type of views display (not blocks or pages, I think it was called a context display) then loading the view as a context in Panels/Page Manager. Then, each pane had appropriate options to choose the range of records e.g. 1-3 in one, then 4-6 in another, etc.

However, I have no such options in Views or Panels, and despite having a wealth of possible search terms here, I can't find the crucial step to enable this. It doesn't help that the word context is used in so many other contexts, I'm getting a wall of unrelated search results.

Did I remember this right, and if so, what do I need to do to access this "context display mode" in views that allows me to chop up the view in Panels?

# Answer
> 1 votes
The module I needed to enable was **Views content panes**. I was looking for something like it in the Views and Panels section of the modules list - it was in neither, it's bundled with ctools and listed under Chaos Tools Suite.

Then, once enabled, you get two new Views display mode options:

* **Context** is the one to allow a view to be loaded as a context behind a panel.
* **Content pane** is like a smart block where you can allow settings to be set per panel pane (e.g. offset and pager, allowing the view to be sliced up), toggling fields on and off, changing titles, etc. A few gotchas:
    + All such options are disabled from being edited in Panels by default, you have to enable them each time using the "Allow settings" option in the middle in Views
    + Panels can be a bit fussy about showing newly added view panes. You might need to save/update the panel/page manager page before it'll register the new view displays, even though it seems to load everything new each time. If even that doesn't work, try clearing caches.

---
Tags: 7, views, panels
---


# Question
Title: How to access a node's menu link title in Views?
I'm surprised to not be able to find anything about this seemingly simple or routine request.

Suppose I have nodes that have long titles. They have menu items created the usual way, with short form titles.

I want to make a view of nodes that uses the menu item title of the nodes instead of the full title. However:

* There are no fields I can see that relate to the menu item,
* I can't see any available relationships that would access the menu item and make it available.

As a workaround I'm creating a custom field "subtitle" specifically for the views titles, but it's a bad workaround. Is there no way for Views to see the menu item of a node?

# Answer
Out of the box, there isn't a way.

The only thing that may possibly help you is the

### Menu Node Views

> The Menu Node Views module provides Views integration for nodes assigned to the menu system. This module is in alpha development.

Else, a workaround is the only way.
> 1 votes

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


title: How to remove RSS Feed-icon?

text:
# Question
Title: How to remove RSS Feed-icon?
I am using Drupal 8.1.1. I have made a copy of the Bartik theme and enabled that theme and using that as default theme. I want to disable the RSS feed-icon. I was hoping to find some control/code in the templates folder to disable the RSS feed icon, but could not find anything like that. (Though there is some reference to feed-icon in theme.libraries.yml).

Can someone suggest how to remove the RSS feed icon in Drupal 8.1.1? Thanks.

# Answer
if you **don't want to disable** the feed, but **just remove the icon**.

According to FiNeX comment in Disable RSS icon in Drupal 8 via Views \> Frontpage

> A better way to remove the icon leaving the RSS feed active is to simply disable the feed attachment option.
>
> 1) Structure \> Views \> Frontpage Edit
>
> 2) Click on "Feed" tab display
>
> 3) Click on "Page" next to "Attach"
>
> 4) Uncheck "Page"
>
> 5) Save

---

Now if you want to **disable** RSS, then

According to couturier in Disable RSS icon in Drupal 8 via Views \> Frontpage

> Go to Structure \> Views \> Frontpage \> Edit
>
> Then click on "Feed" at the top. In the second drop-down box, select "Disable Feed." Then "Save" the change.
> 8 votes

---
Tags: theming, 8
---


# Question
Title: Receive error message for radio buttons ."An illegal choice has been detected. Please contact the site administrator."
I have created a multi step form, in which I have added radio buttons dynamically by using data from the database. The radio buttons added here are not required. But still I get the following error. I have created a custom module.

> An illegal choice has been detected. Please contact the site administrator.

Kindly help me resolve this issue. This is not a duplicate issue. Other issues listed have mentioned that the radios button are used as required field in that case. Please find the code added :

```
$opt = array(
        'f' => 'Friend or Business Associate',
        'b' => 'Brochure',
        'c' => 'Company',
        'a' => 'Another Columbia Asia Hospital',
        'ad' => 'Advertisement',
        'an' => 'Another Doctor',

);
$step1['questions']['learn_abt'] = array (
        '#type' => 'radios',
        '#title' => t ( 'In How did you first learn about the Hospital' ),
        '#options' => $opt,

);

```

# Answer
I somehow fixed the issue. Normally if it is not a required field we don't need to add the following code.

> '#required' =\> FALSE,

But adding this code fixed my issue. Please let me know if there is any better or correct way to fix this.
> 0 votes

---
Tags: forms
---


# Question
Title: How to change the size of the avatar in Drupal 7?
When i visualize user avatar in Drupal 7 using this code:

```
$account = user_load(2);
print theme('user_picture', array('account' => $account));

```

The following image is generated:

```
<a href="/drupal/en/user/2" title="View user profile."><img typeof="foaf:Image" src="http://localhost/drupal/sites/default/files/styles/thumbnail/public/pictures/picture-2-1303917742.jpg" alt="ksu's picture" title="ksu's picture"></a>

```

How can i control such parameters as size of the image, title, alt? And how can i get rid of the link (or change the path) which is generated automatically with the image?

```
<a href="/drupal/en/user/1" title="View user profile.">...<a/>

```

# Answer
You should use theme\_image\_style instead.

\**Update:

Example setting width/height attributes by hand (until it's resolved in Drupal core):

```
global $user;
$user = user_load($user->uid);
print theme('image_style', array( 'path' =>  $user->picture->uri, 'style_name' => 'thumbnail', 'width' => '150', 'height' => '162'));

```

Remember to change your image style 'thumbnail' in this case to your desired width/height. Now that I think about it you don't necessarily need to use theme\_image\_style, you could just edit the image style thumbnail presets and get the desired results. If you want width/height HTML attributes, use the example above.
> 5 votes

# Answer
Here is my workaround:

```
$GLOBALS['conf']['user_picture_style'] = 'PRESET NAME';
$user_picture = theme('user_picture', array('account' => $account));

```

To change user picture style in node template

```
/**
 * Override or insert vars into the node template.
 */
function HOOK_preprocess_node(&$vars) {
  if ($vars['user_picture'] && $vars['display_submitted']) {
    $GLOBALS['conf']['user_picture_style'] = 'PRESET NAME';
    $vars['user_picture'] = theme('user_picture', array('account' => $vars['node']));
  }
}

```

To change user picture style in comment template

```
/**
 * Override or insert vars into the comment template.
 */
function HOOK_preprocess_comment(&$vars) {
  if ($vars['picture']) {
    $GLOBALS['conf']['user_picture_style'] = 'PRESET NAME';
    $vars['picture'] = theme('user_picture', array('account' => $vars['comment']));
  }
}

```

Note: To display original image use empty string as preset name.
> 3 votes

# Answer
You can try this!!

global $user;
$user\_item = user\_load( $user-\>uid );

```
 print theme('user_picture', array('account' =>$user_item ,'style_name' => 'thumbnail', 'width' => '150', 'height' => '162'));

```
> 1 votes

---
Tags: users, media
---


# Question
Title: How to save a file using file_save_upload in multistep AJAX form
How can I save a file using file\_save\_upload in a AJAX multistep form? This works for a simple form, but I'm not sure where I'm going wrong in the multistep. Any help is very much appreciated!

File save works in simple form:

```
function xmlimport_form_submit($form, &$form_state){
$validators = array('file_validate_extensions' => array());
$file = file_save_upload('fid', $validators,'public://',FILE_EXISTS_RENAME);
 }

```

But doesn't seem to work in multistep. The error I get in my block says, "No file chosen" when I click Next Step on my form. AJAX form taken from Form API Example module.

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

  $form['#prefix'] = '<div id="wizard-form-wrapper">';
  $form['#suffix'] = '</div>';
  $form['#tree'] = TRUE; // We want to deal with hierarchical form values.

  $step = empty($form_state['storage']['step']) ? 1 : $form_state['storage']['step'];
  $form_state['storage']['step'] = $step;

  switch ($step) {
    case 1:
      $form['step1'] = array(
        '#type' => 'fieldset',
        '#title' => t('Step 1: Log RFI from XML'),
      );
      $form['step1']['fid'] = array(
        '#type' => 'file',
        '#title' => t('Your XML file'),
        '#default_value' => empty($form_state['values']['step1']['fid']) ? '' : $form_state['values']['step1']['fid'],
        '#required' => TRUE,
      );
      break;

    case 2:
      $form['step2'] = array(
        '#type' => 'fieldset',
        '#title' => t('Step 2: Street address info'),
      );
      $form['step2']['project'] = array(
        '#type' => 'textfield',
        '#title' => t('Project Name'),
        '#default_value' => empty($form_state['values']['step2']['project']) ? '' : $form_state['values']['step2']['project'],
        '#required' => TRUE,
        '#size' => 23,
      );
      break;
  }
  if ($step == 2) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t("Submit your information"),
    );
  }
  if ($step < 2) {
    $form['next'] = array(
      '#type' => 'submit',
      '#value' => t('Next step'),
      '#ajax' => array(
        'wrapper' => 'wizard-form-wrapper',
        'callback' => 'xmlimport_wizard_callback',
      ),
    );
  }
  if ($step > 1) {
    $form['prev'] = array(
      '#type' => 'submit',
      '#value' => t("Previous step"),

      // Since all info will be discarded, don't validate on 'prev'.
      '#limit_validation_errors' => array(),
      // #submit is required to use #limit_validation_errors
      '#submit' => array('xmlimport_wizard_submit'),
      '#ajax' => array(
        'wrapper' => 'wizard-form-wrapper',
        'callback' => 'xmlimport_wizard_callback',
      ),
    );
  }
  return $form;
}

function xmlimport_wizard_callback($form, $form_state) {
    $validators = array('file_validate_extensions' => array());
    $file = file_save_upload('fid', $validators,'public://',FILE_EXISTS_RENAME);

  return $form;
}

/**
 * Submit function for xmlimport_wizard.
 *
 * In AJAX this is only submitted when the final submit button is clicked,
 * but in the non-javascript situation, it is submitted with every
 * button click.
 */
function xmlimport_wizard_submit($form, &$form_state) {

  // Save away the current information.
  $current_step = 'step' . $form_state['storage']['step'];
  if (!empty($form_state['values'][$current_step])) {
    $form_state['storage']['values'][$current_step] = $form_state['values'][$current_step];
  }

  // Increment or decrement the step as needed. Recover values if they exist.
  if ($form_state['triggering_element']['#value'] == t('Next step')) {
    $form_state['storage']['step']++;
    // If values have already been entered for this step, recover them from
    // $form_state['storage'] to pre-populate them.
    $step_name = 'step' . $form_state['storage']['step'];
    if (!empty($form_state['storage']['values'][$step_name])) {
      $form_state['values'][$step_name] = $form_state['storage']['values'][$step_name];
    }
  }
  if ($form_state['triggering_element']['#value'] == t('Previous step')) {
    $form_state['storage']['step']--;
    // Recover our values from $form_state['storage'] to pre-populate them.
    $step_name = 'step' . $form_state['storage']['step'];
    $form_state['values'][$step_name] = $form_state['storage']['values'][$step_name];
  }

  // If they're done, submit.
  if ($form_state['triggering_element']['#value'] == t('Submit your information')) {
    $value_message = t('Your information has been submitted:') . ' ';
    foreach ($form_state['storage']['values'] as $step => $values) {
      $value_message .= "$step: ";
      foreach ($values as $key => $value) {
        $value_message .= "$key=$value, ";
      }
    }
    drupal_set_message($value_message);
    $form_state['rebuild'] = FALSE;
    return;
  }

  // Otherwise, we still have work to do.
  $form_state['rebuild'] = TRUE;
}

```

# Answer
> 1 votes
have you tried instead of using `'#type' => 'file'` for your file upload field to use the `'#type' => 'managed_file'` ? it's easier to validate and it's ajax enabled by default. You can read more about it here

# Answer
> 0 votes
You can try this!!

$form\['--Name--'\] = array(

```
         '#type' => 'managed_file',

        '#name' => 'files[]',

        '#title' => t('Upload some multifile'),

        '#description' => t('Allow to upload jpg, jpeg and png, 5MB Max Size'),

        '#attributes' => array('multiple' => 'multiple'),

  );

```

---
Tags: 7, forms
---


# Question
Title: Do we need hash in Config Sync Directory if outside root
If we set the config directory to be outside root and plan on committing the configuration to git, do we need (or is it recommended) to use hash in the config folder name?

# Answer
> 3 votes
The only purpose of the hash is to make it impossible to guess the location of the exported config. This is an additional access control in case .htaccess in the sync folder fails to do this.

If the config folder is outside of the root of the webserver you don't need the hash.

---
Tags: 8, configuration
---


# Question
Title: How to remove spaces and beginning 0 from a contact number in Views PHP view?
I have tried multiple variations and I cannot get this right. I have a contact number field that is user input; therefore, I need to clean it up so that I can use it in a `tel:` link on mobile devices.

Users could add numbers using different formats, such as:

* 021 457 7890
* +27 21 567 7089
* 0214577898

What I want to do (using Views PHP) is to strip the spaces, +27, and 0 at the beginning. My PHP skills are limited, but the confusing part for me is the Value code input and the Output code input and getting this to output correctly.

Note: if there is a non-Views PHP workaround, that would be preferred.

# Answer
> 3 votes
You can do it using the PHP function str\_replace

```
$number = $row->field_contact_number;
// Remove the spaces.
$number = str_replace(' ', '', $number);
// Grab the first number.
$first_number = substr($number, 0, 1);
if ($first_number == 0) {
  // Check if the first number is 0.
  // Get rid of the first number.
  $number = substr($number, 1, 999);
}
// Remove the + sign.
$number = str_replace('+', '', $number);
echo $number;

```

---

Although the question asked using Views PHP, it is not a good idea to enable the Views PHP and PHP Filter module. In Drupal 7, the alternative/preferred method would be to add the following code to the bottom of your **template.php** file (located in `/sites/all/themes/yourtheme/` folder).

```
function themename_preprocess_views_view_fields($vars){
  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $number = $vars['fields']['field_contact_number']->content;
    // Remove the spaces.
    $number = str_replace(' ', '', $number);
    // Grab the first number.
    $first_number = substr($number, 0, 1);
    if ($first_number == 0) {
      // Check if the first number is 0.
      // Get rid of the first number.
      $number = substr($number, 1, 999);
    }
    // Remove the + sign.
    $number = str_replace('+', '', $number);
    $vars['fields']['field_contact_number']->content = $number;
  }
}

```
* Replace **themename** with your theme name
* Replace **view\_name** with your view name
* Replace **block\_1** with your machine name

**Remember to flush the cache to see the changes.**

---
Tags: views
---


# Question
Title: How to print correct path to file in .tpl.php?
```
<img src="<?php print($base_path . drupal_get_path('theme', 'bartik')); ?>images/some-image.png">

```

The above code works only if you're in the homepage. If you go to any inner page, it looks for image inside the current URL, not just base URL.

So, it prints the image if you're under `www.address.com` but if you're under `www.address.com/page`, it doesn't print the image, because now it's looking for it inside e.g. `www.address.com/page/sites/all/themes/bartik/images/some-image.png` the problem is, it includes the `/page/` part.

In source, the image URL doesn't include the full path (which is the problem I believe?), only the `sites/all/themes/bartik/images/some-image.png` part.

# Answer
> 3 votes
It appears `$base_path` is empty, which would suggest your code isn't in page.tpl.php (where that var is commonly available, having been added in `template_preprocess_page()`).

To make it available to your current template, implement a preprocess hook like the following, which is for a region.tpl.php template file:

```
function MYTHEME_preprocess_region(&$vars) {
  $vars['base_path'] = base_path();
}

```

---
Tags: 7, theming
---


title: Custom field in a view with a link

text:
# Question
Title: Custom field in a view with a link
I created a view listing some Articles, but displaying a custom field I added to the Article content type instead of the usually used title.

When I would display a title instead of the custom field, I could check the option to include a link together with the title. How can I do that with the custom field instead? It only offers me the option to display the custom field as a plain text, without the link checkbox.

# Answer
> 2 votes
Here is a configuration that should do what you need:

Hope this helps!

---
Tags: theming, views
---


# Question
Title: How can I add a way to jump months using the calendar module
I have a calendar being shown by month. How can I add an exposed filter or dropdown so users can jump ahead to any month and year?

# Answer
Add Below code for your calendar. Click This link for example

```
$(function () {
  $("#datepicker").datepicker({
    changeMonth: true,
    changeYear: true
 });
});

```
> 1 votes

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


# Question
Title: Which hook is invoked when pressing the remove button with widget image?
In a content type named "R" there is a image field say "I". When a node with R-\>I is filled with a image file then standard you can remove this by pressing the remove button. The standard images widget is used in drupal 7.

When I press this remove button something is executed as I get a message just 2 cm above the field "I" which is displaying the following message:

> content\_type\_name, content\_type\_title has been updated.

How do I find out which hook is invoked?

# Answer
This message is coming from `node_form_submit`.
That function subsequently calls `node_save` which in turn calls the following hooks:

```
// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');
...
module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

```

where $op is one of 'update' or 'insert'.

---
> 0 votes

---
Tags: 7, debugging
---


# Question
Title: Export and Import Taxonomies and Extra Fields
I created extra field in Login Form, I Installed even Extra Module (address) and create Taxonomies

Now I want to Export these configurations to another Drupal. This Drupal is the Clone of the main Drupal.

I Tried to use import/export Configuration (admin/config/development) But I have several error during import ( shortcut and error Ajax 500 )

I don't have active and staging folder (link)

Is it correct to use Conguration Management to export Module and Taxonomies?

# Answer
According to this drupal link

```
drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'

```
> 0 votes

---
Tags: taxonomy-terms, 8
---


# Question
Title: Allow users to register using username in drupal commons throw Integrity constraint violation error
I'm using drupal commons and I want to allow user to pick his username on registration.

Currently drupal commons does not allow user to choose his own username but generates one automatically.

What I have done so far through hook\_user\_register\_form\_alter :

I changed the #type of name (username machine name) from hidden to textfield. This display the field.

```
$form['account']['name']['#type'] = 'textfield';

```

I removed the default value

```
$form['account']['name']['#value'] = NULL;

```

Now when I try to add a new user, I get the following error message:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, name, pass, mail, signature, signature_format, created, status, timezone, language, picture, init, data, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13); Array ( [:db_insert_placeholder_0] => 824 [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => $S$DgHF.OcL6K0hxQ0A4v.O67r4FUp4kpfeuywOrGHvb4zmoEzjpQrW [:db_insert_placeholder_3] => test@test.com [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => filtered_html [:db_insert_placeholder_6] => 1463562222 [:db_insert_placeholder_7] => 1 [:db_insert_placeholder_8] => Europe/Brussels [:db_insert_placeholder_9] => en [:db_insert_placeholder_10] => 0 [:db_insert_placeholder_11] => test@test.com [:db_insert_placeholder_12] => a:2:{s:7:"contact";i:0;s:20:"l10n_client_disabled";b:0;} [:db_insert_placeholder_13] => 267c9864-8fe0-4cc5-81ef-22bd53befcf8 ) in drupal_write_record() (line 7333 of /home/me/websites/customprojects/mysite.local/docroot/includes/common.inc). Backtrace:
PDOStatement->execute(Array) database.inc:2171
DatabaseStatementBase->execute(Array, Array) database.inc:683
DatabaseConnection->query('INSERT INTO {users} (uid, name, pass, mail, signature, signature_format, created, status, timezone, language, picture, init, data, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13)', Array, Array) query.inc:36
InsertQuery_mysql->execute() common.inc:7333
drupal_write_record('users', Object) user.module:582
user_save(Object, Array) user.module:3912
user_register_submit(Array, Array) form.inc:1519
form_execute_handlers('submit', Array, Array) form.inc:903
drupal_process_form('user_register_form', Array, Array) form.inc:385
drupal_build_form('user_register_form', Array) form.inc:130
drupal_get_form('user_register_form')
call_user_func_array('drupal_get_form', Array) menu.inc:527
menu_execute_active_handler() index.php:21

```

I understand that it is a duplicate problem on the username field but checking in the database there is no username matches the one I have chosen. So don't understand the error.

Also, I'm wondering if the fact of having username can have a side effect ?

# Answer
> I removed the default value

Sort of but not really - what you've actually done is set a static value of NULL for that field, which will be carried through to the submission regardless of any user input.

Your best bet to avoid these sort of problems would be to implement the field again from scratch:

```
$form['account']['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Username'),
  // ...
);

```

Note that this won't remove any extra validation that Commons might add, so YMMV and there may be some additional steps to complete your feature.

Just for future reference, to set an initial value for an element that doesn't nuke user input, use `#default_value` in place of `#value`.
> 4 votes

---
Tags: users, 7
---


# Question
Title: Contextual filter with Node Reference and Pathauto
I work for an organization that makes research grants. We periodically write "research briefs" for our grants to summarize what they found. My test Drupal site has a view of research briefs, and what I'd like is to display a block of grant information as a user is looking at a specific research brief.

I've got two custom content types: grants and research-briefs. The research-brief content type has a node reference field to grant ID. I use pathauto, so an example research-brief path is: site.org/research-brief/551023442 where 551023442 is the grant ID.

The way it seems I should set up the block view contextual filter is: Content: Parent ID (field\_parent\_id) When the filter is not available: Provide the default value. Type: Raw value from URL Path component: 2 Use path alias: checked

This doesn't work and I've tried any number of fields and any number of configuration options and would sure appreciate any helpful pointers. If I display all results I can see all grants in the block.

# Answer
> 0 votes
I'd try this with a contextual filter for the research brief `content:nid` and then use the default value: `node id from the url`. This works regardless of pathauto and always provides the correct node is for the research brief.

Then add a Views relationship (join) from the Research brief to the Grant. Select the node reference field for this relationship.

Finally select the fields you want to display, using the Grant relationship.

# Answer
> 0 votes
Please use Contextual Filter :

View Of the Page URL Should be : `research-brief/%`

In Context Filter : Please Click on Add Button

It will display all the fields of the Content type : research briefs

In which search, reference Id field in the research brief of grant. It might be grant ID. Then select it.

---
Tags: views
---


# Question
Title: How to enforce edit suggestions of a post to require approval from the author of the post?
I'm creating a user community site and one of the features is to reward points to registered users.

One feature I'm trying to implement is to reward points for every edit on a post only if the author accepts the edit, the user who submitted the edit should get a point only if the edit is accepted by the author of the post.

How would I implement this in Drupal 7?

# Answer
> 2 votes
Try User Points

> This module provides an API for users to gain or lose points for performing certain actions on your site.
>
> In conjunction with other modules, such as the Userpoints Nodes and Comments users can accumulate points for actions such as posting nodes, commenting or moderation duties.
>
> Use one of the many contributed modules to extend the functionality of the module to include point accumulation on page views or votes, upgrade roles based on point balance, or purchase goods from your store.

And if you need to do states of content, try Workflow

> This module allows you to create arbitrary Workflows, and assign them to Entities.
>
> Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, **a workflow with the states *Draft*, *Review*, and *Published*** could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment and a special workflow tab.
>
> Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published (and becomes visible on your website).

# Answer
> 1 votes
# Step 1 - Add workflow

Use the Workflow module to manage the suggested edit before it actually get published. Here are some typical values you may want to use for the actual workflow management:

* Draft
* Needs review
* Needs work
* Needs author approval **(1)**
* Published

**(1)**: Feel free to use what fits for your case, but make sure to include "a" value like "***Needs author approval***" (or something similar to that), which will be used to collect the author's approval.

# Step 2 - Verify author approval

Use the Rules module to check if, for "Needs author approval", it is the posts's author who is actually attempting to change the status to "Published". For any other user trying to do so, issue a Rules Action to just set an appropriate Drupal error (not just warning) message, indicating that only the post author can change the status to published (which is like a final approve). If the approve is indeed given by the post author, then assign the appropriate User Points (also via Rules).

You can implement this as 2 separated rules, or if you also use the Conditional Rules module you can combine them both in a single rule.

---
Tags: 7
---


# Question
Title: An invalid implementation mymodule_form_alter was added by hook_module_implements_alter
I am trying to have my module alter `menu_ui` functions. Changing my module's weight didnt help and I read that `hook_module_implements_alter` is the way to go. So, as described here I am appending my module to the end of the implementations:

```
/**
 * Implements hook_module_implements_alter.
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ('form_alter' == $hook) {
    $group = $implementations['mecca_hierarchy_access'];
    unset($implementations['mecca_hierarchy_access']);
    $implementations['mecca_hierarchy_access'] = $group;
  }
}

```

But this just throws:

> Uncaught PHP Exception RuntimeException: "An invalid implementation mymodule\_form\_alter was added by hook\_module\_implements\_alter()" at /path/to/core/lib/Drupal/Core/Extension/ModuleHandler.php line 591

My form alter looks like this:

```
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // commented code
}

```

What do I do wrong?

# Answer
The exception is raised from the following code. (See `ModuleHandler::buildImplementationInfo()`.)

```
// If a new implementation was added, verify that the function exists.
if (!function_exists($module . '_' . $hook)) {
  throw new \RuntimeException("An invalid implementation {$module}_{$hook} was added by hook_module_implements_alter()");
}

```

In your case, it simply happens because there isn't any `mecca_hierarchy_access_form_alter()` function.

Since you want Drupal to invoke the `hook_form_alter()` implementation of your module after the other `hook_form_alter()` implementations, and since *mymodule* seems to be your module's machine name, this is the code you want to use.

```
/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter' && isset($implementations['mymodule'])) {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

```

Always verify the implementation of your module hasn't been already removed from another module, or your hook implementation would actually set `$implementations['mymodule']` to `NULL`.
> 4 votes

---
Tags: 8, hooks, forms
---


# Question
Title: How to redirect user after submitting an article?
In Drupal 8 I would like to redirect users to the frontpage and display a status message after submitting an article?

How can I do that? form\_alter and custom submit handler?

# Answer
Yes, form\_alter and a custom submit handler was the solution.

```
function _custom_admin_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = '_custom_admin_article_form_submit';
    }
  }
}

function _custom_admin_article_form_submit($form, FormStateInterface $form_state) {
  drupal_set_message(t('Thank you for submitting an article.'));

  $url = Url::fromRoute('<front>');
  $form_state->setRedirectUrl($url);
}

```
> 1 votes

---
Tags: forms, 8, redirection
---


title: EditableViews without a table?

text:
# Question
Title: EditableViews without a table?
I'm looking for the features of the editable views module without having to use a table (In Drupal 7).

I have a view that I use as an input form. I'm using the "editable views" module to expose those fields as editable. However, I would like to customize this beyond what a Table will provide. There's some CSS trickery I can do (e.g. moving cells around with CSS), but that seems very hackish. Are there any modules/methods out there to do what I'm trying to do?

(example)

I have...

```
 | Title | Description | Author | Feedback (Editable) | Rating (Editable)

```

I want...

```
 Title, Author
 Description
 Feedback (Editable) | Rating (Editable)

```

Thanks

# Answer
> 1 votes
Found the solution!

A patch is in the works to provide this exact functionality.

Patch: https://www.drupal.org/node/2579113

Installation:

1. go to your /sites/all/modules/editableviews directory
2. wget \[get the patch file link\]
3. run `patch < editableviews-style-unformatted-2579113-26.patch`

Setup:

1. Clear Cache (I used the dev module's clear cache functionality)
2. Edit your view
3. Change your View Format:Format to be "Editable Unformatted"
4. Change your View Format:Show to be "Fields"

When you save/preview, all your fields will be in \<span\> tags that you can customize in CSS.

# Answer
> 1 votes
You can use EditableFields instead, which will let you use `Unformatted list` instead of `table`.

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It **also works within views** etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

Then you can use CSS to get the view to look how you want it.

```
.field-title { float: left; }
.field-feedback { float: left; }

```

Also, you will probably need to resize the edit button.

---

Else, if you do not want to use CSS then the following may possibly work:

1) Hide all your fields from display

2) In FIELDS, add a Global: Custom field

3) Use the replacement patterns on your custom field.

Ex:

```
[title], [author] <br>
[field_description] <br>
[field_feedback] | [field_rating]

```

---
Tags: 7, views
---


# Question
Title: field_attach_update stopped working - how to debug this?
I am using this simple code:

```
$order = commerce_order_load($order_id);
$order->status='completed';
field_attach_update('commerce_order', $order);

```

To update the status of order to `completed`.

This code use to work but does not work anymore (the order status is not updated).

How to debug this ?

UPDATE:

Using :

```
entity_get_controller('commerce_order')->resetCache(array($order->order_id));

```

Does not work neither.

# Answer
> 1 votes
You can't debug what ain't a bug :)

`status` is a property, not a field, of the commerce\_order entity type - so it isn't affected by running `field_attach_update()`, which just saves field data, and avoids saving the entity itself.

You'll need to use `commerce_order_save()`, `entity_save()`, or manipulate the `commerce_order` table directly, and then clear the cache using the entity controller.

---
Tags: 7, entities, commerce
---


# Question
Title: How to hide blocks based on content type or for specific nodes?
In some of my nodes I need to show only "body" part of node. I don't want to show blocks etc. in those nodes. How can I do this ?

* Create a new "content type" and put the data from existing nodes to that type of node. And excluding that "content type" from each of the blocks.
* By using javascript/jquery like: `$('div'.block).remove()`

Any more elegant answers?

# Answer
The answer very much depends on how the nodes you want to show only bodies of are different from all other nodes of same content type.

I see two possible solutions:

1. Create a new content type and convert all the nodes you want to it. Then you can specify in blocks visibility settings not to show blocks on the nodes of that content type and create a new template for this content type in which only body is printed.
2. Another way is to give the context module a try. The context module provides a much more flexible way to control blocks visibility so you can specify different contexts for your normal nodes (and assign blocks to this context) and your no-blocks nodes with no blocks assigned.

I'm sure there must be other ways to accomplish this, but these two are the first things I thought of :)
> 4 votes

# Answer
Creating a new content type, just for this, seems like something you should try to avoid (the number of content types should always be reduced where possible). These days there is another alternative available: use the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the situation where someone uses an URL that corresponds to "*some of your nodes*" (as in your question), so that the block is NOT shown for those nodes.

For that, create a Rules Component with a Rules Condition that performs a *Text comparison* with `Parameter: Text: [site:current-page:path]` and an appropriate *Matching Text* for the URLs like "NOT (`node/nid1` AND `node/nid2`)", whereas `nid1` and `nid2` or the node ids of nodes for which the blocks should not be shown.
> 0 votes

---
Tags: blocks
---


title: Combine own stream with flagged user

text:
# Question
Title: Combine own stream with flagged user
I am using follow flag latest version and edited the view fbss\_ur\_stream. I also created a following and followers view with the help of this tutorial Twitter style follow following

I took the idea from it and implemented it in fbss\_ur\_stream view. I deleted the relationships and contextual filters and added the new ones. Relationship: Flag follow (current user) and (user) flag user & Cont. filter: (flag user) User: uid. I unchecked "only flagged content" as well as "require this relationship"

Now I am able to see the posts from the person I am following, but my posts are not showing. Why?

Do I have to clone it and create a new view within this master view? how?

# Answer
The problem lies with your contextual filter. It is set to filter the `uid` of `flag user`. This means it will limit the selection to only flags made by the current user (who did not flag himself, thus the user's own content is not selected).

You can probably solve this by having each user flag himself (automatically), but that is kinda ugly.

The alternative would be to use two regular filters and an OR group (remove the contextual filter). You might have to add some additional relationships if below steps do not work, but we basically want to have relations from the content to the user (author) and from the flag to the user (I believe you added that one already).

Add the filter `user: current` and select `yes` twice! For the first dialog, make sure you select the author relationship from content to user. For the second dialog use the flag to user relationship.

Finally, from the dropdown button above the filters section, select `And/Or Rearrange` and Create two groups with `Or` between them:

Now make sure to place one of the filters in each group.

This should show all content where the author is the current user, or content where the author has been flagged by the current user.
> 0 votes

---
Tags: views, flags
---


# Question
Title: Add 150 grams to each order for calculating shipping
how can I add 150 grams to each order for calculating shipping costs (this weight corresponds to the packaging)? I looked in the rules, but I do not see how to do this.

# Answer
I guess you're using commerce\_shipping module, if so, you can add a commerce\_flat\_rate service to every order.

Otherwise I would suggest you start using these modules ;)
> 0 votes

---
Tags: commerce
---


title: List users with custom fields

text:
# Question
Title: List users with custom fields
Is there way to list all users? I haven't found such method on `UserInterface`. The few hints I found on internet are for version 7 or using `entityManager` which is deprecated. Loading custom fields is a bonus.

# Answer
```
$users = \Drupal\user\Entity\User::loadMultiple();
$field = $user->get('field_custom_field');
$value = $field->getString();

```
> 2 votes

---
Tags: users, 8
---


# Question
Title: What is the best way to extend \Drupal\node\Entity\Node?
When dealing with nodes on Drupal 8, we usually receive an instance from \Drupal\node\Entity\Node, that is great in many aspects, but i'm not sure on how to extend it so that I can use classes that represent something in my own domain, rather that generically using Node. I can make this here:

```
class Video extends \Drupal\node\Entity\Node {}

```

Ok. But to have Video::load() and that sort of things, i'm seeing that I need to probably also extend NodeStorage, because everything returns a Node class and type changing seems to be not so easy in PHP from what i'm seeing until now. I'm not sure if this is really the way to go.

I really like to work extending Node(I used to extend EntityDrupalWrapper on D7), as it becomes easier for newcomers to the project and to have stuff like $Video-\>getFileUrl()

Any ideas?

# Answer
> 2 votes
The recommended solution is to extend `ContentEntityBase` which is tedious task if you want to do it manually, or a quick one if you use drupal console and it's `generate:entity:content` command.

## However

It is still possible to extend Node class and so far my experiments prove that it works fine. The important part is that after extending `Drupal\node\Entity\Node` you also have to tell drupal to use your class instead by implementing hook\_entity\_type\_build.

You can see my detailed answer for How to alter the entity type class in Drupal 8? question that explains how to do this and why it works.

# Answer
> 1 votes
You can't do that. All entities of the same type have use the same class.

I believe there are some issues to allow this, possibly through a per-bundle classmap instead of a single class entry, but it would be quite complicated at the moment, as there are different places where entity classes are instantiated and you'd have to override them all (create and load, for example).

---
Tags: 8
---


# Question
Title: Stop Varnish from caching 302 redirect from POST responses
`drupal_goto()` uses a 302 redirect by default, which means a lot of redirects, including form redirects, get served with a 302 response code.

Having a issue in Varnish that is caching 302 response from user submitted forms for anonymous traffic.

It caches the first 302 redirect but then if the customer selects different options on the form it should be redirected to another url.

Not being able to cache product pages on our Drupal commerce site amounts to millions of cache misses a month and excessive performance issues. Drupal based page level caching is not a option as we have over 4,500 stores deployed.

How can this be fixed?

# Answer
> 2 votes
Disable caching in fetch if response status is 302

```
sub vcl_fetch {
set beresp.grace = 24h;

if (beresp.status >= 400) {
     return (hit_for_pass);
}

// New Set Longer Cache
if (req.http.user-agent ~ "(Googlebot|msnbot|Yandex|Slurp|Bot|Crawl|bot|Baid|Mediapartners-Google)") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 5d;
    return (deliver);
}
if (req.request == "GET" && req.url ~ "\.(css|xml|txt)$") {
    set beresp.ttl = 5d;
    unset beresp.http.set-cookie;
    return (deliver);
}
// multimedia
if (req.request == "GET" && req.url ~ "\.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|img|tga|woff|eot|ttf|svg|wmf|js|swf|ico)$") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 5d;
    return (deliver);
}
//Fix to stop caching 302 responses
if (beresp.status == 302) {
  remove beresp.http.Cache-Control;
  set beresp.http.Cache-Control = "private, no-cache";
  set beresp.ttl = 0s;
}
set beresp.ttl = 5d;
return (deliver);

```

}

Setting cache control for 302 redirect:

```
sub vcl_deliver {
// Remove Varnish identifying information from headers
// Note: Both cache hits and cache misses will use this subroutine.

set resp.http.Access-Control-Allow-Origin = req.http.X-Saved-Origin;

remove resp.http.Via;
unset resp.http.Server;
remove resp.http.Age;
remove resp.http.X-Powered-By;
remove resp.http.X-Varnish;
remove resp.http.X-Generator;
remove resp.http.X-Mod-Pagespeed;
remove resp.http.X-Drupal-Cache;
remove resp.http.Link;
set resp.http.Server = "Prism";
// Stop Caching 302 redirects
if (resp.status == 302) {
  remove resp.http.Cache-Control;
  set resp.http.Cache-Control = "private, no-cache";
}

if(req.http.host ~ "printsites.net"){
     set resp.http.X-Robots-Tag = "noindex, nofollow";
}

return(deliver);

```

}

---
Tags: caching, proxies
---


# Question
Title: How to send an email to a node author after selecting a specific value in a selected list field?
Actually this is my content and I have one select list field in it. If I select a "New litter" and click on save, I have to generate an email to the author. If however I select any other value for that field (and click on save), then there is no need to generate an email.

How can I do this?

# Answer
You can use hook\_node\_presave() and in this function check if the select value is "new litter" and generate email.

```
function YOUR_MODULE_NAME_node_presave($node){
    if($node->type == 'YOUR_CONTENT_TYPE'){
        //get your field value
        $field = field_get_items('node', $node, 'YOUR_FIELD_MACHINE_NAME')[0]['value'];
        //check if value equals "new litter" key
        if($field == 'NEW_LITTER_KEY'){
            generate_email();
        }
    }
}

```

change uppercase strings with your module and machine names
> 1 votes

# Answer
Hope below code will help you.

```
function mycustom_node_insert($node) {
  switch ($node->type) {
    case 'cage-card-info':
      $warning = $node->field_warnings['und'][0]['value']
    if($warning == "new litter"){

      $user = user_load($node->uid);
       $authr_email = $user->email;
      //Send mail function to the author
     }
     break;
  }
}

```
> 1 votes

# Answer
Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

```
{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [], "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:author:mail]",
          "subject" : "Notification about a node with a special field value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with a value you needed to be informed about ..."
        }
      }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event I'm using is "After saving new content" or "Updating existing content.
* In my case I have a selection list field with machine name `field_optionlist`.
* This field actually has 3 possible values, like so:
    + A (=Advanced).
    + B (=Basic).
    + C (=Custom).
* As a sample, I decided to use as condition "The selected value must be `Custom`".
* If that value is selected, then (as Rules action), an eMail will be triggered to the node author.

Change the field name of `field_optionlist` to match the field name of your content type, and adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the rules UI). That's it.
> 0 votes

---
Tags: entities, emails
---


# Question
Title: Css redirect to other css file after logging out. Bug?
I have styled the class .tab-content and it works fine whenever i logged in, but i logged out then the css file is changed to a different file as you can see on the screenshoots below. I have ran drush cc all and drush cron as well as I don't have boost module installed. Do you have any idea to fixed this?

when i login

when i logout

# Answer
> 1 votes
Drupal serves aggregated CSS. If one or more CSS files are not available (or required) for anonymous users they are not included in the aggregated file for the sake of a smaller file size. This file can obviously not be saved with the same name.

If you disable CSS aggregation (Configuration \> Performance), you can see all individual files and this might explain the difference.

---
Tags: 7, debugging
---


title: Filter by field user role permission

text:
# Question
Title: Filter by field user role permission
I have created *View permission* field in the *events* content type. Its field type is *Role*, so I can select which roles can see the node.

This works fine, but when I add events content type in the view this will displays all the data. I want to filter the data by the *View permission* field for the currently logged-in user.

I want to show data to the roles which I selected in the node *View permission* field. I have tried with contextual filter with user:uid, but I don't get what I am expecting. Actually, I don't know how to do that.

How can I achieve this?

Note: I want to integrate with my content type field *View permission*. I will select a role in View permission field. That roles only can see the view result.

# Answer
> 0 votes
It sounds like the only requirement here is a per-node, role-based, permission setting on content. If that's the case, I'd drop your role reference field in lieu of Content Access. The module enables such a requirement and it hooks deeper into the Drupal permission system so you don't have to build a bespoke permission checking for every situation (e.g. views access, node page access, etc.).

---
Tags: views, users
---


# Question
Title: How do I adjust the 'Create New Account' settings?
New registrations are asked to create a password which is, in my opinion, excessively strong. Where do I go to adjust the password strength and other 'new account' settings? When I looked in the listed modules, the 'User Module' was greyed out.

I am using Drupal version 6.

# Answer
> 0 votes
There were a few options for Drupal 6 so it's hard to give generic instructions. Check the module page for modules that include the word password and check for a "Configure" link.

*Take Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.*

---
Tags: users, 6
---


# Question
Title: Views output realname field as a contextual link
Contextual is set up to display all content from a user for a specific content type.
www.example.com/users/realname/gallery where realname is contextual filter.
Realname is used with token that reflects field from registration: field-choose-realname.

Lets say we have 2 users and 1st writes "One" as realname and 2nd writes "One Two".
Realname contextual filter is setup to use lowercase and change spaces to dash.

Here is what happens:
www.example.com/users/one/gallery - ok

www.example.com/users/one-two/gallery - page not found error
www.example.com/users/one%20two/gallery - ok

For Contextual "when the filter is in the URL or a default is provided" i am using this php code (i did not write it so i have no clue what it does really):

```
if (!isset($argument)) {
  return FALSE;
}
$query = db_query('SELECT uid, realname FROM {realname} WHERE realname = :realname', array(':realname' => $argument));
$row = $query->fetchAssoc();
if (isset($row['uid'])) {
  return TRUE;
}
return FALSE;

```

To better explain what i want to do:
Get sidebar menu like on myspace for bands. When you land on bands page you can use sidebar menu to check their foto galleries, band members, video gallery and links must be made with a field that is not default username (it can be realname module or some other text field). Field validation is used so i do not get same name twice, and all links in pathauto are made example.com/bands/realname.
To repeat again it does work if realname contains 1 word.

# Answer
Setting the contextual filter to transform spaces to dashes will not make the Realname field in the database contain dashes, so the filter fails. In your url you look for `one-two`, in the database this is `One Two` they are not the same and it doesn't work (`one-two ≠ One Two`).

First make sure pathauto is installed and enabled. It will provide your users with a pretty url. This will make sure every user has a unique path. If you replace spaces and dashes in the URL as you do now, the contextual filter for these users `One Two, One-Two, One'Two` will all become `one-two` even if they are if fact different users. So your results will be mixed up. Pathauto will make sure they become unique; `one-two`, `one-two2` and so on.

Do not rely on simple pattern matching, but use the uid from the instead. Luckily we can hide this entirely from the url by using a View's contextual filter.

**Update**

It seems I have missed a module requirement; Sub-pathauto (Sub-path URL Aliases).

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
>
> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead.

The is required to properly obtain the UID from the url.

Then create your view as follows:

Use must use the unaliased path for the `path`. So if your user is at `/users/url-safe-realname` and your gallery at `/users/url-safe-realname/gallery`, you enter `/user/%/gallery` (omit the s in users pathauto adds if using default settings).

For the contextual filter, in the *WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED* section, check `Specify validation criteria`, choose `user` and `numeric UIDs`.

The result will be a page that has the url-safe realname in the path and shows only content created by the user:
> 2 votes

---
Tags: 7, views
---


# Question
Title: Controlling the display order of custom field sets that are shown both in a webform and in CiviCRM, via the webform_civicrm integration module
I've created a webform that is integrated with my CiviCRM implementation. The webform has five major sections to it, each of which is reflected by a custom field set within the CiviCRM module as shown below.

All five custom field sets are linked to a specific activity type as indicated in the first screenshot. The five custom field sets are ordered, by weight, in the list of custom field sets within CiviCRM because I want the summary information displayed first to the administrator viewing the activity.:

However I want the summary questions displayed at the end of the webform, as presented to the user, so I've used webform's flexibility to let me do that.

So far so good. But when I submit the webform, the CiviCRM activity record, when in view mode, reflects the field order as specified in the webform, rather than as specified in CiviCRM, which seems odd.

However, if I edit the activity record, the field order and field sets are as ordered in my original CiviCRM field definitions.

How can I set it up so that the field order in the Activity record, when viewed rather than edited, reflects the order specified within CiviCRM?

(I'm aware that this question is more about CiviCRM than it is about Drupal per se, but given that CiviCRM is a Drupal module, and there's no SE site dedicated to CiviCRM - yet - I hope you'll bear with me and allow answers to this question.

# Answer
This bug was resolved in CiviCRM 4.5.2, the relevant issue was CRM-15435: Case ActivityView popups do not respect custom group weights.
> 1 votes

---
Tags: webforms, civicrm
---


title: Create dynamic textfield?

text:
# Question
Title: Create dynamic textfield?
I have a form builder containing the following code.

```
  $form['finput']['noreff1'] = array(
  '#type' => 'textfield',
  '#title' => t('No Reff1'),
  '#size' => 60,
  '#default_value' => $noreff1,
  //'#required' => TRUE,
  '#autocomplete_path' =>'noreff/autocomplete',
  '#ahah' => array(
      'event'   => 'change',
      'path'    => ahah_helper_path(array('finput')),
      'wrapper' => 'finput-wrapper',
     'method' => 'replace',
         'progress' => 'throbber',
  ),
  '#prefix' => '<div class="finput-form">', '#suffix' => '</div>',
  );

  $form['finput']['noreff2'] = array(
  '#type' => 'textfield',
  '#title' => t('No Reff2'),
  '#size' => 60,
  '#default_value' => $noreff2,
  //'#required' => TRUE,
  '#autocomplete_path' =>'noreff/autocomplete',
  '#ahah' => array(
      'event'   => 'change',
      'path'    => ahah_helper_path(array('finput')),
      'wrapper' => 'finput-wrapper',
     'method' => 'replace',
         'progress' => 'throbber',
  ),
  '#prefix' => '<div class="finput-form">', '#suffix' => '</div>',
  );

  $form['finput']['noreff3'] = array(
  '#type' => 'textfield',
  '#title' => t('No Reff3'),
  '#size' => 60,
  '#default_value' => $noreff3,
  //'#required' => TRUE,
  '#autocomplete_path' =>'noreff/autocomplete',
  '#ahah' => array(
      'event'   => 'change',
      'path'    => ahah_helper_path(array('finput')),
      'wrapper' => 'finput-wrapper',
     'method' => 'replace',
         'progress' => 'throbber',
  ),
  '#prefix' => '<div class="finput-form">', '#suffix' => '</div>',
  );

```

This code shows a fixed number of form fields (noreff1, noreff2, noreff3). If I want to dynamically increase those form fields, how can I do?

# Answer
> 0 votes
> So, I just want to show one textfield for starting. If user not use that form, it doesn't show new form. But, if user input some value in that form, when user finish inputing that value (confirm by click enter button on keyboard for example), new textfield form showd up so user can fill new value, and so on.. – bandungeuy

I don't think there is a Drupal way to do that, but you can always do this with jQuery.

For example:

**HTML**

```
<form>
<div class="form-item" id="edit-first-name-wrapper">

  First name:<br>
  <input type="text" name="firstname" id="edit-first-name"><br>

</div>

<div class="form-item" id="edit-last-name-wrapper">

  Last name:<br>
  <input type="text" name="last-name" id="edit-last-name">

</div>
</form>

```

**jQuery**

```
(function ($) {

   $('#edit-last-name-wrapper').hide();

   (function Forever(){

     var grabs = $('#edit-first-name').val();

     if (grabs != '') {
       $('#edit-last-name-wrapper').slideDown(1500);
     }
     // slides down and shows the last name field if the first name field is not empty
     else if (grabs == '') {
     // checks if the first name field is empty
       $('#edit-last-name').val('');
         // empties the last name field, since there is no first name
       $('#edit-last-name-wrapper').slideUp(1500);
         // slides up and hides the last name field

     }

   setTimeout(Forever, 1);

   })();

})(jQuery);

```

### JS Fiddle DEMO

---
Tags: forms, 6
---


title: Use a block in a panel

text:
# Question
Title: Use a block in a panel
Like the title says, is there a way I can use a block inside my panel? It looks like it can't be done...

As you can see here, there is no option to add a block to my panel...

# Answer
> 9 votes
Most of the blocks are under the "Miscellaneous" category.

I'm not sure exactly what the distinction is, but a few of them, such as user login, end up under "Widgets" instead.

# Answer
> 0 votes
If your block from a view you can use Views but If you want to add a block there is an option called widgets to add your block like poll

# Answer
> 0 votes
I have same problem that I can't see block view on Miscellaneous.

My solution is go to Module menu. Find the module "Views content panes" and uninstall it. So, the block view will display on Miscellaneous of panel.

Regards, Bien

---
Tags: 7, blocks, panels
---


title: Start only one quiz per day

text:
# Question
Title: Start only one quiz per day
I used quiz module version 7.x-4.0-rc2 and drupal7 to create content in my site. I created student role to access quiz content.

I want each student can start only one quiz per day. Example: Today is 22/04/12, a student can start only one quiz. If they open and start quiz1, they can't start any other quiz until to 23/04/2012.

Please help me, How to do that. Thank you so much, Bien Hoang

# Answer
> 1 votes
I have never used the Quiz module myself so I can only give you a generic answer.

What I would do, is to create a custom module which contains a hook implementation and a helper function:

* In the helper function, check if the current has the permission to create quiz content and if the user has already posted a quiz today. You may need to write a database query to retrieve this information, but I'm not sure, that depends on the way the quiz module was programmed. Return `TRUE` if the user is allowed to post a quiz, return `FALSE` if not.
* In a hook\_menu\_alter implementation, change the `access callback` property of the quiz creation form, setting it to the helper function you just wrote. This will deny access to the quiz creation page if the use is not allowed to create a new quiz.

Hope that helps.

# Answer
> 0 votes
Thank Marcvangend, I finished this task. I write some coding on quiz dependence module. Now, in my site user can start only one quiz per day and they need pass the quiz one before start the quiz 2.

Thank, Bien

---
Tags: quiz
---


# Question
Title: Attach PDF file to Drupal Commerce Order Notification
How do I attach a views\_pdf file to the commerce email?

I have views\_pdf, commerce\_coupon.

As Sally I would like to buy a coupon and have a copy emailed to me.

I am stumped on how to get the pdf view into a File object.

```
function yhivecoupons_mail_alter(&$message) {
  global $user;

  if (!empty($message['id']) && ('message_notify_commerce_order_order_confirmation' ==  $message['id'])) {
$pdf_coupon = views_embed_view('commerce_gc_user_giftcards', $display_id = 'pdf_1');

  $my_attachment = array(
    'filecontent' => $pdf_coupon,
    'filemime' => $pdf_coupon->filemime,
    'filename' => $pdf_coupon->filename,
    'filepath' => NULL,
  );
  $message['params']['attachments'][] = $my_attachment;
 }
}

```

# Answer
Problem #1. Getting a copy of the PDF.

The function views\_pdf\_rules\_action\_save() almost did it. I changed

```
$display->handler->execute('', 'F')

```

to

```
$display->handler->execute('', 'E')

```

As TCPDF has an option to generate the PDF as an email format. I don't need to save the file with the resulting security and overwriting challenges.

Problem #2. Stripping the email and base64decode

The email format added the HTML already has the headers. I didn't dig enough to bypass the Drupal mail array processing. Instead the heading was stripped. You could use more of the provided mail headers.

```
$email_attachment = _yhivecoupons_views_pdf_rules_action_save('commerce_gc_user_giftcards:pdf_1', null, '');
$email_attachment_parts = explode("\n", $email_attachment);
$content_type = array_shift($email_attachment_parts);
$name = array_shift($email_attachment_parts);
$encoding = array_shift($email_attachment_parts);
$disposition = array_shift($email_attachment_parts);
$filename = array_shift($email_attachment_parts);

$clean_email_attachment = implode("\n", $email_attachment_parts);
$clean_email_nobase64 = base64_decode($clean_email_attachment);

      $my_attachment = array(
    'filecontent' => $clean_email_nobase64,
    'filemime' => 'application/pdf',
    'filename' => "tester.pdf",
    'filepath' => NULL,
  );
  $message['params']['attachments'][] = $my_attachment;

```

Problem #3 Permissions

This process is still executed in a context where the user was not logged in. I am printing out a person's coupons so need their login details.

I don't think this is the best way to do this, as the process is not checking unique email addresses yet.

```
global $user;
$user_obj = user_load_by_mail($message['to']);
$user = user_load($user_obj->uid);

```

Log out user at end.

Instead I am using commerce\_immediate\_login which does the same thing but in a rule using the ui generated by 'create login for anonymous users'. The order of the rules is specific.

This is my views PDF call function with the 1 character change from views\_pdf\_rules\_action\_save(). A tested way of getting PDF content from views\_pdf.

```
function _yhivecoupons_views_pdf_rules_action_save($views_pdf, $arguments, $path) {
  $splits = explode(':', $views_pdf);
  $view_id = $splits[0];
  $display_id = $splits[1];

  if (!empty($view_id)) {
    $view = views_get_view($view_id);

    $view->set_arguments(preg_split("/\r\n|\n|\r/", $arguments));

    // Try to get pdf display
    if (!$view->set_display($display_id)) {
       // Try the display type
       if (!$view->set_display('pdf_1')) {
        // There is definitly no pdf display
        return;
       }
    }

    $view->pre_execute();
    foreach ($view->display as $id => $display) {
      if ($display->display_plugin == 'pdf' && isset($display->handler)) {
        // arguments '' and I
        return $display->handler->execute('', 'E');
       }
     }
  }
}

```
> 1 votes

---
Tags: commerce
---


title: Automatically generated invaild URL

text:
# Question
Title: Automatically generated invaild URL
In admin/config/search/redirect/404, I found a lot of invalid url, it's a lot of additional "products" on our url, for example, News/products/products/products/products/products/products; LED-Replacement-Lamps/LED-RGB-Lights/products/products/products/products/products/products/products/products/products;  The "NEWS" is our Contents, but "LED-Replacement-Lamps/LED-RGB-Lights/" is 301 redirect I do by "URL redirects”. So I want to know it's the problem of "URL redirect" tool or others?

I have check the patterns,but i did not find the issue. I want to know why there is many links with additional "product" repeat again and again?

# Answer
Problem is in your `pathauto` Patterns, go to `admin/config/search/path/patterns1` and check your pattern, it seems you have a pattern that when each time the content edited Url added to your `Url Alias` again.

I guess something like this exists there

```
 products/[node:url]

```
> 0 votes

---
Tags: uri, redirection
---


# Question
Title: How to definitely stop inside a Rule and prevent any further actions in the rule from executing?
I have not seen that the Rules module can do this out of the box, but how can I prevent further execution of subsequent actions in a rule?

For example, I have multiple components in a rule. The first one has a condition and if that is TRUE, it will execute one action, but the other components following the first one, MUST NOT BE EXECUTED.

So without adding further conditions to the rest of the components in order to prevent execution, I want to jump out of the complete Rule after executing the fist component.

I guess this can be accomplished with php inside the first component?

# Answer
This seems like a perfect use case the Conditional Rules module. Some more details about this module (from its project page):

> ... provides Rules plugins for conditionally altering execution flow directly inside a group of **actions**.

Using this module, there is no need for "*PHP inside the first component*" (as in your question.

Refer to my answer to "How to prevent a node being saved when using the Rules module?" for an illustration of how to use this module.
> 0 votes

---
Tags: rules
---


title: How do I conditionally add a field?

text:
# Question
Title: How do I conditionally add a field?
I'm trying to find out any example of adding new conditional field using ajax in Drupal 8 form API, but I can't find it.

This is my code.

```
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#maxlength' => 64,
    '#size' => 64,
    '#default_value' => $name,
);

$form['floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Floor'),
    '#default_value' => $floor,
);

$form['flat_per_floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Flat Per Floor'),
    '#default_value' => $flatPerFloor,
    '#ajax' => array(
        'callback' => 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' => 'fade',
        'event' => 'change',
        'method' => 'replace',
        'progress' => array(
            'type' => 'throbber',
            'message' => "Generating..",
        ),
    ),
);

if ($form_values['floor']) {
  $form['flats'] = array(
    '#type' => 'checkboxes',
    '#title' => $this->t('Content Type'),
    '#options' => node_type_get_names(),
  );
}

$form['submit'] = array(
    '#type' => 'submit',
    '#title' => $this->t('Submit'),
    '#default_value' => $this->t($submit),
);

```

This is the callback function.

```
public function flatGenerate(array &$form, FormStateInterface $form_state) {
  // …
}

```

How do I add a new field after filling-up my *Flat Per Floor* field?

# Answer
> 0 votes
I don't have much experience in Drupal 8. Please refer my suggestion bellow.

1. Please add wrapper item for the ajax call eg:
```
$form['flat_per_floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Flat Per Floor'),
    '#default_value' => $flatPerFloor,
    '#ajax' => array(
        'callback' => 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' => 'fade',
        'event' => 'change',
        'method' => 'replace',
        'progress' => array(
            'type' => 'throbber',
            'message' => "Generating..",
        ),
        'wrapper' => 'flat-per-floor-wrapper',
    ),
);

```
2. Add the wrapper container under the flat\_per\_floor field

```

$form['flat_per_floor_wrapper'] =  array(
  '#type' => 'container',
  '#attributes' => ['id' => 'flat-per-floor-wrapper']
);

```

For more details please refer the example module for drupal 8 and check the ajax form https://www.drupal.org/project/examples

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


# Question
Title: "Error: Undefined class constant 'Symfony\Component\DependencyInjection\ContainerInterface::SCOPE_CONTAINER'"
I am using drush 8.1.2 and drupal 8.1.

I ran `composer update` in /core as well as in the project root. From what I can see it updates /core/vendor as well as /vendor (in project root).

Obviously this means that many of the libraries are duplicated; I am not sure if this is the idea.

Anyhow, when execute any drush command from /sites/default I get the following error:

> Error: Undefined class constant 'Symfony\Component\DependencyInjection\ContainerInterface::SCOPE\_CONTAINER' in /myproject/core/lib/Drupal/Core/DependencyInjection/Container.php, line 16

If I open core/lib/Drupal/Core/DependencyInjection/Container.php in my IDE (PHPStorm), the IDE tells me there are multiple definitions for `Symfony\Component\DependencyInjection\ContainerInterface`, which is fair enough because there is one in core/vendor as well as vendor (in the project root).

Either way, the versions of `Symfony\Component\DependencyInjection\ContainerInterface` is exactly the same (version 2.8.6)

According to this post, it is important that they are the same, which they are, and the class constant is defined in both files.

I get the impression, the file is not being 'auto-loaded', but I do not know enough about Drupal 8 to figure out if it is or not.

For the record, when I open the project in my browser (hit the web site), it is working fine.

So the drush / drupal boot-strap process is not working.

Any ideas where to start looking please.

# Answer
> 1 votes
The problem is exactly that you executed `composer update` twice, in two different directories. You don't execute it from the core directory, but only from the directory containing the core directory. In fact, the composer.json file you find in the directory where you decompressed the Drupal archive contains the following lines.

```
    "merge-plugin": {
        "include": [
            "core/composer.json",
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }

```

The `include` part is telling to Composer to include the core/composer.json file too when updating. Supposing that mysite is the directory containing the core directory and the other Drupal files, it is enough you execute the following commands to get in mysite/vendor all the dependencies necessary.

```
cd mysite
composer update

```

In my case, I get the following output. (It may change, basing on how often you execute those commands.)

> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Removing symfony/polyfill-iconv (v1.1.1)
> Installing symfony/polyfill-iconv (v1.2.0)
> Downloading: 100%
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Removing symfony/polyfill-mbstring (v1.1.1)
> Installing symfony/polyfill-mbstring (v1.2.0)
> Downloading: 100%
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Removing symfony/polyfill-php54 (v1.1.1)
> Installing symfony/polyfill-php54 (v1.2.0)
> Downloading: 100%
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Removing symfony/polyfill-php55 (v1.1.1)
> Installing symfony/polyfill-php55 (v1.2.0)
> Downloading: 100%
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Removing guzzlehttp/promises (1.1.0)
> Installing guzzlehttp/promises (1.2.0)
> Downloading: 100%
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Removing symfony/polyfill-apcu (v1.1.1)
> Installing symfony/polyfill-apcu (v1.2.0)
> Downloading: 100%
>
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
> Writing lock file
> Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

Both Drupal 8 and Drush work for me.

```
drush status

```

> Drupal version : 8.1.1
> Site URI : http://default
> Database driver : mysql
> Database hostname : localhost
> Database port :
> Database username : database\_username
> Database name : database\_name
> Drupal bootstrap : Successful
> Drupal user :
> Default theme : bartik
> Administration theme : seven
> PHP configuration : /etc/php.ini
> PHP OS : Darwin
> Drush script : /usr/local/bin/drush
> Drush version : 8.0.5
> Drush temp directory : /tmp
> Drush configuration :
> Drush alias files :
> Install profile : standard
> Drupal root : /Library/Server/Web/Data/Sites/mysite
> Drupal Settings File : sites/default/settings.php
> Site path : sites/default
> File directory path : sites/default/files
> Temporary file directory path : /tmp
> Sync config path : sites/default/files/config\_WZrobbGFfHIWBRmKDknFVfKgdyG1gKNFLBYcpBlbTZtEarG\_rPEixLJFW6faE9yNFTjdkieQbA/sync

As side note, if you need to include the composer.json files modules could have, you can edit the mysite/composer.json file to contain the following lines.

```
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }

```

Alternatively, you can use the Composer Manager module. I would suggest installing it, if you need to include any dependecy modules could have.

---
Tags: 8, drush
---


# Question
Title: How do you include a field.tpl.php, to a custom views field handler. outside of the theme?
so i've created my custom field handler in views. and i want to include a field template in the module. i can achieve what i need by copying the views-view-field.tpl.php into my theme. but i want views-view-field--MYMODULE.tpl.php to be scanned and used from the module folder..

do i need to "declare a theme function" in my

class views\_handler\_MYMODULE extends views\_handler\_field

THANKS

# Answer
> 0 votes
Just adding a field template to the templates folder of your module won't work because, by default views doesn't utilize field templates. However you can explicitly set a template file using the \_theme function in your module ie:

```
function MODULE_NAME_theme($existing) {
  return array(
    'views_view_field__FIELD_NAME' => array(
      'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
      'template' => 'views-view-field--FIELD-NAME',
      'original hook' => 'views_view_field',
      'path' => drupal_get_path('module', 'MODULE_NAME') . '/templates',
    ),
  );
}

```

Source: http://grayside.org/2010/09/how-override-views-field-template-module

# Answer
> 0 votes
If you want to have a template file being loaded from your module's templates folder, you should do the following:

1. Implement hook\_views\_api to tell Views where you keep views templates, e.g. `your_module/templates`
2. Following the naming conventions for Views and add views-view-field.tpl.php into your module's template folder, e.g. `your_module/templates`

After you clear your cache and rescan the template folders using Views UI, your tpl file should be selected.

Hope this helps, the main source for this answer was https://stevenyeung.com/article/template-override-drupal-views-3-from-module/

---
Tags: views
---


# Question
Title: How to hide taxonomy terms with no content
How to display only those taxonomy terms that have content? Can this be done with the help of relationships or contextual filters?

# Answer
If you create a view to show terms, you can create a relationship for "Taxonomy term: Content with term". This will allow you to access all the nodes referencing each term.

In the configuration screen for the relationship, you can check the "Require this relationship" checkbox (see screenshot below). Like that, terms that are not referenced by any node will not be displayed.
> 2 votes

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


title: Correct way to render entity fields?

text:
# Question
Title: Correct way to render entity fields?
According to Rendering Drupal 7 fields (the right way), the correct way to render fields is with code similar to the following one.

```
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

```

This is for rendering node fields.

I am using the Paragraphs module which lets you create custom bundles in the predefined "paragraph" entity. I could use *entity.tpl.php* to override the output of Paragraph module fields.

I want to print my fields that are stored in the entity, but the above code won't work because it is for nodes.

What is the code for a generic entity's field?

# Answer
The equivalent to the sample code you posted from the article, but for an entity type other than node would be the following one.

```
$entities = entity_load('ENTITY_TYPE_NAME', array($YOUR_ENTITY_ID));
$entity = $entities[$YOUR_ENTITY_ID];
$field = field_get_items('ENTITY_TYPE_NAME', $entity, 'field_name');
$output = field_view_value('ENTITY_TYPE_NAME', $entity, 'field_name', $field[$delta]);

```

If you're doing this in a template, the entity fields should have already been retrieved by `template_preprocess_entity()` and made available under the `$content` variable, so you shouldn't have to do all these steps in an overridden entity template.
> 3 votes

# Answer
There is a function for that: `field_attach_view()`.

I had to use it to get a renderable array from Paragraph entities. You can render this array with `render()`.

```
$paragraphEntity = entity_load("paragraphs_item",array($paragraph['value']));
$renderableParagraphBundle = field_attach_view(
  "paragraphs_item",
  $paragraphEntity[$paragraph['value']], "full",
  $GLOBALS['language']->language,
  array()
);

print render($renderableParagraphBundle);

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How can I get the language name of the current node?
I'm trying to figure out how to get the name of the language of the current node in display suite. I find a language option under one of the node categories in the dynamic field content selector, but that outputs the language code, not the name. Do I need to handle this in a preprocess function or is there some way of getting this that I've not managed to find?

# Answer
I didn't find anything there available for clickers. I could suggest the following alternative:

1. Activate the "Display Suite Format" module
2. Create Display Suite "Code field" with following content:

```
<?php
  return t(locale_language_name($entity->language));
?>

```
3. Don't forget to activate the "Display Suite code" text format for this code field.
4. Add this code field to your content type's display!

Hope this helps!
> 2 votes

# Answer
Here's what I've done. I'd love a better answer:

in my templates.php in my theme (the dynamic field I created in display suite is called language):

```
function MYTHEME_preprocess_field(&$variables) {
    if ($fieldname == 'language') {
        $item['#markup'] = locale_language_name($item['#markup']);
    }
}

```
> 0 votes

---
Tags: 7, nodes, display-suite
---


# Question
Title: How to troubleshoot Rules when a required variable for an event is not provided?
I'm seeing a strange behavior on my site and I'm trying to figure out how to correct it.

I have a rule that triggers on the event *After updating an existing user account*. This rule uses two variables, **account** and **account-unchanged**. Both of these should be provided by default.

However, for some reason user accounts are being saved upon login-- and when they are saved at login, **account-unchanged** is unset. This leaves a PHP warning in watchdog.

To remove this error, I attempted to add a condition, **Not data value is empty (account-unchanged**, but this just gives me another watchdog warning like so:

> Unable to evaluate condition data\_is\_empty.

Ideally I will be able to find the reason why user accounts are being saved on login, but in the meantime, is there a way to prevent the rule from being evaluated when a required variable is not set?

# Answer
> 2 votes
Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so *that* can't be the reason anymore then why things don't work as expected).

**Note**: maybe it's worth to do some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?"

---
Tags: 7, rules, debugging
---


title: How to run hook_update for the database

text:
# Question
Title: How to run hook_update for the database
Suppose we have a simple module with 3 files: test.info, test. install and test.module.

### test.install

```
<?php
function test_schema() {

    $schema['test'] = array(
        //fields
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true
                ),
            ),
        //additional properties
        'primary key' => array('id'),
        );

    return $schema;
}

```

When I install the module via the web interface, the table is created. Then I add hook\_update:

```
function test_update_7100() {
    $spec = array(
        'type' => 'varchar',
        'description' => "New Col",
        'length' => 20,
        'not null' => FALSE,
        );
    db_add_field( 'test', 'name', $spec);
}

```

Now I need to run the update function to modify the table. But I don't know where I can do it. Module is not present in "Modules" -\> "Update".

# Answer
You can run just `drush updb -y` on your site folder.
> 3 votes

---
Tags: database, updating
---


# Question
Title: Issues sending HTML email with Simplenews module
I am able to send plaintext emails with the Simplenews module. I have installed the Mimemail module; I configured the mail system to use Mime Mail Mailer in DEFAULT MAIL SYSTEM. After sending the emails to queue, when I run the CRON job, Drupal displays an error message:

> Unable to send email. Contact the site administrator if the problem persists.

Has anyone used Simplenews to send HTML emails in Drupal 8.1.1? If so, can you please advise how to do this?

# Answer
Check out the following modules, in their configuration it's easy to set email system and html format:

Select mime mail in the config of mail system. Also make sure that content text format and newsletter settings is full html and it should do it.
> 3 votes

---
Tags: 8, emails
---


title: Use profile2 fields in custom form

text:
# Question
Title: Use profile2 fields in custom form
I'm trying to add profile2 fields in my custom form. I have created a path in my custom module in hook\_menu() and in page arguments inside array, I have passed my custom\_form.

In my custom\_form I have returned the following code:

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

    global $user;
    module_load_include('inc', 'user', 'user.pages');
    return drupal_get_form('user_profile_form', $user);
}

```

When I go to the path I do not see the fields which I had created for a particular profile type through manage fields. Instead it renders the default user-profile-form fields.

Where I'm going wrong? Please suggest any ideas.

Thanks In advance

# Answer
Solved it with the following code:

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

global $user;

if (!isset($form_state['profiles'])) {

  $profile = profile2_load_by_user($user, 'profile_machine_name');
  if (!$profile)
  {
    $profile = profile_create(array(
      'type' => 'profile_machine_name',
      'uid' => $user->uid
    ));
  }
  $form_state['profiles'][$profile->type] = $profile;
}

profile2_attach_form($form, &$form_state);

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

```
> 3 votes

---
Tags: 7, forms
---


# Question
Title: How to display the form fields of content type in a table using custom template file?
I have created a content type **Article** including the fields **Field 1**, **Field 2**, **Field 3** ......

All these fields have multiple values. I also created the **custom template** for this content type.

Now I want to display all fields of the form in a table and use only one button **Add another item** to add a line for all the fields.

# Answer
Add the following snippet in **template.php** of your active theme;

```
<?php
function THEMENAME_theme($existing, $type, $theme, $path) {
    return array(
        'article_node_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'node--add--article',
            'render element' => 'form',
            ),
    );
}
?>

```

Then create a template file called **node--add--article.tpl.php** (same as the 'template' field in template.php.)

This is **node--add--article.tpl.php**:

```
<table >
  <tr>
    <td><?php print drupal_render_children($form['field_1']); ?></td>
    <td><?php print drupal_render_children($form['field_2']);  ?></td>
    <td><?php print drupal_render_children($form['field_3']);  ?></td>
  </tr>
</table>

<?php print drupal_render_children($form);  ?>

```

Now **Clear Cache** and see the result.
> 1 votes

# Answer
Try to use the Css Column Property to distribute them as table or use the combination of modules Panels & Panelizer (try the first option, it might be lighter to implement).
> 0 votes

# Answer
You need to use field group multiple module

And for displaying that as table you can add to that module field group table module
> 0 votes

# Answer
try this Field Collection Table it work with: Field collection

Regards
> 0 votes

---
Tags: entities, theming
---


# Question
Title: Feeds import - Skip importing item based on some condition
I am making API call to import data into Drupal. The API provides 2 filters by which I can get the data. Now I want to apply additional filter on the returned data and only save data which validate the third filter. E.g. The API - http://example.com/users?country=US&state=NY Requirement - I want to import users data into Drupal only if users age is above 18 (And from US-NYC).

Now the API do not have age filter, but it provides age in the response. How can I write a code to ask feed importer to skip import if age is below 18.

Hope I am clear asking this question.

# Answer
You can do this using hook\_feeds\_presave to check the data prior to it being saved.

```
function mymodule_feeds_presave(FeedsSource $source, $entity, $item) {

  // check that this is fired only for the importer being used
  if($source->importer->id=='my_user_importer'){

    // check that the age is over 18
    if($item['age'] < '18'){
      $entity->feeds_item->skip = TRUE;
      drupal_set_message(t("Skipping user who's age is below 18", 'warning');
    }
  }
}

```
> 2 votes

---
Tags: feeds, importing-exporting
---