# Question
Title: What is the mechanism used to control how Drupal pages are rendered?
I'm a Java programmer trying to get started with Drupal. Specifically, I want to be able to create custom pages. More specifically, I want to understand the nuts and bolts of how this is done (I'm an engineer; it's just my nature) I have a little PHP experience and I've configured Drupal installations for years. I'm aware of many of the modules that help make this process easier (such as the Views module), but again--I'm interested in working through the nuts and bolts myself.

I'm not specifically interested in creating new Drupal modules, unless that is the only way to create new pages in Drupal. My primary interest is in being able to create a custom page. Let me give a few examples:

1. I have a db of funny quotes. I'd like to be able to use Drupal to display a selected quote AND HAVE COMPLETE CONTROL OVER THE PAGE LAYOUT (and again--not using an existing module; I want to understand the inner workings). Don't ask why I'd want to use Drupal for this, or suggest alternate methods of accomplishing it. It's a made up example to illustrate what I'm wanting to learn. :-)
2. This is a less made up example. I'd like to create a "newsletter" where the site editors can select submitted content and customize layout (all in a custom UI) and then create a page with that content, one suitable for either viewing in a browser or printing. Sort of a "desktop publishing" concept for Drupal. Again, don't suggest ways of accomplishing this. It's an example to illustrate what I'm wanting to learn.

Basically, I like Drupal's permissioning, modularity, and content management but I'd like to learn how to control display (as complete control over display as possible). The problem is that I don't even know what topics to start learning. Creating modules? Themeing? Something else? What is the mechanism or system that I need to learn to be able to completely control how Drupal pages are rendered?

Corollary question: does such control (not limited to just a block or region, but including menus, headers, footers, and everything visible on the page) require modifying the Drupal code directly or can it all be done in the theme/module systems?

# Answer
Aaron is right that you'd likely want to handle much of this at the theme layer. You'd want to familiarize yourself with how drupal handles templates.

As for the actual creation of a page in code, this page does a pretty good outline of a method. I've not done this myself, but it reads correctly.

You'll first want to understand how to build a module. The basics are, you need a `mymodule` folder, and a `mymodule.module` file and `mymodule.info` file. Anywhere you see a resource that says to use `hook_some_function`, you're going to replace hook with `mymodule`.

The nuts and bolts of the page above outline:

-- Implementing of hook\_menu (in this instance, the module's name is `starting_drupal_dev`)

```
/**
* Implements hook_menu().
*/
function starting_drupal_dev_menu() {
  $items['starting_drupal_dev/custom'] = array(
    'title' => 'Custom page',
    'page callback' => 'starting_drupal_dev_custom',
    'access arguments' => array('access content'),
  );

  return $items;
}

```

-- Using the custom function `starting_drupal_dev_custom` to define how the page renders

```
/**
* Custom callback function.
*/
function starting_drupal_dev_custom() {
  $content['raw_markup'] = array(
    '#type' => 'markup',
    '#markup' => '<p>Hello world</p>',
  );

  return $content;
}

```

You could then assign your various database queries to variables in order to render them within `#markup`.

Again, I've not used this particular method myself, but it seems to me that you could at least use this as a starting point for what you're trying to do. Not sure whether or not you could combine this method with theme templates for layout or not. Maybe somebody else could chime in with regard to that.

As for your final question, NEVER (usually) HACK CORE. Handle everything in modules and themes.
> 1 votes

# Answer
control over the layout is intended to be accomplished through the theme layer, so you'll want to learn theming to control display. Drupal.org provides a good starting place for learning theming (https://www.drupal.org/documentation/theme), though other resources may be found through learning services like https://drupalize.me.

This is a question with a very lengthy answer and the best thing I can do is point you towards the right resources. Best of luck and welcome to the Drupal community!
> 0 votes

---
Tags: theming
---


title: Specifying parameters for block_load

text:
# Question
Title: Specifying parameters for block_load
I'm attempting to load a Book Navigation block programmatically inside another block. After doing some research it seems that I need to take advantage of the bload\_load function. I'm using

```
$block = block_load('book', 'navigation');
$output =_block_get_renderable_array(_block_render_blocks(array($block)));
$res_output = drupal_render($res_output);
print render($res_output);

```

However there is no output. I have a feeling that the parameters for block\_load are incorrect. I based them off of what the URL contained

```
/admin/structure/block/manage/book/navigation/configure

```

# Answer
> 1 votes
The problem isn't with `block_load()`; you've specified the correct parameters with the function (the module is 'block' & the delta for the block is 'navigation'). The problem is your typo prevents the render array going to the `print_render()`. It should be:

```
$res_output = drupal_render($output);

```

---
Tags: 7, blocks
---


# Question
Title: Fetch user's realname (from Name Field) within database query (or an alternative method)?
I'm building a custom field for a form based off of the values stored in a user reference field. The options for this field are being built from the following database query:

```
<?php
// Fetch the users referenced in the provided node
$args = array(':nid' => $nid);
$result = db_query("
    SELECT
        field_data_field_user_ref.field_user_ref_target_id,
        users.name
    FROM field_data_field_user_ref
        JOIN users
            ON field_data_field_user_ref.field_user_ref_target_id=users.uid
    WHERE entity_id = :nid", $args);
$arr = $result->fetchAll();

// Add these users as an array to be displayed
$users = array();
foreach ($arr as $val) {
    $crafters[$val->field_user_ref_target_id] = $val->name;
}

```

...returning the array in the form of...

```
uid 1 => name 1
uid 2 => name 2
uid 3 => name 3

```

This works fine, except for the fact that the user's username is displayed instead of their "real name." In my case, the Real Name is being generated by a Name Field (from the Name project). I can't seem to figure out a way to grab the real name from the database. Not sure if it is even stored in there.

Is there an alternative way to grab each user's real name? I'm assuming I could use some application of `user_load` but I don't know if there's a performance hit associated with loading an unknown number of users one by one just to grab their names. Probably will never be more than a handful of users, but I'd rather keep it optimized.

# Answer
> 0 votes
The Name project used entity fields that can be queried in the DB, just like any other field. All you need to know is the machine name of field that you attached to the user entity. To use your example above:

```
$result = db_query("
    SELECT
        field_data_field_user.field_user_target_id,
        nf.*,
        users.name
    FROM field_data_field_user
        JOIN users
            ON field_data_field_user.field_user_target_id=users.uid
        JOIN field_data_field_MY_NAME_FIELD AS nf
            ON nf.entity_id=users.uid AND nf.entity_type = 'user' AND nf.bundle = 'user'
    WHERE field_data_field_user.entity_id = :nid", $args);

```

All you need to do is replace `MY_NAME_FIELD` with the machine name of your actual field. The result will be rows that contain name columns associated with the user reference.

---
Tags: forms, database, users
---


title: Cloning site and $config_directories

text:
# Question
Title: Cloning site and $config_directories
On my local Drupal 8 multisite environment in sites/default/settings.php I have:

```
$config_directories['staging'] = 'sites/default/config/staging';
$config_directories = array();

```

Because the default direction for the configuration files `sites/default/files` is .gitignored.

Is above correct, or do I have to delete `$config_directories = array();` and put only the first line? How do I have to setup `$config_directories` properly so I can version my Configuration with Git?

Is `$config_directories` the same in both settings.php for the local site and production environment. In other words; is settings.php the same for the local site and production environment, except the database information?

Acquia Dev Desktop also gives:

```
$config_directories['sync'] = 'sites/griffioenrotterdam-dev.dd/files/config_CBOBWbcJU487p7Gc5z5e4GPzL6pSuEKQytsN6heKUULhL8ziYY7DUJoAbHI-dUxnFEfpzk0W7Q/sync'

```

What about that?

My steps to set this all up where:

* I set up a local Drupal 8 multisite environment using Acquia Dev Desktop. All worked fine.
* I have a Git workflow setup
* Now I try to make instances of my local site (clone) for Dev and Prod environments
* With git I pull the Drupal 8 code to my production server
* I adjust settings.php in sites/default/settings.php
* I dumped my local Database using drush
* I import the Database in Database connected to staging (Dev) environment

But when I visit http://staging.griffioenrotterdam.nl/ it doesn’t look good.

**--- Update ---**

```
$config_directories['staging'] = 'sites/default/config/staging';

```

Is from an old Drupal 8 version.

Now you have to use:

```
$config_directories = array(
    CONFIG_SYNC_DIRECTORY => './../config/sync',
);

```

But when I go in admin to Reports \> Status report \> it says:

> The ./../config/sync folder does not exist. You may need to set the correct directory at the file system settings page or change the current directory's permissions so that it is writable.

# Answer
> 0 votes
I don't know what you try to do with the config directories.

This doesn't make sense at all, setting a value and deleting it:

```
$config_directories['staging'] = 'sites/default/config/staging';
$config_directories = array();

```

The config directory `staging` does not exists anymore, it must be from an old drupal 8 version. You only need `sync`. This can be any directory. The hash is only for security reasons and is not needed outside the public files directory.

And I don't see anything in your workflow that would need a special configuration of the config directory, because you transfer the config in the database.

---
Tags: 8, version-control, acquia-dev-desktop
---


# Question
Title: How can I show menu according their role?
I have three roles Business Manager, General Manager and Handler.

How can I show only specific menu according their role?

# Answer
> 1 votes
Note: This answer is for drupal 7.

You can use Menu Block. And make blocks of menu and use on page. And you can set visibility settings for that block.

# Answer
> 0 votes
# Part 1: Rules block visibility

Have a look at 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 implement the logic to check your roles.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

Here is a Rules Component you could use for a role with role id "4", assuming one of those three roles have "4" as role id, change that digit to whatever role id that matches for your case:

```
{ "rules_block_visibility_show_menu_block_for_role_4" : {
    "LABEL" : "Show menu block for role 4",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user YES or NO has the role with role ID equal to `4`.

With that, we're coming close to an actual answer to your question, as explained in Part 3 below.

# Part 3:

Head over to the "Block" settings for each of your menu blocks you want to conditionally show. At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

So if you create 1 such Rules Component for each of your menu blocks from Part 2, you just pick the one that fits for each role. Done!

---
Tags: users
---


title: Add PHP code to block's content

text:
# Question
Title: Add PHP code to block's content
Is there a module that allows a php text filter in drupal 8? This was a possibility in drupal-7 but I can not find something similar to 8.

# Answer
> 5 votes
The PHP filter module was removed from core, because of the inherent security problems it presents.

It now exists as a separate contrib module, but beware that even the module description itself warns against using it:

> **Warning**
>
> Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site. There are better alternatives out there that do not expose such vulnerabilities on your site.

---
Tags: 8, blocks
---


# Question
Title: How do I programmatically assign the access to a block?
I have created a block programmatically but I don't know how I can programmatically assign the access to it. How can I achieve it?

# Answer
> 9 votes
Setting the "roles" array in the array returned from `hook_block_info()` doesn't work because:

* The roles that are allowed to see a block, and which are set in the user interface, are saved from block\_admin\_configure\_submit() in the "block\_role" table

```
$query = db_insert('block_role')->fields(array('rid', 'module', 'delta'));
foreach (array_filter($form_state['values']['roles']) as $rid) {
  $query->values(array(
    'rid' => $rid,
    'module' => $form_state['values']['module'],
    'delta' => $form_state['values']['delta'],
  ));
}
$query->execute();

```
* The code that decides which blocks should be shown to the currently logged-in user is contained in block\_block\_list\_alter(), which is an implementation of hook\_block\_list\_alter(), and uses only the content of that table

```
$result = db_query('SELECT module, delta, rid FROM {block_role}');
foreach ($result as $record) {
  $block_roles[$record->module][$record->delta][] = $record->rid;
}

foreach ($blocks as $key => $block) {
  if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
    // This block was added by a contrib module, leave it in the list.
    continue;
  }

  // If a block has no roles associated, it is displayed for every role.
  // For blocks with roles associated, if none of the user's roles matches
  // the settings from this block, remove it from the block list.
  if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
    // No match.
    unset($blocks[$key]);
    continue;
  }

  // …

}

```
* There isn't another Drupal function that checks the *roles* property in the data returned from `hook_block_info()`, nor is the content of the "block\_role" table merged with what returned from the `hook_block_info()` implementations.

You could verify the user has the required role to see the block in `hook_block_view()`, but at that point Drupal is already rendering the block; that means the user would still see the block title, if one has been already set.

What you can do is implementing `hook_block_list_alter()` to remove the information about that block when the user doesn't have the required role.
To avoid confusion to the users who administer the blocks, I would also alter the form used to edit a block, and disable the form field used to set which roles can see that block, since the module implementing it is going to use its own list of roles; the minimal code should at least show a message about the role settings not having any effect, but I would also disable the form elements for the role settings.

Since the Block module already shows form fields to select which roles see a block, you could also simply set a default for your block, and let the administrator users change it if necessary.

>

As per checking the roles a user has versus checking the permissions a user has, the last is preferred, especially when the alternative would be hard-coding a list of roles in a module.
As shown from the Block module, using permission is not the only alternative: A module could have setting for deciding which roles are allowed to see something.
Clearly, it is not always worth having a setting for which roles are allowed to do something. I imagine also what for the administrator users would mean if 10 modules would have their own settings for which roles are allowed to do something, instead of using permissions, and allowing the administrator users to use a single page to set them.

# Answer
> 1 votes
In your hook\_block\_info you could try something like:

```
$blocks['myblock'] = array(
   ...
   'roles' => array(
      'administrator' => '3',
      'authenticated user' => '2',
   )

```

# Answer
> 0 votes
Assuming that you are making the blocks yourself with hook\_block\_info() then you could just do user\_access() in your hook\_block\_view() function. Check out the api docs since they have an example of this.

# Answer
> 0 votes
It is impossible in hook\_block\_info(), but you can use this query to achive this. Change MODULE\_NAME, BLOCK\_DELTA and RID accordingly

```
$query = db_insert('block_role')
  ->fields(array(
    'module' => 'MODULE_NAME',
    'delta' => 'BLOCK_DELTA',
    'rid' => 2, // Authenticated User
  ))
  ->execute();

```

# Answer
> 0 votes
In hook\_block\_view , you can use `global $user` to get information about the user , then based on user's role you can assign different `block['subject']` and `block['content']` or even do not assign any subject and content to block if it is going to be invisible for that role . here is an example :

```
function ModuleNAME_block_view($delta = '') {
  switch ($delta) {
    case 'Your_BLOCK' :
      Global $user;
      if($user->uid != '0') {
        $block['subject'] = 'SUBJECT';
        $block['content'] = 'SOME CONTENT OR A FUNCTION FOR BLOCK';
      }
      break;
  }
  return $block;
}

```

using this code authenticated users (not guests) will have block become visible for authenticated users.

---
Tags: 7, blocks, users
---


title: Contextual filter for taxonomy terms

text:
# Question
Title: Contextual filter for taxonomy terms
I have a taxonomy terms display that list a taxonomy\_list, this taxonomy\_list has parents and childs:

```
Parent
 child
Parent
 child
 child

```

Is there a contextual filter in views that i can use to pass the parent id and it would return the childs under this parent.

# Answer
You can use "**Taxonomy term: Parent term**" as contextual filter in your view.

Most likely you will need to provide a default value for the filter, such as "**Taxonomy term ID from URL**".

Provide a default value for your filter according to your preferred usage. The options for setting the default value of the filter should be self-explanatory.

Since you didn't specify where this view is supposed to be displayed, I can't give any other insight.
> 2 votes

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


# Question
Title: Uncaught TypeError: Cannot set property 'bootstrap' of undefined
I'm receiving the following two errors, i'm unsure how to fix them. after doing some research this file has had issues before. The solutions did not solve my problem. Could this be a simple script load order?

> Uncaught TypeError: Cannot set property 'bootstrap' of undefined (anonymous function) @ bootstrap.js?ny6rj2:13
>
> ```
> var Drupal = Drupal || {};
>
> (function($, Drupal){
>   "use strict";
>
>   Drupal.behaviors.bootstrap = {
>     attach: function(context) {
>       // Provide some Bootstrap tab/Drupal integration.
>
> ```
>
> (anonymous function) @ bootstrap.js?ny6rj2:230
>
> ```
> })(jQuery, Drupal);
>
> ```

# Answer
> 0 votes
Drupal exports in javascript the Drupal variable that has several subitems inside depending on your configuration. Your error suggest that the bootsrap property does not exist (at least yet). You can easily make sure that this is the case by opening the console in your browser (f12 in chrome) and type: `console.log(Drupal.behaviors);` if the property is not there you cannot use it.

Make sure you re loading the bootstrap library correctly. Usually you can do this by downloading the bootstrap module/theme or by using the libraries module.

Also note that Drupal behaviors intend to run every time an 'ajax' call is made by in a drupal page. I m putting ajax in quotes because drupal actually uses a legacy way for ajax called AHAH

# Answer
> 0 votes
If you use Vasil Dinkov\` smartmenus plugin for Bootstrap, then jquery.smartmenus.bootstrap.js should be placed AFTER jquery.smartmenus.js, not vice versa.

---
Tags: javascript
---


# Question
Title: How to do something BEFORE a view is updated via ajax submit button?
I have a view with exposed filters and Ajax activated. I would like to validate my exposed filters values before my view is updated by the submit button. The following code works without Ajax, but when I activate this functionalitty it doesn't validate!

```
jQuery('FORM ID').submit(function () {
  jQuery('FILTER TEXTFIELD').val(MY VALIDATION);
  return true;
});

```

How can i capture the ajax execution and validate my values BEFORE the ajax call?

# Answer
> 0 votes
You have to capture the mousedown event on the submit / apply button, prevent submission using e.preventDefault(), validate and if everything is fine submit the form using $('#form-id').submit()

**Update:**

Here is a fully tested and working code:

```
(function ($) {
    Drupal.behaviors.ValidateAjaxForm = {
        attach : function (context, settings) {

            var $form = $("form#views-exposed-form-list", context); // ajax form selector, or better specify by class name
            var $submitButton = $('#edit-submit-list', $form); // ajax submit button selector, or better specify by class name

            // Use off to remove any existing submit handler
            $form
            .off('submit')
            .on('submit', function (e) {
                e.preventDefault();
                var $form = $(this);

                var valid = false;

                // Run some validation on $form object.
                // check conditions here and if all is fine declare valid = true

                // If vaild, trigger event on button
                if (valid) {
                    $form[0].submit();
                }

            });
        }
    };
}
    (jQuery));

```

# Answer
> 0 votes
In order to make validation work in case *ajax is enabled*, do the following:

1) You have to apply this patch to */misc/ajax.js* .. (should be committed to core in near future I expect)

2) Use this code to capture the submit event and to do validation before actual form submission:

```
(function ($) {
    Drupal.behaviors.ValidateAjaxForm = {
        attach : function (context, settings) {

            Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options) {

                // First make sure that the Ajax event is triggered by the form to be validated
                if ($(element.context).is($("form#views-exposed-form-ID"))) { // relpace with form id

                    var isValid = true;

                    // Do validation work here
                    // if anything is wrong decalre isValid = false

                    return isValid;
                }
            };
        }
    };
}
    (jQuery));

```

---
Tags: 7, ajax, views
---


# Question
Title: Display the total weight of the order in the basket
I installed the module https://www.drupal.org/project/physical in my cart view, I'd see the total weight of the order. How to do this ?

# Answer
You need to add weight as a field to the product entity type first. Then you can see. Then you need to install this module, make a view and calculate the total.

Hope that helps.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: How to set permission for exposed filter in Views block
I have a View with several blocks or displays. In one of these displays I have added the filter "Published" and made it exposed, so that user can switch between published and unpublished content.

Now I only want users with the administrator role to be able to see this filter, but I cannot figure out how to do this. Can anyone give me a hint?

Thanks in advance

# Answer
> 1 votes
If you expose the filter as a block from within the view (Advanced - exposed form in block) then you could set the permissions on the exposed form block in the block system to Admin role users. Alternatively I can only think that you might need to use hook\_form\_alter to amend the permissions on that form if you want everyone others to see the view but not the exposed form.

# Answer
> 1 votes
I post the answer myself in case anyone is having the same problem. The solution was to use views-view--display\_name.tpl.php and simply add a check if the user is admin or not for the exposed item... like this:

```
<?php global $user; ?>
<?php if (in_array('administrator', $user->roles)):?>
  <?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>
<?php endif; ?>

```

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


# Question
Title: Summary or trimmed body field formatter does not display anything when the trim length is anything below 888
I am creating a view for blog items to be displayed on the home page.

Obviously I would not want the whole blog to show on the home page and I want a summary of this to be displayed.

Whenever I set the summary to anything less than 888 it seems to delete the markup completely from the page.

Does anyone perhaps have a solution for me? Thank you in advance.

# Answer
Well I still don't know exactly what the solution to the issue with Drupal's own summary or trim option. I did however get the trim right using the Smart Trim Module. Thank you to the developers of the Smart Trim module.
> -1 votes

---
Tags: 7, views
---


# Question
Title: Add more fieldset with remove option custom module
I'm developing custom module and there's one fieldset that can be added multiple times and can be removed any particular entry also. Can anyone please suggest to achieve this? Here is my code:

```
function hook_form($form,&$form_state){
$form_state['storage']['emails'] =
isset($form_state['storage']['emails']) ? $form_state['storage']['emails'] : 0;

$form['emails'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '<div id="emails">',
    '#suffix' => '</div>',

);
if(empty($form_state['storage']['emails'])) {
    $form_state['storage']['emails'] = 0;
}
for ($j = 0; $j <= $form_state['storage']['emails']; $j++) {
    $form['emails'][$j]['candidate_email'] = array(
        '#title' => 'Email',
        '#type' => 'textfield',
        '#size' => '30',
        '#required' => FALSE,
    );
}
$form['emails']['add_email'] = array(
    '#type' => 'button',
    '#value' => t('Add Email'),
    '#href' => '',
    '#ajax' => array(
        'callback' => 'hook_ajax_add_emails',
        'wrapper' => 'emails',
    ),
);
$form_state['storage']['emails']++;

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

function hook_ajax_add_emails($form, $form_state) {
    return $form['emails'];
}

```

# Answer
> 0 votes
I got solution by this way. Here is solution code:

```
$form['emails'] = array(
    '#title' => 'Education Information',
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    //'#size' => '30',
    '#required' => FALSE,
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
);
if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
$form['emails'][$i]['candidate_email'] = array(
    '#title' => 'Email',
    '#type' => 'textfield',
    '#size' => '30',
    '#required' => FALSE,
);
}

$form['emails']['add_name'] = array(
'#type' => 'submit',
'#value' => t('Add one more'),
'#submit' => array('hook_add_more_add_one'),
// See the examples in ajax_example.module for more details on the
// properties of #ajax.
'#ajax' => array(
  'callback' => 'hook_add_more_callback',
  'wrapper' => 'names-fieldset-wrapper',
),
);

if ($form_state['num_names'] > 1) {
$form['emails']['remove_name'] = array(
  '#type' => 'submit',
  '#value' => t('Remove one'),
  '#submit' => array('hook_add_more_remove_one'),
  '#ajax' => array(
    'callback' => 'hook_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);
}

```

---
Tags: forms, hooks
---


# Question
Title: Setting a field collection default value for a field using form
I'm trying to set up a default value programmatically to my field which is in field collection. This has proved quite hard and I cant seem to get around it. Any assistance will be appreciated. This is the code i have tried to far without any success.This field is a select list with different select items. Now i want it to pre-select one of the items.

```
$field_collect = $form["field_fielc_collection_group"][LANGUAGE_NONE];

                            foreach ($field_collect as $fielders){
                                        if(is_array($fielders)){
                                        $somethin = $fielders["field_to_set_default"][LANGUAGE_NONE]["#default_value"];
                                        $default_val =array(t('something'));
                            array_push($somethin,$default_val);

```

# Answer
This is how I resolved this.

```
$language = $form['field_fielc_collection_group']["#language"];
                    $iterates = $form['field_fielc_collection_group'][$language];

                foreach($iterates as $multi__key => $iterate){
                            if (is_integer($multi__key)){
                                        if(is_array($iterate)){
                                            $delt = $form['field_fielc_collection_group'][$language][$multi__key]["#delta"];
$form["field_fielc_collection_group"][$language][$multi__key]["field_to_set_default"][$language]["#default_value"][$delt] = 'default_value' ;
                                        }
                            }
                }

```
> 0 votes

---
Tags: entities
---


title: Get the current path in Views

text:
# Question
Title: Get the current path in Views
What's the best way to get access to the current path in Views?

My use case is I want to use the current page path in a text area (i.e. I want to have a text field like More).

At the moment I'm handling it by using hook\_views\_re\_view to rewrite a "Global: Custom Text" field value with drupal\_get\_path\_alias().

Ideally I'd like something more portable, i.e. the ability to add a "Global: Current Path" field to my view.

What combination of hooks/handlers/plugins do I need to use?

# Answer
Thanks a lot. I did go down the Views PHP route initially, but it struck me as a bit un-Drupally, and even Views PHP says to use handlers where possible.

In the end I used hook\_views\_data and did:

```
function mymodule_views_views_data() {
  $data['views']['current_path'] = array(
    'title' => t('Current Path'),
    'help' => t('Provide current path.'),
    'field' => array(
      'handler' => 'concept2_views_handler_field_current_path',
    ),
  );
  return $data;
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function mymodule_views_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'mymodule') . '/handlers',
    ),
    'handlers' => array(
      // The name of my handler
      'mymodule_views_handler_field_current_path' => array(
        // The name of the handler we are extending.
        'parent' => 'views_handler_field',
      ),
    ),
  );
}

```

With a handler file like:

```
/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
class mymodule_views_handler_field_current_path extends views_handler_field {
  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE, 'bool' => TRUE);
    $options['hide_alter_empty'] = array('default' => FALSE, 'bool' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    unset($form['help']);
  }

  function render($values) {
    // Return the text, so the code never thinks the value is empty.
    return drupal_get_path_alias();
  }
}

```
> 3 votes

# Answer
Use this module views\_current\_path
> 2 votes

# Answer
Depending on what you need to do, you can choose one.

l() : print l(t('click here'), 'node/5'); This should print a link (a tag) with correct path of node/5. Aliased, and base paths are added automatically. Strongly recommended.

url(): print url('node/5'); This will print the correct path without an a tag. Base paths will be added. See api.drupal.org for its extra parameters.

request\_uri(): this will give the current request uri.

base\_path(): this will give base path of drupal site.
> 0 votes

# Answer
Have you checked out Views PHP? It has some bugs when accessing the $row variable but it works great for injecting PHP into a Views field.

You could use request\_path() in a Views PHP field:

```
Whatever text you want plus a <a href="<?php print request_path(); ?>">link</a> to the current page.

```
> -3 votes

---
Tags: 7, views
---


title: Overriding field label

text:
# Question
Title: Overriding field label
I'm trying to override the label of the picture field. I've started with the code here:

How to change the field label on my registration form? Drupal 7

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
if ($form_id == 'user_profile_form') {
  dsm($form_id);
    $form['account']['picture']['#title'] = t('Profile Picture');
}
}

```

I just want to override the "PICTURE" title to something else.

# Answer
Actual code should be:

I have used hook\_form\_FORM\_ID\_alter() instead of hook\_form\_alter().

```
function test_form_user_profile_form_alter(&$form, &$form_state) {
  // Used dpm() to check for picture array.
  $form['picture']['#title'] = t('Profile Picture');
}

```

Result:

**Note:** The capitalization of all the character must be coming from theming layer.

Use dpm() for development: The structure has changed and the account array no longer holds picture array.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Generically detecting changed fields in a custom form prior to saving a node
I'm adding certain fields from a content type into a custom form using field\_attach\_form(). When the form is submitted I'm processing those fields by calling field\_attach\_form\_validate() and field\_attach\_submit() from #validate and #submit callbacks.

At that point, I want to compare the post-submit, prepared node object to the original node and only bother to node\_save() it if any of the fields have changed. Therefore, I begin by loading the original node using `entity_load_unchanged()`.

Unfortunately, the field arrays in the original node object don't match the field arrays in the prepared node object which is waiting to be saved, even if no changes have been made to the fields, so a simple "$old\_field == $new\_field" comparison is impossible. For example, a simple text field appears like this in the original:

```
$old_node->field_text['und'][0] = array(
  'value' => 'Test',
  'format' => NULL,
  'safe_value' => 'Test',
);

```

Whereas in the prepared node it appears like this.

```
$node->field_text['und'][0] = array(
  'value' => 'Test',
);

```

You might think to just compare the 'value' key, but then you run into fields made up of other elements which don't have 'value' keys. For example, let's look at an address field where there is no 'value' key *and* there are keys in both the old and prepared nodes which don't have counterparts.

### Old node

```
$old_node->field_address['und'][0] = array(
  'country' => 'GB',
  'administrative_area' => 'Test',
  'sub_administrative_area' => NULL,
  'locality' => 'Test',
  'dependent_locality' => NULL,
  'postal_code' => 'Test',
  'thoroughfare' => 'Test',
  'premise' => 'Test',
  'sub_premise' => NULL,
  'organisation_name' => 'Test',
  'name_line' => 'Test',
  'first_name' => NULL,
  'last_name' => NULL,
  'data' => NULL,
);

```

### Prepared node

```
$node->field_address['und'][0] = array(
  'element_key' => 'node|page|field_address|und|0',
  'thoroughfare' => 'Test',
  'premise' => 'Test',
  'locality' => 'Test',
  'administrative_area' => 'Test',
  'postal_code' => 'Test',
  'country' => 'GB',
  'organisation_name' => 'Test',
  'name_line' => 'Test',
);

```

For empty fields, there is yet another discrepancy.

### Old node

```
$old_node->field_text = array();

```

### Prepared node

```
$node->field_text = array(
  'und' => array(),
);

```

Can I generically compare any field's old and new value to detect whether it has changed or not?
Is this just an impossibility?

# Answer
> 11 votes
This, at long last, should work as a generic solution. Thanks to Clive and morbiD for all the input.

Pass both versions of the node to the following function. It will:

1. Pull all of the detected content type's editable fields and their editable columns (i.e. items that could possibly appear on the custom form) from the database in a single query.
2. Ignore fields and columns that are completely empty in both versions.
3. Treat a field that has a different number of values between the two versions as a change.
4. Iterate through every field, value, and column and compare the two versions.
5. Compare items non-identically (!=) if they are numeric and identically (!==) if they are anything else.
6. Immediately return TRUE on the first change it detects (since one change is enough to know we need to resave the node).
7. Return FALSE if no change is detected after all the values are compared.
8. Recursively compare field collections by loading them and their schema and passing the results to itself. This SHOULD even allow it to compare nested field collections. The code should NOT have any dependency on the Field Collection module.

Let me know if there are any more bugs or typos in this code.

```
/*
 * Pass both versions of the node to this function. Returns TRUE if it detects any changes and FALSE if not.
 * Pass field collections as an array keyed by field collection ID.
 *
 * @param object $old_entity
 *   The original (stored in the database) node object.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 * @param object $new_entity
 *   The prepared node object for comparison.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 */
function _fields_changed($old_entity, $new_entity) {
  // Check for node or field collection.
  $entity_is_field_collection = (get_class($old_entity) == 'FieldCollectionItemEntity');

  $bundle = ($entity_is_field_collection ? $old_entity->field_name : $old_entity->type);

  // Sanity check. Exit and throw an error if the content types don't match.
  if($bundle !== ($entity_is_field_collection ? $new_entity->field_name : $new_entity->type)) {
    drupal_set_message('Content type mismatch. Unable to save changes.', 'error');
    return FALSE;
  }

  // Get field info.
  $field_read_params = array(
    'entity_type' => ($entity_is_field_collection ? 'field_collection_item' : 'node'),
    'bundle' => $bundle
  );
  $fields_info = field_read_fields($field_read_params);

  foreach($fields_info as $field_name => $field_info) {
    $old_field = $old_entity->$field_name;
    $new_field = $new_entity->$field_name;

    // Check the number of values for each field, or if they are populated at all.
    $old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
    $new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

    if ($old_field_count != $new_field_count) {
      // The two versions have a different number of values. Something has changed.
      return TRUE;
    } elseif ($old_field_count > 0 && $new_field_count > 0) {
      // Both versions have an equal number of values. Time to compare.

      // See if this field is a field collection.
      if ($field_info['type'] == 'field_collection') {

        foreach ($new_field[LANGUAGE_NONE] as $delta => $values) {
          $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
          $new_field_collection = $values['entity'];

          if (_fields_changed($old_field_collection, $new_field_collection)) {
            return TRUE;
          }
        }
        unset($delta, $values);

      } else {
        foreach($old_field[LANGUAGE_NONE] as $delta => $value) {
          foreach($field_info['columns'] as $field_column_name => $field_column_info) {
            $old_value = $old_field[LANGUAGE_NONE][$delta][$field_column_name];
            $new_value = $new_field[LANGUAGE_NONE][$delta][$field_column_name];
            $field_column_type = $field_column_info['type'];

            // As with the overall field, exit if one version has a value and the other doesn't.
            if (isset($old_value) != isset($new_value)) {
              return TRUE;
            } elseif (isset($old_value) && isset($new_value)) {
              // The column stores numeric data so compare values non-identically.
              if (in_array($field_column_type, array('int', 'float', 'numeric'))) {
                if ($new_value != $old_value) {
                  return TRUE;
                }
              }
              // The column stores non-numeric data so compare values identically,
              elseif ($new_value !== $old_value) {
                return TRUE;
              }
            } else {
              // Included for clarity. Both values are empty so there was obviously no change.
            }
          }
          unset($field_column_name, $field_column_info);
        }
        unset($delta, $value);
      }
    } else {
      // Included for clarity. Both values are empty so there was obviously no change.
    }
  }
  unset($field_name, $field_info);
  // End of field comparison loop.

  // We didn't find any changes. Don't resave the node.
  return FALSE;
}

```

**EDIT (7/30/2013)** Tightened up field collection support. Added support for fields with multiple values.

# Answer
> 3 votes
Here's another, simpler, approach that avoids the complex server side value comparisons, and would work with any form:

1. Use jQuery to detect if the form values have changed
2. Set a hidden element value to indicate the form has changed.
3. Check the hidden element value server side and process as required.

You could use a jQuery dirty form plugin such as https://github.com/codedance/jquery.AreYouSure

Although others that let you listen to the form changed / dirty status would also work.

Add a listener to set the value of a hidden form element:

Set the hidden form element to a default value of 'changed' to save by default for those users with javascript disabled (~2%).

e.g:

```
// Clear initial state for js-enabled user
$('input#hidden-indicator').val('')
// Add changed listener
$('#my-form').areYouSure({
    change: function() {
      // Set hidden element value
      if ($(this).hasClass('dirty')) {
        $('input#hidden-indicator').val('changed');
      } else {
        $('input#hidden-indicator').val('');
      }
    }
 });

```

You can then check the value of the hidden element

`if ($form_state['values']['hidden_indicator'] == 'changed') { /* node_save($node) */ }`

in your form validate / submit handlers.

# Answer
> 0 votes
I'm not sure that is perfect, but why not taking it the other way around, **by comparing the forms instead of the node objects** ?

I'm not sure you're if you're strictly in a node form, but anyway you can render the form with your old node and your new node :

```
module_load_include('inc', 'node', 'node.pages');
node_object_prepare($new_node);
$new_form = drupal_get_form($new_node->node_type . '_node_form', $new_node);
node_object_prepare($old_node);
$old_form = drupal_get_form($old_node->node_type . '_node_form', $old_node);

```

Compare your forms...

I hope it's a good track... let me know.

# Answer
> 0 votes
Here is a method using hook\_node\_presave($node). It is just a mockup, if you think it helps, test it and improve it to your needs!

```
  /**
   * Implements hook_node_presave().
   *
   * Look for changes in node fields, before they are saved
   */
  function mymodule_node_presave($node) {

    $changes = array();

    $node_before = node_load($node->nid);

    $fields = field_info_instances('node', $node->type);
    foreach (array_keys($fields) as $field_name) {

      $val_before = field_get_items('node', $node_before, $field_name);
      $val = field_get_items('node', $node, $field_name);

      if ($val_before != $val) {

        //if new field values has more instances then old one, it has changed
        if (count($val) != count($val_before)) {
          $changes[] = $field_name;
        } else {
          //cycle throught 1 or multiple field value instances
          foreach ($val as $k_i => $val_i) {
            if (is_array($val_i)) {
              foreach ($val_i as $k => $v) {
                if (isset($val_before[$k_i][$k]) && $val_before[$k_i][$k] != $val[$k_i][$k]) {
                  $changes[] = $field_name;
                }
              }
            }
          }
        }
      }
    }
    dpm($changes);
  }

```

I suppose that, for each field value, the instances that are defined in $node must be defined and equal in $node\_before. I don't care for field value's fields that are in $node\_before and are not in $node, I suppose they stay the same.

# Answer
> 0 votes
This is just some code I cobbled together. All credit must go to @eclecto for doing all of the leg work. This is just a (similarly untested) variation which takes the node objects directly, reduces the DB hits a bit and takes care of language negotiation.

```
function _node_fields_have_changed($old_node, $new_node) {
  // @TODO Sanity checks (e.g. node types match).

  // Get the fields attached to the node type.
  $params = array('entity_type' => 'node', 'bundle' => $old_node->type);
  foreach (field_read_fields($params) as $field) {
    // Get the field data for both nodes.
    $old_field_data = field_get_items('node', $old_node, $field['field_name']);
    $new_field_data = field_get_items('node', $new_node, $field['field_name']);

    // If the field existed on the old node, but not the new, it's changed.
    if ($old_field_data && !$new_field_data) {
      return TRUE;
    }
    // Ditto but in reverse.
    elseif ($new_field_data && !$old_field_data) {
      return TRUE;
    }

    foreach ($field['columns'] as $column_name => $column) {
      // If there's data in both columns we need an equality check.
      if (isset($old_field_data[$column_name]) && isset($new_field_data[$column_name])) {
        // Equality checking based on column type.
        if (in_array($column['type'], array('int', 'float', 'numeric')) && $old_field_data[$column_name] != $new_field_data[$column_name]) {
          return TRUE;
        }
        elseif ($old_field_data[$column_name] !== $new_field_data[$column_name]) {
          return TRUE;
        }
      }
      // Otherwise, if there's data for one column but not the other,
      // something changed.
      elseif (isset($old_field_data[$column_name]) || isset($new_field_data[$column_name])) {
        return TRUE;
      }
    }
  }

  return FALSE;
}

```

# Answer
> 0 votes
The answer provided is great and it helped me, but there is something I had to correct.

```
// See if this field is a field collection.
if ($field_info['type'] == 'field_collection') {
  foreach ($old_field[LANGUAGE_NONE] as $delta => $values) {
    $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
    $new_field_collection = $values['entity'];

    $fields_changed = array_merge($fields_changed, erplain_api_fields_changed($old_field_collection, $new_field_collection));
  }
  unset($delta, $values);
}

```

In the `foreach()` loop, I had to change from `$new_field` to `$old_field`. I don't know if this is a new version of Drupal or only my code (might be due to another code somewhere else), but I don't have access to `$new_field['entity']`.

# Answer
> 0 votes
Thanks for the post, really saved me a lot of time. I fixed a bunch of the warnings and notices that function was outputting:

```
/*
 * Pass both versions of the node to this function. Returns an array of
 * fields that were changed or an empty array if none were changed.
 * Pass field collections as an array keyed by field collection ID.
 *
 * @param object $old_entity
 *   The original (stored in the database) node object.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 * @param object $new_entity
 *   The prepared node object for comparison.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 */
function _fields_changed($old_entity, $new_entity) {
  $fields_changed = array();

  // Check for node or field collection.
  if (is_object($old_entity)) {
    $entity_is_field_collection = (get_class($old_entity) == 'FieldCollectionItemEntity');
    $bundle = !empty($entity_is_field_collection) ? $old_entity->field_name : $old_entity->type;
  }

  // Sanity check. Exit and throw an error if the content types don't match.
  if (is_object($new_entity)) {
    if ($bundle !== (!empty($entity_is_field_collection) ? $new_entity->field_name : $new_entity->type)) {
      drupal_set_message('Content type mismatch. Unable to save changes.', 'error');
      return FALSE;
    }
  }

  // Get field info.
  $field_read_params = array(
    'entity_type' => !empty($entity_is_field_collection) ? 'field_collection_item' : 'node',
  );

  if (!empty($bundle)) {
    $field_read_params['bundle'] = $bundle;
  }

  $fields_info = field_read_fields($field_read_params);

  foreach ($fields_info as $field_name => $field_info) {
    $old_field = isset($old_entity->$field_name) ? $old_entity->$field_name : NULL;
    $new_field = isset($new_entity->$field_name) ? $new_entity->$field_name : NULL;

    // Check the number of values for each field, or if they are populated at all.
    $old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
    $new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

    if ($old_field_count != $new_field_count) {
      // The two versions have a different number of values. Something has changed.
      $fields_changed[] = $field_name;
    }
    elseif ($old_field_count > 0 && $new_field_count > 0) {
      // Both versions have an equal number of values. Time to compare.

      // See if this field is a field collection.
      if ($field_info['type'] == 'field_collection') {

        foreach ($new_field[LANGUAGE_NONE] as $delta => $values) {
          $old_field_collection = NULL;
          if (!empty($values['entity']->item_id)) {
            $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
          }

          $new_field_collection = NULL;
          if (isset($values['entity'])) {
            $new_field_collection = $values['entity'];
          }

          $fields_changed = array_merge($fields_changed, _fields_changed($old_field_collection, $new_field_collection));
        }
        unset($delta, $values);

      }
      else {
        foreach ($old_field[LANGUAGE_NONE] as $delta => $value) {
          foreach ($field_info['columns'] as $field_column_name => $field_column_info) {
            $old_value = isset($old_field[LANGUAGE_NONE][$delta][$field_column_name]) ? $old_field[LANGUAGE_NONE][$delta][$field_column_name] : NULL;
            $new_value = isset($new_field[LANGUAGE_NONE][$delta][$field_column_name]) ? $new_field[LANGUAGE_NONE][$delta][$field_column_name] : NULL;
            $field_column_type = $field_column_info['type'];

            // As with the overall field, exit if one version has a value and the other doesn't.
            if (isset($old_value) != isset($new_value)) {
              $fields_changed[] = $old_field;
            }
            elseif (isset($old_value) && isset($new_value)) {
              // The column stores numeric data so compare values non-identically.
              if (in_array($field_column_type, array(
                'int',
                'float',
                'numeric'
              ))) {
                if ($new_value != $old_value) {
                  $fields_changed[] = $field_name;
                }
              }
              // The column stores non-numeric data so compare values identically,
              elseif ($new_value !== $old_value) {
                $fields_changed[] = $field_name;
              }
            }
            else {
              // Included for clarity. Both values are empty so there was obviously no change.
            }
          }
          unset($field_column_name, $field_column_info);
        }
        unset($delta, $value);
      }
    }
    else {
      // Included for clarity. Both values are empty so there was obviously no change.
    }
  }
  unset($field_name, $field_info);
  // End of field comparison loop.

  return $fields_changed;
}

```

---
Tags: 7, entities
---


title: How to decrypt data from Encrypt module

text:
# Question
Title: How to decrypt data from Encrypt module
One of my webform component is using Webform Encrypt. The Encrypt feature is from Encrypt and Key modules. I set the key and encrypt as following. Everything is working fine in the submission data, but how can I decrypt the encrypted data if I send the data to someone? I have been searching this for days with no solution. Some online AES calculator has "IV" input and I don't know where to get that information.

Key:
type type: AES Encryption
key size: 256
key provider: file
file location: something/encrypt\_key.key with based64-encoded

Encrypt:
General setting: enabled
Encryption Method: Mcrypt AES (CBC mode)
Key Provider: Key module(It's the key I made from Key module)

**--- update question --- Apr 14th 12:24pm<br>How the person decrypt the data when I sent the encrypted data to him/her?**

# Answer
> 2 votes
You can call the `decrypt()` function as seen in `_webform_encrypt_decrypt_nested_values`:

```
/**
 * Helper function to recursively decrypt values in a webform structure.
 */
function _webform_encrypt_decrypt_nested_values(&$element, $key = '#default_value', $restrict = array()) {
  // Determine if we are checking access.
  $access = empty($restrict) ? TRUE : user_access('view encrypted values', $restrict['account']);

  // Loop through each item and decrypt the value.
  foreach (element_children($element) as $name) {
    $component = &$element[$name];
    if (!empty($component['#webform_component']['extra']['encrypt'])) {
      if (is_array($component[$key])) {
        foreach ($component[$key] as &$value) {
          $value = $access ? decrypt($value, array('base64' => TRUE)) : t('[Value Encrypted]');
        }
      }
      else {
        $component[$key] = $access ? decrypt($component[$key], array('base64' => TRUE)) : t('[Value Encrypted]');
      }
    }

    // Recurse if the current item has children.
    _webform_encrypt_decrypt_nested_values($component, $key, $restrict);
  }
}

```

So in your own code you want to call something like `decrypt($value, array('base64' => TRUE))` where `$value` is (saved) encrypted webform submission data.

---
Tags: 7
---


# Question
Title: How to verify only the email address on user registration?
I have a registration form. On the registration form the user can enter his username, email address and password and confirm password.

When the user registered, he/she should receive an email to verify his/her email address before login to the system.

Before email verification he/she should not be allowed to login to the system.

Also he/she should set his/her password on registration, no on email verification.

Is it possible?

I am using the logintoboggan with the Rules module. Through Rules, I set the status of a user to `block` upon registration. Then through rules with the event `When the user account is validated` (this event is provided by the logintoboggan rules integration module), I am activating the user.

But the problem is the loggintoboggan module automatically login the user upon email validation, which display an error message that `the user is currently not active or blocked` although the user has been actived. Because the rule event is triggered after validation of the email address.

Is there any way to prevent loggintoboggan module from automatically login the user upon email validation?

# Answer
> 2 votes
I would NOT block the user at first. That will for sure also not cause that error message you try to get rid of. And instead use the Flag module (in combination with the Rules module) to implement your logic like so:

* Use that same event `When the user account is validated` to flag that user with a flag labeled (say) "Validated".
* Any time you want to check if an authenticated user has been validated, you just have to verify if that "Validated" flag has been set for that user (which you can typically do with the Rules module also.

As a remedy to the fact that a user who registers can login to the site without email verification (as in your comment below), you can add some Rules logic like so:

* Rules Condition: if this user is not flagged (with that 'Validated' flag)
* Rules Action: perform redirect to `user/logout`

Possibly with an extra message you could set (in the same Rules Action) like "sorry, your account has not been validated yet, please do so and so first".

---
Tags: 7, users, emails
---


title: Features confilict with content types

text:
# Question
Title: Features confilict with content types
I have 3 different environments such as Dev, Test and Stage. I'm currently facing an issue when trying to propagate my changes from Dev into Test and Stage envs. In order to propagate the changes i use the Features module. Within features i export all my Content Types. Some of them (e.g. Basic Page) are already exist into Test and Stage environments. When i'm trying to install the feature export from Dev into the other environments, the Basic Page content type of Test and Stage actually seems to be overridden. This means that the predefined fields that already has are not erased by the feature but it just adds the new created fields. How can i solve this issue. The desired functionality is to have the same fields after importing the future to all environments.

# Answer
> 0 votes
If I'm not mistaken, Features doesn't delete fields it only synchronizes the configuration and creates new fields if they are not present. So, deleting obsolete fields is one of the processes you have to do by hand (or write an update function in a custom module).

Features is a handy tool, but certainly has some limits (for instance when you want to synchronize blocks).

# Answer
> 0 votes
I believe 1 approach using features do manage your setup like your doing is to use `hook_update_n()` to delete fields you no longer want in versions of your module. So some tidying up code is in an update function assure only the fields you want in your content type exist at a certain version.

For Drupal 8 Dries has a recent blog post describing the Deploy, Replication and other modules to help move content around: http://buytaert.net/improving-drupal-content-workflow

---
Tags: features
---


# Question
Title: Takes too long to render a product display with 6000+ variations
I have a product with several attributes and each one with several options. The total variations is over 6000. The problem is that rendering takes too long. I've enable Devel module and here are the results:

* Executed 72 queries in 323.6 ms.
* Page execution time was 13870.81 ms.
* Memory used at: devel\_boot()=1.44 MB, devel\_shutdown()=62.56 MB, PHP peak=69.5 MB.

So I guess there's some bottleneck at the code.

Some notes about the implementation:

* I need a unique price for each variation.
* I'm using vanilla Drupal Commerce.

There's any way I could improve performance?

# Answer
> 2 votes
Didn't find a proper solution to increase the performance or, at least a clean solution. So I decided to create a module that basically holds an alternative view formatter to the "Add to cart" that comes with Drupal Commerce.

You can find the module here: https://www.drupal.org/sandbox/marcofernandes/2705035

Basically it's a "clone" of "Add to cart" view formatter but it avoids iterations over all variations and field options. It's not perfect but it fits my needs (variations for all possible combinations). I'll keep it as a sandbox until it reaches a more mature state (it lacks some validations and, probably it misses some code styling).

# Answer
> 0 votes
Getting a cachegrind/flamegraph would be ideal. There most likely is some code that can be optimized in there.

> There's any way I could improve performance?

Most likely yes. If you can wrap the call to the expensive code in a cache call that can be a quick fix. If the data changes quite regularly, and you're ok with data that is a couple of minutes old, you can use HTTPRL's function cache (httprl\_call\_user\_func\_array\_cache). We use it for some crazy expensive things that take 10 minutes to calculate (stats on every user of our site). The nice thing is it has cache\_lifetime\_min and cache\_lifetime\_max; cache\_lifetime\_min is how long to wait until new data is generated and cache\_lifetime\_max is how old of data do you want to use. It uses "threading" to make the cache generation part non blocking. Example code below. The first 2 parameters are the same as call\_user\_func\_array(), the last parameter is an array and it controls how the function cache works.

```
// Don't regenerate until data is 2 minutes old.
// Use data up to 1 day old.
// Function is slow give it 1 minute to run.
// Return NULL if there is no cache data. If FALSE and the cached data doesn't exist, the function will block.
// Store cached data in the cache_custom table/bin. This table needs to exist, or choose to not set it and it defaults to the cache bin.
return httprl_call_user_func_array_cache('function_name', array($uid), array(
  'cache_lifetime_min' => 120,
  'cache_lifetime_max' => 86400,
  'lock_timeout' => 60,
  'return_null_cache_miss' => TRUE,
  'bin' => 'cache_custom',
));

```

---
Tags: 7, commerce, performance
---


# Question
Title: Diff module not tracking fields that existed before module was installed
I have a Drupal project in the final stages of development. It has quite a lot of content types and a lot of fields. I have recently enabled revisions and added the diff module (7.x-3.2). It isn't tracking changes on my existing fields. When I choose 'compare' it shows 'No visible changes' and the current revision area only shows the new fields.

If I add a new field diff starts working on it. If I remove a field and re-add it diff starts working on the new version of the field. Any idea why this is happening? Are there any ways I can get diff working on all my fields without removing an re-adding all of them?

I tried editing and saving a field without making any changes to it, but this did not make diff tracking start working on it. I have looked in the DB and both a field being tracked and a field that isn't being tracked have a revision\_id.

I have tested in a sandbox server and the diff module works as expected. Therefore it must be a conflict or a bug that is being triggered by my install.

# Answer
Did you read the README for the module and go through the module configuration? See CONFIGURATION section of the readme.

```
2) Field revisioning settings

   Global settings per field type can be found here:

   http://www.example.com/admin/config/content/diff/fields

   "Show field title" toggles field title visibility on the comparison page.

   "Markdown callback" is the callback used to render the field when viewing the
   page in the "Marked down" page view.

   "Line counter" is an optional. This shows the approximate line number where
   the change occurred. This is an approximate counter only.

   Other fields add additional settings here.

```

This Diff Issue Queue item describes a similar "No visible changes." problem encountered by another user.

From the issue it sounds like the diff comparison view, which is typically `"Standard comparision preview" settings == "Full content"` needs to be configured to show the fields you want, or be the correct view\_mode for the content.
> 0 votes

---
Tags: 7
---


# Question
Title: Cloning / Copying value of multi-value field
I do not wanna create another wheel but could not find a solution yet.

I have multi-value field (which I implemented myself) and I would like to have possibility to add 'new item' with already predefined values.

What would you recommend to do?

I googled and did not find anything suitable for me and considering to create my own module for this.

# Answer
Consider using Entity References and not a complex compound field like your using now.

By using references you can use either the Inline Entity Form or the References Dialog modules to provide a more streamlined UI for adding new events from new popup windows. I was hoping you could reference exisitng events through a search using these modules (you can) but it won't clone the reference directly.

BUT, you could use the Replicate module, to replicated the entity reference you've selected to then edit it -- using custom code.

An example way to replicate a referenced entity can be seen in this replicate issue, as shown below:

```
/**
 * Replicate entities that are the target of entityreference fields
 *
 * Implements hook_replicate_field_FIELD_TYPE
 *
 * For entites that have one or more entity reference fields we need to replicate the
 * referenced entities as well so the cloned parents don't all point to the same children.
 * We also need to update the entityreference fields to point to them.
 *
 * @param object $replica
 *   Reference to the fully loaded entity object being saved (the clone) that
 *   can be altered as needed.
 * @param string $entity_type
 *   Type of the entity containing the field.
 * @param string $field_name
 *   Name of the field that is going to be processed.
 *
 * @see replicate_clone_entity()
 */

function MY_MODULE_replicate_field_entityreference(&$replica, $entity_type, $field_name) {

  // Only replicate entity reference field you are interested in
  if ($field_name == 'field_MY_ENTITYREFERENCE_FIELD') {

    // Wrap the replicated entity.
    $wrapper = entity_metadata_wrapper($entity_type, $replica);

    // Loop over the field values
    foreach ($wrapper->$field_name as $delta => $referenced_field_item_wrapper) {
      $referenced_entity = $referenced_field_item_wrapper->value();

      // Replicate the referenced entity and get the new id
      $replicated_referenced_entity_id = replicate_entity('node', $referenced_entity);

      // Give the replica reference field the new target id
      $replica->{$field_name}[LANGUAGE_NONE][$delta]['target_id'] = $replicated_referenced_entity_id;
    }
  }
}

```

So I'm saying Replicate and 1 of the many "dialog" modules could help make what you want to create more pretty. You could probably use the Replicate API and a custom button in your own form too -- if you want to do even more learning ... :)
> 1 votes

---
Tags: entities
---


title: Drush unable to untar Drupal 8

text:
# Question
Title: Drush unable to untar Drupal 8
Something has happened to my Drush and I've run out of ideas.

It is unable to untar drupal-8.0.6.tar.gz. I discovered this while trying to update a site but it's nothing to do with the site because it happens when I try to download drupal into an empty directory.

The weird thing is that it works with Drupal 7. I'm running Ubuntu 14.04. Drush is installed globally with Composer.

```

ross@ross-laptop:~/drush-test$ drush --version
 Drush Version   :  8.0.5

ross@ross-laptop:~/drush-test$ drush -v dl drupal
Loading version_control engine.                                                                                [notice]
Loading package_handler engine.                                                                                [notice]
Executing: wget --version
Loading release_info engine.                                                                                [notice]
Downloading release history from https://updates.drupal.org/release-history/drupal/8.x                                                                            [notice]
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_filec9M7oQ https://updates.drupal.org/release-history/drupal/8.x
Downloading project drupal ...                                                                                [notice]
Executing: wget -q --timeout=30 -O /tmp/download_fileW1T2nI https://ftp.drupal.org/files/projects/drupal-8.0.6.tar.gz
Downloading drupal-8.0.6.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-8.0.6.tar.gz verified.                                                                                [notice]
Executing: tar  -C /tmp/drush_tmp_1460638235_570f921b1a52f -xzf drupal-8.0.6.tar.gz
Unable to untar /tmp/drush_tmp_1460638235_570f921b1a52f/drupal-8.0.6.tar.gz.                                                                                [error]
Error downloading drupal                                                                                [notice]
Command dispatch complete                                                                                [notice]
ross@ross-laptop:~/drush-test$

```

Now trying Drupal 7

```

ross@ross-laptop:~/drush-test$ drush -v dl drupal-7
Loading version_control engine.                                                                                [notice]
Loading package_handler engine.                                                                                [notice]
Executing: wget --version
Loading release_info engine.                                                                                [notice]
Downloading release history from https://updates.drupal.org/release-history/drupal/7.x                                                                            [notice]
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_file9HXrRX https://updates.drupal.org/release-history/drupal/7.x
Downloading project drupal ...                                                                                [notice]
Executing: wget -q --timeout=30 -O /tmp/download_filelb2ETq https://ftp.drupal.org/files/projects/drupal-7.43.tar.gz
Downloading drupal-7.43.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-7.43.tar.gz verified.                                                                                [notice]
Executing: tar  -C /tmp/drush_tmp_1460638348_570f928cdd995 -xzf drupal-7.43.tar.gz
Executing: tar -tzf drupal-7.43.tar.gz
Executing: svn info /home/ross/drush-test
Executing: bzr root /home/ross/drush-test
Project drupal (7.43) downloaded to /home/ross/drush-test/drupal-7.43.                                                                                [success]
Project drupal contains:                                                                                [success]
 - 3 profiles: minimal, testing, standard
 - 4 themes: garland, stark, bartik, seven
 - 47 modules: drupal_system_listing_compatible_test, drupal_system_listing_incompatible_test, toolbar, simpletest, image, openid, trigger, path, search,
forum, translation, statistics, locale, color, rdf, syslog, contact, menu, book, update, help, php, blog, filter, file, tracker, profile, block, dblog, poll,
overlay, taxonomy, shortcut, comment, user, number, field_sql_storage, options, list, text, field, node, system, contextual, field_ui, dashboard, aggregator

Command dispatch complete                                                                                [notice]
ross@ross-laptop:~/drush-test$

```

It successfully updated a module on my D8 site. The problem just seems to be with D8 core. I've checked permissions. The user I'm logged in as can create files and directories in /tmp.

# Answer
> 1 votes
Well, that's a tough one. I just downloaded Drupal 8.0.6 successfully on my machine; it untarred just fine. I can't think of anything that could explain why Drupal 8 wouldn't download, but Drupal 7 would. Well, I can think of one thing -- when I first tried this, Drush told me it was "retrieved from cache". I ran `drush cc drush` and tried again, and it downloaded from drupal.org and untarred just fine. I might guess that the file was somehow corrupted on download, but (a) Drush checks the checksum, and (b) your debug output above shows that you're getting a fresh download.

Try running `drush -v dl drupal --select --all` and pick some other versions of Drupal 8. Is it only 8.0.6 that will not untar, or are other releases also broken?

(Sorry for the long non-answer, but this didn't fit well in a comment.)

# Answer
> 0 votes
Oops...

My laptop is almost out of disk space on the partition where /tmp is. :-)

It downloads successfully but fails when it tries to copy. Each version of Drupal is a bit bigger than earlier versions.

---
Tags: 8, drush
---


# Question
Title: Limit a View with a relationship to show only the first (by sort) relationship of each of the original entities
*(note - I've tried aggregation and Distinct, see final paragraph. This is different to questions like this one about Views duplicates because I want to remove the "duplicate" relationship-derived items with the first "original" determined by sort criteria, not ID)*

To give a simple use-case, imagine a shop with products (*italics*) and a taxonomy vocabulary 'colour' (**bold**) something like this. Using products here simply for an easy-to-understand use case.

Each product has a field relating to sales:

* **Red** \- Weight: -5
    + *Fire truck*. Sales: 12
    + *Telephone*. Sales: 128
* **Blue** \- Weight: 0
    + *Whale*. Sales: 0
    + *Bottle*. Sales: 914
* **Yellow** \- Weight: 5
    + *Banana*. Sales: 1,941
    + *Submarine*. Sales: 1
* more...

I want something like a view which, for each term (sorted by weight, limited to the top three), shows the term name with the image of the top-selling item, as an example of that category. For example:

* **Red**. *picture of a red telephone*
* **Blue**. *picture of a blue bottle*
* **Yellow**. *picture of a yellow banana*

I could do this using Views Field View module, with each item in a Taxonomy Term view contains a nested view of products restricted to one item, receiving a contextual filter that is the taxonomy term ID, then sorts by sales to show only the top seller. This is my "last resort" option, since Views Field View can create very complex queries. I'd prefer to avoid views within views for somethig that seems so simple.

What I've tried to make work is, making a view of terms, with a relationship to products, then sort it first by product sales then by term weight. This works, but it gives me *every* product with the term, and I can't find a way to restrict it. With results limited to three the above example would show:

* **Red**. *picture of a red telephone*
* **Red**. *picture of a red firetruck*
* **Blue**. *picture of a blue bottle*

Based on an old similar question on SO, turning on `Use aggregation` under Advanced view settings and ticking **Distinct** under `Query settings` under Advanced view settings, I've managed to get something that removes the "duplicates" from the original list. However, because of the timing of when they're removed, the sort isn't able to apply, and it seems to simply get the first by ID, not by my sort criteria:

* **Red**. *picture of a red fire truck*
* **Blue**. *picture of a blue whale*
* **Yellow**. *picture of a yellow banana*

# Answer
I found a module that does almost exactly what I'm looking for: **Views Grouping Row Limit**.

The bad news is, it's unmaintained and never got a stable release, but it seems to work from my limited testing. I set the original field to be a grouping field, and then set the Views Grouping Row Limit to 1 item, and it shows the correct one based on my sort criteria.

---

From my testing so far, it seems to work as expected against up-to-date Views and other common modules in April 2016, and appears to meet all the criteria of my answer, if the patch on this issue is applied: https://www.drupal.org/node/1315888.

It gives incorrect results when mixed with the normal Views pager/item limit (in my example, it'd show the red and blue items only, then nothing because the in-built Views three item limit counts the not-shown other red item), but with this patch, you can limit the number of groups as well as the number of items within each group. It also adds the ability to add a group offset (i.e. skip X groups then show the next Y).
> 0 votes

# Answer
I believe your issue is a good example of needing additional meta information on your Product (Node) to do (simple) views searches. The approach you've take, by embedding the information into a Field of the node is typically difficult to use. I recommend 2 possible solutions:

* This may not have a solution for you but I suggest looking at https://www.drupal.org/project/views\_aggregator for complicated aggregated views.
* Another option is that instead of using the field with nested values. To use something like the Relation module to store your heuristics (sales data). Relations be linked together to get information like you requested from your products.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to programmatically delete taxonomies when a module is uninstalled?
Taxonomy vocabularies are in the CMI as of Drupal 8, but I want to also keep the Taxonomy terms in code. I am programmatically creating terms in a custom module.

```
function taxonomy_vocab_install() {
  foreach (taxonomy_term_info() as $term_info) {
    $term = Term::create(array(
      'parent' => array(),
      'name' => $term_info['name'],
      'description' => [
        'value' => $term_info['description'],
        'format' => 'full_html',
      ],
        'vid' => 'department',
    ));
    $term->save();
  };
};

```

Now, I want to delete the terms on uninstall, but taxonomy\_term\_delete is depreciated. Any help on how to programmatically delete the created taxonomy terms in D8 when the module is uninstalled would be greatly appreciated.

```
function taxonomy_department_uninstall() {
  // ??
};

```

# Answer
I did not test it myself, but as far as I see in the documentation, Term is using Entity::delete(). You might try to load the terms you wish to delete and call this method directly on them:

```
$term->delete();

```
> 4 votes

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


# Question
Title: Custom image style conversion - how to read back from a file?
I'm making a custom image style in Drupal 8.

It takes various parameters and passes the image to an external service for processing, and it now needs to read back the processed image from a file.

However, in applyEffect I'm expected to work with the `Image $image` object passed in.

The site is using the standard GD2 toolkit, which provides a `load()` method, but alas it's protected (presumably because the `Image` object that owns it would need updating).

Previously (porting this effect from D7) I was able to create a new Image object from the new image and replace the original object's `resource` and `info` properties, thus moving the altered image data into the image object. But this is no longer possible.

To summarise I want to:

```
public function applyEffect(ImageInterface $image) {
    $image->save('/some/path');
    $new_image_filename = call_some_external_process('/some/path');
    $image->load($new_image_filename); // ← this does not work :-)
    return TRUE;
}

```

# Answer
Here's how I did it.

```
public function applyEffect(ImageInterface $image) {

    // Save the image and process it externally...
    $some_tempoaray_filename = '/tmp/foo';
    $image->save($some_tempoaray_filename);
    call_some_external_process($some_tempoaray_filename);

    $toolkit = \Drupal::service('image.toolkit.manager')->getDefaultToolkit();
    // Re-call the existing Image object's constructor with the name of the
    // new file.
    $image->__construct($toolkit, $some_tempoaray_filename);
    // Next we have to make sure it loads the file into memory
    // because $image->save() requires it to be loaded, but this
    // happens outside of this function and we want to delete
    // the $some_tempoaray_filename so as not to leave temp files.
    $toolkit->getResource(); // forces a load.
    // Now we can lose our temporary file.
    unlink($some_tempoaray_filename);

    return TRUE;
}

```
> 0 votes

---
Tags: 8, media
---


# Question
Title: Decryption failed because the HMAC could not be validated - error on Migration d2d dashboard page
I'm trying to migrate Drupal 6 to Drupal 7 with Migrate d2d module. Problem is that I get 2 errors on Migrate dashboard page:

```
Decryption failed because the HMAC could not be validated.
Migration c9b87f5afFile could not be constructed.

```

And they are repeating many times. I can run migrate process, but custom defined field values are not migrated since I didn't map them. I can't access field mapping page because of this error.

Any idea how to resolve this?

# Answer
I am not sure this will help you, but I ran into this error while using webforms:

> Decryption failed because the HMAC could not be validated.

My issue was I tried to encrypt a webform field after there was already unencrypted data saved for that field in the database. So when I tried to view the results of my webform, I would get the above error because it was trying to decrypt data that was not encrypted.

Perhaps this is what is happening when you try to migrate?

My solution was to manually clear the data from the database. Once I did that, I was able to get to the webform results page in the drupal admin and clear the data from there to be sure all evidence of it was gone. Because I am in development this was an ok solution.

I am guessing clearing the data will not work for you, but perhaps this will help point you in the right direction.
> 1 votes

---
Tags: 7, migrations
---


title: Views and node_access

text:
# Question
Title: Views and node_access
I have a D7 installation with about 2k "project" nodes, which have a multi-entry field "team members" used to control view and edit access.

So far, I have my (pretty complex) logic inside node\_access, and it works fine. But views (e.g. a "new projects" feed) don't respect node\_access. The mymod\_node\_access hook is called (I see it with dpm()), but the nodes still appear in the view result.

Obviously I could simply hide the elements using a view field template, but that breaks the paging system (e.g. user selects "10 projects per page", but sees only four).

How can I make the Views module respect node\_access as a filter?

# Answer
If you are willing to give it a try to "*replace node\_access AND drupal filters with one solution*" (as per one of your comments), then have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

# Resources
> 0 votes

---
Tags: 7, views
---


title: Theming logo and site name

text:
# Question
Title: Theming logo and site name
I am using Corporate Clean theme and I want to make some changes to how the logo and site name are displayed. What file would do that in? Sorry, newbie here!

# Answer
find **page.tpl.php** file in theme's root folder (`sites/all/themes/corporateclean/page.tpl.php`).

You'll see that this file defines how and where variables and regions get printed. You can make changes right there.

What you're looking for is **$logo** and **$site\_name** variables.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to get Users Email address in an Rest Export View for auth users
i build a Rest export view for autocompletion of an textfield. The input should autocomplete email addresses of all logged in users. As admin thats possible, but not as authenticated user, the email addresses get stripped from the result on field access level.

The use case is a share form between users on the same platform ( contact form is not suitable ).

I know this is a security measurement but this platform is for logged in users only and all users are from the same company.

I could hack around the core functions but i wanted to ask if there is a better way to do this?

Greetings,

yobottehg

# Answer
Access to the user fields is controlled by \Drupal\user\UserAccessControlHandler::checkFieldAccess(). Which returns forbidden() for email except if it's the current user or the user has administer users permission (which you obviously don't want to grant your normal users).

That is called by \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess(), collects the default access and everything returned by `hook_entity_field_access()`. You can't directly overrrule a forbidden(), but you can implement `hook_entity_field_access_alter()` and replace the default access check with one that allows access.
> -1 votes

---
Tags: views, 8
---


# Question
Title: Getting an error adding a new field with a custom Field Type
I defined a new Field Type named `country` following this nice tutorial: http://capgemini.github.io/drupal/writing-custom-fields-in-drupal-8/

These are main files from the `country` custom Field Type:

`modules/custom/country/src/Plugin/Field/FieldType/CountryItem.php`

```
/**
 * Plugin implementation of the 'country' field type.
 *
 * @FieldType(
 *   id = "country",
 *   label = @Translation("Country"),
 *   description = @Translation("Stores the ISO-2 name of a country."),
 *   category = @Translation("Custom"),
 *   default_widget = "country_default",
 *   default_formatter = "country_default"
 * )
 */
class CountryItem extends FieldItemBase {

  const COUNTRY_ISO2_MAXLENGTH = 2;

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(t('Country'));
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return array(
      'columns' => array(
        'value' => array(
          'type' => 'char',
          'length' => static::COUNTRY_ISO2_MAXLENGTH,
          'not null' => FALSE,
        ),
      ),
      'indexes' => array(
        'value' => array('value'),
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('value')->getValue();
    return $value === NULL || $value === '';
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();
    $constraints[] = $constraint_manager->create('ComplexData', array(
      'value' => array(
        'Length' => array(
          'max' => static::COUNTRY_ISO2_MAXLENGTH,
          'maxMessage' => t('%name: the country iso-2 code may not be longer than @max characters.', array('%name' => $this->getFieldDefinition()->getLabel(), '@max' => static::COUNTRY_ISO2_MAXLENGTH)),
        )
      ),
    ));
    return $constraints;
  }
}

```

`modules/custom/country/src/Plugin/Field/FieldFormatter/CountryDefaultFormatter.php`

```
/**
 * Plugin implementation of the 'country' formatter.
 *
 * @FieldFormatter(
 *   id = "country_default",
 *   module = "country",
 *   label = @Translation("Country"),
 *   field_types = {
 *     "country"
 *   }
 * )
 */
class CountryDefaultFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = array();
    $countries = \Drupal::service('country_manager')->getList();
    foreach ($items as $delta => $item) {
      if (isset($countries[$item->value])) {
        $elements[$delta] = array('#markup' => $countries[$item->value]);
      }
    }
    return $elements;
  }

}

```

`modules/custom/country/src/Plugin/Field/FieldWidget/CountryDefaultWidget.php`

```
/**
 * Plugin implementation of the 'country_default' widget.
 *
 * @FieldWidget(
 *   id = "country_default",
 *   label = @Translation("Country select"),
 *   field_types = {
 *     "country"
 *   }
 * )
 */
class CountryDefaultWidget extends WidgetBase {

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $countries = \Drupal::service('country_manager')->getList();
    $element['value'] = $element + array(
        '#type' => 'select',
        '#options' => $countries,
        '#empty_value' => '',
        '#default_value' => (isset($items[$delta]->value) && isset($countries[$items[$delta]->value])) ? $items[$delta]->value : NULL,
        '#description' => t('Select a country'),
      );
    return $element;
  }

}

```

All works fine: I'm able to create new fields of type `country` and set values on them.

The only problem is when I add a new field of type `country` in some Content Type, when I click the "Save and continue" button (after set a value for the field's label) I get a 500 http error page inside the browser and this error in the PHP log:

> PHP Fatal error: Declaration of Drupal\country\Plugin\Field\FieldFormatter\CountryDefaultFormatter::viewElements() must be compatible with Drupal\Core\Field\FormatterInterface::viewElements(Drupal\Core\Field\FieldItemListInterface $items, $langcode) in /path/to/drupal/website/modules/custom/country/src/Plugin/Field/FieldFormatter/CountryDefaultFormatter.php on line 0

What is wrong?

# Answer
Your tutorial is outdated, as the error says, viewElements() has an additional langcode argument that you need to add as well.
> 5 votes

---
Tags: entities, 8
---


title: Export sorted View to JSON

text:
# Question
Title: Export sorted View to JSON
I need some expert help. I need to export data into JSON. Here are the steps I followed:

1\> Created a draggable view to allow admin to provide appropriate sort order. ref (https://3cwebservices.com/drupal/creating-drag-drop-sorting-interface-drupal-view)

2\> Adding a page on the same view, with format as 'JSON data document'

I can see the output in JSON format but the SORT order provided by admin is missing.

Any help is appreciated.

# Answer
> 0 votes
I used the query generated by the drupal page and generated JSON programmatically.

---
Tags: 7, views
---


# Question
Title: Passing product info to PayPal using Comment1 and Comment2
We need to pass information to PayPal using their Comment1 and Comment2 fields for accounting purposes. We have several units using the cart for different fees and our finance team needs to be able to see and sort by the units in question on the PayPal Manager website. The Comment1 and Comment2 fields seem to be the ideal place to pass this information to PayPal, but we can't figure out how to populate and pass these fields to them in the module code.

How would you recommend accomplishing this?

# Answer
> 0 votes
I've been researching this very issue myself. I spoke with PayPal and they told me the following.

**First**, they recommend you use the PayFlow Pro Module.

**Second**, to add `$comment1` and `$comment2` variables to your code you need to:

Create the form fields for COMMENT1 and COMMENT2 to add to the Return Array at lines 293 (of commerce\_payflow.module):

‘comment1’ =\> $\_POST\[‘your\_form\_field\_here’\], ‘comment2’ =\> $\_POST\[‘your\_form\_field\_here’\],

*Note: You may need to build the form fields in the function starting at line 336.*

**This is really a half-solution, because:**

Now, I'm still trying to parse out exactly how to do this myself but I'm pretty sure it involves a custom module that uses a hook to alter a function in that module (possibly commerce\_payflow\_link\_settings\_form or commerce\_payflow\_link\_default\_settings).

---
Tags: commerce
---


# Question
Title: How do I programmatically use the S3FS module?
I've included S3FS module in Drupal 7. I'm able to store files by using S3FS as a field of a node.

Now, I need to store a file on S3 bucket when a cron job is executed. How can I programmatically use the module?

# Answer
I used the following command to write the file. The system picks up the S3 connection (as I mentioned earlier that I'm able to store file as a field of a node):

```
file_put_contents('s3://Dir1/output.json', $jsonStr);

```
> 1 votes

# Answer
I created this module that copies images, css, js to s3 https://www.drupal.org/sandbox/mikeytown2/2678270
> 0 votes

---
Tags: 7
---


# Question
Title: Determining the $POST variables of a submitted form
I have a form on my site. Users fill out the form and submit it. When I want to target one of the fields in the form with a custom module I'd target it with something like the following:

```
$form['customer_profile_billing']['field_organization'];

```

But, if I want to target the value a user entered - after they clicked submit, in a custom module, what would be the proper syntax to use, or how would I figure out what my $POST variables are?

# Answer
> 2 votes
The submitted values are available in your custom validate/submit handler in the `$form_state['values']` or `$form_state['input']` (with the later one storing raw and unvalidated user input). I think this is considered better practice than accessing the values through the $POST variable.

---
Tags: forms, commerce
---